blob: 45d825d44142478a5c56d126be16f3a4851c19cc [file] [log] [blame]
John Thompsond977c1e2013-03-27 18:34:38 +00001//===- extra/modularize/Modularize.cpp - Check modularized headers --------===//
John Thompson4f8ba652013-03-12 02:07:30 +00002//
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
John Thompsonf5db45b2013-03-27 01:02:46 +000015// headers to behave poorly, and should be fixed before introducing a module
John Thompson4f8ba652013-03-12 02:07:30 +000016// 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.
John Thompsonf5db45b2013-03-27 01:02:46 +000020// Lines beginning with '#' and empty lines are ignored.
John Thompson4f8ba652013-03-12 02:07:30 +000021// Modularize also accepts regular front-end arguments.
22//
John Thompsonf5db45b2013-03-27 01:02:46 +000023// Usage: modularize [-prefix (optional header path prefix)]
John Thompsona2de1082013-03-26 01:17:48 +000024// (include-files_list) [(front-end-options) ...]
25//
John Thompsona44f85a2013-04-15 22:32:28 +000026// Note that unless a "-prefix (header path)" option is specified,
John Thompsona2de1082013-03-26 01:17:48 +000027// non-absolute file paths in the header list file will be relative
28// to the header list file directory. Use -prefix to specify a different
29// directory.
John Thompson4f8ba652013-03-12 02:07:30 +000030//
John Thompsonfd8ca382013-03-27 19:31:22 +000031// Note that by default, the underlying Clang front end assumes .h files
32// contain C source. If your .h files in the file list contain C++ source,
John Thompsonea6c8db2013-03-27 21:23:21 +000033// you should append the following to your command lines: -x c++
John Thompsonfd8ca382013-03-27 19:31:22 +000034//
John Thompson4f8ba652013-03-12 02:07:30 +000035// Modularize will do normal parsing, reporting normal errors and warnings,
36// but will also report special error messages like the following:
37//
John Thompsona44f85a2013-04-15 22:32:28 +000038// error: '(symbol)' defined at multiple locations:
39// (file):(row):(column)
40// (file):(row):(column)
John Thompson4f8ba652013-03-12 02:07:30 +000041//
42// error: header '(file)' has different contents dependening on how it was
43// included
44//
45// The latter might be followed by messages like the following:
46//
47// note: '(symbol)' in (file) at (row):(column) not always provided
48//
John Thompsonce601e22013-03-14 01:41:29 +000049// Future directions:
50//
51// Basically, we want to add new checks for whatever we can check with respect
52// to checking headers for module'ability.
53//
54// Some ideas:
55//
John Thompson3b1ee2b2013-03-28 02:46:25 +000056// 1. Try to figure out the preprocessor conditional directives that
John Thompsonce601e22013-03-14 01:41:29 +000057// contribute to problems.
58//
John Thompson3b1ee2b2013-03-28 02:46:25 +000059// 2. Check for correct and consistent usage of extern "C" {} and other
John Thompsonce601e22013-03-14 01:41:29 +000060// directives. Warn about #include inside extern "C" {}.
61//
John Thompson3b1ee2b2013-03-28 02:46:25 +000062// 3. What else?
John Thompsonce601e22013-03-14 01:41:29 +000063//
64// General clean-up and refactoring:
65//
66// 1. The Location class seems to be something that we might
67// want to design to be applicable to a wider range of tools, and stick it
68// somewhere into Tooling/ in mainline
69//
John Thompson4f8ba652013-03-12 02:07:30 +000070//===----------------------------------------------------------------------===//
John Thompsonf5db45b2013-03-27 01:02:46 +000071
John Thompsond977c1e2013-03-27 18:34:38 +000072#include "clang/AST/ASTConsumer.h"
73#include "clang/AST/ASTContext.h"
74#include "clang/AST/RecursiveASTVisitor.h"
75#include "clang/Basic/SourceManager.h"
76#include "clang/Frontend/CompilerInstance.h"
77#include "clang/Frontend/FrontendActions.h"
78#include "clang/Lex/Preprocessor.h"
79#include "clang/Tooling/CompilationDatabase.h"
80#include "clang/Tooling/Tooling.h"
81#include "llvm/ADT/OwningPtr.h"
82#include "llvm/ADT/StringRef.h"
John Thompson4f8ba652013-03-12 02:07:30 +000083#include "llvm/Config/config.h"
John Thompsona2de1082013-03-26 01:17:48 +000084#include "llvm/Support/CommandLine.h"
John Thompson4f8ba652013-03-12 02:07:30 +000085#include "llvm/Support/FileSystem.h"
John Thompsonf5db45b2013-03-27 01:02:46 +000086#include "llvm/Support/MemoryBuffer.h"
John Thompsona2de1082013-03-26 01:17:48 +000087#include "llvm/Support/Path.h"
John Thompson4f8ba652013-03-12 02:07:30 +000088#include <algorithm>
John Thompsond977c1e2013-03-27 18:34:38 +000089#include <fstream>
John Thompson4f8ba652013-03-12 02:07:30 +000090#include <iterator>
John Thompsond977c1e2013-03-27 18:34:38 +000091#include <string>
92#include <vector>
John Thompson1e010142013-07-26 18:16:22 +000093#include "PreprocessorTracker.h"
John Thompson4f8ba652013-03-12 02:07:30 +000094
95using namespace clang::tooling;
96using namespace clang;
John Thompsona2de1082013-03-26 01:17:48 +000097using namespace llvm;
John Thompson1e010142013-07-26 18:16:22 +000098using namespace Modularize;
John Thompson4f8ba652013-03-12 02:07:30 +000099
John Thompsonea6c8db2013-03-27 21:23:21 +0000100// Option to specify a file name for a list of header files to check.
John Thompsonb809dfc2013-07-19 14:19:31 +0000101cl::opt<std::string>
102ListFileName(cl::Positional,
103 cl::desc("<name of file containing list of headers to check>"));
John Thompsonea6c8db2013-03-27 21:23:21 +0000104
105// Collect all other arguments, which will be passed to the front end.
John Thompson161381e2013-06-27 18:52:23 +0000106cl::list<std::string>
John Thompsonb809dfc2013-07-19 14:19:31 +0000107CC1Arguments(cl::ConsumeAfter,
108 cl::desc("<arguments to be passed to front end>..."));
John Thompsonea6c8db2013-03-27 21:23:21 +0000109
110// Option to specify a prefix to be prepended to the header names.
111cl::opt<std::string> HeaderPrefix(
112 "prefix", cl::init(""),
113 cl::desc(
114 "Prepend header file paths with this prefix."
115 " If not specified,"
116 " the files are considered to be relative to the header list file."));
117
118// Read the header list file and collect the header file names.
John Thompson54c83692013-06-18 19:56:05 +0000119error_code getHeaderFileNames(SmallVectorImpl<std::string> &headerFileNames,
John Thompsonea6c8db2013-03-27 21:23:21 +0000120 StringRef listFileName, StringRef headerPrefix) {
121
122 // By default, use the path component of the list file name.
123 SmallString<256> headerDirectory(listFileName);
124 sys::path::remove_filename(headerDirectory);
125
126 // Get the prefix if we have one.
127 if (headerPrefix.size() != 0)
128 headerDirectory = headerPrefix;
129
130 // Read the header list file into a buffer.
131 OwningPtr<MemoryBuffer> listBuffer;
John Thompson26b567a2013-06-19 20:35:50 +0000132 if (error_code ec = MemoryBuffer::getFile(listFileName, listBuffer)) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000133 return ec;
134 }
135
136 // Parse the header list into strings.
137 SmallVector<StringRef, 32> strings;
138 listBuffer->getBuffer().split(strings, "\n", -1, false);
139
140 // Collect the header file names from the string list.
141 for (SmallVectorImpl<StringRef>::iterator I = strings.begin(),
142 E = strings.end();
143 I != E; ++I) {
144 StringRef line = (*I).trim();
145 // Ignore comments and empty lines.
146 if (line.empty() || (line[0] == '#'))
147 continue;
148 SmallString<256> headerFileName;
149 // Prepend header file name prefix if it's not absolute.
150 if (sys::path::is_absolute(line))
151 headerFileName = line;
152 else {
153 headerFileName = headerDirectory;
154 sys::path::append(headerFileName, line);
155 }
156 // Save the resulting header file path.
157 headerFileNames.push_back(headerFileName.str());
158 }
159
160 return error_code::success();
161}
162
John Thompsonce601e22013-03-14 01:41:29 +0000163// FIXME: The Location class seems to be something that we might
164// want to design to be applicable to a wider range of tools, and stick it
165// somewhere into Tooling/ in mainline
John Thompson4f8ba652013-03-12 02:07:30 +0000166struct Location {
167 const FileEntry *File;
168 unsigned Line, Column;
John Thompsonf5db45b2013-03-27 01:02:46 +0000169
170 Location() : File(), Line(), Column() {}
171
John Thompson4f8ba652013-03-12 02:07:30 +0000172 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
173 Loc = SM.getExpansionLoc(Loc);
174 if (Loc.isInvalid())
175 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000176
John Thompson4f8ba652013-03-12 02:07:30 +0000177 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
178 File = SM.getFileEntryForID(Decomposed.first);
179 if (!File)
180 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000181
John Thompson4f8ba652013-03-12 02:07:30 +0000182 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
183 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
184 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000185
John Thompson4f8ba652013-03-12 02:07:30 +0000186 operator bool() const { return File != 0; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000187
John Thompson4f8ba652013-03-12 02:07:30 +0000188 friend bool operator==(const Location &X, const Location &Y) {
189 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
190 }
191
192 friend bool operator!=(const Location &X, const Location &Y) {
193 return !(X == Y);
194 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000195
John Thompson4f8ba652013-03-12 02:07:30 +0000196 friend bool operator<(const Location &X, const Location &Y) {
197 if (X.File != Y.File)
198 return X.File < Y.File;
199 if (X.Line != Y.Line)
200 return X.Line < Y.Line;
201 return X.Column < Y.Column;
202 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000203 friend bool operator>(const Location &X, const Location &Y) { return Y < X; }
John Thompson4f8ba652013-03-12 02:07:30 +0000204 friend bool operator<=(const Location &X, const Location &Y) {
205 return !(Y < X);
206 }
207 friend bool operator>=(const Location &X, const Location &Y) {
208 return !(X < Y);
209 }
John Thompson4f8ba652013-03-12 02:07:30 +0000210};
211
John Thompson4f8ba652013-03-12 02:07:30 +0000212struct Entry {
John Thompson52d98862013-03-28 18:38:43 +0000213 enum EntryKind {
214 EK_Tag,
215 EK_Value,
216 EK_Macro,
217
218 EK_NumberOfKinds
John Thompson4f8ba652013-03-12 02:07:30 +0000219 } Kind;
John Thompsonf5db45b2013-03-27 01:02:46 +0000220
John Thompson4f8ba652013-03-12 02:07:30 +0000221 Location Loc;
John Thompson4e4d9b32013-03-28 01:20:19 +0000222
223 StringRef getKindName() { return getKindName(Kind); }
John Thompson52d98862013-03-28 18:38:43 +0000224 static StringRef getKindName(EntryKind kind);
John Thompson4f8ba652013-03-12 02:07:30 +0000225};
226
John Thompson4e4d9b32013-03-28 01:20:19 +0000227// Return a string representing the given kind.
John Thompson52d98862013-03-28 18:38:43 +0000228StringRef Entry::getKindName(Entry::EntryKind kind) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000229 switch (kind) {
John Thompson52d98862013-03-28 18:38:43 +0000230 case EK_Tag:
John Thompson4e4d9b32013-03-28 01:20:19 +0000231 return "tag";
John Thompson52d98862013-03-28 18:38:43 +0000232 case EK_Value:
John Thompson4e4d9b32013-03-28 01:20:19 +0000233 return "value";
John Thompson52d98862013-03-28 18:38:43 +0000234 case EK_Macro:
John Thompson4e4d9b32013-03-28 01:20:19 +0000235 return "macro";
John Thompson52d98862013-03-28 18:38:43 +0000236 case EK_NumberOfKinds:
John Thompson4e4d9b32013-03-28 01:20:19 +0000237 break;
John Thompson4e4d9b32013-03-28 01:20:19 +0000238 }
David Blaikiec66c07d2013-03-28 02:30:37 +0000239 llvm_unreachable("invalid Entry kind");
John Thompson4e4d9b32013-03-28 01:20:19 +0000240}
241
John Thompson4f8ba652013-03-12 02:07:30 +0000242struct HeaderEntry {
243 std::string Name;
244 Location Loc;
John Thompsonf5db45b2013-03-27 01:02:46 +0000245
John Thompson4f8ba652013-03-12 02:07:30 +0000246 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
247 return X.Loc == Y.Loc && X.Name == Y.Name;
248 }
249 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
250 return !(X == Y);
251 }
252 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
253 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
254 }
255 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
256 return Y < X;
257 }
258 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) {
259 return !(Y < X);
260 }
261 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) {
262 return !(X < Y);
263 }
264};
265
266typedef std::vector<HeaderEntry> HeaderContents;
267
John Thompsonf5db45b2013-03-27 01:02:46 +0000268class EntityMap : public StringMap<SmallVector<Entry, 2> > {
John Thompson4f8ba652013-03-12 02:07:30 +0000269public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000270 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches;
271
John Thompson52d98862013-03-28 18:38:43 +0000272 void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) {
John Thompson4f8ba652013-03-12 02:07:30 +0000273 // Record this entity in its header.
274 HeaderEntry HE = { Name, Loc };
275 CurHeaderContents[Loc.File].push_back(HE);
John Thompsonf5db45b2013-03-27 01:02:46 +0000276
John Thompson4f8ba652013-03-12 02:07:30 +0000277 // Check whether we've seen this entry before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000278 SmallVector<Entry, 2> &Entries = (*this)[Name];
John Thompson4f8ba652013-03-12 02:07:30 +0000279 for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
280 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
281 return;
282 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000283
John Thompson4f8ba652013-03-12 02:07:30 +0000284 // We have not seen this entry before; record it.
285 Entry E = { Kind, Loc };
286 Entries.push_back(E);
287 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000288
John Thompson4f8ba652013-03-12 02:07:30 +0000289 void mergeCurHeaderContents() {
John Thompsonf5db45b2013-03-27 01:02:46 +0000290 for (DenseMap<const FileEntry *, HeaderContents>::iterator
291 H = CurHeaderContents.begin(),
292 HEnd = CurHeaderContents.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000293 H != HEnd; ++H) {
294 // Sort contents.
295 std::sort(H->second.begin(), H->second.end());
296
297 // Check whether we've seen this header before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000298 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH =
299 AllHeaderContents.find(H->first);
John Thompson4f8ba652013-03-12 02:07:30 +0000300 if (KnownH == AllHeaderContents.end()) {
301 // We haven't seen this header before; record its contents.
302 AllHeaderContents.insert(*H);
303 continue;
304 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000305
John Thompson4f8ba652013-03-12 02:07:30 +0000306 // If the header contents are the same, we're done.
307 if (H->second == KnownH->second)
308 continue;
John Thompsonf5db45b2013-03-27 01:02:46 +0000309
John Thompson4f8ba652013-03-12 02:07:30 +0000310 // Determine what changed.
John Thompsonf5db45b2013-03-27 01:02:46 +0000311 std::set_symmetric_difference(
312 H->second.begin(), H->second.end(), KnownH->second.begin(),
313 KnownH->second.end(),
314 std::back_inserter(HeaderContentMismatches[H->first]));
John Thompson4f8ba652013-03-12 02:07:30 +0000315 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000316
John Thompson4f8ba652013-03-12 02:07:30 +0000317 CurHeaderContents.clear();
318 }
John Thompson161381e2013-06-27 18:52:23 +0000319
John Thompson1f67ccb2013-03-12 18:51:47 +0000320private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000321 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents;
322 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents;
John Thompson4f8ba652013-03-12 02:07:30 +0000323};
324
John Thompson161381e2013-06-27 18:52:23 +0000325class CollectEntitiesVisitor
326 : public RecursiveASTVisitor<CollectEntitiesVisitor> {
John Thompson4f8ba652013-03-12 02:07:30 +0000327public:
328 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000329 : SM(SM), Entities(Entities) {}
330
John Thompson4f8ba652013-03-12 02:07:30 +0000331 bool TraverseStmt(Stmt *S) { return true; }
332 bool TraverseType(QualType T) { return true; }
333 bool TraverseTypeLoc(TypeLoc TL) { return true; }
334 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000335 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
336 return true;
337 }
338 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
339 return true;
340 }
John Thompson4f8ba652013-03-12 02:07:30 +0000341 bool TraverseTemplateName(TemplateName Template) { return true; }
342 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000343 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
344 return true;
345 }
John Thompson4f8ba652013-03-12 02:07:30 +0000346 bool TraverseTemplateArguments(const TemplateArgument *Args,
John Thompsonf5db45b2013-03-27 01:02:46 +0000347 unsigned NumArgs) {
348 return true;
349 }
John Thompson4f8ba652013-03-12 02:07:30 +0000350 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
351 bool TraverseLambdaCapture(LambdaExpr::Capture C) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000352
John Thompson4f8ba652013-03-12 02:07:30 +0000353 bool VisitNamedDecl(NamedDecl *ND) {
354 // We only care about file-context variables.
355 if (!ND->getDeclContext()->isFileContext())
356 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000357
John Thompson4f8ba652013-03-12 02:07:30 +0000358 // Skip declarations that tend to be properly multiply-declared.
359 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
John Thompsonf5db45b2013-03-27 01:02:46 +0000360 isa<NamespaceAliasDecl>(ND) ||
361 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
362 isa<UsingShadowDecl>(ND) || isa<FunctionDecl>(ND) ||
363 isa<FunctionTemplateDecl>(ND) ||
John Thompson4f8ba652013-03-12 02:07:30 +0000364 (isa<TagDecl>(ND) &&
365 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
366 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000367
John Thompson4f8ba652013-03-12 02:07:30 +0000368 std::string Name = ND->getNameAsString();
369 if (Name.empty())
370 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000371
John Thompson4f8ba652013-03-12 02:07:30 +0000372 Location Loc(SM, ND->getLocation());
373 if (!Loc)
374 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000375
John Thompson52d98862013-03-28 18:38:43 +0000376 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000377 return true;
378 }
John Thompson161381e2013-06-27 18:52:23 +0000379
John Thompson1f67ccb2013-03-12 18:51:47 +0000380private:
381 SourceManager &SM;
382 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000383};
384
385class CollectEntitiesConsumer : public ASTConsumer {
John Thompson4f8ba652013-03-12 02:07:30 +0000386public:
John Thompson1e010142013-07-26 18:16:22 +0000387 CollectEntitiesConsumer(EntityMap &Entities,
388 PreprocessorTracker &preprocessorTracker,
389 Preprocessor &PP, StringRef InFile)
390 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP) {
391 PPTracker.handlePreprocessorEntry(PP, InFile);
392 }
393
394 ~CollectEntitiesConsumer() { PPTracker.handlePreprocessorExit(); }
John Thompsonf5db45b2013-03-27 01:02:46 +0000395
John Thompson4f8ba652013-03-12 02:07:30 +0000396 virtual void HandleTranslationUnit(ASTContext &Ctx) {
397 SourceManager &SM = Ctx.getSourceManager();
John Thompsonf5db45b2013-03-27 01:02:46 +0000398
John Thompson4f8ba652013-03-12 02:07:30 +0000399 // Collect declared entities.
400 CollectEntitiesVisitor(SM, Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000401 .TraverseDecl(Ctx.getTranslationUnitDecl());
402
John Thompson4f8ba652013-03-12 02:07:30 +0000403 // Collect macro definitions.
404 for (Preprocessor::macro_iterator M = PP.macro_begin(),
John Thompsonf5db45b2013-03-27 01:02:46 +0000405 MEnd = PP.macro_end();
John Thompson4f8ba652013-03-12 02:07:30 +0000406 M != MEnd; ++M) {
407 Location Loc(SM, M->second->getLocation());
408 if (!Loc)
409 continue;
410
John Thompson52d98862013-03-28 18:38:43 +0000411 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000412 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000413
John Thompson4f8ba652013-03-12 02:07:30 +0000414 // Merge header contents.
415 Entities.mergeCurHeaderContents();
416 }
John Thompson161381e2013-06-27 18:52:23 +0000417
John Thompson1f67ccb2013-03-12 18:51:47 +0000418private:
419 EntityMap &Entities;
John Thompson1e010142013-07-26 18:16:22 +0000420 PreprocessorTracker &PPTracker;
John Thompson1f67ccb2013-03-12 18:51:47 +0000421 Preprocessor &PP;
John Thompson4f8ba652013-03-12 02:07:30 +0000422};
423
424class CollectEntitiesAction : public SyntaxOnlyAction {
John Thompson1f67ccb2013-03-12 18:51:47 +0000425public:
John Thompson1e010142013-07-26 18:16:22 +0000426 CollectEntitiesAction(EntityMap &Entities,
427 PreprocessorTracker &preprocessorTracker)
428 : Entities(Entities), PPTracker(preprocessorTracker) {}
John Thompson161381e2013-06-27 18:52:23 +0000429
John Thompson4f8ba652013-03-12 02:07:30 +0000430protected:
John Thompson161381e2013-06-27 18:52:23 +0000431 virtual clang::ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
432 StringRef InFile) {
John Thompson1e010142013-07-26 18:16:22 +0000433 return new CollectEntitiesConsumer(Entities, PPTracker,
434 CI.getPreprocessor(), InFile);
John Thompson4f8ba652013-03-12 02:07:30 +0000435 }
John Thompson161381e2013-06-27 18:52:23 +0000436
John Thompson1f67ccb2013-03-12 18:51:47 +0000437private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000438 EntityMap &Entities;
John Thompson1e010142013-07-26 18:16:22 +0000439 PreprocessorTracker &PPTracker;
John Thompson4f8ba652013-03-12 02:07:30 +0000440};
441
442class ModularizeFrontendActionFactory : public FrontendActionFactory {
John Thompson4f8ba652013-03-12 02:07:30 +0000443public:
John Thompson1e010142013-07-26 18:16:22 +0000444 ModularizeFrontendActionFactory(EntityMap &Entities,
445 PreprocessorTracker &preprocessorTracker)
446 : Entities(Entities), PPTracker(preprocessorTracker) {}
John Thompson4f8ba652013-03-12 02:07:30 +0000447
448 virtual CollectEntitiesAction *create() {
John Thompson1e010142013-07-26 18:16:22 +0000449 return new CollectEntitiesAction(Entities, PPTracker);
John Thompson4f8ba652013-03-12 02:07:30 +0000450 }
John Thompson161381e2013-06-27 18:52:23 +0000451
John Thompson1f67ccb2013-03-12 18:51:47 +0000452private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000453 EntityMap &Entities;
John Thompson1e010142013-07-26 18:16:22 +0000454 PreprocessorTracker &PPTracker;
John Thompson4f8ba652013-03-12 02:07:30 +0000455};
456
457int main(int argc, const char **argv) {
John Thompsona2de1082013-03-26 01:17:48 +0000458
459 // This causes options to be parsed.
460 cl::ParseCommandLineOptions(argc, argv, "modularize.\n");
461
462 // No go if we have no header list file.
463 if (ListFileName.size() == 0) {
464 cl::PrintHelpMessage();
John Thompsonea6c8db2013-03-27 21:23:21 +0000465 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000466 }
John Thompsona2de1082013-03-26 01:17:48 +0000467
John Thompsonea6c8db2013-03-27 21:23:21 +0000468 // Get header file names.
John Thompsonf5db45b2013-03-27 01:02:46 +0000469 SmallVector<std::string, 32> Headers;
John Thompson54c83692013-06-18 19:56:05 +0000470 if (error_code ec = getHeaderFileNames(Headers, ListFileName, HeaderPrefix)) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000471 errs() << argv[0] << ": error: Unable to get header list '" << ListFileName
472 << "': " << ec.message() << '\n';
473 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000474 }
John Thompsona2de1082013-03-26 01:17:48 +0000475
John Thompson4f8ba652013-03-12 02:07:30 +0000476 // Create the compilation database.
John Thompsona2de1082013-03-26 01:17:48 +0000477 SmallString<256> PathBuf;
John Thompsonf5db45b2013-03-27 01:02:46 +0000478 sys::fs::current_path(PathBuf);
479 OwningPtr<CompilationDatabase> Compilations;
480 Compilations.reset(
481 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments));
John Thompsona2de1082013-03-26 01:17:48 +0000482
John Thompson1e010142013-07-26 18:16:22 +0000483 // Create preprocessor tracker, to watch for macro and conditional problems.
484 OwningPtr<PreprocessorTracker> PPTracker(PreprocessorTracker::create());
485
John Thompson4f8ba652013-03-12 02:07:30 +0000486 // Parse all of the headers, detecting duplicates.
487 EntityMap Entities;
488 ClangTool Tool(*Compilations, Headers);
John Thompson1e010142013-07-26 18:16:22 +0000489 int HadErrors =
490 Tool.run(new ModularizeFrontendActionFactory(Entities, *PPTracker));
John Thompsonce601e22013-03-14 01:41:29 +0000491
John Thompson4e4d9b32013-03-28 01:20:19 +0000492 // Create a place to save duplicate entity locations, separate bins per kind.
493 typedef SmallVector<Location, 8> LocationArray;
John Thompson52d98862013-03-28 18:38:43 +0000494 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
John Thompson4e4d9b32013-03-28 01:20:19 +0000495 EntryBinArray EntryBins;
Michael Gottesman4b249212013-03-28 06:07:15 +0000496 int kindIndex;
John Thompson52d98862013-03-28 18:38:43 +0000497 for (kindIndex = 0; kindIndex < Entry::EK_NumberOfKinds; ++kindIndex) {
498 LocationArray array;
499 EntryBins.push_back(array);
Michael Gottesman4b249212013-03-28 06:07:15 +0000500 }
John Thompson4e4d9b32013-03-28 01:20:19 +0000501
John Thompson4f8ba652013-03-12 02:07:30 +0000502 // Check for the same entity being defined in multiple places.
503 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
504 E != EEnd; ++E) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000505 // If only one occurance, exit early.
506 if (E->second.size() == 1)
507 continue;
508 // Clear entity locations.
509 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
510 CI != CE; ++CI) {
John Thompson52d98862013-03-28 18:38:43 +0000511 CI->clear();
John Thompson4e4d9b32013-03-28 01:20:19 +0000512 }
513 // Walk the entities of a single name, collecting the locations,
514 // separated into separate bins.
John Thompson4f8ba652013-03-12 02:07:30 +0000515 for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
John Thompson52d98862013-03-28 18:38:43 +0000516 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
John Thompson4e4d9b32013-03-28 01:20:19 +0000517 }
518 // Report any duplicate entity definition errors.
519 int kindIndex = 0;
520 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
521 DI != DE; ++DI, ++kindIndex) {
John Thompson52d98862013-03-28 18:38:43 +0000522 int eCount = DI->size();
John Thompson4e4d9b32013-03-28 01:20:19 +0000523 // If only 1 occurance, skip;
524 if (eCount <= 1)
John Thompson4f8ba652013-03-12 02:07:30 +0000525 continue;
John Thompson52d98862013-03-28 18:38:43 +0000526 LocationArray::iterator FI = DI->begin();
John Thompsonb809dfc2013-07-19 14:19:31 +0000527 StringRef kindName = Entry::getKindName((Entry::EntryKind)kindIndex);
John Thompson4e4d9b32013-03-28 01:20:19 +0000528 errs() << "error: " << kindName << " '" << E->first()
529 << "' defined at multiple locations:\n";
John Thompson52d98862013-03-28 18:38:43 +0000530 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000531 errs() << " " << FI->File->getName() << ":" << FI->Line << ":"
532 << FI->Column << "\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000533 }
John Thompson4f8ba652013-03-12 02:07:30 +0000534 HadErrors = 1;
535 }
536 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000537
John Thompson1e010142013-07-26 18:16:22 +0000538 // Complain about macro instance in header files that differ based on how
539 // they are included.
540 if (PPTracker->reportInconsistentMacros(errs()))
541 HadErrors = 1;
542
543 // Complain about preprocessor conditional directives in header files that
544 // differ based on how they are included.
545 if (PPTracker->reportInconsistentConditionals(errs()))
546 HadErrors = 1;
547
John Thompson4f8ba652013-03-12 02:07:30 +0000548 // Complain about any headers that have contents that differ based on how
549 // they are included.
John Thompsonce601e22013-03-14 01:41:29 +0000550 // FIXME: Could we provide information about which preprocessor conditionals
551 // are involved?
John Thompsonf5db45b2013-03-27 01:02:46 +0000552 for (DenseMap<const FileEntry *, HeaderContents>::iterator
553 H = Entities.HeaderContentMismatches.begin(),
554 HEnd = Entities.HeaderContentMismatches.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000555 H != HEnd; ++H) {
556 if (H->second.empty()) {
John Thompsonf5db45b2013-03-27 01:02:46 +0000557 errs() << "internal error: phantom header content mismatch\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000558 continue;
559 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000560
John Thompson4f8ba652013-03-12 02:07:30 +0000561 HadErrors = 1;
John Thompsonf5db45b2013-03-27 01:02:46 +0000562 errs() << "error: header '" << H->first->getName()
John Thompson1e010142013-07-26 18:16:22 +0000563 << "' has different contents depending on how it was included.\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000564 for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
John Thompson161381e2013-06-27 18:52:23 +0000565 errs() << "note: '" << H->second[I].Name << "' in "
566 << H->second[I].Loc.File->getName() << " at "
567 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column
568 << " not always provided\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000569 }
570 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000571
John Thompson4f8ba652013-03-12 02:07:30 +0000572 return HadErrors;
573}