blob: 7d4d0c3204d3970fe33b520df063912ca7240971 [file] [log] [blame]
John Thompson4f8ba652013-03-12 02:07:30 +00001//===- tools/clang/Modularize.cpp - Check modularized headers -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a tool that checks whether a set of headers provides
11// the consistent definitions required to use modules. For example, it detects
12// whether the same entity (say, a NULL macro or size_t typedef) is defined in
13// multiple headers or whether a header produces different definitions under
14// different circumstances. These conditions cause modules built from the
15// headers to behave poorly, and should be fixed before introducing a module
16// map.
17//
18// Modularize takes as argument a file name for a file containing the
19// newline-separated list of headers to check with respect to each other.
20// Modularize also accepts regular front-end arguments.
21//
22// Usage: modularize (include-files_list) [(front-end-options) ...]
23//
24// Modularize will do normal parsing, reporting normal errors and warnings,
25// but will also report special error messages like the following:
26//
27// error: '(symbol)' defined at both (file):(row):(column) and
28// (file):(row):(column)
29//
30// error: header '(file)' has different contents dependening on how it was
31// included
32//
33// The latter might be followed by messages like the following:
34//
35// note: '(symbol)' in (file) at (row):(column) not always provided
36//
37//===----------------------------------------------------------------------===//
38
39#include "llvm/Config/config.h"
40#include "llvm/Support/FileSystem.h"
41#include "llvm/ADT/StringRef.h"
42#include "clang/Basic/SourceManager.h"
43#include "clang/Lex/Preprocessor.h"
44#include "clang/AST/ASTConsumer.h"
45#include "clang/AST/ASTContext.h"
46#include "clang/AST/RecursiveASTVisitor.h"
47#include "clang/Frontend/CompilerInstance.h"
48#include "clang/Frontend/FrontendActions.h"
49#include "clang/Tooling/CompilationDatabase.h"
50#include "clang/Tooling/Tooling.h"
51#include <vector>
52#include <string>
53#include <fstream>
54#include <algorithm>
55#include <iterator>
56
57using namespace clang::tooling;
58using namespace clang;
59using llvm::StringRef;
60
61struct Location {
62 const FileEntry *File;
63 unsigned Line, Column;
64
65 Location() : File(), Line(), Column() { }
66
67 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
68 Loc = SM.getExpansionLoc(Loc);
69 if (Loc.isInvalid())
70 return;
71
72 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
73 File = SM.getFileEntryForID(Decomposed.first);
74 if (!File)
75 return;
76
77 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
78 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
79 }
80
81 operator bool() const { return File != 0; }
82
83 friend bool operator==(const Location &X, const Location &Y) {
84 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
85 }
86
87 friend bool operator!=(const Location &X, const Location &Y) {
88 return !(X == Y);
89 }
90
91 friend bool operator<(const Location &X, const Location &Y) {
92 if (X.File != Y.File)
93 return X.File < Y.File;
94 if (X.Line != Y.Line)
95 return X.Line < Y.Line;
96 return X.Column < Y.Column;
97 }
98 friend bool operator>(const Location &X, const Location &Y) {
99 return Y < X;
100 }
101 friend bool operator<=(const Location &X, const Location &Y) {
102 return !(Y < X);
103 }
104 friend bool operator>=(const Location &X, const Location &Y) {
105 return !(X < Y);
106 }
107
108};
109
110
111struct Entry {
112 enum Kind {
113 Tag,
114 Value,
115 Macro
116 } Kind;
117
118 Location Loc;
119};
120
121struct HeaderEntry {
122 std::string Name;
123 Location Loc;
124
125 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
126 return X.Loc == Y.Loc && X.Name == Y.Name;
127 }
128 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
129 return !(X == Y);
130 }
131 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
132 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
133 }
134 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
135 return Y < X;
136 }
137 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) {
138 return !(Y < X);
139 }
140 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) {
141 return !(X < Y);
142 }
143};
144
145typedef std::vector<HeaderEntry> HeaderContents;
146
147class EntityMap : public llvm::StringMap<llvm::SmallVector<Entry, 2> > {
148 llvm::DenseMap<const FileEntry *, HeaderContents> CurHeaderContents;
149 llvm::DenseMap<const FileEntry *, HeaderContents> AllHeaderContents;
150
151public:
152 llvm::DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches;
153
154 void add(const std::string &Name, enum Entry::Kind Kind, Location Loc) {
155 // Record this entity in its header.
156 HeaderEntry HE = { Name, Loc };
157 CurHeaderContents[Loc.File].push_back(HE);
158
159 // Check whether we've seen this entry before.
160 llvm::SmallVector<Entry, 2> &Entries = (*this)[Name];
161 for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
162 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
163 return;
164 }
165
166 // We have not seen this entry before; record it.
167 Entry E = { Kind, Loc };
168 Entries.push_back(E);
169 }
170
171 void mergeCurHeaderContents() {
172 for (llvm::DenseMap<const FileEntry *, HeaderContents>::iterator
173 H = CurHeaderContents.begin(), HEnd = CurHeaderContents.end();
174 H != HEnd; ++H) {
175 // Sort contents.
176 std::sort(H->second.begin(), H->second.end());
177
178 // Check whether we've seen this header before.
179 llvm::DenseMap<const FileEntry *, HeaderContents>::iterator KnownH
180 = AllHeaderContents.find(H->first);
181 if (KnownH == AllHeaderContents.end()) {
182 // We haven't seen this header before; record its contents.
183 AllHeaderContents.insert(*H);
184 continue;
185 }
186
187 // If the header contents are the same, we're done.
188 if (H->second == KnownH->second)
189 continue;
190
191 // Determine what changed.
192 std::set_symmetric_difference(H->second.begin(), H->second.end(),
193 KnownH->second.begin(),
194 KnownH->second.end(),
195 std::back_inserter(HeaderContentMismatches[H->first]));
196 }
197
198 CurHeaderContents.clear();
199 }
200};
201
202class CollectEntitiesVisitor
203 : public RecursiveASTVisitor<CollectEntitiesVisitor>
204{
205 SourceManager &SM;
206 EntityMap &Entities;
207
208public:
209 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities)
210 : SM(SM), Entities(Entities) { }
211
212 bool TraverseStmt(Stmt *S) { return true; }
213 bool TraverseType(QualType T) { return true; }
214 bool TraverseTypeLoc(TypeLoc TL) { return true; }
215 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
216 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { return true; }
217 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) { return true; }
218 bool TraverseTemplateName(TemplateName Template) { return true; }
219 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
220 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) { return true; }
221 bool TraverseTemplateArguments(const TemplateArgument *Args,
222 unsigned NumArgs) { return true; }
223 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
224 bool TraverseLambdaCapture(LambdaExpr::Capture C) { return true; }
225
226 bool VisitNamedDecl(NamedDecl *ND) {
227 // We only care about file-context variables.
228 if (!ND->getDeclContext()->isFileContext())
229 return true;
230
231 // Skip declarations that tend to be properly multiply-declared.
232 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
233 isa<NamespaceAliasDecl>(ND) ||
234 isa<ClassTemplateSpecializationDecl>(ND) ||
235 isa<UsingDecl>(ND) || isa<UsingShadowDecl>(ND) ||
236 isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
237 (isa<TagDecl>(ND) &&
238 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
239 return true;
240
241 std::string Name = ND->getNameAsString();
242 if (Name.empty())
243 return true;
244
245 Location Loc(SM, ND->getLocation());
246 if (!Loc)
247 return true;
248
249 Entities.add(Name, isa<TagDecl>(ND)? Entry::Tag : Entry::Value, Loc);
250 return true;
251 }
252};
253
254class CollectEntitiesConsumer : public ASTConsumer {
255 EntityMap &Entities;
256 Preprocessor &PP;
257
258public:
259 CollectEntitiesConsumer(EntityMap &Entities, Preprocessor &PP)
260 : Entities(Entities), PP(PP) { }
261
262 virtual void HandleTranslationUnit(ASTContext &Ctx) {
263 SourceManager &SM = Ctx.getSourceManager();
264
265 // Collect declared entities.
266 CollectEntitiesVisitor(SM, Entities)
267 .TraverseDecl(Ctx.getTranslationUnitDecl());
268
269 // Collect macro definitions.
270 for (Preprocessor::macro_iterator M = PP.macro_begin(),
271 MEnd = PP.macro_end();
272 M != MEnd; ++M) {
273 Location Loc(SM, M->second->getLocation());
274 if (!Loc)
275 continue;
276
277 Entities.add(M->first->getName().str(), Entry::Macro, Loc);
278 }
279
280 // Merge header contents.
281 Entities.mergeCurHeaderContents();
282 }
283};
284
285class CollectEntitiesAction : public SyntaxOnlyAction {
286 EntityMap &Entities;
287
288protected:
289 virtual clang::ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
290 StringRef InFile) {
291 return new CollectEntitiesConsumer(Entities, CI.getPreprocessor());
292 }
293
294public:
295 CollectEntitiesAction(EntityMap &Entities) : Entities(Entities) { }
296};
297
298class ModularizeFrontendActionFactory : public FrontendActionFactory {
299 EntityMap &Entities;
300
301public:
302 ModularizeFrontendActionFactory(EntityMap &Entities) : Entities(Entities) { }
303
304 virtual CollectEntitiesAction *create() {
305 return new CollectEntitiesAction(Entities);
306 }
307};
308
309int main(int argc, const char **argv) {
310 // Figure out command-line arguments.
311 if (argc < 2) {
312 llvm::errs() << "Usage: modularize <file containing header names> <arguments>\n";
313 return 1;
314 }
315
316 // Load the list of headers.
317 std::string File = argv[1];
318 llvm::SmallVector<std::string, 8> Headers;
319 {
320 std::ifstream In(File.c_str());
321 if (!In) {
322 llvm::errs() << "Unable to open header list file \"" << File.c_str() << "\"\n";
323 return 2;
324 }
325
326 std::string Line;
327 while (std::getline(In, Line)) {
328 if (Line.empty() || Line[0] == '#')
329 continue;
330
331 Headers.push_back(Line);
332 }
333 }
334
335 // Create the compilation database.
336 llvm::OwningPtr<CompilationDatabase> Compilations;
337 {
338 std::vector<std::string> Arguments;
339 for (int I = 2; I < argc; ++I)
340 Arguments.push_back(argv[I]);
341 SmallString<256> PathBuf;
342 llvm::sys::fs::current_path(PathBuf);
343 Compilations.reset(new FixedCompilationDatabase(Twine(PathBuf), Arguments));
344 }
345
346 // Parse all of the headers, detecting duplicates.
347 EntityMap Entities;
348 ClangTool Tool(*Compilations, Headers);
349 int HadErrors = Tool.run(new ModularizeFrontendActionFactory(Entities));
350
351 // Check for the same entity being defined in multiple places.
352 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
353 E != EEnd; ++E) {
354 Location Tag, Value, Macro;
355 for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
356 Location *Which;
357 switch (E->second[I].Kind) {
358 case Entry::Tag: Which = &Tag; break;
359 case Entry::Value: Which = &Value; break;
360 case Entry::Macro: Which = &Macro; break;
361 }
362
363 if (!Which->File) {
364 *Which = E->second[I].Loc;
365 continue;
366 }
367
368 llvm::errs() << "error: '" << E->first().str().c_str()
369 << "' defined at both " << Which->File->getName()
370 << ":" << Which->Line << ":" << Which->Column
371 << " and " << E->second[I].Loc.File->getName() << ":"
372 << E->second[I].Loc.Line << ":" << E->second[I].Loc.Column << "\n";
373 HadErrors = 1;
374 }
375 }
376
377 // Complain about any headers that have contents that differ based on how
378 // they are included.
379 for (llvm::DenseMap<const FileEntry *, HeaderContents>::iterator
380 H = Entities.HeaderContentMismatches.begin(),
381 HEnd = Entities.HeaderContentMismatches.end();
382 H != HEnd; ++H) {
383 if (H->second.empty()) {
384 llvm::errs() << "internal error: phantom header content mismatch\n";
385 continue;
386 }
387
388 HadErrors = 1;
389 llvm::errs() << "error: header '" << H->first->getName()
390 << "' has different contents dependening on how it was included\n";
391 for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
392 llvm::errs() << "note: '" << H->second[I].Name.c_str()
393 << "' in " << H->second[I].Loc.File->getName() << " at "
394 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column
395 << " not always provided\n";
396 }
397 }
398
399 return HadErrors;
400}