blob: 0c3269a0472495956184a9cae23a291bb6b61414 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/Lex/Preprocessor.h"
Benjamin Kramer596eea72013-04-16 19:08:41 +000020#include "llvm/ADT/SmallString.h"
David Blaikie8c0b3782012-06-06 18:52:13 +000021#include "llvm/Support/raw_ostream.h"
22
23using namespace clang;
24using namespace llvm;
25
26namespace {
27
28class InclusionRewriter : public PPCallbacks {
29 /// Information about which #includes were actually performed,
30 /// created by preprocessor callbacks.
31 struct FileChange {
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +000032 const Module *Mod;
David Blaikie8c0b3782012-06-06 18:52:13 +000033 SourceLocation From;
34 FileID Id;
35 SrcMgr::CharacteristicKind FileType;
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +000036 FileChange(SourceLocation From, const Module *Mod) : Mod(Mod), From(From) {
David Blaikie8c0b3782012-06-06 18:52:13 +000037 }
38 };
Dmitri Gribenko49fdccb2012-06-08 23:13:42 +000039 Preprocessor &PP; ///< Used to find inclusion directives.
40 SourceManager &SM; ///< Used to read and manage source files.
41 raw_ostream &OS; ///< The destination stream for rewritten contents.
42 bool ShowLineMarkers; ///< Show #line markers.
43 bool UseLineDirective; ///< Use of line directives or line markers.
David Blaikie8c0b3782012-06-06 18:52:13 +000044 typedef std::map<unsigned, FileChange> FileChangeMap;
Dmitri Gribenko959dc842013-02-16 22:21:38 +000045 FileChangeMap FileChanges; ///< Tracks which files were included where.
David Blaikie8c0b3782012-06-06 18:52:13 +000046 /// Used transitively for building up the FileChanges mapping over the
47 /// various \c PPCallbacks callbacks.
48 FileChangeMap::iterator LastInsertedFileChange;
49public:
50 InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers);
51 bool Process(FileID FileId, SrcMgr::CharacteristicKind FileType);
52private:
53 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
54 SrcMgr::CharacteristicKind FileType,
55 FileID PrevFID);
56 virtual void FileSkipped(const FileEntry &ParentFile,
57 const Token &FilenameTok,
58 SrcMgr::CharacteristicKind FileType);
59 virtual void InclusionDirective(SourceLocation HashLoc,
60 const Token &IncludeTok,
61 StringRef FileName,
62 bool IsAngled,
Argyrios Kyrtzidisda313592012-09-27 01:42:07 +000063 CharSourceRange FilenameRange,
David Blaikie8c0b3782012-06-06 18:52:13 +000064 const FileEntry *File,
David Blaikie8c0b3782012-06-06 18:52:13 +000065 StringRef SearchPath,
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +000066 StringRef RelativePath,
67 const Module *Imported);
David Blaikie8c0b3782012-06-06 18:52:13 +000068 void WriteLineInfo(const char *Filename, int Line,
69 SrcMgr::CharacteristicKind FileType,
70 StringRef EOL, StringRef Extra = StringRef());
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +000071 void WriteImplicitModuleImport(const Module *Mod, StringRef EOL);
David Blaikie8c0b3782012-06-06 18:52:13 +000072 void OutputContentUpTo(const MemoryBuffer &FromFile,
73 unsigned &WriteFrom, unsigned WriteTo,
74 StringRef EOL, int &lines,
75 bool EnsureNewline = false);
76 void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken,
77 const MemoryBuffer &FromFile, StringRef EOL,
78 unsigned &NextToWrite, int &Lines);
Benjamin Kramer596eea72013-04-16 19:08:41 +000079 bool HandleHasInclude(FileID FileId, Lexer &RawLex,
80 const DirectoryLookup *Lookup, Token &Tok,
81 bool &FileExists);
David Blaikie8c0b3782012-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)
91 : PP(PP), SM(PP.getSourceManager()), OS(OS),
92 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) {
108 OS << "#line" << ' ' << Line << ' ' << '"' << Filename << '"';
109 } else {
110 // Use GNU linemarkers as described here:
111 // http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html
112 OS << '#' << ' ' << Line << ' ' << '"' << Filename << '"';
113 if (!Extra.empty())
114 OS << Extra;
115 if (FileType == SrcMgr::C_System)
116 // "`3' This indicates that the following text comes from a system header
117 // file, so certain warnings should be suppressed."
118 OS << " 3";
119 else if (FileType == SrcMgr::C_ExternCSystem)
120 // as above for `3', plus "`4' This indicates that the following text
121 // should be treated as being wrapped in an implicit extern "C" block."
122 OS << " 3 4";
123 }
124 OS << EOL;
125}
126
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000127void InclusionRewriter::WriteImplicitModuleImport(const Module *Mod,
128 StringRef EOL) {
129 OS << "@import " << Mod->getFullModuleName() << ";"
130 << " /* clang -frewrite-includes: implicit import */" << EOL;
131}
132
David Blaikie8c0b3782012-06-06 18:52:13 +0000133/// FileChanged - Whenever the preprocessor enters or exits a #include file
134/// it invokes this handler.
135void InclusionRewriter::FileChanged(SourceLocation Loc,
136 FileChangeReason Reason,
137 SrcMgr::CharacteristicKind NewFileType,
138 FileID) {
139 if (Reason != EnterFile)
140 return;
141 if (LastInsertedFileChange == FileChanges.end())
142 // we didn't reach this file (eg: the main file) via an inclusion directive
143 return;
144 LastInsertedFileChange->second.Id = FullSourceLoc(Loc, SM).getFileID();
145 LastInsertedFileChange->second.FileType = NewFileType;
146 LastInsertedFileChange = FileChanges.end();
147}
148
149/// Called whenever an inclusion is skipped due to canonical header protection
150/// macros.
151void InclusionRewriter::FileSkipped(const FileEntry &/*ParentFile*/,
152 const Token &/*FilenameTok*/,
153 SrcMgr::CharacteristicKind /*FileType*/) {
154 assert(LastInsertedFileChange != FileChanges.end() && "A file, that wasn't "
155 "found via an inclusion directive, was skipped");
156 FileChanges.erase(LastInsertedFileChange);
157 LastInsertedFileChange = FileChanges.end();
158}
159
160/// This should be called whenever the preprocessor encounters include
161/// directives. It does not say whether the file has been included, but it
162/// provides more information about the directive (hash location instead
163/// of location inside the included file). It is assumed that the matching
164/// FileChanged() or FileSkipped() is called after this.
165void InclusionRewriter::InclusionDirective(SourceLocation HashLoc,
166 const Token &/*IncludeTok*/,
167 StringRef /*FileName*/,
168 bool /*IsAngled*/,
Argyrios Kyrtzidisda313592012-09-27 01:42:07 +0000169 CharSourceRange /*FilenameRange*/,
David Blaikie8c0b3782012-06-06 18:52:13 +0000170 const FileEntry * /*File*/,
David Blaikie8c0b3782012-06-06 18:52:13 +0000171 StringRef /*SearchPath*/,
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +0000172 StringRef /*RelativePath*/,
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000173 const Module *Imported) {
David Blaikie8c0b3782012-06-06 18:52:13 +0000174 assert(LastInsertedFileChange == FileChanges.end() && "Another inclusion "
175 "directive was found before the previous one was processed");
176 std::pair<FileChangeMap::iterator, bool> p = FileChanges.insert(
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000177 std::make_pair(HashLoc.getRawEncoding(), FileChange(HashLoc, Imported)));
David Blaikie8c0b3782012-06-06 18:52:13 +0000178 assert(p.second && "Unexpected revisitation of the same include directive");
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000179 if (!Imported)
180 LastInsertedFileChange = p.first;
David Blaikie8c0b3782012-06-06 18:52:13 +0000181}
182
183/// Simple lookup for a SourceLocation (specifically one denoting the hash in
184/// an inclusion directive) in the map of inclusion information, FileChanges.
185const InclusionRewriter::FileChange *
186InclusionRewriter::FindFileChangeLocation(SourceLocation Loc) const {
187 FileChangeMap::const_iterator I = FileChanges.find(Loc.getRawEncoding());
188 if (I != FileChanges.end())
189 return &I->second;
190 return NULL;
191}
192
David Blaikie8c0b3782012-06-06 18:52:13 +0000193/// Detect the likely line ending style of \p FromFile by examining the first
194/// newline found within it.
195static StringRef DetectEOL(const MemoryBuffer &FromFile) {
196 // detect what line endings the file uses, so that added content does not mix
197 // the style
198 const char *Pos = strchr(FromFile.getBufferStart(), '\n');
199 if (Pos == NULL)
200 return "\n";
201 if (Pos + 1 < FromFile.getBufferEnd() && Pos[1] == '\r')
202 return "\n\r";
203 if (Pos - 1 >= FromFile.getBufferStart() && Pos[-1] == '\r')
204 return "\r\n";
205 return "\n";
206}
207
208/// Writes out bytes from \p FromFile, starting at \p NextToWrite and ending at
209/// \p WriteTo - 1.
210void InclusionRewriter::OutputContentUpTo(const MemoryBuffer &FromFile,
211 unsigned &WriteFrom, unsigned WriteTo,
212 StringRef EOL, int &Line,
213 bool EnsureNewline) {
214 if (WriteTo <= WriteFrom)
215 return;
216 OS.write(FromFile.getBufferStart() + WriteFrom, WriteTo - WriteFrom);
217 // count lines manually, it's faster than getPresumedLoc()
Benjamin Kramer31598192012-06-09 13:18:14 +0000218 Line += std::count(FromFile.getBufferStart() + WriteFrom,
219 FromFile.getBufferStart() + WriteTo, '\n');
David Blaikie8c0b3782012-06-06 18:52:13 +0000220 if (EnsureNewline) {
221 char LastChar = FromFile.getBufferStart()[WriteTo - 1];
222 if (LastChar != '\n' && LastChar != '\r')
223 OS << EOL;
224 }
225 WriteFrom = WriteTo;
226}
227
228/// Print characters from \p FromFile starting at \p NextToWrite up until the
229/// inclusion directive at \p StartToken, then print out the inclusion
230/// inclusion directive disabled by a #if directive, updating \p NextToWrite
231/// and \p Line to track the number of source lines visited and the progress
232/// through the \p FromFile buffer.
233void InclusionRewriter::CommentOutDirective(Lexer &DirectiveLex,
234 const Token &StartToken,
235 const MemoryBuffer &FromFile,
236 StringRef EOL,
237 unsigned &NextToWrite, int &Line) {
238 OutputContentUpTo(FromFile, NextToWrite,
239 SM.getFileOffset(StartToken.getLocation()), EOL, Line);
240 Token DirectiveToken;
241 do {
242 DirectiveLex.LexFromRawLexer(DirectiveToken);
243 } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof));
David Blaikie60ad16b2012-06-14 17:36:01 +0000244 OS << "#if 0 /* expanded by -frewrite-includes */" << EOL;
David Blaikie8c0b3782012-06-06 18:52:13 +0000245 OutputContentUpTo(FromFile, NextToWrite,
246 SM.getFileOffset(DirectiveToken.getLocation()) + DirectiveToken.getLength(),
247 EOL, Line);
David Blaikie60ad16b2012-06-14 17:36:01 +0000248 OS << "#endif /* expanded by -frewrite-includes */" << EOL;
David Blaikie8c0b3782012-06-06 18:52:13 +0000249}
250
251/// Find the next identifier in the pragma directive specified by \p RawToken.
252StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex,
253 Token &RawToken) {
254 RawLex.LexFromRawLexer(RawToken);
255 if (RawToken.is(tok::raw_identifier))
256 PP.LookUpIdentifierInfo(RawToken);
257 if (RawToken.is(tok::identifier))
258 return RawToken.getIdentifierInfo()->getName();
259 return StringRef();
260}
261
Benjamin Kramer596eea72013-04-16 19:08:41 +0000262// Expand __has_include and __has_include_next if possible. If there's no
263// definitive answer return false.
264bool InclusionRewriter::HandleHasInclude(
265 FileID FileId, Lexer &RawLex, const DirectoryLookup *Lookup, Token &Tok,
266 bool &FileExists) {
267 // Lex the opening paren.
268 RawLex.LexFromRawLexer(Tok);
269 if (Tok.isNot(tok::l_paren))
270 return false;
271
272 RawLex.LexFromRawLexer(Tok);
273
274 SmallString<128> FilenameBuffer;
275 StringRef Filename;
276 // Since the raw lexer doesn't give us angle_literals we have to parse them
277 // ourselves.
278 // FIXME: What to do if the file name is a macro?
279 if (Tok.is(tok::less)) {
280 RawLex.LexFromRawLexer(Tok);
281
282 FilenameBuffer += '<';
283 do {
284 if (Tok.is(tok::eod)) // Sanity check.
285 return false;
286
287 if (Tok.is(tok::raw_identifier))
288 PP.LookUpIdentifierInfo(Tok);
289
290 // Get the string piece.
291 SmallVector<char, 128> TmpBuffer;
292 bool Invalid = false;
293 StringRef TmpName = PP.getSpelling(Tok, TmpBuffer, &Invalid);
294 if (Invalid)
295 return false;
296
297 FilenameBuffer += TmpName;
298
299 RawLex.LexFromRawLexer(Tok);
300 } while (Tok.isNot(tok::greater));
301
302 FilenameBuffer += '>';
303 Filename = FilenameBuffer;
304 } else {
305 if (Tok.isNot(tok::string_literal))
306 return false;
307
308 bool Invalid = false;
309 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
310 if (Invalid)
311 return false;
312 }
313
314 // Lex the closing paren.
315 RawLex.LexFromRawLexer(Tok);
316 if (Tok.isNot(tok::r_paren))
317 return false;
318
319 // Now ask HeaderInfo if it knows about the header.
320 // FIXME: Subframeworks aren't handled here. Do we care?
321 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
322 const DirectoryLookup *CurDir;
323 const FileEntry *File = PP.getHeaderSearchInfo().LookupFile(
324 Filename, isAngled, 0, CurDir,
325 PP.getSourceManager().getFileEntryForID(FileId), 0, 0, 0, false);
326
327 FileExists = File != 0;
328 return true;
329}
330
David Blaikie8c0b3782012-06-06 18:52:13 +0000331/// Use a raw lexer to analyze \p FileId, inccrementally copying parts of it
332/// and including content of included files recursively.
333bool InclusionRewriter::Process(FileID FileId,
334 SrcMgr::CharacteristicKind FileType)
335{
336 bool Invalid;
337 const MemoryBuffer &FromFile = *SM.getBuffer(FileId, &Invalid);
David Blaikiebae2b312012-06-14 17:36:05 +0000338 if (Invalid) // invalid inclusion
Argyrios Kyrtzidis507d4962013-04-10 01:53:37 +0000339 return false;
David Blaikie8c0b3782012-06-06 18:52:13 +0000340 const char *FileName = FromFile.getBufferIdentifier();
341 Lexer RawLex(FileId, &FromFile, PP.getSourceManager(), PP.getLangOpts());
342 RawLex.SetCommentRetentionState(false);
343
344 StringRef EOL = DetectEOL(FromFile);
345
346 // Per the GNU docs: "1" indicates the start of a new file.
347 WriteLineInfo(FileName, 1, FileType, EOL, " 1");
348
349 if (SM.getFileIDSize(FileId) == 0)
Argyrios Kyrtzidis507d4962013-04-10 01:53:37 +0000350 return false;
David Blaikie8c0b3782012-06-06 18:52:13 +0000351
352 // The next byte to be copied from the source file
353 unsigned NextToWrite = 0;
354 int Line = 1; // The current input file line number.
355
356 Token RawToken;
357 RawLex.LexFromRawLexer(RawToken);
358
359 // TODO: Consider adding a switch that strips possibly unimportant content,
360 // such as comments, to reduce the size of repro files.
361 while (RawToken.isNot(tok::eof)) {
362 if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) {
363 RawLex.setParsingPreprocessorDirective(true);
364 Token HashToken = RawToken;
365 RawLex.LexFromRawLexer(RawToken);
366 if (RawToken.is(tok::raw_identifier))
367 PP.LookUpIdentifierInfo(RawToken);
Lubos Lunakce6af112013-07-20 14:23:27 +0000368 if (RawToken.getIdentifierInfo() != NULL) {
David Blaikie8c0b3782012-06-06 18:52:13 +0000369 switch (RawToken.getIdentifierInfo()->getPPKeywordID()) {
370 case tok::pp_include:
371 case tok::pp_include_next:
372 case tok::pp_import: {
373 CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite,
374 Line);
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000375 StringRef LineInfoExtra;
David Blaikie8c0b3782012-06-06 18:52:13 +0000376 if (const FileChange *Change = FindFileChangeLocation(
377 HashToken.getLocation())) {
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000378 if (Change->Mod) {
379 WriteImplicitModuleImport(Change->Mod, EOL);
380
381 // else now include and recursively process the file
382 } else if (Process(Change->Id, Change->FileType)) {
David Blaikie8c0b3782012-06-06 18:52:13 +0000383 // and set lineinfo back to this file, if the nested one was
384 // actually included
385 // `2' indicates returning to a file (after having included
386 // another file.
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000387 LineInfoExtra = " 2";
Argyrios Kyrtzidis507d4962013-04-10 01:53:37 +0000388 }
Argyrios Kyrtzidis03409962013-04-10 01:53:50 +0000389 }
390 // fix up lineinfo (since commented out directive changed line
391 // numbers) for inclusions that were skipped due to header guards
392 WriteLineInfo(FileName, Line, FileType, EOL, LineInfoExtra);
David Blaikie8c0b3782012-06-06 18:52:13 +0000393 break;
394 }
395 case tok::pp_pragma: {
396 StringRef Identifier = NextIdentifierName(RawLex, RawToken);
397 if (Identifier == "clang" || Identifier == "GCC") {
398 if (NextIdentifierName(RawLex, RawToken) == "system_header") {
399 // keep the directive in, commented out
400 CommentOutDirective(RawLex, HashToken, FromFile, EOL,
401 NextToWrite, Line);
402 // update our own type
403 FileType = SM.getFileCharacteristic(RawToken.getLocation());
404 WriteLineInfo(FileName, Line, FileType, EOL);
405 }
406 } else if (Identifier == "once") {
407 // keep the directive in, commented out
408 CommentOutDirective(RawLex, HashToken, FromFile, EOL,
409 NextToWrite, Line);
410 WriteLineInfo(FileName, Line, FileType, EOL);
411 }
412 break;
413 }
Benjamin Kramer596eea72013-04-16 19:08:41 +0000414 case tok::pp_if:
Lubos Lunakce6af112013-07-20 14:23:27 +0000415 case tok::pp_elif: {
416 bool elif = (RawToken.getIdentifierInfo()->getPPKeywordID() ==
417 tok::pp_elif);
Benjamin Kramer596eea72013-04-16 19:08:41 +0000418 // Rewrite special builtin macros to avoid pulling in host details.
419 do {
420 // Walk over the directive.
421 RawLex.LexFromRawLexer(RawToken);
422 if (RawToken.is(tok::raw_identifier))
423 PP.LookUpIdentifierInfo(RawToken);
424
425 if (RawToken.is(tok::identifier)) {
426 bool HasFile;
427 SourceLocation Loc = RawToken.getLocation();
428
429 // Rewrite __has_include(x)
430 if (RawToken.getIdentifierInfo()->isStr("__has_include")) {
431 if (!HandleHasInclude(FileId, RawLex, 0, RawToken, HasFile))
432 continue;
433 // Rewrite __has_include_next(x)
434 } else if (RawToken.getIdentifierInfo()->isStr(
435 "__has_include_next")) {
436 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
437 if (Lookup)
438 ++Lookup;
439
440 if (!HandleHasInclude(FileId, RawLex, Lookup, RawToken,
441 HasFile))
442 continue;
443 } else {
444 continue;
445 }
446 // Replace the macro with (0) or (1), followed by the commented
447 // out macro for reference.
448 OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(Loc),
449 EOL, Line);
450 OS << '(' << (int) HasFile << ")/*";
451 OutputContentUpTo(FromFile, NextToWrite,
452 SM.getFileOffset(RawToken.getLocation()) +
453 RawToken.getLength(),
454 EOL, Line);
455 OS << "*/";
456 }
457 } while (RawToken.isNot(tok::eod));
Lubos Lunakce6af112013-07-20 14:23:27 +0000458 if (elif) {
459 OutputContentUpTo(FromFile, NextToWrite,
460 SM.getFileOffset(RawToken.getLocation()) +
461 RawToken.getLength(),
462 EOL, Line, /*EnsureNewLine*/ true);
463 WriteLineInfo(FileName, Line, FileType, EOL);
464 }
Benjamin Kramer596eea72013-04-16 19:08:41 +0000465 break;
Lubos Lunakce6af112013-07-20 14:23:27 +0000466 }
467 case tok::pp_endif:
468 case tok::pp_else: {
469 // We surround every #include by #if 0 to comment it out, but that
470 // changes line numbers. These are fixed up right after that, but
471 // the whole #include could be inside a preprocessor conditional
472 // that is not processed. So it is necessary to fix the line
473 // numbers one the next line after each #else/#endif as well.
474 RawLex.SetKeepWhitespaceMode(true);
475 do {
476 RawLex.LexFromRawLexer(RawToken);
477 } while (RawToken.isNot(tok::eod) && RawToken.isNot(tok::eof));
478 OutputContentUpTo(
479 FromFile, NextToWrite,
480 SM.getFileOffset(RawToken.getLocation()) + RawToken.getLength(),
481 EOL, Line, /*EnsureNewLine*/ true);
482 WriteLineInfo(FileName, Line, FileType, EOL);
483 RawLex.SetKeepWhitespaceMode(false);
484 }
David Blaikie8c0b3782012-06-06 18:52:13 +0000485 default:
486 break;
487 }
488 }
489 RawLex.setParsingPreprocessorDirective(false);
490 }
491 RawLex.LexFromRawLexer(RawToken);
492 }
493 OutputContentUpTo(FromFile, NextToWrite,
Argyrios Kyrtzidisb18840d2013-05-07 04:29:22 +0000494 SM.getFileOffset(SM.getLocForEndOfFile(FileId)), EOL, Line,
David Blaikie8c0b3782012-06-06 18:52:13 +0000495 /*EnsureNewline*/true);
496 return true;
497}
498
David Blaikie60ad16b2012-06-14 17:36:01 +0000499/// InclusionRewriterInInput - Implement -frewrite-includes mode.
David Blaikie8c0b3782012-06-06 18:52:13 +0000500void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS,
501 const PreprocessorOutputOptions &Opts) {
502 SourceManager &SM = PP.getSourceManager();
503 InclusionRewriter *Rewrite = new InclusionRewriter(PP, *OS,
504 Opts.ShowLineMarkers);
505 PP.addPPCallbacks(Rewrite);
506
507 // First let the preprocessor process the entire file and call callbacks.
508 // Callbacks will record which #include's were actually performed.
509 PP.EnterMainSourceFile();
510 Token Tok;
511 // Only preprocessor directives matter here, so disable macro expansion
512 // everywhere else as an optimization.
513 // TODO: It would be even faster if the preprocessor could be switched
514 // to a mode where it would parse only preprocessor directives and comments,
515 // nothing else matters for parsing or processing.
516 PP.SetMacroExpansionOnlyInDirectives();
517 do {
518 PP.Lex(Tok);
519 } while (Tok.isNot(tok::eof));
520 Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User);
521 OS->flush();
522}