[MD settings] moving attached() code
[chromium-blink-merge.git] / tools / clang / plugins / ChromeClassTester.cpp
blobaf5de10f745c02647d8828c841dcf57e4502a299
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++
6 // code.
8 #include "ChromeClassTester.h"
10 #include <algorithm>
12 #include "clang/AST/AST.h"
13 #include "clang/Basic/FileManager.h"
14 #include "clang/Basic/SourceManager.h"
16 #ifdef LLVM_ON_UNIX
17 #include <sys/param.h>
18 #endif
20 using namespace clang;
21 using chrome_checker::Options;
23 namespace {
25 bool ends_with(const std::string& one, const std::string& two) {
26 if (two.size() > one.size())
27 return false;
29 return one.compare(one.size() - two.size(), two.size(), two) == 0;
32 } // namespace
34 ChromeClassTester::ChromeClassTester(CompilerInstance& instance,
35 const Options& options)
36 : options_(options),
37 instance_(instance),
38 diagnostic_(instance.getDiagnostics()) {
39 BuildBannedLists();
42 ChromeClassTester::~ChromeClassTester() {}
44 void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
45 pending_class_decls_.push_back(tag);
48 bool ChromeClassTester::HandleTopLevelDecl(DeclGroupRef group_ref) {
49 for (size_t i = 0; i < pending_class_decls_.size(); ++i)
50 CheckTag(pending_class_decls_[i]);
51 pending_class_decls_.clear();
53 return true; // true means continue parsing.
56 void ChromeClassTester::CheckTag(TagDecl* tag) {
57 // We handle class types here where we have semantic information. We can only
58 // check structs/classes/enums here, but we get a bunch of nice semantic
59 // information instead of just parsing information.
61 if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) {
62 if (InBannedNamespace(record))
63 return;
65 SourceLocation record_location = record->getInnerLocStart();
66 if (InBannedDirectory(record_location))
67 return;
69 // We sadly need to maintain a blacklist of types that violate these
70 // rules, but do so for good reason or due to limitations of this
71 // checker (i.e., we don't handle extern templates very well).
72 std::string base_name = record->getNameAsString();
73 if (IsIgnoredType(base_name))
74 return;
76 // We ignore all classes that end with "Matcher" because they're probably
77 // GMock artifacts.
78 if (ends_with(base_name, "Matcher"))
79 return;
81 CheckChromeClass(record_location, record);
82 } else if (EnumDecl* enum_decl = dyn_cast<EnumDecl>(tag)) {
83 SourceLocation enum_location = enum_decl->getInnerLocStart();
84 if (InBannedDirectory(enum_location))
85 return;
87 std::string base_name = enum_decl->getNameAsString();
88 if (IsIgnoredType(base_name))
89 return;
91 CheckChromeEnum(enum_location, enum_decl);
95 void ChromeClassTester::emitWarning(SourceLocation loc,
96 const char* raw_error) {
97 FullSourceLoc full(loc, instance().getSourceManager());
98 std::string err;
99 err = "[chromium-style] ";
100 err += raw_error;
102 DiagnosticIDs::Level level = getErrorLevel() == DiagnosticsEngine::Error
103 ? DiagnosticIDs::Error : DiagnosticIDs::Warning;
105 unsigned id = diagnostic().getDiagnosticIDs()->getCustomDiagID(level, err);
106 DiagnosticBuilder builder = diagnostic().Report(full, id);
110 bool ChromeClassTester::InBannedDirectory(SourceLocation loc) {
111 if (instance().getSourceManager().isInSystemHeader(loc))
112 return true;
114 std::string filename;
115 if (!GetFilename(loc, &filename)) {
116 // If the filename cannot be determined, simply treat this as a banned
117 // location, instead of going through the full lookup process.
118 return true;
121 // We need to special case scratch space; which is where clang does its
122 // macro expansion. We explicitly want to allow people to do otherwise bad
123 // things through macros that were defined due to third party libraries.
124 if (filename == "<scratch space>")
125 return true;
127 // Don't complain about autogenerated protobuf files.
128 if (ends_with(filename, ".pb.h")) {
129 return true;
132 #if defined(LLVM_ON_UNIX)
133 // Resolve the symlinktastic relative path and make it absolute.
134 char resolvedPath[MAXPATHLEN];
135 if (realpath(filename.c_str(), resolvedPath)) {
136 filename = resolvedPath;
138 #endif
140 #if defined(LLVM_ON_WIN32)
141 std::replace(filename.begin(), filename.end(), '\\', '/');
143 // On Posix, realpath() has made the path absolute. On Windows, this isn't
144 // necessarily true, so prepend a '/' to the path to make sure the
145 // banned_directories_ loop below works correctly.
146 // This turns e.g. "gen/dir/file.cc" to "/gen/dir/file.cc" which lets the
147 // "/gen/" banned_dir work.
148 // This seems simpler than converting to utf16, calling GetFullPathNameW(),
149 // and converting back to utf8.
150 filename.insert(filename.begin(), '/');
151 #endif
153 for (const std::string& banned_dir : banned_directories_) {
154 // If any of the banned directories occur as a component in filename,
155 // this file is rejected.
156 assert(banned_dir.front() == '/' && "Banned dir must start with '/'");
157 assert(banned_dir.back() == '/' && "Banned dir must end with '/'");
159 if (filename.find(banned_dir) != std::string::npos)
160 return true;
163 return false;
166 bool ChromeClassTester::InBannedNamespace(const Decl* record) {
167 std::string n = GetNamespace(record);
168 if (!n.empty()) {
169 return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
170 != banned_namespaces_.end();
173 return false;
176 std::string ChromeClassTester::GetNamespace(const Decl* record) {
177 return GetNamespaceImpl(record->getDeclContext(), "");
180 bool ChromeClassTester::InImplementationFile(SourceLocation record_location) {
181 std::string filename;
182 if (!GetFilename(record_location, &filename))
183 return false;
185 if (ends_with(filename, ".cc") || ends_with(filename, ".cpp") ||
186 ends_with(filename, ".mm")) {
187 return true;
190 return false;
193 void ChromeClassTester::BuildBannedLists() {
194 banned_namespaces_.push_back("std");
195 banned_namespaces_.push_back("__gnu_cxx");
197 banned_namespaces_.push_back("blink");
198 banned_namespaces_.push_back("WTF");
200 banned_directories_.push_back("/third_party/");
201 banned_directories_.push_back("/native_client/");
202 banned_directories_.push_back("/breakpad/");
203 banned_directories_.push_back("/courgette/");
204 banned_directories_.push_back("/pdf/");
205 banned_directories_.push_back("/ppapi/");
206 banned_directories_.push_back("/usr/include/");
207 banned_directories_.push_back("/usr/lib/");
208 banned_directories_.push_back("/usr/local/include/");
209 banned_directories_.push_back("/usr/local/lib/");
210 banned_directories_.push_back("/testing/");
211 banned_directories_.push_back("/v8/");
212 banned_directories_.push_back("/dart/");
213 banned_directories_.push_back("/sdch/");
214 banned_directories_.push_back("/icu4c/");
215 banned_directories_.push_back("/frameworks/");
217 // Don't check autogenerated headers.
218 // Make puts them below $(builddir_name)/.../gen and geni.
219 // Ninja puts them below OUTPUT_DIR/.../gen
220 // Xcode has a fixed output directory for everything.
221 banned_directories_.push_back("/gen/");
222 banned_directories_.push_back("/geni/");
223 banned_directories_.push_back("/xcodebuild/");
225 // You are standing in a mazy of twisty dependencies, all resolved by
226 // putting everything in the header.
227 banned_directories_.push_back("/automation/");
229 // Used in really low level threading code that probably shouldn't be out of
230 // lined.
231 ignored_record_names_.insert("ThreadLocalBoolean");
233 // A complicated pickle derived struct that is all packed integers.
234 ignored_record_names_.insert("Header");
236 // Part of the GPU system that uses multiple included header
237 // weirdness. Never getting this right.
238 ignored_record_names_.insert("Validators");
240 // Has a UNIT_TEST only constructor. Isn't *terribly* complex...
241 ignored_record_names_.insert("AutocompleteController");
242 ignored_record_names_.insert("HistoryURLProvider");
244 // Because of chrome frame
245 ignored_record_names_.insert("ReliabilityTestSuite");
247 // Used over in the net unittests. A large enough bundle of integers with 1
248 // non-pod class member. Probably harmless.
249 ignored_record_names_.insert("MockTransaction");
251 // Enum type with _LAST members where _LAST doesn't mean last enum value.
252 ignored_record_names_.insert("ServerFieldType");
254 // Used heavily in ui_base_unittests and once in views_unittests. Fixing this
255 // isn't worth the overhead of an additional library.
256 ignored_record_names_.insert("TestAnimationDelegate");
258 // Part of our public interface that nacl and friends use. (Arguably, this
259 // should mean that this is a higher priority but fixing this looks hard.)
260 ignored_record_names_.insert("PluginVersionInfo");
262 // Measured performance improvement on cc_perftests. See
263 // https://codereview.chromium.org/11299290/
264 ignored_record_names_.insert("QuadF");
266 // Enum type with _LAST members where _LAST doesn't mean last enum value.
267 ignored_record_names_.insert("ViewID");
270 std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
271 const std::string& candidate) {
272 switch (context->getDeclKind()) {
273 case Decl::TranslationUnit: {
274 return candidate;
276 case Decl::Namespace: {
277 const NamespaceDecl* decl = dyn_cast<NamespaceDecl>(context);
278 std::string name_str;
279 llvm::raw_string_ostream OS(name_str);
280 if (decl->isAnonymousNamespace())
281 OS << "<anonymous namespace>";
282 else
283 OS << *decl;
284 return GetNamespaceImpl(context->getParent(),
285 OS.str());
287 default: {
288 return GetNamespaceImpl(context->getParent(), candidate);
293 bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
294 return ignored_record_names_.find(base_name) != ignored_record_names_.end();
297 bool ChromeClassTester::GetFilename(SourceLocation loc,
298 std::string* filename) {
299 const SourceManager& source_manager = instance_.getSourceManager();
300 SourceLocation spelling_location = source_manager.getSpellingLoc(loc);
301 PresumedLoc ploc = source_manager.getPresumedLoc(spelling_location);
302 if (ploc.isInvalid()) {
303 // If we're in an invalid location, we're looking at things that aren't
304 // actually stated in the source.
305 return false;
308 *filename = ploc.getFilename();
309 return true;
312 DiagnosticsEngine::Level ChromeClassTester::getErrorLevel() {
313 if (options_.warn_only)
314 return DiagnosticsEngine::Warning;
316 return diagnostic().getWarningsAsErrors() ? DiagnosticsEngine::Error
317 : DiagnosticsEngine::Warning;