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 : instance_(instance),
41 diagnostic_(instance.getDiagnostics()) {
45 ChromeClassTester::~ChromeClassTester() {}
47 void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
48 pending_class_decls_.push_back(tag);
51 bool ChromeClassTester::HandleTopLevelDecl(DeclGroupRef group_ref) {
52 for (size_t i = 0; i < pending_class_decls_.size(); ++i)
53 CheckTag(pending_class_decls_[i]);
54 pending_class_decls_.clear();
56 return true; // true means continue parsing.
59 void ChromeClassTester::CheckTag(TagDecl* tag) {
60 // We handle class types here where we have semantic information. We can only
61 // check structs/classes/enums here, but we get a bunch of nice semantic
62 // information instead of just parsing information.
64 if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) {
65 // If this is a POD or a class template or a type dependent on a
66 // templated class, assume there's no ctor/dtor/virtual method
67 // optimization that we can do.
68 if (record->isPOD() ||
69 record->getDescribedClassTemplate() ||
70 record->getTemplateSpecializationKind() ||
71 record->isDependentType())
74 if (InBannedNamespace(record))
77 SourceLocation record_location = record->getInnerLocStart();
78 if (InBannedDirectory(record_location))
81 // We sadly need to maintain a blacklist of types that violate these
82 // rules, but do so for good reason or due to limitations of this
83 // checker (i.e., we don't handle extern templates very well).
84 std::string base_name = record->getNameAsString();
85 if (IsIgnoredType(base_name))
88 // We ignore all classes that end with "Matcher" because they're probably
90 if (ends_with(base_name, "Matcher"))
93 CheckChromeClass(record_location, record);
94 } else if (EnumDecl* enum_decl = dyn_cast<EnumDecl>(tag)) {
95 SourceLocation enum_location = enum_decl->getInnerLocStart();
96 if (InBannedDirectory(enum_location))
99 std::string base_name = enum_decl->getNameAsString();
100 if (IsIgnoredType(base_name))
103 CheckChromeEnum(enum_location, enum_decl);
107 void ChromeClassTester::emitWarning(SourceLocation loc,
108 const char* raw_error) {
109 FullSourceLoc full(loc, instance().getSourceManager());
111 err = "[chromium-style] ";
113 DiagnosticIDs::Level level =
114 diagnostic().getWarningsAsErrors() ?
115 DiagnosticIDs::Error :
116 DiagnosticIDs::Warning;
117 unsigned id = diagnostic().getDiagnosticIDs()->getCustomDiagID(level, err);
118 DiagnosticBuilder builder = diagnostic().Report(full, id);
121 bool ChromeClassTester::InBannedNamespace(const Decl* record) {
122 std::string n = GetNamespace(record);
124 return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
125 != banned_namespaces_.end();
131 std::string ChromeClassTester::GetNamespace(const Decl* record) {
132 return GetNamespaceImpl(record->getDeclContext(), "");
135 bool ChromeClassTester::InImplementationFile(SourceLocation record_location) {
136 std::string filename;
137 if (!GetFilename(record_location, &filename))
140 if (ends_with(filename, ".cc") || ends_with(filename, ".cpp") ||
141 ends_with(filename, ".mm")) {
148 void ChromeClassTester::BuildBannedLists() {
149 banned_namespaces_.push_back("std");
150 banned_namespaces_.push_back("__gnu_cxx");
152 banned_namespaces_.push_back("blink");
153 banned_namespaces_.push_back("WTF");
155 banned_directories_.push_back("/third_party/");
156 banned_directories_.push_back("/native_client/");
157 banned_directories_.push_back("/breakpad/");
158 banned_directories_.push_back("/courgette/");
159 banned_directories_.push_back("/pdf/");
160 banned_directories_.push_back("/ppapi/");
161 banned_directories_.push_back("/usr/");
162 banned_directories_.push_back("/testing/");
163 banned_directories_.push_back("/v8/");
164 banned_directories_.push_back("/dart/");
165 banned_directories_.push_back("/sdch/");
166 banned_directories_.push_back("/icu4c/");
167 banned_directories_.push_back("/frameworks/");
169 // Don't check autogenerated headers.
170 // Make puts them below $(builddir_name)/.../gen and geni.
171 // Ninja puts them below OUTPUT_DIR/.../gen
172 // Xcode has a fixed output directory for everything.
173 banned_directories_.push_back("/gen/");
174 banned_directories_.push_back("/geni/");
175 banned_directories_.push_back("/xcodebuild/");
177 // You are standing in a mazy of twisty dependencies, all resolved by
178 // putting everything in the header.
179 banned_directories_.push_back("/automation/");
181 // Don't check system headers.
182 banned_directories_.push_back("/Developer/");
184 // Used in really low level threading code that probably shouldn't be out of
186 ignored_record_names_.insert("ThreadLocalBoolean");
188 // A complicated pickle derived struct that is all packed integers.
189 ignored_record_names_.insert("Header");
191 // Part of the GPU system that uses multiple included header
192 // weirdness. Never getting this right.
193 ignored_record_names_.insert("Validators");
195 // Has a UNIT_TEST only constructor. Isn't *terribly* complex...
196 ignored_record_names_.insert("AutocompleteController");
197 ignored_record_names_.insert("HistoryURLProvider");
199 // Because of chrome frame
200 ignored_record_names_.insert("ReliabilityTestSuite");
202 // Used over in the net unittests. A large enough bundle of integers with 1
203 // non-pod class member. Probably harmless.
204 ignored_record_names_.insert("MockTransaction");
206 // Enum type with _LAST members where _LAST doesn't mean last enum value.
207 ignored_record_names_.insert("ServerFieldType");
209 // Used heavily in ui_unittests and once in views_unittests. Fixing this
210 // isn't worth the overhead of an additional library.
211 ignored_record_names_.insert("TestAnimationDelegate");
213 // Part of our public interface that nacl and friends use. (Arguably, this
214 // should mean that this is a higher priority but fixing this looks hard.)
215 ignored_record_names_.insert("PluginVersionInfo");
217 // Measured performance improvement on cc_perftests. See
218 // https://codereview.chromium.org/11299290/
219 ignored_record_names_.insert("QuadF");
221 // Enum type with _LAST members where _LAST doesn't mean last enum value.
222 ignored_record_names_.insert("ViewID");
225 std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
226 const std::string& candidate) {
227 switch (context->getDeclKind()) {
228 case Decl::TranslationUnit: {
231 case Decl::Namespace: {
232 const NamespaceDecl* decl = dyn_cast<NamespaceDecl>(context);
233 std::string name_str;
234 llvm::raw_string_ostream OS(name_str);
235 if (decl->isAnonymousNamespace())
236 OS << "<anonymous namespace>";
239 return GetNamespaceImpl(context->getParent(),
243 return GetNamespaceImpl(context->getParent(), candidate);
248 bool ChromeClassTester::InBannedDirectory(SourceLocation loc) {
249 std::string filename;
250 if (!GetFilename(loc, &filename)) {
251 // If the filename cannot be determined, simply treat this as a banned
252 // location, instead of going through the full lookup process.
256 // We need to special case scratch space; which is where clang does its
257 // macro expansion. We explicitly want to allow people to do otherwise bad
258 // things through macros that were defined due to third party libraries.
259 if (filename == "<scratch space>")
262 // Don't complain about autogenerated protobuf files.
263 if (ends_with(filename, ".pb.h")) {
267 // We need to munge the paths so that they are relative to the repository
268 // srcroot. We first resolve the symlinktastic relative path and then
269 // remove our known srcroot from it if needed.
270 char resolvedPath[MAXPATHLEN];
271 if (realpath(filename.c_str(), resolvedPath)) {
272 filename = resolvedPath;
275 // On linux, chrome is often checked out to /usr/local/google. Due to the
276 // "usr" rule in banned_directories_, all diagnostics would be suppressed
277 // in that case. As a workaround, strip that prefix.
278 filename = lstrip(filename, "/usr/local/google");
280 for (size_t i = 0; i < banned_directories_.size(); ++i) {
281 // If any of the banned directories occur as a component in filename,
282 // this file is rejected.
283 const std::string& banned_dir = banned_directories_[i];
284 assert(banned_dir.front() == '/' && "Banned dir must start with '/'");
285 assert(banned_dir.back() == '/' && "Banned dir must end with '/'");
287 if (filename.find(banned_dir) != std::string::npos)
294 bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
295 return ignored_record_names_.find(base_name) != ignored_record_names_.end();
298 bool ChromeClassTester::GetFilename(SourceLocation loc,
299 std::string* filename) {
300 const SourceManager& source_manager = instance_.getSourceManager();
301 SourceLocation spelling_location = source_manager.getSpellingLoc(loc);
302 PresumedLoc ploc = source_manager.getPresumedLoc(spelling_location);
303 if (ploc.isInvalid()) {
304 // If we're in an invalid location, we're looking at things that aren't
305 // actually stated in the source.
309 *filename = ploc.getFilename();