blob: b23d5c6f70d1dbd21eae9765bbfbda80a4760692 [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//
26// Note that unless a "-prefex (header path)" option is specified,
27// 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//
38// error: '(symbol)' defined at both (file):(row):(column) and
39// (file):(row):(column)
40//
41// error: header '(file)' has different contents dependening on how it was
42// included
43//
44// The latter might be followed by messages like the following:
45//
46// note: '(symbol)' in (file) at (row):(column) not always provided
47//
John Thompsonce601e22013-03-14 01:41:29 +000048// Future directions:
49//
50// Basically, we want to add new checks for whatever we can check with respect
51// to checking headers for module'ability.
52//
53// Some ideas:
54//
John Thompson3b1ee2b2013-03-28 02:46:25 +000055// 1. Try to figure out the preprocessor conditional directives that
John Thompsonce601e22013-03-14 01:41:29 +000056// contribute to problems.
57//
John Thompson3b1ee2b2013-03-28 02:46:25 +000058// 2. Check for correct and consistent usage of extern "C" {} and other
John Thompsonce601e22013-03-14 01:41:29 +000059// directives. Warn about #include inside extern "C" {}.
60//
John Thompson3b1ee2b2013-03-28 02:46:25 +000061// 3. What else?
John Thompsonce601e22013-03-14 01:41:29 +000062//
63// General clean-up and refactoring:
64//
65// 1. The Location class seems to be something that we might
66// want to design to be applicable to a wider range of tools, and stick it
67// somewhere into Tooling/ in mainline
68//
John Thompson4f8ba652013-03-12 02:07:30 +000069//===----------------------------------------------------------------------===//
John Thompsonf5db45b2013-03-27 01:02:46 +000070
John Thompsond977c1e2013-03-27 18:34:38 +000071#include "clang/AST/ASTConsumer.h"
72#include "clang/AST/ASTContext.h"
73#include "clang/AST/RecursiveASTVisitor.h"
74#include "clang/Basic/SourceManager.h"
75#include "clang/Frontend/CompilerInstance.h"
76#include "clang/Frontend/FrontendActions.h"
77#include "clang/Lex/Preprocessor.h"
78#include "clang/Tooling/CompilationDatabase.h"
79#include "clang/Tooling/Tooling.h"
80#include "llvm/ADT/OwningPtr.h"
81#include "llvm/ADT/StringRef.h"
John Thompson4f8ba652013-03-12 02:07:30 +000082#include "llvm/Config/config.h"
John Thompsona2de1082013-03-26 01:17:48 +000083#include "llvm/Support/CommandLine.h"
John Thompson4f8ba652013-03-12 02:07:30 +000084#include "llvm/Support/FileSystem.h"
John Thompsonf5db45b2013-03-27 01:02:46 +000085#include "llvm/Support/MemoryBuffer.h"
John Thompsona2de1082013-03-26 01:17:48 +000086#include "llvm/Support/Path.h"
John Thompson4f8ba652013-03-12 02:07:30 +000087#include <algorithm>
John Thompsond977c1e2013-03-27 18:34:38 +000088#include <fstream>
John Thompson4f8ba652013-03-12 02:07:30 +000089#include <iterator>
John Thompsond977c1e2013-03-27 18:34:38 +000090#include <string>
91#include <vector>
John Thompson4f8ba652013-03-12 02:07:30 +000092
93using namespace clang::tooling;
94using namespace clang;
John Thompsona2de1082013-03-26 01:17:48 +000095using namespace llvm;
John Thompson4f8ba652013-03-12 02:07:30 +000096
John Thompsonea6c8db2013-03-27 21:23:21 +000097// Option to specify a file name for a list of header files to check.
98cl::opt<std::string>
99ListFileName(cl::Positional,
100 cl::desc("<name of file containing list of headers to check>"));
101
102// Collect all other arguments, which will be passed to the front end.
103cl::list<std::string> CC1Arguments(
104 cl::ConsumeAfter, cl::desc("<arguments to be passed to front end>..."));
105
106// Option to specify a prefix to be prepended to the header names.
107cl::opt<std::string> HeaderPrefix(
108 "prefix", cl::init(""),
109 cl::desc(
110 "Prepend header file paths with this prefix."
111 " If not specified,"
112 " the files are considered to be relative to the header list file."));
113
114// Read the header list file and collect the header file names.
115error_code GetHeaderFileNames(SmallVectorImpl<std::string> &headerFileNames,
116 StringRef listFileName, StringRef headerPrefix) {
117
118 // By default, use the path component of the list file name.
119 SmallString<256> headerDirectory(listFileName);
120 sys::path::remove_filename(headerDirectory);
121
122 // Get the prefix if we have one.
123 if (headerPrefix.size() != 0)
124 headerDirectory = headerPrefix;
125
126 // Read the header list file into a buffer.
127 OwningPtr<MemoryBuffer> listBuffer;
128 if (error_code ec = MemoryBuffer::getFile(ListFileName, listBuffer)) {
129 return ec;
130 }
131
132 // Parse the header list into strings.
133 SmallVector<StringRef, 32> strings;
134 listBuffer->getBuffer().split(strings, "\n", -1, false);
135
136 // Collect the header file names from the string list.
137 for (SmallVectorImpl<StringRef>::iterator I = strings.begin(),
138 E = strings.end();
139 I != E; ++I) {
140 StringRef line = (*I).trim();
141 // Ignore comments and empty lines.
142 if (line.empty() || (line[0] == '#'))
143 continue;
144 SmallString<256> headerFileName;
145 // Prepend header file name prefix if it's not absolute.
146 if (sys::path::is_absolute(line))
147 headerFileName = line;
148 else {
149 headerFileName = headerDirectory;
150 sys::path::append(headerFileName, line);
151 }
152 // Save the resulting header file path.
153 headerFileNames.push_back(headerFileName.str());
154 }
155
156 return error_code::success();
157}
158
John Thompsonce601e22013-03-14 01:41:29 +0000159// FIXME: The Location class seems to be something that we might
160// want to design to be applicable to a wider range of tools, and stick it
161// somewhere into Tooling/ in mainline
John Thompson4f8ba652013-03-12 02:07:30 +0000162struct Location {
163 const FileEntry *File;
164 unsigned Line, Column;
John Thompsonf5db45b2013-03-27 01:02:46 +0000165
166 Location() : File(), Line(), Column() {}
167
John Thompson4f8ba652013-03-12 02:07:30 +0000168 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
169 Loc = SM.getExpansionLoc(Loc);
170 if (Loc.isInvalid())
171 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000172
John Thompson4f8ba652013-03-12 02:07:30 +0000173 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
174 File = SM.getFileEntryForID(Decomposed.first);
175 if (!File)
176 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000177
John Thompson4f8ba652013-03-12 02:07:30 +0000178 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
179 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
180 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000181
John Thompson4f8ba652013-03-12 02:07:30 +0000182 operator bool() const { return File != 0; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000183
John Thompson4f8ba652013-03-12 02:07:30 +0000184 friend bool operator==(const Location &X, const Location &Y) {
185 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
186 }
187
188 friend bool operator!=(const Location &X, const Location &Y) {
189 return !(X == Y);
190 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000191
John Thompson4f8ba652013-03-12 02:07:30 +0000192 friend bool operator<(const Location &X, const Location &Y) {
193 if (X.File != Y.File)
194 return X.File < Y.File;
195 if (X.Line != Y.Line)
196 return X.Line < Y.Line;
197 return X.Column < Y.Column;
198 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000199 friend bool operator>(const Location &X, const Location &Y) { return Y < X; }
John Thompson4f8ba652013-03-12 02:07:30 +0000200 friend bool operator<=(const Location &X, const Location &Y) {
201 return !(Y < X);
202 }
203 friend bool operator>=(const Location &X, const Location &Y) {
204 return !(X < Y);
205 }
206
207};
208
John Thompson4f8ba652013-03-12 02:07:30 +0000209struct Entry {
John Thompson52d98862013-03-28 18:38:43 +0000210 enum EntryKind {
211 EK_Tag,
212 EK_Value,
213 EK_Macro,
214
215 EK_NumberOfKinds
John Thompson4f8ba652013-03-12 02:07:30 +0000216 } Kind;
John Thompsonf5db45b2013-03-27 01:02:46 +0000217
John Thompson4f8ba652013-03-12 02:07:30 +0000218 Location Loc;
John Thompson4e4d9b32013-03-28 01:20:19 +0000219
220 StringRef getKindName() { return getKindName(Kind); }
John Thompson52d98862013-03-28 18:38:43 +0000221 static StringRef getKindName(EntryKind kind);
John Thompson4f8ba652013-03-12 02:07:30 +0000222};
223
John Thompson4e4d9b32013-03-28 01:20:19 +0000224// Return a string representing the given kind.
John Thompson52d98862013-03-28 18:38:43 +0000225StringRef Entry::getKindName(Entry::EntryKind kind) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000226 switch (kind) {
John Thompson52d98862013-03-28 18:38:43 +0000227 case EK_Tag:
John Thompson4e4d9b32013-03-28 01:20:19 +0000228 return "tag";
John Thompson52d98862013-03-28 18:38:43 +0000229 case EK_Value:
John Thompson4e4d9b32013-03-28 01:20:19 +0000230 return "value";
John Thompson52d98862013-03-28 18:38:43 +0000231 case EK_Macro:
John Thompson4e4d9b32013-03-28 01:20:19 +0000232 return "macro";
John Thompson52d98862013-03-28 18:38:43 +0000233 case EK_NumberOfKinds:
John Thompson4e4d9b32013-03-28 01:20:19 +0000234 break;
John Thompson4e4d9b32013-03-28 01:20:19 +0000235 }
David Blaikiec66c07d2013-03-28 02:30:37 +0000236 llvm_unreachable("invalid Entry kind");
John Thompson4e4d9b32013-03-28 01:20:19 +0000237}
238
John Thompson4f8ba652013-03-12 02:07:30 +0000239struct HeaderEntry {
240 std::string Name;
241 Location Loc;
John Thompsonf5db45b2013-03-27 01:02:46 +0000242
John Thompson4f8ba652013-03-12 02:07:30 +0000243 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
244 return X.Loc == Y.Loc && X.Name == Y.Name;
245 }
246 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
247 return !(X == Y);
248 }
249 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
250 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
251 }
252 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
253 return Y < X;
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 !(X < Y);
260 }
261};
262
263typedef std::vector<HeaderEntry> HeaderContents;
264
John Thompsonf5db45b2013-03-27 01:02:46 +0000265class EntityMap : public StringMap<SmallVector<Entry, 2> > {
John Thompson4f8ba652013-03-12 02:07:30 +0000266public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000267 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches;
268
John Thompson52d98862013-03-28 18:38:43 +0000269 void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) {
John Thompson4f8ba652013-03-12 02:07:30 +0000270 // Record this entity in its header.
271 HeaderEntry HE = { Name, Loc };
272 CurHeaderContents[Loc.File].push_back(HE);
John Thompsonf5db45b2013-03-27 01:02:46 +0000273
John Thompson4f8ba652013-03-12 02:07:30 +0000274 // Check whether we've seen this entry before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000275 SmallVector<Entry, 2> &Entries = (*this)[Name];
John Thompson4f8ba652013-03-12 02:07:30 +0000276 for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
277 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
278 return;
279 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000280
John Thompson4f8ba652013-03-12 02:07:30 +0000281 // We have not seen this entry before; record it.
282 Entry E = { Kind, Loc };
283 Entries.push_back(E);
284 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000285
John Thompson4f8ba652013-03-12 02:07:30 +0000286 void mergeCurHeaderContents() {
John Thompsonf5db45b2013-03-27 01:02:46 +0000287 for (DenseMap<const FileEntry *, HeaderContents>::iterator
288 H = CurHeaderContents.begin(),
289 HEnd = CurHeaderContents.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000290 H != HEnd; ++H) {
291 // Sort contents.
292 std::sort(H->second.begin(), H->second.end());
293
294 // Check whether we've seen this header before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000295 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH =
296 AllHeaderContents.find(H->first);
John Thompson4f8ba652013-03-12 02:07:30 +0000297 if (KnownH == AllHeaderContents.end()) {
298 // We haven't seen this header before; record its contents.
299 AllHeaderContents.insert(*H);
300 continue;
301 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000302
John Thompson4f8ba652013-03-12 02:07:30 +0000303 // If the header contents are the same, we're done.
304 if (H->second == KnownH->second)
305 continue;
John Thompsonf5db45b2013-03-27 01:02:46 +0000306
John Thompson4f8ba652013-03-12 02:07:30 +0000307 // Determine what changed.
John Thompsonf5db45b2013-03-27 01:02:46 +0000308 std::set_symmetric_difference(
309 H->second.begin(), H->second.end(), KnownH->second.begin(),
310 KnownH->second.end(),
311 std::back_inserter(HeaderContentMismatches[H->first]));
John Thompson4f8ba652013-03-12 02:07:30 +0000312 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000313
John Thompson4f8ba652013-03-12 02:07:30 +0000314 CurHeaderContents.clear();
315 }
John Thompson1f67ccb2013-03-12 18:51:47 +0000316private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000317 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents;
318 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents;
John Thompson4f8ba652013-03-12 02:07:30 +0000319};
320
John Thompsonf5db45b2013-03-27 01:02:46 +0000321class CollectEntitiesVisitor :
322 public RecursiveASTVisitor<CollectEntitiesVisitor> {
John Thompson4f8ba652013-03-12 02:07:30 +0000323public:
324 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000325 : SM(SM), Entities(Entities) {}
326
John Thompson4f8ba652013-03-12 02:07:30 +0000327 bool TraverseStmt(Stmt *S) { return true; }
328 bool TraverseType(QualType T) { return true; }
329 bool TraverseTypeLoc(TypeLoc TL) { return true; }
330 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000331 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
332 return true;
333 }
334 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
335 return true;
336 }
John Thompson4f8ba652013-03-12 02:07:30 +0000337 bool TraverseTemplateName(TemplateName Template) { return true; }
338 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000339 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
340 return true;
341 }
John Thompson4f8ba652013-03-12 02:07:30 +0000342 bool TraverseTemplateArguments(const TemplateArgument *Args,
John Thompsonf5db45b2013-03-27 01:02:46 +0000343 unsigned NumArgs) {
344 return true;
345 }
John Thompson4f8ba652013-03-12 02:07:30 +0000346 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
347 bool TraverseLambdaCapture(LambdaExpr::Capture C) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000348
John Thompson4f8ba652013-03-12 02:07:30 +0000349 bool VisitNamedDecl(NamedDecl *ND) {
350 // We only care about file-context variables.
351 if (!ND->getDeclContext()->isFileContext())
352 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000353
John Thompson4f8ba652013-03-12 02:07:30 +0000354 // Skip declarations that tend to be properly multiply-declared.
355 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
John Thompsonf5db45b2013-03-27 01:02:46 +0000356 isa<NamespaceAliasDecl>(ND) ||
357 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
358 isa<UsingShadowDecl>(ND) || isa<FunctionDecl>(ND) ||
359 isa<FunctionTemplateDecl>(ND) ||
John Thompson4f8ba652013-03-12 02:07:30 +0000360 (isa<TagDecl>(ND) &&
361 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
362 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000363
John Thompson4f8ba652013-03-12 02:07:30 +0000364 std::string Name = ND->getNameAsString();
365 if (Name.empty())
366 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000367
John Thompson4f8ba652013-03-12 02:07:30 +0000368 Location Loc(SM, ND->getLocation());
369 if (!Loc)
370 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000371
John Thompson52d98862013-03-28 18:38:43 +0000372 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000373 return true;
374 }
John Thompson1f67ccb2013-03-12 18:51:47 +0000375private:
376 SourceManager &SM;
377 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000378};
379
380class CollectEntitiesConsumer : public ASTConsumer {
John Thompson4f8ba652013-03-12 02:07:30 +0000381public:
382 CollectEntitiesConsumer(EntityMap &Entities, Preprocessor &PP)
John Thompsonf5db45b2013-03-27 01:02:46 +0000383 : Entities(Entities), PP(PP) {}
384
John Thompson4f8ba652013-03-12 02:07:30 +0000385 virtual void HandleTranslationUnit(ASTContext &Ctx) {
386 SourceManager &SM = Ctx.getSourceManager();
John Thompsonf5db45b2013-03-27 01:02:46 +0000387
John Thompson4f8ba652013-03-12 02:07:30 +0000388 // Collect declared entities.
389 CollectEntitiesVisitor(SM, Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000390 .TraverseDecl(Ctx.getTranslationUnitDecl());
391
John Thompson4f8ba652013-03-12 02:07:30 +0000392 // Collect macro definitions.
393 for (Preprocessor::macro_iterator M = PP.macro_begin(),
John Thompsonf5db45b2013-03-27 01:02:46 +0000394 MEnd = PP.macro_end();
John Thompson4f8ba652013-03-12 02:07:30 +0000395 M != MEnd; ++M) {
396 Location Loc(SM, M->second->getLocation());
397 if (!Loc)
398 continue;
399
John Thompson52d98862013-03-28 18:38:43 +0000400 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000401 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000402
John Thompson4f8ba652013-03-12 02:07:30 +0000403 // Merge header contents.
404 Entities.mergeCurHeaderContents();
405 }
John Thompson1f67ccb2013-03-12 18:51:47 +0000406private:
407 EntityMap &Entities;
408 Preprocessor &PP;
John Thompson4f8ba652013-03-12 02:07:30 +0000409};
410
411class CollectEntitiesAction : public SyntaxOnlyAction {
John Thompson1f67ccb2013-03-12 18:51:47 +0000412public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000413 CollectEntitiesAction(EntityMap &Entities) : Entities(Entities) {}
John Thompson4f8ba652013-03-12 02:07:30 +0000414protected:
John Thompsonf5db45b2013-03-27 01:02:46 +0000415 virtual clang::ASTConsumer *
416 CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
John Thompson4f8ba652013-03-12 02:07:30 +0000417 return new CollectEntitiesConsumer(Entities, CI.getPreprocessor());
418 }
John Thompson1f67ccb2013-03-12 18:51:47 +0000419private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000420 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000421};
422
423class ModularizeFrontendActionFactory : public FrontendActionFactory {
John Thompson4f8ba652013-03-12 02:07:30 +0000424public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000425 ModularizeFrontendActionFactory(EntityMap &Entities) : Entities(Entities) {}
John Thompson4f8ba652013-03-12 02:07:30 +0000426
427 virtual CollectEntitiesAction *create() {
428 return new CollectEntitiesAction(Entities);
429 }
John Thompson1f67ccb2013-03-12 18:51:47 +0000430private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000431 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000432};
433
434int main(int argc, const char **argv) {
John Thompsona2de1082013-03-26 01:17:48 +0000435
436 // This causes options to be parsed.
437 cl::ParseCommandLineOptions(argc, argv, "modularize.\n");
438
439 // No go if we have no header list file.
440 if (ListFileName.size() == 0) {
441 cl::PrintHelpMessage();
John Thompsonea6c8db2013-03-27 21:23:21 +0000442 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000443 }
John Thompsona2de1082013-03-26 01:17:48 +0000444
John Thompsonea6c8db2013-03-27 21:23:21 +0000445 // Get header file names.
John Thompsonf5db45b2013-03-27 01:02:46 +0000446 SmallVector<std::string, 32> Headers;
John Thompsonea6c8db2013-03-27 21:23:21 +0000447 if (error_code ec = GetHeaderFileNames(Headers, ListFileName, HeaderPrefix)) {
448 errs() << argv[0] << ": error: Unable to get header list '" << ListFileName
449 << "': " << ec.message() << '\n';
450 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000451 }
John Thompsona2de1082013-03-26 01:17:48 +0000452
John Thompson4f8ba652013-03-12 02:07:30 +0000453 // Create the compilation database.
John Thompsona2de1082013-03-26 01:17:48 +0000454 SmallString<256> PathBuf;
John Thompsonf5db45b2013-03-27 01:02:46 +0000455 sys::fs::current_path(PathBuf);
456 OwningPtr<CompilationDatabase> Compilations;
457 Compilations.reset(
458 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments));
John Thompsona2de1082013-03-26 01:17:48 +0000459
John Thompson4f8ba652013-03-12 02:07:30 +0000460 // Parse all of the headers, detecting duplicates.
461 EntityMap Entities;
462 ClangTool Tool(*Compilations, Headers);
463 int HadErrors = Tool.run(new ModularizeFrontendActionFactory(Entities));
John Thompsonce601e22013-03-14 01:41:29 +0000464
John Thompson4e4d9b32013-03-28 01:20:19 +0000465 // Create a place to save duplicate entity locations, separate bins per kind.
466 typedef SmallVector<Location, 8> LocationArray;
John Thompson52d98862013-03-28 18:38:43 +0000467 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
John Thompson4e4d9b32013-03-28 01:20:19 +0000468 EntryBinArray EntryBins;
Michael Gottesman4b249212013-03-28 06:07:15 +0000469 int kindIndex;
John Thompson52d98862013-03-28 18:38:43 +0000470 for (kindIndex = 0; kindIndex < Entry::EK_NumberOfKinds; ++kindIndex) {
471 LocationArray array;
472 EntryBins.push_back(array);
Michael Gottesman4b249212013-03-28 06:07:15 +0000473 }
John Thompson4e4d9b32013-03-28 01:20:19 +0000474
John Thompson4f8ba652013-03-12 02:07:30 +0000475 // Check for the same entity being defined in multiple places.
476 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
477 E != EEnd; ++E) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000478 // If only one occurance, exit early.
479 if (E->second.size() == 1)
480 continue;
481 // Clear entity locations.
482 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
483 CI != CE; ++CI) {
John Thompson52d98862013-03-28 18:38:43 +0000484 CI->clear();
John Thompson4e4d9b32013-03-28 01:20:19 +0000485 }
486 // Walk the entities of a single name, collecting the locations,
487 // separated into separate bins.
John Thompson4f8ba652013-03-12 02:07:30 +0000488 for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
John Thompson52d98862013-03-28 18:38:43 +0000489 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
John Thompson4e4d9b32013-03-28 01:20:19 +0000490 }
491 // Report any duplicate entity definition errors.
492 int kindIndex = 0;
493 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
494 DI != DE; ++DI, ++kindIndex) {
John Thompson52d98862013-03-28 18:38:43 +0000495 int eCount = DI->size();
John Thompson4e4d9b32013-03-28 01:20:19 +0000496 // If only 1 occurance, skip;
497 if (eCount <= 1)
John Thompson4f8ba652013-03-12 02:07:30 +0000498 continue;
John Thompson52d98862013-03-28 18:38:43 +0000499 LocationArray::iterator FI = DI->begin();
500 StringRef kindName = Entry::getKindName((Entry::EntryKind) kindIndex);
John Thompson4e4d9b32013-03-28 01:20:19 +0000501 errs() << "error: " << kindName << " '" << E->first()
502 << "' defined at multiple locations:\n";
John Thompson52d98862013-03-28 18:38:43 +0000503 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000504 errs() << " " << FI->File->getName() << ":" << FI->Line << ":"
505 << FI->Column << "\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000506 }
John Thompson4f8ba652013-03-12 02:07:30 +0000507 HadErrors = 1;
508 }
509 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000510
John Thompson4f8ba652013-03-12 02:07:30 +0000511 // Complain about any headers that have contents that differ based on how
512 // they are included.
John Thompsonce601e22013-03-14 01:41:29 +0000513 // FIXME: Could we provide information about which preprocessor conditionals
514 // are involved?
John Thompsonf5db45b2013-03-27 01:02:46 +0000515 for (DenseMap<const FileEntry *, HeaderContents>::iterator
516 H = Entities.HeaderContentMismatches.begin(),
517 HEnd = Entities.HeaderContentMismatches.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000518 H != HEnd; ++H) {
519 if (H->second.empty()) {
John Thompsonf5db45b2013-03-27 01:02:46 +0000520 errs() << "internal error: phantom header content mismatch\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000521 continue;
522 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000523
John Thompson4f8ba652013-03-12 02:07:30 +0000524 HadErrors = 1;
John Thompsonf5db45b2013-03-27 01:02:46 +0000525 errs() << "error: header '" << H->first->getName()
526 << "' has different contents dependening on how it was included\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000527 for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
John Thompsonf5db45b2013-03-27 01:02:46 +0000528 errs() << "note: '" << H->second[I].Name << "' in " << H->second[I]
529 .Loc.File->getName() << " at " << H->second[I].Loc.Line << ":"
530 << H->second[I].Loc.Column << " not always provided\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000531 }
532 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000533
John Thompson4f8ba652013-03-12 02:07:30 +0000534 return HadErrors;
535}