blob: 7dca4d28ca5f4878e6b5bd02a3426ecfc09e8626 [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 Thompson4f8ba652013-03-12 02:07:30 +000093
94using namespace clang::tooling;
95using namespace clang;
John Thompsona2de1082013-03-26 01:17:48 +000096using namespace llvm;
John Thompson4f8ba652013-03-12 02:07:30 +000097
John Thompsonea6c8db2013-03-27 21:23:21 +000098// Option to specify a file name for a list of header files to check.
John Thompson161381e2013-06-27 18:52:23 +000099cl::opt<std::string> ListFileName(
100 cl::Positional,
101 cl::desc("<name of file containing list of headers to check>"));
John Thompsonea6c8db2013-03-27 21:23:21 +0000102
103// Collect all other arguments, which will be passed to the front end.
John Thompson161381e2013-06-27 18:52:23 +0000104cl::list<std::string>
105 CC1Arguments(cl::ConsumeAfter,
106 cl::desc("<arguments to be passed to front end>..."));
John Thompsonea6c8db2013-03-27 21:23:21 +0000107
108// Option to specify a prefix to be prepended to the header names.
109cl::opt<std::string> HeaderPrefix(
110 "prefix", cl::init(""),
111 cl::desc(
112 "Prepend header file paths with this prefix."
113 " If not specified,"
114 " the files are considered to be relative to the header list file."));
115
116// Read the header list file and collect the header file names.
John Thompson54c83692013-06-18 19:56:05 +0000117error_code getHeaderFileNames(SmallVectorImpl<std::string> &headerFileNames,
John Thompsonea6c8db2013-03-27 21:23:21 +0000118 StringRef listFileName, StringRef headerPrefix) {
119
120 // By default, use the path component of the list file name.
121 SmallString<256> headerDirectory(listFileName);
122 sys::path::remove_filename(headerDirectory);
123
124 // Get the prefix if we have one.
125 if (headerPrefix.size() != 0)
126 headerDirectory = headerPrefix;
127
128 // Read the header list file into a buffer.
129 OwningPtr<MemoryBuffer> listBuffer;
John Thompson26b567a2013-06-19 20:35:50 +0000130 if (error_code ec = MemoryBuffer::getFile(listFileName, listBuffer)) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000131 return ec;
132 }
133
134 // Parse the header list into strings.
135 SmallVector<StringRef, 32> strings;
136 listBuffer->getBuffer().split(strings, "\n", -1, false);
137
138 // Collect the header file names from the string list.
139 for (SmallVectorImpl<StringRef>::iterator I = strings.begin(),
140 E = strings.end();
141 I != E; ++I) {
142 StringRef line = (*I).trim();
143 // Ignore comments and empty lines.
144 if (line.empty() || (line[0] == '#'))
145 continue;
146 SmallString<256> headerFileName;
147 // Prepend header file name prefix if it's not absolute.
148 if (sys::path::is_absolute(line))
149 headerFileName = line;
150 else {
151 headerFileName = headerDirectory;
152 sys::path::append(headerFileName, line);
153 }
154 // Save the resulting header file path.
155 headerFileNames.push_back(headerFileName.str());
156 }
157
158 return error_code::success();
159}
160
John Thompsonce601e22013-03-14 01:41:29 +0000161// FIXME: The Location class seems to be something that we might
162// want to design to be applicable to a wider range of tools, and stick it
163// somewhere into Tooling/ in mainline
John Thompson4f8ba652013-03-12 02:07:30 +0000164struct Location {
165 const FileEntry *File;
166 unsigned Line, Column;
John Thompsonf5db45b2013-03-27 01:02:46 +0000167
168 Location() : File(), Line(), Column() {}
169
John Thompson4f8ba652013-03-12 02:07:30 +0000170 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
171 Loc = SM.getExpansionLoc(Loc);
172 if (Loc.isInvalid())
173 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000174
John Thompson4f8ba652013-03-12 02:07:30 +0000175 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
176 File = SM.getFileEntryForID(Decomposed.first);
177 if (!File)
178 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000179
John Thompson4f8ba652013-03-12 02:07:30 +0000180 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
181 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
182 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000183
John Thompson4f8ba652013-03-12 02:07:30 +0000184 operator bool() const { return File != 0; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000185
John Thompson4f8ba652013-03-12 02:07:30 +0000186 friend bool operator==(const Location &X, const Location &Y) {
187 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
188 }
189
190 friend bool operator!=(const Location &X, const Location &Y) {
191 return !(X == Y);
192 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000193
John Thompson4f8ba652013-03-12 02:07:30 +0000194 friend bool operator<(const Location &X, const Location &Y) {
195 if (X.File != Y.File)
196 return X.File < Y.File;
197 if (X.Line != Y.Line)
198 return X.Line < Y.Line;
199 return X.Column < Y.Column;
200 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000201 friend bool operator>(const Location &X, const Location &Y) { return Y < X; }
John Thompson4f8ba652013-03-12 02:07:30 +0000202 friend bool operator<=(const Location &X, const Location &Y) {
203 return !(Y < X);
204 }
205 friend bool operator>=(const Location &X, const Location &Y) {
206 return !(X < Y);
207 }
208
209};
210
John Thompson4f8ba652013-03-12 02:07:30 +0000211struct Entry {
John Thompson52d98862013-03-28 18:38:43 +0000212 enum EntryKind {
213 EK_Tag,
214 EK_Value,
215 EK_Macro,
216
217 EK_NumberOfKinds
John Thompson4f8ba652013-03-12 02:07:30 +0000218 } Kind;
John Thompsonf5db45b2013-03-27 01:02:46 +0000219
John Thompson4f8ba652013-03-12 02:07:30 +0000220 Location Loc;
John Thompson4e4d9b32013-03-28 01:20:19 +0000221
222 StringRef getKindName() { return getKindName(Kind); }
John Thompson52d98862013-03-28 18:38:43 +0000223 static StringRef getKindName(EntryKind kind);
John Thompson4f8ba652013-03-12 02:07:30 +0000224};
225
John Thompson4e4d9b32013-03-28 01:20:19 +0000226// Return a string representing the given kind.
John Thompson52d98862013-03-28 18:38:43 +0000227StringRef Entry::getKindName(Entry::EntryKind kind) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000228 switch (kind) {
John Thompson52d98862013-03-28 18:38:43 +0000229 case EK_Tag:
John Thompson4e4d9b32013-03-28 01:20:19 +0000230 return "tag";
John Thompson52d98862013-03-28 18:38:43 +0000231 case EK_Value:
John Thompson4e4d9b32013-03-28 01:20:19 +0000232 return "value";
John Thompson52d98862013-03-28 18:38:43 +0000233 case EK_Macro:
John Thompson4e4d9b32013-03-28 01:20:19 +0000234 return "macro";
John Thompson52d98862013-03-28 18:38:43 +0000235 case EK_NumberOfKinds:
John Thompson4e4d9b32013-03-28 01:20:19 +0000236 break;
John Thompson4e4d9b32013-03-28 01:20:19 +0000237 }
David Blaikiec66c07d2013-03-28 02:30:37 +0000238 llvm_unreachable("invalid Entry kind");
John Thompson4e4d9b32013-03-28 01:20:19 +0000239}
240
John Thompson4f8ba652013-03-12 02:07:30 +0000241struct HeaderEntry {
242 std::string Name;
243 Location Loc;
John Thompsonf5db45b2013-03-27 01:02:46 +0000244
John Thompson4f8ba652013-03-12 02:07:30 +0000245 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
246 return X.Loc == Y.Loc && X.Name == Y.Name;
247 }
248 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
249 return !(X == Y);
250 }
251 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
252 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
253 }
254 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
255 return Y < X;
256 }
257 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) {
258 return !(Y < X);
259 }
260 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) {
261 return !(X < Y);
262 }
263};
264
265typedef std::vector<HeaderEntry> HeaderContents;
266
John Thompsonf5db45b2013-03-27 01:02:46 +0000267class EntityMap : public StringMap<SmallVector<Entry, 2> > {
John Thompson4f8ba652013-03-12 02:07:30 +0000268public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000269 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches;
270
John Thompson52d98862013-03-28 18:38:43 +0000271 void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) {
John Thompson4f8ba652013-03-12 02:07:30 +0000272 // Record this entity in its header.
273 HeaderEntry HE = { Name, Loc };
274 CurHeaderContents[Loc.File].push_back(HE);
John Thompsonf5db45b2013-03-27 01:02:46 +0000275
John Thompson4f8ba652013-03-12 02:07:30 +0000276 // Check whether we've seen this entry before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000277 SmallVector<Entry, 2> &Entries = (*this)[Name];
John Thompson4f8ba652013-03-12 02:07:30 +0000278 for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
279 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
280 return;
281 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000282
John Thompson4f8ba652013-03-12 02:07:30 +0000283 // We have not seen this entry before; record it.
284 Entry E = { Kind, Loc };
285 Entries.push_back(E);
286 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000287
John Thompson4f8ba652013-03-12 02:07:30 +0000288 void mergeCurHeaderContents() {
John Thompsonf5db45b2013-03-27 01:02:46 +0000289 for (DenseMap<const FileEntry *, HeaderContents>::iterator
290 H = CurHeaderContents.begin(),
291 HEnd = CurHeaderContents.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000292 H != HEnd; ++H) {
293 // Sort contents.
294 std::sort(H->second.begin(), H->second.end());
295
296 // Check whether we've seen this header before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000297 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH =
298 AllHeaderContents.find(H->first);
John Thompson4f8ba652013-03-12 02:07:30 +0000299 if (KnownH == AllHeaderContents.end()) {
300 // We haven't seen this header before; record its contents.
301 AllHeaderContents.insert(*H);
302 continue;
303 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000304
John Thompson4f8ba652013-03-12 02:07:30 +0000305 // If the header contents are the same, we're done.
306 if (H->second == KnownH->second)
307 continue;
John Thompsonf5db45b2013-03-27 01:02:46 +0000308
John Thompson4f8ba652013-03-12 02:07:30 +0000309 // Determine what changed.
John Thompsonf5db45b2013-03-27 01:02:46 +0000310 std::set_symmetric_difference(
311 H->second.begin(), H->second.end(), KnownH->second.begin(),
312 KnownH->second.end(),
313 std::back_inserter(HeaderContentMismatches[H->first]));
John Thompson4f8ba652013-03-12 02:07:30 +0000314 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000315
John Thompson4f8ba652013-03-12 02:07:30 +0000316 CurHeaderContents.clear();
317 }
John Thompson161381e2013-06-27 18:52:23 +0000318
John Thompson1f67ccb2013-03-12 18:51:47 +0000319private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000320 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents;
321 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents;
John Thompson4f8ba652013-03-12 02:07:30 +0000322};
323
John Thompson161381e2013-06-27 18:52:23 +0000324class CollectEntitiesVisitor
325 : public RecursiveASTVisitor<CollectEntitiesVisitor> {
John Thompson4f8ba652013-03-12 02:07:30 +0000326public:
327 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000328 : SM(SM), Entities(Entities) {}
329
John Thompson4f8ba652013-03-12 02:07:30 +0000330 bool TraverseStmt(Stmt *S) { return true; }
331 bool TraverseType(QualType T) { return true; }
332 bool TraverseTypeLoc(TypeLoc TL) { return true; }
333 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000334 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
335 return true;
336 }
337 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
338 return true;
339 }
John Thompson4f8ba652013-03-12 02:07:30 +0000340 bool TraverseTemplateName(TemplateName Template) { return true; }
341 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000342 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
343 return true;
344 }
John Thompson4f8ba652013-03-12 02:07:30 +0000345 bool TraverseTemplateArguments(const TemplateArgument *Args,
John Thompsonf5db45b2013-03-27 01:02:46 +0000346 unsigned NumArgs) {
347 return true;
348 }
John Thompson4f8ba652013-03-12 02:07:30 +0000349 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
350 bool TraverseLambdaCapture(LambdaExpr::Capture C) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000351
John Thompson4f8ba652013-03-12 02:07:30 +0000352 bool VisitNamedDecl(NamedDecl *ND) {
353 // We only care about file-context variables.
354 if (!ND->getDeclContext()->isFileContext())
355 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000356
John Thompson4f8ba652013-03-12 02:07:30 +0000357 // Skip declarations that tend to be properly multiply-declared.
358 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
John Thompsonf5db45b2013-03-27 01:02:46 +0000359 isa<NamespaceAliasDecl>(ND) ||
360 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
361 isa<UsingShadowDecl>(ND) || isa<FunctionDecl>(ND) ||
362 isa<FunctionTemplateDecl>(ND) ||
John Thompson4f8ba652013-03-12 02:07:30 +0000363 (isa<TagDecl>(ND) &&
364 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
365 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000366
John Thompson4f8ba652013-03-12 02:07:30 +0000367 std::string Name = ND->getNameAsString();
368 if (Name.empty())
369 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000370
John Thompson4f8ba652013-03-12 02:07:30 +0000371 Location Loc(SM, ND->getLocation());
372 if (!Loc)
373 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000374
John Thompson52d98862013-03-28 18:38:43 +0000375 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000376 return true;
377 }
John Thompson161381e2013-06-27 18:52:23 +0000378
John Thompson1f67ccb2013-03-12 18:51:47 +0000379private:
380 SourceManager &SM;
381 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000382};
383
384class CollectEntitiesConsumer : public ASTConsumer {
John Thompson4f8ba652013-03-12 02:07:30 +0000385public:
386 CollectEntitiesConsumer(EntityMap &Entities, Preprocessor &PP)
John Thompsonf5db45b2013-03-27 01:02:46 +0000387 : Entities(Entities), PP(PP) {}
388
John Thompson4f8ba652013-03-12 02:07:30 +0000389 virtual void HandleTranslationUnit(ASTContext &Ctx) {
390 SourceManager &SM = Ctx.getSourceManager();
John Thompsonf5db45b2013-03-27 01:02:46 +0000391
John Thompson4f8ba652013-03-12 02:07:30 +0000392 // Collect declared entities.
393 CollectEntitiesVisitor(SM, Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000394 .TraverseDecl(Ctx.getTranslationUnitDecl());
395
John Thompson4f8ba652013-03-12 02:07:30 +0000396 // Collect macro definitions.
397 for (Preprocessor::macro_iterator M = PP.macro_begin(),
John Thompsonf5db45b2013-03-27 01:02:46 +0000398 MEnd = PP.macro_end();
John Thompson4f8ba652013-03-12 02:07:30 +0000399 M != MEnd; ++M) {
400 Location Loc(SM, M->second->getLocation());
401 if (!Loc)
402 continue;
403
John Thompson52d98862013-03-28 18:38:43 +0000404 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000405 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000406
John Thompson4f8ba652013-03-12 02:07:30 +0000407 // Merge header contents.
408 Entities.mergeCurHeaderContents();
409 }
John Thompson161381e2013-06-27 18:52:23 +0000410
John Thompson1f67ccb2013-03-12 18:51:47 +0000411private:
412 EntityMap &Entities;
413 Preprocessor &PP;
John Thompson4f8ba652013-03-12 02:07:30 +0000414};
415
416class CollectEntitiesAction : public SyntaxOnlyAction {
John Thompson1f67ccb2013-03-12 18:51:47 +0000417public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000418 CollectEntitiesAction(EntityMap &Entities) : Entities(Entities) {}
John Thompson161381e2013-06-27 18:52:23 +0000419
John Thompson4f8ba652013-03-12 02:07:30 +0000420protected:
John Thompson161381e2013-06-27 18:52:23 +0000421 virtual clang::ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
422 StringRef InFile) {
John Thompson4f8ba652013-03-12 02:07:30 +0000423 return new CollectEntitiesConsumer(Entities, CI.getPreprocessor());
424 }
John Thompson161381e2013-06-27 18:52:23 +0000425
John Thompson1f67ccb2013-03-12 18:51:47 +0000426private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000427 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000428};
429
430class ModularizeFrontendActionFactory : public FrontendActionFactory {
John Thompson4f8ba652013-03-12 02:07:30 +0000431public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000432 ModularizeFrontendActionFactory(EntityMap &Entities) : Entities(Entities) {}
John Thompson4f8ba652013-03-12 02:07:30 +0000433
434 virtual CollectEntitiesAction *create() {
435 return new CollectEntitiesAction(Entities);
436 }
John Thompson161381e2013-06-27 18:52:23 +0000437
John Thompson1f67ccb2013-03-12 18:51:47 +0000438private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000439 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000440};
441
442int main(int argc, const char **argv) {
John Thompsona2de1082013-03-26 01:17:48 +0000443
444 // This causes options to be parsed.
445 cl::ParseCommandLineOptions(argc, argv, "modularize.\n");
446
447 // No go if we have no header list file.
448 if (ListFileName.size() == 0) {
449 cl::PrintHelpMessage();
John Thompsonea6c8db2013-03-27 21:23:21 +0000450 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000451 }
John Thompsona2de1082013-03-26 01:17:48 +0000452
John Thompsonea6c8db2013-03-27 21:23:21 +0000453 // Get header file names.
John Thompsonf5db45b2013-03-27 01:02:46 +0000454 SmallVector<std::string, 32> Headers;
John Thompson54c83692013-06-18 19:56:05 +0000455 if (error_code ec = getHeaderFileNames(Headers, ListFileName, HeaderPrefix)) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000456 errs() << argv[0] << ": error: Unable to get header list '" << ListFileName
457 << "': " << ec.message() << '\n';
458 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000459 }
John Thompsona2de1082013-03-26 01:17:48 +0000460
John Thompson4f8ba652013-03-12 02:07:30 +0000461 // Create the compilation database.
John Thompsona2de1082013-03-26 01:17:48 +0000462 SmallString<256> PathBuf;
John Thompsonf5db45b2013-03-27 01:02:46 +0000463 sys::fs::current_path(PathBuf);
464 OwningPtr<CompilationDatabase> Compilations;
465 Compilations.reset(
466 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments));
John Thompsona2de1082013-03-26 01:17:48 +0000467
John Thompson4f8ba652013-03-12 02:07:30 +0000468 // Parse all of the headers, detecting duplicates.
469 EntityMap Entities;
470 ClangTool Tool(*Compilations, Headers);
471 int HadErrors = Tool.run(new ModularizeFrontendActionFactory(Entities));
John Thompsonce601e22013-03-14 01:41:29 +0000472
John Thompson4e4d9b32013-03-28 01:20:19 +0000473 // Create a place to save duplicate entity locations, separate bins per kind.
474 typedef SmallVector<Location, 8> LocationArray;
John Thompson52d98862013-03-28 18:38:43 +0000475 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
John Thompson4e4d9b32013-03-28 01:20:19 +0000476 EntryBinArray EntryBins;
Michael Gottesman4b249212013-03-28 06:07:15 +0000477 int kindIndex;
John Thompson52d98862013-03-28 18:38:43 +0000478 for (kindIndex = 0; kindIndex < Entry::EK_NumberOfKinds; ++kindIndex) {
479 LocationArray array;
480 EntryBins.push_back(array);
Michael Gottesman4b249212013-03-28 06:07:15 +0000481 }
John Thompson4e4d9b32013-03-28 01:20:19 +0000482
John Thompson4f8ba652013-03-12 02:07:30 +0000483 // Check for the same entity being defined in multiple places.
484 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
485 E != EEnd; ++E) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000486 // If only one occurance, exit early.
487 if (E->second.size() == 1)
488 continue;
489 // Clear entity locations.
490 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
491 CI != CE; ++CI) {
John Thompson52d98862013-03-28 18:38:43 +0000492 CI->clear();
John Thompson4e4d9b32013-03-28 01:20:19 +0000493 }
494 // Walk the entities of a single name, collecting the locations,
495 // separated into separate bins.
John Thompson4f8ba652013-03-12 02:07:30 +0000496 for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
John Thompson52d98862013-03-28 18:38:43 +0000497 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
John Thompson4e4d9b32013-03-28 01:20:19 +0000498 }
499 // Report any duplicate entity definition errors.
500 int kindIndex = 0;
501 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
502 DI != DE; ++DI, ++kindIndex) {
John Thompson52d98862013-03-28 18:38:43 +0000503 int eCount = DI->size();
John Thompson4e4d9b32013-03-28 01:20:19 +0000504 // If only 1 occurance, skip;
505 if (eCount <= 1)
John Thompson4f8ba652013-03-12 02:07:30 +0000506 continue;
John Thompson52d98862013-03-28 18:38:43 +0000507 LocationArray::iterator FI = DI->begin();
508 StringRef kindName = Entry::getKindName((Entry::EntryKind) kindIndex);
John Thompson4e4d9b32013-03-28 01:20:19 +0000509 errs() << "error: " << kindName << " '" << E->first()
510 << "' defined at multiple locations:\n";
John Thompson52d98862013-03-28 18:38:43 +0000511 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000512 errs() << " " << FI->File->getName() << ":" << FI->Line << ":"
513 << FI->Column << "\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000514 }
John Thompson4f8ba652013-03-12 02:07:30 +0000515 HadErrors = 1;
516 }
517 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000518
John Thompson4f8ba652013-03-12 02:07:30 +0000519 // Complain about any headers that have contents that differ based on how
520 // they are included.
John Thompsonce601e22013-03-14 01:41:29 +0000521 // FIXME: Could we provide information about which preprocessor conditionals
522 // are involved?
John Thompsonf5db45b2013-03-27 01:02:46 +0000523 for (DenseMap<const FileEntry *, HeaderContents>::iterator
524 H = Entities.HeaderContentMismatches.begin(),
525 HEnd = Entities.HeaderContentMismatches.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000526 H != HEnd; ++H) {
527 if (H->second.empty()) {
John Thompsonf5db45b2013-03-27 01:02:46 +0000528 errs() << "internal error: phantom header content mismatch\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000529 continue;
530 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000531
John Thompson4f8ba652013-03-12 02:07:30 +0000532 HadErrors = 1;
John Thompsonf5db45b2013-03-27 01:02:46 +0000533 errs() << "error: header '" << H->first->getName()
John Thompson54c83692013-06-18 19:56:05 +0000534 << "' has different contents depending on how it was included\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000535 for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
John Thompson161381e2013-06-27 18:52:23 +0000536 errs() << "note: '" << H->second[I].Name << "' in "
537 << H->second[I].Loc.File->getName() << " at "
538 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column
539 << " not always provided\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000540 }
541 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000542
John Thompson4f8ba652013-03-12 02:07:30 +0000543 return HadErrors;
544}