blob: 5b33307cbb204a97bdaff61cc6458ccf17c611aa [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)
Craig Topper8ae12032014-05-07 06:21:57 +000091 : PP(PP), SM(PP.getSourceManager()), OS(OS), PredefinesBuffer(nullptr),
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;
Craig Topper8ae12032014-05-07 06:21:57 +0000194 return nullptr;
David Blaikied5321242012-06-06 18:52:13 +0000195}
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');
Craig Topper8ae12032014-05-07 06:21:57 +0000203 if (!Pos)
David Blaikied5321242012-06-06 18:52:13 +0000204 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;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000336 const FileEntry *FileEnt = PP.getSourceManager().getFileEntryForID(FileId);
337 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 1>
338 Includers;
339 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000340 const FileEntry *File = PP.getHeaderSearchInfo().LookupFile(
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000341 Filename, SourceLocation(), isAngled, nullptr, CurDir, Includers, nullptr,
342 nullptr, nullptr, false);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000343
Craig Topper8ae12032014-05-07 06:21:57 +0000344 FileExists = File != nullptr;
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000345 return true;
346}
347
Benjamin Kramere2881572013-10-13 12:02:16 +0000348/// Use a raw lexer to analyze \p FileId, incrementally copying parts of it
David Blaikied5321242012-06-06 18:52:13 +0000349/// and including content of included files recursively.
350bool InclusionRewriter::Process(FileID FileId,
351 SrcMgr::CharacteristicKind FileType)
352{
353 bool Invalid;
354 const MemoryBuffer &FromFile = *SM.getBuffer(FileId, &Invalid);
David Blaikie76cae512012-06-14 17:36:05 +0000355 if (Invalid) // invalid inclusion
Argyrios Kyrtzidis953ef332013-04-10 01:53:37 +0000356 return false;
David Blaikied5321242012-06-06 18:52:13 +0000357 const char *FileName = FromFile.getBufferIdentifier();
358 Lexer RawLex(FileId, &FromFile, PP.getSourceManager(), PP.getLangOpts());
359 RawLex.SetCommentRetentionState(false);
360
361 StringRef EOL = DetectEOL(FromFile);
362
Lubos Lunak10961c02014-05-01 13:50:44 +0000363 // Per the GNU docs: "1" indicates entering a new file.
Lubos Lunak72cad682014-05-01 21:10:08 +0000364 if (FileId == SM.getMainFileID() || FileId == PP.getPredefinesFileID())
Lubos Lunak10961c02014-05-01 13:50:44 +0000365 WriteLineInfo(FileName, 1, FileType, EOL, "");
366 else
367 WriteLineInfo(FileName, 1, FileType, EOL, " 1");
David Blaikied5321242012-06-06 18:52:13 +0000368
369 if (SM.getFileIDSize(FileId) == 0)
Argyrios Kyrtzidis953ef332013-04-10 01:53:37 +0000370 return false;
David Blaikied5321242012-06-06 18:52:13 +0000371
Alp Toker3dfeafd2013-11-28 07:21:44 +0000372 // The next byte to be copied from the source file, which may be non-zero if
373 // the lexer handled a BOM.
Alp Toker52937ab2013-12-05 17:28:42 +0000374 unsigned NextToWrite = SM.getFileOffset(RawLex.getSourceLocation());
375 assert(SM.getLineNumber(FileId, NextToWrite) == 1);
David Blaikied5321242012-06-06 18:52:13 +0000376 int Line = 1; // The current input file line number.
377
378 Token RawToken;
379 RawLex.LexFromRawLexer(RawToken);
380
381 // TODO: Consider adding a switch that strips possibly unimportant content,
382 // such as comments, to reduce the size of repro files.
383 while (RawToken.isNot(tok::eof)) {
384 if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) {
385 RawLex.setParsingPreprocessorDirective(true);
386 Token HashToken = RawToken;
387 RawLex.LexFromRawLexer(RawToken);
388 if (RawToken.is(tok::raw_identifier))
389 PP.LookUpIdentifierInfo(RawToken);
Craig Topper8ae12032014-05-07 06:21:57 +0000390 if (RawToken.getIdentifierInfo() != nullptr) {
David Blaikied5321242012-06-06 18:52:13 +0000391 switch (RawToken.getIdentifierInfo()->getPPKeywordID()) {
392 case tok::pp_include:
393 case tok::pp_include_next:
394 case tok::pp_import: {
395 CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite,
396 Line);
Lubos Lunak4526b462014-05-01 21:11:57 +0000397 if (FileId != PP.getPredefinesFileID())
398 WriteLineInfo(FileName, Line - 1, FileType, EOL, "");
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000399 StringRef LineInfoExtra;
David Blaikied5321242012-06-06 18:52:13 +0000400 if (const FileChange *Change = FindFileChangeLocation(
401 HashToken.getLocation())) {
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000402 if (Change->Mod) {
403 WriteImplicitModuleImport(Change->Mod, EOL);
404
405 // else now include and recursively process the file
406 } else if (Process(Change->Id, Change->FileType)) {
David Blaikied5321242012-06-06 18:52:13 +0000407 // and set lineinfo back to this file, if the nested one was
408 // actually included
409 // `2' indicates returning to a file (after having included
410 // another file.
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000411 LineInfoExtra = " 2";
Argyrios Kyrtzidis953ef332013-04-10 01:53:37 +0000412 }
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000413 }
414 // fix up lineinfo (since commented out directive changed line
415 // numbers) for inclusions that were skipped due to header guards
416 WriteLineInfo(FileName, Line, FileType, EOL, LineInfoExtra);
David Blaikied5321242012-06-06 18:52:13 +0000417 break;
418 }
419 case tok::pp_pragma: {
420 StringRef Identifier = NextIdentifierName(RawLex, RawToken);
421 if (Identifier == "clang" || Identifier == "GCC") {
422 if (NextIdentifierName(RawLex, RawToken) == "system_header") {
423 // keep the directive in, commented out
424 CommentOutDirective(RawLex, HashToken, FromFile, EOL,
425 NextToWrite, Line);
426 // update our own type
427 FileType = SM.getFileCharacteristic(RawToken.getLocation());
428 WriteLineInfo(FileName, Line, FileType, EOL);
429 }
430 } else if (Identifier == "once") {
431 // keep the directive in, commented out
432 CommentOutDirective(RawLex, HashToken, FromFile, EOL,
433 NextToWrite, Line);
434 WriteLineInfo(FileName, Line, FileType, EOL);
435 }
436 break;
437 }
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000438 case tok::pp_if:
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000439 case tok::pp_elif: {
440 bool elif = (RawToken.getIdentifierInfo()->getPPKeywordID() ==
441 tok::pp_elif);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000442 // Rewrite special builtin macros to avoid pulling in host details.
443 do {
444 // Walk over the directive.
445 RawLex.LexFromRawLexer(RawToken);
446 if (RawToken.is(tok::raw_identifier))
447 PP.LookUpIdentifierInfo(RawToken);
448
449 if (RawToken.is(tok::identifier)) {
450 bool HasFile;
451 SourceLocation Loc = RawToken.getLocation();
452
453 // Rewrite __has_include(x)
454 if (RawToken.getIdentifierInfo()->isStr("__has_include")) {
Craig Topper8ae12032014-05-07 06:21:57 +0000455 if (!HandleHasInclude(FileId, RawLex, nullptr, RawToken,
456 HasFile))
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000457 continue;
458 // Rewrite __has_include_next(x)
459 } else if (RawToken.getIdentifierInfo()->isStr(
460 "__has_include_next")) {
461 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
462 if (Lookup)
463 ++Lookup;
464
465 if (!HandleHasInclude(FileId, RawLex, Lookup, RawToken,
466 HasFile))
467 continue;
468 } else {
469 continue;
470 }
471 // Replace the macro with (0) or (1), followed by the commented
472 // out macro for reference.
473 OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(Loc),
Alp Toker08c25002013-12-13 17:04:55 +0000474 EOL, Line, false);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000475 OS << '(' << (int) HasFile << ")/*";
476 OutputContentUpTo(FromFile, NextToWrite,
477 SM.getFileOffset(RawToken.getLocation()) +
478 RawToken.getLength(),
Alp Toker08c25002013-12-13 17:04:55 +0000479 EOL, Line, false);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000480 OS << "*/";
481 }
482 } while (RawToken.isNot(tok::eod));
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000483 if (elif) {
484 OutputContentUpTo(FromFile, NextToWrite,
485 SM.getFileOffset(RawToken.getLocation()) +
486 RawToken.getLength(),
487 EOL, Line, /*EnsureNewLine*/ true);
488 WriteLineInfo(FileName, Line, FileType, EOL);
489 }
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000490 break;
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000491 }
492 case tok::pp_endif:
493 case tok::pp_else: {
494 // We surround every #include by #if 0 to comment it out, but that
495 // changes line numbers. These are fixed up right after that, but
496 // the whole #include could be inside a preprocessor conditional
497 // that is not processed. So it is necessary to fix the line
498 // numbers one the next line after each #else/#endif as well.
499 RawLex.SetKeepWhitespaceMode(true);
500 do {
501 RawLex.LexFromRawLexer(RawToken);
502 } while (RawToken.isNot(tok::eod) && RawToken.isNot(tok::eof));
503 OutputContentUpTo(
504 FromFile, NextToWrite,
505 SM.getFileOffset(RawToken.getLocation()) + RawToken.getLength(),
506 EOL, Line, /*EnsureNewLine*/ true);
507 WriteLineInfo(FileName, Line, FileType, EOL);
508 RawLex.SetKeepWhitespaceMode(false);
509 }
David Blaikied5321242012-06-06 18:52:13 +0000510 default:
511 break;
512 }
513 }
514 RawLex.setParsingPreprocessorDirective(false);
515 }
516 RawLex.LexFromRawLexer(RawToken);
517 }
518 OutputContentUpTo(FromFile, NextToWrite,
Argyrios Kyrtzidisd3910462013-05-07 04:29:22 +0000519 SM.getFileOffset(SM.getLocForEndOfFile(FileId)), EOL, Line,
David Blaikied5321242012-06-06 18:52:13 +0000520 /*EnsureNewline*/true);
521 return true;
522}
523
David Blaikie619117a2012-06-14 17:36:01 +0000524/// InclusionRewriterInInput - Implement -frewrite-includes mode.
David Blaikied5321242012-06-06 18:52:13 +0000525void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS,
526 const PreprocessorOutputOptions &Opts) {
527 SourceManager &SM = PP.getSourceManager();
528 InclusionRewriter *Rewrite = new InclusionRewriter(PP, *OS,
529 Opts.ShowLineMarkers);
530 PP.addPPCallbacks(Rewrite);
Lubos Lunak576a0412014-05-01 12:54:03 +0000531 PP.IgnorePragmas();
David Blaikied5321242012-06-06 18:52:13 +0000532
533 // First let the preprocessor process the entire file and call callbacks.
534 // Callbacks will record which #include's were actually performed.
535 PP.EnterMainSourceFile();
536 Token Tok;
537 // Only preprocessor directives matter here, so disable macro expansion
538 // everywhere else as an optimization.
539 // TODO: It would be even faster if the preprocessor could be switched
540 // to a mode where it would parse only preprocessor directives and comments,
541 // nothing else matters for parsing or processing.
542 PP.SetMacroExpansionOnlyInDirectives();
543 do {
544 PP.Lex(Tok);
545 } while (Tok.isNot(tok::eof));
Argyrios Kyrtzidis17ff2e52013-07-26 15:32:04 +0000546 Rewrite->setPredefinesBuffer(SM.getBuffer(PP.getPredefinesFileID()));
547 Rewrite->Process(PP.getPredefinesFileID(), SrcMgr::C_User);
David Blaikied5321242012-06-06 18:52:13 +0000548 Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User);
549 OS->flush();
550}