Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / tools / clang / plugins / ChromeClassTester.cpp
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.
4
5 // A general interface for filtering and only acting on classes in Chromium C++
6 // code.
7
8 #include "ChromeClassTester.h"
9
10 #include <sys/param.h>
11
12 #include "clang/AST/AST.h"
13 #include "clang/Basic/FileManager.h"
14 #include "clang/Basic/SourceManager.h"
15
16 using namespace clang;
17
18 namespace {
19
20 bool starts_with(const std::string& one, const std::string& two) {
21   return one.compare(0, two.size(), two) == 0;
22 }
23
24 std::string lstrip(const std::string& one, const std::string& two) {
25   if (starts_with(one, two))
26     return one.substr(two.size());
27   return one;
28 }
29
30 bool ends_with(const std::string& one, const std::string& two) {
31   if (two.size() > one.size())
32     return false;
33
34   return one.compare(one.size() - two.size(), two.size(), two) == 0;
35 }
36
37 }  // namespace
38
39 ChromeClassTester::ChromeClassTester(CompilerInstance& instance,
40                                      bool check_url_directory)
41     : instance_(instance),
42       diagnostic_(instance.getDiagnostics()),
43       check_url_directory_(check_url_directory) {
44   BuildBannedLists();
45 }
46
47 ChromeClassTester::~ChromeClassTester() {}
48
49 void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
50   pending_class_decls_.push_back(tag);
51 }
52
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();
57
58   return true;  // true means continue parsing.
59 }
60
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.
65
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())
74       return;
75
76     if (InBannedNamespace(record))
77       return;
78
79     SourceLocation record_location = record->getInnerLocStart();
80     if (InBannedDirectory(record_location))
81       return;
82
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))
88       return;
89
90     // We ignore all classes that end with "Matcher" because they're probably
91     // GMock artifacts.
92     if (ends_with(base_name, "Matcher"))
93         return;
94
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))
99       return;
100
101     std::string base_name = enum_decl->getNameAsString();
102     if (IsIgnoredType(base_name))
103       return;
104
105     CheckChromeEnum(enum_location, enum_decl);
106   }
107 }
108
109 void ChromeClassTester::emitWarning(SourceLocation loc,
110                                     const char* raw_error) {
111   FullSourceLoc full(loc, instance().getSourceManager());
112   std::string err;
113   err = "[chromium-style] ";
114   err += raw_error;
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);
121 }
122
123 bool ChromeClassTester::InBannedNamespace(const Decl* record) {
124   std::string n = GetNamespace(record);
125   if (!n.empty()) {
126     return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
127         != banned_namespaces_.end();
128   }
129
130   return false;
131 }
132
133 std::string ChromeClassTester::GetNamespace(const Decl* record) {
134   return GetNamespaceImpl(record->getDeclContext(), "");
135 }
136
137 bool ChromeClassTester::InImplementationFile(SourceLocation record_location) {
138   std::string filename;
139   if (!GetFilename(record_location, &filename))
140     return false;
141
142   if (ends_with(filename, ".cc") || ends_with(filename, ".cpp") ||
143       ends_with(filename, ".mm")) {
144     return true;
145   }
146
147   return false;
148 }
149
150 void ChromeClassTester::BuildBannedLists() {
151   banned_namespaces_.push_back("std");
152   banned_namespaces_.push_back("__gnu_cxx");
153
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");
158
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/");
172
173   if (!check_url_directory_)
174     banned_directories_.push_back("url/");
175
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/");
183
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/");
187
188   // Don't check system headers.
189   banned_directories_.push_back("/Developer/");
190
191   // Used in really low level threading code that probably shouldn't be out of
192   // lined.
193   ignored_record_names_.insert("ThreadLocalBoolean");
194
195   // A complicated pickle derived struct that is all packed integers.
196   ignored_record_names_.insert("Header");
197
198   // Part of the GPU system that uses multiple included header
199   // weirdness. Never getting this right.
200   ignored_record_names_.insert("Validators");
201
202   // Has a UNIT_TEST only constructor. Isn't *terribly* complex...
203   ignored_record_names_.insert("AutocompleteController");
204   ignored_record_names_.insert("HistoryURLProvider");
205
206   // Because of chrome frame
207   ignored_record_names_.insert("ReliabilityTestSuite");
208
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");
212
213   // Enum type with _LAST members where _LAST doesn't mean last enum value.
214   ignored_record_names_.insert("ServerFieldType");
215
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");
219
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");
223
224   // Measured performance improvement on cc_perftests. See
225   // https://codereview.chromium.org/11299290/
226   ignored_record_names_.insert("QuadF");
227
228   // Enum type with _LAST members where _LAST doesn't mean last enum value.
229   ignored_record_names_.insert("ViewID");
230 }
231
232 std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
233                                                 const std::string& candidate) {
234   switch (context->getDeclKind()) {
235     case Decl::TranslationUnit: {
236       return candidate;
237     }
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>";
244       else
245         OS << *decl;
246       return GetNamespaceImpl(context->getParent(),
247                               OS.str());
248     }
249     default: {
250       return GetNamespaceImpl(context->getParent(), candidate);
251     }
252   }
253 }
254
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.
260     return true;
261   }
262
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>")
267     return true;
268
269   // Don't complain about autogenerated protobuf files.
270   if (ends_with(filename, ".pb.h")) {
271     return true;
272   }
273
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;
280   }
281
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");
286
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] == '/';
295       if ((*it)[0] == '/')
296         matches_full_dir_name = true;
297       if (matches_full_dir_name)
298         return true;
299     }
300   }
301
302   return false;
303 }
304
305 bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
306   return ignored_record_names_.find(base_name) != ignored_record_names_.end();
307 }
308
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.
317     return false;
318   }
319
320   *filename = ploc.getFilename();
321   return true;
322 }