blob: d6a434d80adbc036de6645aab1d11eed47128637 [file] [log] [blame]
David Blaikied5321242012-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 Kremenekcdf81492012-09-01 05:09:24 +000015#include "clang/Rewrite/Frontend/Rewriters.h"
David Blaikied5321242012-06-06 18:52:13 +000016#include "clang/Basic/SourceManager.h"
17#include "clang/Frontend/PreprocessorOutputOptions.h"
Benjamin Kramerb10e6152013-04-16 19:08:41 +000018#include "clang/Lex/HeaderSearch.h"
Lubos Lunakba5ee4d2013-07-20 14:30:01 +000019#include "clang/Lex/Pragma.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Lex/Preprocessor.h"
Benjamin Kramerb10e6152013-04-16 19:08:41 +000021#include "llvm/ADT/SmallString.h"
David Blaikied5321242012-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 Kyrtzidiscf22d1f2013-04-10 01:53:50 +000033 const Module *Mod;
David Blaikied5321242012-06-06 18:52:13 +000034 SourceLocation From;
35 FileID Id;
36 SrcMgr::CharacteristicKind FileType;
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +000037 FileChange(SourceLocation From, const Module *Mod) : Mod(Mod), From(From) {
David Blaikied5321242012-06-06 18:52:13 +000038 }
39 };
Dmitri Gribenko4280e5c2012-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 Kyrtzidis17ff2e52013-07-26 15:32:04 +000043 const llvm::MemoryBuffer *PredefinesBuffer; ///< The preprocessor predefines.
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +000044 bool ShowLineMarkers; ///< Show #line markers.
45 bool UseLineDirective; ///< Use of line directives or line markers.
David Blaikied5321242012-06-06 18:52:13 +000046 typedef std::map<unsigned, FileChange> FileChangeMap;
Dmitri Gribenko20b16ac2013-02-16 22:21:38 +000047 FileChangeMap FileChanges; ///< Tracks which files were included where.
David Blaikied5321242012-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 Kyrtzidis17ff2e52013-07-26 15:32:04 +000054 void setPredefinesBuffer(const llvm::MemoryBuffer *Buf) {
55 PredefinesBuffer = Buf;
56 }
David Blaikied5321242012-06-06 18:52:13 +000057private:
Craig Topperfb6b25b2014-03-15 04:29:04 +000058 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
59 SrcMgr::CharacteristicKind FileType,
60 FileID PrevFID) override;
61 void FileSkipped(const FileEntry &ParentFile, const Token &FilenameTok,
62 SrcMgr::CharacteristicKind FileType) override;
63 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
64 StringRef FileName, bool IsAngled,
65 CharSourceRange FilenameRange, const FileEntry *File,
66 StringRef SearchPath, StringRef RelativePath,
67 const Module *Imported) override;
David Blaikied5321242012-06-06 18:52:13 +000068 void WriteLineInfo(const char *Filename, int Line,
69 SrcMgr::CharacteristicKind FileType,
70 StringRef EOL, StringRef Extra = StringRef());
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +000071 void WriteImplicitModuleImport(const Module *Mod, StringRef EOL);
David Blaikied5321242012-06-06 18:52:13 +000072 void OutputContentUpTo(const MemoryBuffer &FromFile,
73 unsigned &WriteFrom, unsigned WriteTo,
74 StringRef EOL, int &lines,
Alp Toker08c25002013-12-13 17:04:55 +000075 bool EnsureNewline);
David Blaikied5321242012-06-06 18:52:13 +000076 void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken,
77 const MemoryBuffer &FromFile, StringRef EOL,
78 unsigned &NextToWrite, int &Lines);
Benjamin Kramerb10e6152013-04-16 19:08:41 +000079 bool HandleHasInclude(FileID FileId, Lexer &RawLex,
80 const DirectoryLookup *Lookup, Token &Tok,
81 bool &FileExists);
David Blaikied5321242012-06-06 18:52:13 +000082 const FileChange *FindFileChangeLocation(SourceLocation Loc) const;
83 StringRef NextIdentifierName(Lexer &RawLex, Token &RawToken);
84};
85
86} // end anonymous namespace
87
88/// Initializes an InclusionRewriter with a \p PP source and \p OS destination.
89InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS,
90 bool ShowLineMarkers)
Argyrios Kyrtzidis17ff2e52013-07-26 15:32:04 +000091 : PP(PP), SM(PP.getSourceManager()), OS(OS), PredefinesBuffer(0),
David Blaikied5321242012-06-06 18:52:13 +000092 ShowLineMarkers(ShowLineMarkers),
93 LastInsertedFileChange(FileChanges.end()) {
94 // If we're in microsoft mode, use normal #line instead of line markers.
95 UseLineDirective = PP.getLangOpts().MicrosoftExt;
96}
97
98/// Write appropriate line information as either #line directives or GNU line
99/// markers depending on what mode we're in, including the \p Filename and
100/// \p Line we are located at, using the specified \p EOL line separator, and
101/// any \p Extra context specifiers in GNU line directives.
102void InclusionRewriter::WriteLineInfo(const char *Filename, int Line,
103 SrcMgr::CharacteristicKind FileType,
104 StringRef EOL, StringRef Extra) {
105 if (!ShowLineMarkers)
106 return;
107 if (UseLineDirective) {
Eli Friedman9fc443a2013-09-17 00:51:31 +0000108 OS << "#line" << ' ' << Line << ' ' << '"';
109 OS.write_escaped(Filename);
110 OS << '"';
David Blaikied5321242012-06-06 18:52:13 +0000111 } else {
112 // Use GNU linemarkers as described here:
113 // http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html
Eli Friedman80e45b82013-08-29 01:42:42 +0000114 OS << '#' << ' ' << Line << ' ' << '"';
115 OS.write_escaped(Filename);
116 OS << '"';
David Blaikied5321242012-06-06 18:52:13 +0000117 if (!Extra.empty())
118 OS << Extra;
119 if (FileType == SrcMgr::C_System)
120 // "`3' This indicates that the following text comes from a system header
121 // file, so certain warnings should be suppressed."
122 OS << " 3";
123 else if (FileType == SrcMgr::C_ExternCSystem)
124 // as above for `3', plus "`4' This indicates that the following text
125 // should be treated as being wrapped in an implicit extern "C" block."
126 OS << " 3 4";
127 }
128 OS << EOL;
129}
130
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000131void InclusionRewriter::WriteImplicitModuleImport(const Module *Mod,
132 StringRef EOL) {
133 OS << "@import " << Mod->getFullModuleName() << ";"
134 << " /* clang -frewrite-includes: implicit import */" << EOL;
135}
136
David Blaikied5321242012-06-06 18:52:13 +0000137/// FileChanged - Whenever the preprocessor enters or exits a #include file
138/// it invokes this handler.
139void InclusionRewriter::FileChanged(SourceLocation Loc,
140 FileChangeReason Reason,
141 SrcMgr::CharacteristicKind NewFileType,
142 FileID) {
143 if (Reason != EnterFile)
144 return;
145 if (LastInsertedFileChange == FileChanges.end())
146 // we didn't reach this file (eg: the main file) via an inclusion directive
147 return;
148 LastInsertedFileChange->second.Id = FullSourceLoc(Loc, SM).getFileID();
149 LastInsertedFileChange->second.FileType = NewFileType;
150 LastInsertedFileChange = FileChanges.end();
151}
152
153/// Called whenever an inclusion is skipped due to canonical header protection
154/// macros.
155void InclusionRewriter::FileSkipped(const FileEntry &/*ParentFile*/,
156 const Token &/*FilenameTok*/,
157 SrcMgr::CharacteristicKind /*FileType*/) {
158 assert(LastInsertedFileChange != FileChanges.end() && "A file, that wasn't "
159 "found via an inclusion directive, was skipped");
160 FileChanges.erase(LastInsertedFileChange);
161 LastInsertedFileChange = FileChanges.end();
162}
163
164/// This should be called whenever the preprocessor encounters include
165/// directives. It does not say whether the file has been included, but it
166/// provides more information about the directive (hash location instead
167/// of location inside the included file). It is assumed that the matching
168/// FileChanged() or FileSkipped() is called after this.
169void InclusionRewriter::InclusionDirective(SourceLocation HashLoc,
170 const Token &/*IncludeTok*/,
171 StringRef /*FileName*/,
172 bool /*IsAngled*/,
Argyrios Kyrtzidis4fcd2882012-09-27 01:42:07 +0000173 CharSourceRange /*FilenameRange*/,
David Blaikied5321242012-06-06 18:52:13 +0000174 const FileEntry * /*File*/,
David Blaikied5321242012-06-06 18:52:13 +0000175 StringRef /*SearchPath*/,
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000176 StringRef /*RelativePath*/,
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000177 const Module *Imported) {
David Blaikied5321242012-06-06 18:52:13 +0000178 assert(LastInsertedFileChange == FileChanges.end() && "Another inclusion "
179 "directive was found before the previous one was processed");
180 std::pair<FileChangeMap::iterator, bool> p = FileChanges.insert(
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000181 std::make_pair(HashLoc.getRawEncoding(), FileChange(HashLoc, Imported)));
David Blaikied5321242012-06-06 18:52:13 +0000182 assert(p.second && "Unexpected revisitation of the same include directive");
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000183 if (!Imported)
184 LastInsertedFileChange = p.first;
David Blaikied5321242012-06-06 18:52:13 +0000185}
186
187/// Simple lookup for a SourceLocation (specifically one denoting the hash in
188/// an inclusion directive) in the map of inclusion information, FileChanges.
189const InclusionRewriter::FileChange *
190InclusionRewriter::FindFileChangeLocation(SourceLocation Loc) const {
191 FileChangeMap::const_iterator I = FileChanges.find(Loc.getRawEncoding());
192 if (I != FileChanges.end())
193 return &I->second;
194 return NULL;
195}
196
David Blaikied5321242012-06-06 18:52:13 +0000197/// Detect the likely line ending style of \p FromFile by examining the first
198/// newline found within it.
199static StringRef DetectEOL(const MemoryBuffer &FromFile) {
200 // detect what line endings the file uses, so that added content does not mix
201 // the style
202 const char *Pos = strchr(FromFile.getBufferStart(), '\n');
203 if (Pos == NULL)
204 return "\n";
205 if (Pos + 1 < FromFile.getBufferEnd() && Pos[1] == '\r')
206 return "\n\r";
207 if (Pos - 1 >= FromFile.getBufferStart() && Pos[-1] == '\r')
208 return "\r\n";
209 return "\n";
210}
211
212/// Writes out bytes from \p FromFile, starting at \p NextToWrite and ending at
213/// \p WriteTo - 1.
214void InclusionRewriter::OutputContentUpTo(const MemoryBuffer &FromFile,
215 unsigned &WriteFrom, unsigned WriteTo,
216 StringRef EOL, int &Line,
217 bool EnsureNewline) {
218 if (WriteTo <= WriteFrom)
219 return;
Argyrios Kyrtzidis17ff2e52013-07-26 15:32:04 +0000220 if (&FromFile == PredefinesBuffer) {
221 // Ignore the #defines of the predefines buffer.
222 WriteFrom = WriteTo;
223 return;
224 }
David Blaikied5321242012-06-06 18:52:13 +0000225 OS.write(FromFile.getBufferStart() + WriteFrom, WriteTo - WriteFrom);
226 // count lines manually, it's faster than getPresumedLoc()
Benjamin Kramer71326382012-06-09 13:18:14 +0000227 Line += std::count(FromFile.getBufferStart() + WriteFrom,
228 FromFile.getBufferStart() + WriteTo, '\n');
David Blaikied5321242012-06-06 18:52:13 +0000229 if (EnsureNewline) {
230 char LastChar = FromFile.getBufferStart()[WriteTo - 1];
231 if (LastChar != '\n' && LastChar != '\r')
232 OS << EOL;
233 }
234 WriteFrom = WriteTo;
235}
236
237/// Print characters from \p FromFile starting at \p NextToWrite up until the
238/// inclusion directive at \p StartToken, then print out the inclusion
239/// inclusion directive disabled by a #if directive, updating \p NextToWrite
240/// and \p Line to track the number of source lines visited and the progress
241/// through the \p FromFile buffer.
242void InclusionRewriter::CommentOutDirective(Lexer &DirectiveLex,
243 const Token &StartToken,
244 const MemoryBuffer &FromFile,
245 StringRef EOL,
246 unsigned &NextToWrite, int &Line) {
247 OutputContentUpTo(FromFile, NextToWrite,
Alp Toker08c25002013-12-13 17:04:55 +0000248 SM.getFileOffset(StartToken.getLocation()), EOL, Line, false);
David Blaikied5321242012-06-06 18:52:13 +0000249 Token DirectiveToken;
250 do {
251 DirectiveLex.LexFromRawLexer(DirectiveToken);
252 } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof));
Lubos Lunak72cad682014-05-01 21:10:08 +0000253 if (&FromFile == PredefinesBuffer) {
254 // OutputContentUpTo() would not output anything anyway.
255 return;
256 }
David Blaikie619117a2012-06-14 17:36:01 +0000257 OS << "#if 0 /* expanded by -frewrite-includes */" << EOL;
David Blaikied5321242012-06-06 18:52:13 +0000258 OutputContentUpTo(FromFile, NextToWrite,
259 SM.getFileOffset(DirectiveToken.getLocation()) + DirectiveToken.getLength(),
Alp Toker08c25002013-12-13 17:04:55 +0000260 EOL, Line, true);
David Blaikie619117a2012-06-14 17:36:01 +0000261 OS << "#endif /* expanded by -frewrite-includes */" << EOL;
David Blaikied5321242012-06-06 18:52:13 +0000262}
263
264/// Find the next identifier in the pragma directive specified by \p RawToken.
265StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex,
266 Token &RawToken) {
267 RawLex.LexFromRawLexer(RawToken);
268 if (RawToken.is(tok::raw_identifier))
269 PP.LookUpIdentifierInfo(RawToken);
270 if (RawToken.is(tok::identifier))
271 return RawToken.getIdentifierInfo()->getName();
272 return StringRef();
273}
274
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000275// Expand __has_include and __has_include_next if possible. If there's no
276// definitive answer return false.
277bool InclusionRewriter::HandleHasInclude(
278 FileID FileId, Lexer &RawLex, const DirectoryLookup *Lookup, Token &Tok,
279 bool &FileExists) {
280 // Lex the opening paren.
281 RawLex.LexFromRawLexer(Tok);
282 if (Tok.isNot(tok::l_paren))
283 return false;
284
285 RawLex.LexFromRawLexer(Tok);
286
287 SmallString<128> FilenameBuffer;
288 StringRef Filename;
289 // Since the raw lexer doesn't give us angle_literals we have to parse them
290 // ourselves.
291 // FIXME: What to do if the file name is a macro?
292 if (Tok.is(tok::less)) {
293 RawLex.LexFromRawLexer(Tok);
294
295 FilenameBuffer += '<';
296 do {
297 if (Tok.is(tok::eod)) // Sanity check.
298 return false;
299
300 if (Tok.is(tok::raw_identifier))
301 PP.LookUpIdentifierInfo(Tok);
302
303 // Get the string piece.
304 SmallVector<char, 128> TmpBuffer;
305 bool Invalid = false;
306 StringRef TmpName = PP.getSpelling(Tok, TmpBuffer, &Invalid);
307 if (Invalid)
308 return false;
309
310 FilenameBuffer += TmpName;
311
312 RawLex.LexFromRawLexer(Tok);
313 } while (Tok.isNot(tok::greater));
314
315 FilenameBuffer += '>';
316 Filename = FilenameBuffer;
317 } else {
318 if (Tok.isNot(tok::string_literal))
319 return false;
320
321 bool Invalid = false;
322 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
323 if (Invalid)
324 return false;
325 }
326
327 // Lex the closing paren.
328 RawLex.LexFromRawLexer(Tok);
329 if (Tok.isNot(tok::r_paren))
330 return false;
331
332 // Now ask HeaderInfo if it knows about the header.
333 // FIXME: Subframeworks aren't handled here. Do we care?
334 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
335 const DirectoryLookup *CurDir;
336 const FileEntry *File = PP.getHeaderSearchInfo().LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000337 Filename, SourceLocation(), isAngled, 0, CurDir,
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000338 PP.getSourceManager().getFileEntryForID(FileId), 0, 0, 0, false);
339
340 FileExists = File != 0;
341 return true;
342}
343
Benjamin Kramere2881572013-10-13 12:02:16 +0000344/// Use a raw lexer to analyze \p FileId, incrementally copying parts of it
David Blaikied5321242012-06-06 18:52:13 +0000345/// and including content of included files recursively.
346bool InclusionRewriter::Process(FileID FileId,
347 SrcMgr::CharacteristicKind FileType)
348{
349 bool Invalid;
350 const MemoryBuffer &FromFile = *SM.getBuffer(FileId, &Invalid);
David Blaikie76cae512012-06-14 17:36:05 +0000351 if (Invalid) // invalid inclusion
Argyrios Kyrtzidis953ef332013-04-10 01:53:37 +0000352 return false;
David Blaikied5321242012-06-06 18:52:13 +0000353 const char *FileName = FromFile.getBufferIdentifier();
354 Lexer RawLex(FileId, &FromFile, PP.getSourceManager(), PP.getLangOpts());
355 RawLex.SetCommentRetentionState(false);
356
357 StringRef EOL = DetectEOL(FromFile);
358
Lubos Lunak10961c02014-05-01 13:50:44 +0000359 // Per the GNU docs: "1" indicates entering a new file.
Lubos Lunak72cad682014-05-01 21:10:08 +0000360 if (FileId == SM.getMainFileID() || FileId == PP.getPredefinesFileID())
Lubos Lunak10961c02014-05-01 13:50:44 +0000361 WriteLineInfo(FileName, 1, FileType, EOL, "");
362 else
363 WriteLineInfo(FileName, 1, FileType, EOL, " 1");
David Blaikied5321242012-06-06 18:52:13 +0000364
365 if (SM.getFileIDSize(FileId) == 0)
Argyrios Kyrtzidis953ef332013-04-10 01:53:37 +0000366 return false;
David Blaikied5321242012-06-06 18:52:13 +0000367
Alp Toker3dfeafd2013-11-28 07:21:44 +0000368 // The next byte to be copied from the source file, which may be non-zero if
369 // the lexer handled a BOM.
Alp Toker52937ab2013-12-05 17:28:42 +0000370 unsigned NextToWrite = SM.getFileOffset(RawLex.getSourceLocation());
371 assert(SM.getLineNumber(FileId, NextToWrite) == 1);
David Blaikied5321242012-06-06 18:52:13 +0000372 int Line = 1; // The current input file line number.
373
374 Token RawToken;
375 RawLex.LexFromRawLexer(RawToken);
376
377 // TODO: Consider adding a switch that strips possibly unimportant content,
378 // such as comments, to reduce the size of repro files.
379 while (RawToken.isNot(tok::eof)) {
380 if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) {
381 RawLex.setParsingPreprocessorDirective(true);
382 Token HashToken = RawToken;
383 RawLex.LexFromRawLexer(RawToken);
384 if (RawToken.is(tok::raw_identifier))
385 PP.LookUpIdentifierInfo(RawToken);
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000386 if (RawToken.getIdentifierInfo() != NULL) {
David Blaikied5321242012-06-06 18:52:13 +0000387 switch (RawToken.getIdentifierInfo()->getPPKeywordID()) {
388 case tok::pp_include:
389 case tok::pp_include_next:
390 case tok::pp_import: {
391 CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite,
392 Line);
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000393 StringRef LineInfoExtra;
David Blaikied5321242012-06-06 18:52:13 +0000394 if (const FileChange *Change = FindFileChangeLocation(
395 HashToken.getLocation())) {
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000396 if (Change->Mod) {
397 WriteImplicitModuleImport(Change->Mod, EOL);
398
399 // else now include and recursively process the file
400 } else if (Process(Change->Id, Change->FileType)) {
David Blaikied5321242012-06-06 18:52:13 +0000401 // and set lineinfo back to this file, if the nested one was
402 // actually included
403 // `2' indicates returning to a file (after having included
404 // another file.
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000405 LineInfoExtra = " 2";
Argyrios Kyrtzidis953ef332013-04-10 01:53:37 +0000406 }
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000407 }
408 // fix up lineinfo (since commented out directive changed line
409 // numbers) for inclusions that were skipped due to header guards
410 WriteLineInfo(FileName, Line, FileType, EOL, LineInfoExtra);
David Blaikied5321242012-06-06 18:52:13 +0000411 break;
412 }
413 case tok::pp_pragma: {
414 StringRef Identifier = NextIdentifierName(RawLex, RawToken);
415 if (Identifier == "clang" || Identifier == "GCC") {
416 if (NextIdentifierName(RawLex, RawToken) == "system_header") {
417 // keep the directive in, commented out
418 CommentOutDirective(RawLex, HashToken, FromFile, EOL,
419 NextToWrite, Line);
420 // update our own type
421 FileType = SM.getFileCharacteristic(RawToken.getLocation());
422 WriteLineInfo(FileName, Line, FileType, EOL);
423 }
424 } else if (Identifier == "once") {
425 // keep the directive in, commented out
426 CommentOutDirective(RawLex, HashToken, FromFile, EOL,
427 NextToWrite, Line);
428 WriteLineInfo(FileName, Line, FileType, EOL);
429 }
430 break;
431 }
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000432 case tok::pp_if:
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000433 case tok::pp_elif: {
434 bool elif = (RawToken.getIdentifierInfo()->getPPKeywordID() ==
435 tok::pp_elif);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000436 // Rewrite special builtin macros to avoid pulling in host details.
437 do {
438 // Walk over the directive.
439 RawLex.LexFromRawLexer(RawToken);
440 if (RawToken.is(tok::raw_identifier))
441 PP.LookUpIdentifierInfo(RawToken);
442
443 if (RawToken.is(tok::identifier)) {
444 bool HasFile;
445 SourceLocation Loc = RawToken.getLocation();
446
447 // Rewrite __has_include(x)
448 if (RawToken.getIdentifierInfo()->isStr("__has_include")) {
449 if (!HandleHasInclude(FileId, RawLex, 0, RawToken, HasFile))
450 continue;
451 // Rewrite __has_include_next(x)
452 } else if (RawToken.getIdentifierInfo()->isStr(
453 "__has_include_next")) {
454 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
455 if (Lookup)
456 ++Lookup;
457
458 if (!HandleHasInclude(FileId, RawLex, Lookup, RawToken,
459 HasFile))
460 continue;
461 } else {
462 continue;
463 }
464 // Replace the macro with (0) or (1), followed by the commented
465 // out macro for reference.
466 OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(Loc),
Alp Toker08c25002013-12-13 17:04:55 +0000467 EOL, Line, false);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000468 OS << '(' << (int) HasFile << ")/*";
469 OutputContentUpTo(FromFile, NextToWrite,
470 SM.getFileOffset(RawToken.getLocation()) +
471 RawToken.getLength(),
Alp Toker08c25002013-12-13 17:04:55 +0000472 EOL, Line, false);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000473 OS << "*/";
474 }
475 } while (RawToken.isNot(tok::eod));
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000476 if (elif) {
477 OutputContentUpTo(FromFile, NextToWrite,
478 SM.getFileOffset(RawToken.getLocation()) +
479 RawToken.getLength(),
480 EOL, Line, /*EnsureNewLine*/ true);
481 WriteLineInfo(FileName, Line, FileType, EOL);
482 }
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000483 break;
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000484 }
485 case tok::pp_endif:
486 case tok::pp_else: {
487 // We surround every #include by #if 0 to comment it out, but that
488 // changes line numbers. These are fixed up right after that, but
489 // the whole #include could be inside a preprocessor conditional
490 // that is not processed. So it is necessary to fix the line
491 // numbers one the next line after each #else/#endif as well.
492 RawLex.SetKeepWhitespaceMode(true);
493 do {
494 RawLex.LexFromRawLexer(RawToken);
495 } while (RawToken.isNot(tok::eod) && RawToken.isNot(tok::eof));
496 OutputContentUpTo(
497 FromFile, NextToWrite,
498 SM.getFileOffset(RawToken.getLocation()) + RawToken.getLength(),
499 EOL, Line, /*EnsureNewLine*/ true);
500 WriteLineInfo(FileName, Line, FileType, EOL);
501 RawLex.SetKeepWhitespaceMode(false);
502 }
David Blaikied5321242012-06-06 18:52:13 +0000503 default:
504 break;
505 }
506 }
507 RawLex.setParsingPreprocessorDirective(false);
508 }
509 RawLex.LexFromRawLexer(RawToken);
510 }
511 OutputContentUpTo(FromFile, NextToWrite,
Argyrios Kyrtzidisd3910462013-05-07 04:29:22 +0000512 SM.getFileOffset(SM.getLocForEndOfFile(FileId)), EOL, Line,
David Blaikied5321242012-06-06 18:52:13 +0000513 /*EnsureNewline*/true);
514 return true;
515}
516
David Blaikie619117a2012-06-14 17:36:01 +0000517/// InclusionRewriterInInput - Implement -frewrite-includes mode.
David Blaikied5321242012-06-06 18:52:13 +0000518void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS,
519 const PreprocessorOutputOptions &Opts) {
520 SourceManager &SM = PP.getSourceManager();
521 InclusionRewriter *Rewrite = new InclusionRewriter(PP, *OS,
522 Opts.ShowLineMarkers);
523 PP.addPPCallbacks(Rewrite);
Lubos Lunak576a0412014-05-01 12:54:03 +0000524 PP.IgnorePragmas();
David Blaikied5321242012-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 Kyrtzidis17ff2e52013-07-26 15:32:04 +0000539 Rewrite->setPredefinesBuffer(SM.getBuffer(PP.getPredefinesFileID()));
540 Rewrite->Process(PP.getPredefinesFileID(), SrcMgr::C_User);
David Blaikied5321242012-06-06 18:52:13 +0000541 Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User);
542 OS->flush();
543}