1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // A general interface for filtering and only acting on classes in Chromium C++
8 #include "ChromeClassTester.h"
10 #include <sys/param.h>
12 #include "clang/AST/AST.h"
13 #include "clang/Basic/FileManager.h"
14 #include "clang/Basic/SourceManager.h"
16 using namespace clang;
20 bool starts_with(const std::string& one, const std::string& two) {
21 return one.compare(0, two.size(), two) == 0;
24 std::string lstrip(const std::string& one, const std::string& two) {
25 if (starts_with(one, two))
26 return one.substr(two.size());
30 bool ends_with(const std::string& one, const std::string& two) {
31 if (two.size() > one.size())
34 return one.compare(one.size() - two.size(), two.size(), two) == 0;
39 ChromeClassTester::ChromeClassTester(CompilerInstance& instance,
40 bool check_url_directory)
41 : instance_(instance),
42 diagnostic_(instance.getDiagnostics()),
43 check_url_directory_(check_url_directory) {
47 ChromeClassTester::~ChromeClassTester() {}
49 void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
50 pending_class_decls_.push_back(tag);
53 bool ChromeClassTester::HandleTopLevelDecl(DeclGroupRef group_ref) {
54 for (size_t i = 0; i < pending_class_decls_.size(); ++i)
55 CheckTag(pending_class_decls_[i]);
56 pending_class_decls_.clear();
58 return true; // true means continue parsing.
61 void ChromeClassTester::CheckTag(TagDecl* tag) {
62 // We handle class types here where we have semantic information. We can only
63 // check structs/classes/enums here, but we get a bunch of nice semantic
64 // information instead of just parsing information.
66 if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) {
67 // If this is a POD or a class template or a type dependent on a
68 // templated class, assume there's no ctor/dtor/virtual method
69 // optimization that we can do.
70 if (record->isPOD() ||
71 record->getDescribedClassTemplate() ||
72 record->getTemplateSpecializationKind() ||
73 record->isDependentType())
76 if (InBannedNamespace(record))
79 SourceLocation record_location = record->getInnerLocStart();
80 if (InBannedDirectory(record_location))
83 // We sadly need to maintain a blacklist of types that violate these
84 // rules, but do so for good reason or due to limitations of this
85 // checker (i.e., we don't handle extern templates very well).
86 std::string base_name = record->getNameAsString();
87 if (IsIgnoredType(base_name))
90 // We ignore all classes that end with "Matcher" because they're probably
92 if (ends_with(base_name, "Matcher"))
95 CheckChromeClass(record_location, record);
96 } else if (EnumDecl* enum_decl = dyn_cast<EnumDecl>(tag)) {
97 SourceLocation enum_location = enum_decl->getInnerLocStart();
98 if (InBannedDirectory(enum_location))
101 std::string base_name = enum_decl->getNameAsString();
102 if (IsIgnoredType(base_name))
105 CheckChromeEnum(enum_location, enum_decl);
109 void ChromeClassTester::emitWarning(SourceLocation loc,
110 const char* raw_error) {
111 FullSourceLoc full(loc, instance().getSourceManager());
113 err = "[chromium-style] ";
115 DiagnosticsEngine::Level level =
116 diagnostic().getWarningsAsErrors() ?
117 DiagnosticsEngine::Error :
118 DiagnosticsEngine::Warning;
119 unsigned id = diagnostic().getCustomDiagID(level, err);
120 DiagnosticBuilder builder = diagnostic().Report(full, id);
123 bool ChromeClassTester::InBannedNamespace(const Decl* record) {
124 std::string n = GetNamespace(record);
126 return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
127 != banned_namespaces_.end();
133 std::string ChromeClassTester::GetNamespace(const Decl* record) {
134 return GetNamespaceImpl(record->getDeclContext(), "");
137 bool ChromeClassTester::InImplementationFile(SourceLocation record_location) {
138 std::string filename;
139 if (!GetFilename(record_location, &filename))
142 if (ends_with(filename, ".cc") || ends_with(filename, ".cpp") ||
143 ends_with(filename, ".mm")) {
150 void ChromeClassTester::BuildBannedLists() {
151 banned_namespaces_.push_back("std");
152 banned_namespaces_.push_back("__gnu_cxx");
154 // We're in the process of renaming WebKit to blink.
155 // TODO(abarth): Remove WebKit once the rename is complete.
156 banned_namespaces_.push_back("WebKit");
157 banned_namespaces_.push_back("blink");
159 banned_directories_.push_back("third_party/");
160 banned_directories_.push_back("native_client/");
161 banned_directories_.push_back("breakpad/");
162 banned_directories_.push_back("courgette/");
163 banned_directories_.push_back("pdf/");
164 banned_directories_.push_back("ppapi/");
165 banned_directories_.push_back("usr/");
166 banned_directories_.push_back("testing/");
167 banned_directories_.push_back("v8/");
168 banned_directories_.push_back("dart/");
169 banned_directories_.push_back("sdch/");
170 banned_directories_.push_back("icu4c/");
171 banned_directories_.push_back("frameworks/");
173 if (!check_url_directory_)
174 banned_directories_.push_back("url/");
176 // Don't check autogenerated headers.
177 // Make puts them below $(builddir_name)/.../gen and geni.
178 // Ninja puts them below OUTPUT_DIR/.../gen
179 // Xcode has a fixed output directory for everything.
180 banned_directories_.push_back("gen/");
181 banned_directories_.push_back("geni/");
182 banned_directories_.push_back("xcodebuild/");
184 // You are standing in a mazy of twisty dependencies, all resolved by
185 // putting everything in the header.
186 banned_directories_.push_back("automation/");
188 // Don't check system headers.
189 banned_directories_.push_back("/Developer/");
191 // Used in really low level threading code that probably shouldn't be out of
193 ignored_record_names_.insert("ThreadLocalBoolean");
195 // A complicated pickle derived struct that is all packed integers.
196 ignored_record_names_.insert("Header");
198 // Part of the GPU system that uses multiple included header
199 // weirdness. Never getting this right.
200 ignored_record_names_.insert("Validators");
202 // Has a UNIT_TEST only constructor. Isn't *terribly* complex...
203 ignored_record_names_.insert("AutocompleteController");
204 ignored_record_names_.insert("HistoryURLProvider");
206 // Because of chrome frame
207 ignored_record_names_.insert("ReliabilityTestSuite");
209 // Used over in the net unittests. A large enough bundle of integers with 1
210 // non-pod class member. Probably harmless.
211 ignored_record_names_.insert("MockTransaction");
213 // Enum type with _LAST members where _LAST doesn't mean last enum value.
214 ignored_record_names_.insert("ServerFieldType");
216 // Used heavily in ui_unittests and once in views_unittests. Fixing this
217 // isn't worth the overhead of an additional library.
218 ignored_record_names_.insert("TestAnimationDelegate");
220 // Part of our public interface that nacl and friends use. (Arguably, this
221 // should mean that this is a higher priority but fixing this looks hard.)
222 ignored_record_names_.insert("PluginVersionInfo");
224 // Measured performance improvement on cc_perftests. See
225 // https://codereview.chromium.org/11299290/
226 ignored_record_names_.insert("QuadF");
228 // Enum type with _LAST members where _LAST doesn't mean last enum value.
229 ignored_record_names_.insert("ViewID");
232 std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
233 const std::string& candidate) {
234 switch (context->getDeclKind()) {
235 case Decl::TranslationUnit: {
238 case Decl::Namespace: {
239 const NamespaceDecl* decl = dyn_cast<NamespaceDecl>(context);
240 std::string name_str;
241 llvm::raw_string_ostream OS(name_str);
242 if (decl->isAnonymousNamespace())
243 OS << "<anonymous namespace>";
246 return GetNamespaceImpl(context->getParent(),
250 return GetNamespaceImpl(context->getParent(), candidate);
255 bool ChromeClassTester::InBannedDirectory(SourceLocation loc) {
256 std::string filename;
257 if (!GetFilename(loc, &filename)) {
258 // If the filename cannot be determined, simply treat this as a banned
259 // location, instead of going through the full lookup process.
263 // We need to special case scratch space; which is where clang does its
264 // macro expansion. We explicitly want to allow people to do otherwise bad
265 // things through macros that were defined due to third party libraries.
266 if (filename == "<scratch space>")
269 // Don't complain about autogenerated protobuf files.
270 if (ends_with(filename, ".pb.h")) {
274 // We need to munge the paths so that they are relative to the repository
275 // srcroot. We first resolve the symlinktastic relative path and then
276 // remove our known srcroot from it if needed.
277 char resolvedPath[MAXPATHLEN];
278 if (realpath(filename.c_str(), resolvedPath)) {
279 filename = resolvedPath;
282 // On linux, chrome is often checked out to /usr/local/google. Due to the
283 // "usr" rule in banned_directories_, all diagnostics would be suppressed
284 // in that case. As a workaround, strip that prefix.
285 filename = lstrip(filename, "/usr/local/google");
287 for (std::vector<std::string>::const_iterator it =
288 banned_directories_.begin();
289 it != banned_directories_.end(); ++it) {
290 // If we can find any of the banned path components in this path, then
291 // this file is rejected.
292 size_t index = filename.find(*it);
293 if (index != std::string::npos) {
294 bool matches_full_dir_name = index == 0 || filename[index - 1] == '/';
296 matches_full_dir_name = true;
297 if (matches_full_dir_name)
305 bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
306 return ignored_record_names_.find(base_name) != ignored_record_names_.end();
309 bool ChromeClassTester::GetFilename(SourceLocation loc,
310 std::string* filename) {
311 const SourceManager& source_manager = instance_.getSourceManager();
312 SourceLocation spelling_location = source_manager.getSpellingLoc(loc);
313 PresumedLoc ploc = source_manager.getPresumedLoc(spelling_location);
314 if (ploc.isInvalid()) {
315 // If we're in an invalid location, we're looking at things that aren't
316 // actually stated in the source.
320 *filename = ploc.getFilename();