blob: 3fba6905e1ef9208b1590cd87922c0c9c13901de [file] [log] [blame]
David Blaikie8c0b3782012-06-06 18:52:13 +00001//===--- InclusionRewriter.cpp - Rewrite includes into their expansions ---===//
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 code rewrites include invocations into their expansions. This gives you
11// a file with all included files merged into it.
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek305c6132012-09-01 05:09:24 +000015#include "clang/Rewrite/Frontend/Rewriters.h"
David Blaikie8c0b3782012-06-06 18:52:13 +000016#include "clang/Basic/SourceManager.h"
17#include "clang/Frontend/PreprocessorOutputOptions.h"
Benjamin Kramer596eea72013-04-16 19:08:41 +000018#include "clang/Lex/HeaderSearch.h"
Lubos Lunak8ee6a0d2013-07-20 14:30:01 +000019#include "clang/Lex/Pragma.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Lex/Preprocessor.h"
Benjamin Kramer596eea72013-04-16 19:08:41 +000021#include "llvm/ADT/SmallString.h"
David Blaikie8c0b3782012-06-06 18:52:13 +000022#include "llvm/Support/raw_ostream.h"
23
24using namespace clang;
25using namespace llvm;
26
27namespace {
28
29class InclusionRewriter : public PPCallbacks {
30 /// Information about which #includes were actually performed,
31 /// created by preprocessor callbacks.
32 struct FileChange {
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +000033 const Module *Mod;
David Blaikie8c0b3782012-06-06 18:52:13 +000034 SourceLocation From;
35 FileID Id;
36 SrcMgr::CharacteristicKind FileType;
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +000037 FileChange(SourceLocation From, const Module *Mod) : Mod(Mod), From(From) {
David Blaikie8c0b3782012-06-06 18:52:13 +000038 }
39 };
Dmitri Gribenko49fdccb2012-06-08 23:13:42 +000040 Preprocessor &PP; ///< Used to find inclusion directives.
41 SourceManager &SM; ///< Used to read and manage source files.
42 raw_ostream &OS; ///< The destination stream for rewritten contents.
Argyrios Kyrtzidise9512e22013-07-26 15:32:04 +000043 const llvm::MemoryBuffer *PredefinesBuffer; ///< The preprocessor predefines.
Dmitri Gribenko49fdccb2012-06-08 23:13:42 +000044 bool ShowLineMarkers; ///< Show #line markers.
45 bool UseLineDirective; ///< Use of line directives or line markers.
David Blaikie8c0b3782012-06-06 18:52:13 +000046 typedef std::map<unsigned, FileChange> FileChangeMap;
Dmitri Gribenko959dc842013-02-16 22:21:38 +000047 FileChangeMap FileChanges; ///< Tracks which files were included where.
David Blaikie8c0b3782012-06-06 18:52:13 +000048 /// Used transitively for building up the FileChanges mapping over the
49 /// various \c PPCallbacks callbacks.
50 FileChangeMap::iterator LastInsertedFileChange;
51public:
52 InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers);
53 bool Process(FileID FileId, SrcMgr::CharacteristicKind FileType);
Argyrios Kyrtzidise9512e22013-07-26 15:32:04 +000054 void setPredefinesBuffer(const llvm::MemoryBuffer *Buf) {
55 PredefinesBuffer = Buf;
56 }
David Blaikie8c0b3782012-06-06 18:52:13 +000057private:
58 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
59 SrcMgr::CharacteristicKind FileType,
60 FileID PrevFID);
61 virtual void FileSkipped(const FileEntry &ParentFile,
62 const Token &FilenameTok,
63 SrcMgr::CharacteristicKind FileType);
64 virtual void InclusionDirective(SourceLocation HashLoc,
65 const Token &IncludeTok,
66 StringRef FileName,
67 bool IsAngled,
Argyrios Kyrtzidisda313592012-09-27 01:42:07 +000068 CharSourceRange FilenameRange,
David Blaikie8c0b3782012-06-06 18:52:13 +000069 const FileEntry *File,
David Blaikie8c0b3782012-06-06 18:52:13 +000070 StringRef SearchPath,
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +000071 StringRef RelativePath,
72 const Module *Imported);
David Blaikie8c0b3782012-06-06 18:52:13 +000073 void WriteLineInfo(const char *Filename, int Line,
74 SrcMgr::CharacteristicKind FileType,
75 StringRef EOL, StringRef Extra = StringRef());
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +000076 void WriteImplicitModuleImport(const Module *Mod, StringRef EOL);
David Blaikie8c0b3782012-06-06 18:52:13 +000077 void OutputContentUpTo(const MemoryBuffer &FromFile,
78 unsigned &WriteFrom, unsigned WriteTo,
79 StringRef EOL, int &lines,
80 bool EnsureNewline = false);
81 void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken,
82 const MemoryBuffer &FromFile, StringRef EOL,
83 unsigned &NextToWrite, int &Lines);
Benjamin Kramer596eea72013-04-16 19:08:41 +000084 bool HandleHasInclude(FileID FileId, Lexer &RawLex,
85 const DirectoryLookup *Lookup, Token &Tok,
86 bool &FileExists);
David Blaikie8c0b3782012-06-06 18:52:13 +000087 const FileChange *FindFileChangeLocation(SourceLocation Loc) const;
88 StringRef NextIdentifierName(Lexer &RawLex, Token &RawToken);
89};
90
91} // end anonymous namespace
92
93/// Initializes an InclusionRewriter with a \p PP source and \p OS destination.
94InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS,
95 bool ShowLineMarkers)
Argyrios Kyrtzidise9512e22013-07-26 15:32:04 +000096 : PP(PP), SM(PP.getSourceManager()), OS(OS), PredefinesBuffer(0),
David Blaikie8c0b3782012-06-06 18:52:13 +000097 ShowLineMarkers(ShowLineMarkers),
98 LastInsertedFileChange(FileChanges.end()) {
99 // If we're in microsoft mode, use normal #line instead of line markers.
100 UseLineDirective = PP.getLangOpts().MicrosoftExt;
101}
102
103/// Write appropriate line information as either #line directives or GNU line
104/// markers depending on what mode we're in, including the \p Filename and
105/// \p Line we are located at, using the specified \p EOL line separator, and
106/// any \p Extra context specifiers in GNU line directives.
107void InclusionRewriter::WriteLineInfo(const char *Filename, int Line,
108 SrcMgr::CharacteristicKind FileType,
109 StringRef EOL, StringRef Extra) {
110 if (!ShowLineMarkers)
111 return;
112 if (UseLineDirective) {
113 OS << "#line" << ' ' << Line << ' ' << '"' << Filename << '"';
114 } else {
115 // Use GNU linemarkers as described here:
116 // http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html
Eli Friedman3432b782013-08-29 01:42:42 +0000117 OS << '#' << ' ' << Line << ' ' << '"';
118 OS.write_escaped(Filename);
119 OS << '"';
David Blaikie8c0b3782012-06-06 18:52:13 +0000120 if (!Extra.empty())
121 OS << Extra;
122 if (FileType == SrcMgr::C_System)
123 // "`3' This indicates that the following text comes from a system header
124 // file, so certain warnings should be suppressed."
125 OS << " 3";
126 else if (FileType == SrcMgr::C_ExternCSystem)
127 // as above for `3', plus "`4' This indicates that the following text
128 // should be treated as being wrapped in an implicit extern "C" block."
129 OS << " 3 4";
130 }
131 OS << EOL;
132}
133
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000134void InclusionRewriter::WriteImplicitModuleImport(const Module *Mod,
135 StringRef EOL) {
136 OS << "@import " << Mod->getFullModuleName() << ";"
137 << " /* clang -frewrite-includes: implicit import */" << EOL;
138}
139
David Blaikie8c0b3782012-06-06 18:52:13 +0000140/// FileChanged - Whenever the preprocessor enters or exits a #include file
141/// it invokes this handler.
142void InclusionRewriter::FileChanged(SourceLocation Loc,
143 FileChangeReason Reason,
144 SrcMgr::CharacteristicKind NewFileType,
145 FileID) {
146 if (Reason != EnterFile)
147 return;
148 if (LastInsertedFileChange == FileChanges.end())
149 // we didn't reach this file (eg: the main file) via an inclusion directive
150 return;
151 LastInsertedFileChange->second.Id = FullSourceLoc(Loc, SM).getFileID();
152 LastInsertedFileChange->second.FileType = NewFileType;
153 LastInsertedFileChange = FileChanges.end();
154}
155
156/// Called whenever an inclusion is skipped due to canonical header protection
157/// macros.
158void InclusionRewriter::FileSkipped(const FileEntry &/*ParentFile*/,
159 const Token &/*FilenameTok*/,
160 SrcMgr::CharacteristicKind /*FileType*/) {
161 assert(LastInsertedFileChange != FileChanges.end() && "A file, that wasn't "
162 "found via an inclusion directive, was skipped");
163 FileChanges.erase(LastInsertedFileChange);
164 LastInsertedFileChange = FileChanges.end();
165}
166
167/// This should be called whenever the preprocessor encounters include
168/// directives. It does not say whether the file has been included, but it
169/// provides more information about the directive (hash location instead
170/// of location inside the included file). It is assumed that the matching
171/// FileChanged() or FileSkipped() is called after this.
172void InclusionRewriter::InclusionDirective(SourceLocation HashLoc,
173 const Token &/*IncludeTok*/,
174 StringRef /*FileName*/,
175 bool /*IsAngled*/,
Argyrios Kyrtzidisda313592012-09-27 01:42:07 +0000176 CharSourceRange /*FilenameRange*/,
David Blaikie8c0b3782012-06-06 18:52:13 +0000177 const FileEntry * /*File*/,
David Blaikie8c0b3782012-06-06 18:52:13 +0000178 StringRef /*SearchPath*/,
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +0000179 StringRef /*RelativePath*/,
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000180 const Module *Imported) {
David Blaikie8c0b3782012-06-06 18:52:13 +0000181 assert(LastInsertedFileChange == FileChanges.end() && "Another inclusion "
182 "directive was found before the previous one was processed");
183 std::pair<FileChangeMap::iterator, bool> p = FileChanges.insert(
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000184 std::make_pair(HashLoc.getRawEncoding(), FileChange(HashLoc, Imported)));
David Blaikie8c0b3782012-06-06 18:52:13 +0000185 assert(p.second && "Unexpected revisitation of the same include directive");
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000186 if (!Imported)
187 LastInsertedFileChange = p.first;
David Blaikie8c0b3782012-06-06 18:52:13 +0000188}
189
190/// Simple lookup for a SourceLocation (specifically one denoting the hash in
191/// an inclusion directive) in the map of inclusion information, FileChanges.
192const InclusionRewriter::FileChange *
193InclusionRewriter::FindFileChangeLocation(SourceLocation Loc) const {
194 FileChangeMap::const_iterator I = FileChanges.find(Loc.getRawEncoding());
195 if (I != FileChanges.end())
196 return &I->second;
197 return NULL;
198}
199
David Blaikie8c0b3782012-06-06 18:52:13 +0000200/// Detect the likely line ending style of \p FromFile by examining the first
201/// newline found within it.
202static StringRef DetectEOL(const MemoryBuffer &FromFile) {
203 // detect what line endings the file uses, so that added content does not mix
204 // the style
205 const char *Pos = strchr(FromFile.getBufferStart(), '\n');
206 if (Pos == NULL)
207 return "\n";
208 if (Pos + 1 < FromFile.getBufferEnd() && Pos[1] == '\r')
209 return "\n\r";
210 if (Pos - 1 >= FromFile.getBufferStart() && Pos[-1] == '\r')
211 return "\r\n";
212 return "\n";
213}
214
215/// Writes out bytes from \p FromFile, starting at \p NextToWrite and ending at
216/// \p WriteTo - 1.
217void InclusionRewriter::OutputContentUpTo(const MemoryBuffer &FromFile,
218 unsigned &WriteFrom, unsigned WriteTo,
219 StringRef EOL, int &Line,
220 bool EnsureNewline) {
221 if (WriteTo <= WriteFrom)
222 return;
Argyrios Kyrtzidise9512e22013-07-26 15:32:04 +0000223 if (&FromFile == PredefinesBuffer) {
224 // Ignore the #defines of the predefines buffer.
225 WriteFrom = WriteTo;
226 return;
227 }
David Blaikie8c0b3782012-06-06 18:52:13 +0000228 OS.write(FromFile.getBufferStart() + WriteFrom, WriteTo - WriteFrom);
229 // count lines manually, it's faster than getPresumedLoc()
Benjamin Kramer31598192012-06-09 13:18:14 +0000230 Line += std::count(FromFile.getBufferStart() + WriteFrom,
231 FromFile.getBufferStart() + WriteTo, '\n');
David Blaikie8c0b3782012-06-06 18:52:13 +0000232 if (EnsureNewline) {
233 char LastChar = FromFile.getBufferStart()[WriteTo - 1];
234 if (LastChar != '\n' && LastChar != '\r')
235 OS << EOL;
236 }
237 WriteFrom = WriteTo;
238}
239
240/// Print characters from \p FromFile starting at \p NextToWrite up until the
241/// inclusion directive at \p StartToken, then print out the inclusion
242/// inclusion directive disabled by a #if directive, updating \p NextToWrite
243/// and \p Line to track the number of source lines visited and the progress
244/// through the \p FromFile buffer.
245void InclusionRewriter::CommentOutDirective(Lexer &DirectiveLex,
246 const Token &StartToken,
247 const MemoryBuffer &FromFile,
248 StringRef EOL,
249 unsigned &NextToWrite, int &Line) {
250 OutputContentUpTo(FromFile, NextToWrite,
251 SM.getFileOffset(StartToken.getLocation()), EOL, Line);
252 Token DirectiveToken;
253 do {
254 DirectiveLex.LexFromRawLexer(DirectiveToken);
255 } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof));
David Blaikie60ad16b2012-06-14 17:36:01 +0000256 OS << "#if 0 /* expanded by -frewrite-includes */" << EOL;
David Blaikie8c0b3782012-06-06 18:52:13 +0000257 OutputContentUpTo(FromFile, NextToWrite,
258 SM.getFileOffset(DirectiveToken.getLocation()) + DirectiveToken.getLength(),
259 EOL, Line);
David Blaikie60ad16b2012-06-14 17:36:01 +0000260 OS << "#endif /* expanded by -frewrite-includes */" << EOL;
David Blaikie8c0b3782012-06-06 18:52:13 +0000261}
262
263/// Find the next identifier in the pragma directive specified by \p RawToken.
264StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex,
265 Token &RawToken) {
266 RawLex.LexFromRawLexer(RawToken);
267 if (RawToken.is(tok::raw_identifier))
268 PP.LookUpIdentifierInfo(RawToken);
269 if (RawToken.is(tok::identifier))
270 return RawToken.getIdentifierInfo()->getName();
271 return StringRef();
272}
273
Benjamin Kramer596eea72013-04-16 19:08:41 +0000274// Expand __has_include and __has_include_next if possible. If there's no
275// definitive answer return false.
276bool InclusionRewriter::HandleHasInclude(
277 FileID FileId, Lexer &RawLex, const DirectoryLookup *Lookup, Token &Tok,
278 bool &FileExists) {
279 // Lex the opening paren.
280 RawLex.LexFromRawLexer(Tok);
281 if (Tok.isNot(tok::l_paren))
282 return false;
283
284 RawLex.LexFromRawLexer(Tok);
285
286 SmallString<128> FilenameBuffer;
287 StringRef Filename;
288 // Since the raw lexer doesn't give us angle_literals we have to parse them
289 // ourselves.
290 // FIXME: What to do if the file name is a macro?
291 if (Tok.is(tok::less)) {
292 RawLex.LexFromRawLexer(Tok);
293
294 FilenameBuffer += '<';
295 do {
296 if (Tok.is(tok::eod)) // Sanity check.
297 return false;
298
299 if (Tok.is(tok::raw_identifier))
300 PP.LookUpIdentifierInfo(Tok);
301
302 // Get the string piece.
303 SmallVector<char, 128> TmpBuffer;
304 bool Invalid = false;
305 StringRef TmpName = PP.getSpelling(Tok, TmpBuffer, &Invalid);
306 if (Invalid)
307 return false;
308
309 FilenameBuffer += TmpName;
310
311 RawLex.LexFromRawLexer(Tok);
312 } while (Tok.isNot(tok::greater));
313
314 FilenameBuffer += '>';
315 Filename = FilenameBuffer;
316 } else {
317 if (Tok.isNot(tok::string_literal))
318 return false;
319
320 bool Invalid = false;
321 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
322 if (Invalid)
323 return false;
324 }
325
326 // Lex the closing paren.
327 RawLex.LexFromRawLexer(Tok);
328 if (Tok.isNot(tok::r_paren))
329 return false;
330
331 // Now ask HeaderInfo if it knows about the header.
332 // FIXME: Subframeworks aren't handled here. Do we care?
333 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
334 const DirectoryLookup *CurDir;
335 const FileEntry *File = PP.getHeaderSearchInfo().LookupFile(
336 Filename, isAngled, 0, CurDir,
337 PP.getSourceManager().getFileEntryForID(FileId), 0, 0, 0, false);
338
339 FileExists = File != 0;
340 return true;
341}
342
David Blaikie8c0b3782012-06-06 18:52:13 +0000343/// Use a raw lexer to analyze \p FileId, inccrementally copying parts of it
344/// and including content of included files recursively.
345bool InclusionRewriter::Process(FileID FileId,
346 SrcMgr::CharacteristicKind FileType)
347{
348 bool Invalid;
349 const MemoryBuffer &FromFile = *SM.getBuffer(FileId, &Invalid);
David Blaikiebae2b312012-06-14 17:36:05 +0000350 if (Invalid) // invalid inclusion
Argyrios Kyrtzidis507d4962013-04-10 01:53:37 +0000351 return false;
David Blaikie8c0b3782012-06-06 18:52:13 +0000352 const char *FileName = FromFile.getBufferIdentifier();
353 Lexer RawLex(FileId, &FromFile, PP.getSourceManager(), PP.getLangOpts());
354 RawLex.SetCommentRetentionState(false);
355
356 StringRef EOL = DetectEOL(FromFile);
357
358 // Per the GNU docs: "1" indicates the start of a new file.
359 WriteLineInfo(FileName, 1, FileType, EOL, " 1");
360
361 if (SM.getFileIDSize(FileId) == 0)
Argyrios Kyrtzidis507d4962013-04-10 01:53:37 +0000362 return false;
David Blaikie8c0b3782012-06-06 18:52:13 +0000363
364 // The next byte to be copied from the source file
365 unsigned NextToWrite = 0;
366 int Line = 1; // The current input file line number.
367
368 Token RawToken;
369 RawLex.LexFromRawLexer(RawToken);
370
371 // TODO: Consider adding a switch that strips possibly unimportant content,
372 // such as comments, to reduce the size of repro files.
373 while (RawToken.isNot(tok::eof)) {
374 if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) {
375 RawLex.setParsingPreprocessorDirective(true);
376 Token HashToken = RawToken;
377 RawLex.LexFromRawLexer(RawToken);
378 if (RawToken.is(tok::raw_identifier))
379 PP.LookUpIdentifierInfo(RawToken);
Lubos Lunakce6af112013-07-20 14:23:27 +0000380 if (RawToken.getIdentifierInfo() != NULL) {
David Blaikie8c0b3782012-06-06 18:52:13 +0000381 switch (RawToken.getIdentifierInfo()->getPPKeywordID()) {
382 case tok::pp_include:
383 case tok::pp_include_next:
384 case tok::pp_import: {
385 CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite,
386 Line);
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000387 StringRef LineInfoExtra;
David Blaikie8c0b3782012-06-06 18:52:13 +0000388 if (const FileChange *Change = FindFileChangeLocation(
389 HashToken.getLocation())) {
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000390 if (Change->Mod) {
391 WriteImplicitModuleImport(Change->Mod, EOL);
392
393 // else now include and recursively process the file
394 } else if (Process(Change->Id, Change->FileType)) {
David Blaikie8c0b3782012-06-06 18:52:13 +0000395 // and set lineinfo back to this file, if the nested one was
396 // actually included
397 // `2' indicates returning to a file (after having included
398 // another file.
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000399 LineInfoExtra = " 2";
Argyrios Kyrtzidis507d4962013-04-10 01:53:37 +0000400 }
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000401 }
402 // fix up lineinfo (since commented out directive changed line
403 // numbers) for inclusions that were skipped due to header guards
404 WriteLineInfo(FileName, Line, FileType, EOL, LineInfoExtra);
David Blaikie8c0b3782012-06-06 18:52:13 +0000405 break;
406 }
407 case tok::pp_pragma: {
408 StringRef Identifier = NextIdentifierName(RawLex, RawToken);
409 if (Identifier == "clang" || Identifier == "GCC") {
410 if (NextIdentifierName(RawLex, RawToken) == "system_header") {
411 // keep the directive in, commented out
412 CommentOutDirective(RawLex, HashToken, FromFile, EOL,
413 NextToWrite, Line);
414 // update our own type
415 FileType = SM.getFileCharacteristic(RawToken.getLocation());
416 WriteLineInfo(FileName, Line, FileType, EOL);
417 }
418 } else if (Identifier == "once") {
419 // keep the directive in, commented out
420 CommentOutDirective(RawLex, HashToken, FromFile, EOL,
421 NextToWrite, Line);
422 WriteLineInfo(FileName, Line, FileType, EOL);
423 }
424 break;
425 }
Benjamin Kramer596eea72013-04-16 19:08:41 +0000426 case tok::pp_if:
Lubos Lunakce6af112013-07-20 14:23:27 +0000427 case tok::pp_elif: {
428 bool elif = (RawToken.getIdentifierInfo()->getPPKeywordID() ==
429 tok::pp_elif);
Benjamin Kramer596eea72013-04-16 19:08:41 +0000430 // Rewrite special builtin macros to avoid pulling in host details.
431 do {
432 // Walk over the directive.
433 RawLex.LexFromRawLexer(RawToken);
434 if (RawToken.is(tok::raw_identifier))
435 PP.LookUpIdentifierInfo(RawToken);
436
437 if (RawToken.is(tok::identifier)) {
438 bool HasFile;
439 SourceLocation Loc = RawToken.getLocation();
440
441 // Rewrite __has_include(x)
442 if (RawToken.getIdentifierInfo()->isStr("__has_include")) {
443 if (!HandleHasInclude(FileId, RawLex, 0, RawToken, HasFile))
444 continue;
445 // Rewrite __has_include_next(x)
446 } else if (RawToken.getIdentifierInfo()->isStr(
447 "__has_include_next")) {
448 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
449 if (Lookup)
450 ++Lookup;
451
452 if (!HandleHasInclude(FileId, RawLex, Lookup, RawToken,
453 HasFile))
454 continue;
455 } else {
456 continue;
457 }
458 // Replace the macro with (0) or (1), followed by the commented
459 // out macro for reference.
460 OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(Loc),
461 EOL, Line);
462 OS << '(' << (int) HasFile << ")/*";
463 OutputContentUpTo(FromFile, NextToWrite,
464 SM.getFileOffset(RawToken.getLocation()) +
465 RawToken.getLength(),
466 EOL, Line);
467 OS << "*/";
468 }
469 } while (RawToken.isNot(tok::eod));
Lubos Lunakce6af112013-07-20 14:23:27 +0000470 if (elif) {
471 OutputContentUpTo(FromFile, NextToWrite,
472 SM.getFileOffset(RawToken.getLocation()) +
473 RawToken.getLength(),
474 EOL, Line, /*EnsureNewLine*/ true);
475 WriteLineInfo(FileName, Line, FileType, EOL);
476 }
Benjamin Kramer596eea72013-04-16 19:08:41 +0000477 break;
Lubos Lunakce6af112013-07-20 14:23:27 +0000478 }
479 case tok::pp_endif:
480 case tok::pp_else: {
481 // We surround every #include by #if 0 to comment it out, but that
482 // changes line numbers. These are fixed up right after that, but
483 // the whole #include could be inside a preprocessor conditional
484 // that is not processed. So it is necessary to fix the line
485 // numbers one the next line after each #else/#endif as well.
486 RawLex.SetKeepWhitespaceMode(true);
487 do {
488 RawLex.LexFromRawLexer(RawToken);
489 } while (RawToken.isNot(tok::eod) && RawToken.isNot(tok::eof));
490 OutputContentUpTo(
491 FromFile, NextToWrite,
492 SM.getFileOffset(RawToken.getLocation()) + RawToken.getLength(),
493 EOL, Line, /*EnsureNewLine*/ true);
494 WriteLineInfo(FileName, Line, FileType, EOL);
495 RawLex.SetKeepWhitespaceMode(false);
496 }
David Blaikie8c0b3782012-06-06 18:52:13 +0000497 default:
498 break;
499 }
500 }
501 RawLex.setParsingPreprocessorDirective(false);
502 }
503 RawLex.LexFromRawLexer(RawToken);
504 }
505 OutputContentUpTo(FromFile, NextToWrite,
Argyrios Kyrtzidisb18840d2013-05-07 04:29:22 +0000506 SM.getFileOffset(SM.getLocForEndOfFile(FileId)), EOL, Line,
David Blaikie8c0b3782012-06-06 18:52:13 +0000507 /*EnsureNewline*/true);
508 return true;
509}
510
David Blaikie60ad16b2012-06-14 17:36:01 +0000511/// InclusionRewriterInInput - Implement -frewrite-includes mode.
David Blaikie8c0b3782012-06-06 18:52:13 +0000512void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS,
513 const PreprocessorOutputOptions &Opts) {
514 SourceManager &SM = PP.getSourceManager();
515 InclusionRewriter *Rewrite = new InclusionRewriter(PP, *OS,
516 Opts.ShowLineMarkers);
517 PP.addPPCallbacks(Rewrite);
Lubos Lunak8ee6a0d2013-07-20 14:30:01 +0000518 // Ignore all pragmas, otherwise there will be warnings about unknown pragmas
519 // (because there's nothing to handle them).
520 PP.AddPragmaHandler(new EmptyPragmaHandler());
521 // Ignore also all pragma in all namespaces created
522 // in Preprocessor::RegisterBuiltinPragmas().
523 PP.AddPragmaHandler("GCC", new EmptyPragmaHandler());
524 PP.AddPragmaHandler("clang", new EmptyPragmaHandler());
David Blaikie8c0b3782012-06-06 18:52:13 +0000525
526 // First let the preprocessor process the entire file and call callbacks.
527 // Callbacks will record which #include's were actually performed.
528 PP.EnterMainSourceFile();
529 Token Tok;
530 // Only preprocessor directives matter here, so disable macro expansion
531 // everywhere else as an optimization.
532 // TODO: It would be even faster if the preprocessor could be switched
533 // to a mode where it would parse only preprocessor directives and comments,
534 // nothing else matters for parsing or processing.
535 PP.SetMacroExpansionOnlyInDirectives();
536 do {
537 PP.Lex(Tok);
538 } while (Tok.isNot(tok::eof));
Argyrios Kyrtzidise9512e22013-07-26 15:32:04 +0000539 Rewrite->setPredefinesBuffer(SM.getBuffer(PP.getPredefinesFileID()));
540 Rewrite->Process(PP.getPredefinesFileID(), SrcMgr::C_User);
David Blaikie8c0b3782012-06-06 18:52:13 +0000541 Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User);
542 OS->flush();
543}