blob: d45cbc01df8ceee5d25de9f539cf3f3497dd1725 [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.
Justin Bogner0707fd02015-07-01 04:40:10 +000032 struct IncludedFile {
David Blaikied5321242012-06-06 18:52:13 +000033 FileID Id;
34 SrcMgr::CharacteristicKind FileType;
Justin Bogner0707fd02015-07-01 04:40:10 +000035 IncludedFile(FileID Id, SrcMgr::CharacteristicKind FileType)
36 : Id(Id), FileType(FileType) {}
David Blaikied5321242012-06-06 18:52:13 +000037 };
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +000038 Preprocessor &PP; ///< Used to find inclusion directives.
39 SourceManager &SM; ///< Used to read and manage source files.
40 raw_ostream &OS; ///< The destination stream for rewritten contents.
Reid Klecknere2793c02014-09-05 16:49:50 +000041 StringRef MainEOL; ///< The line ending marker to use.
Argyrios Kyrtzidis17ff2e52013-07-26 15:32:04 +000042 const llvm::MemoryBuffer *PredefinesBuffer; ///< The preprocessor predefines.
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +000043 bool ShowLineMarkers; ///< Show #line markers.
Reid Kleckner1df0fea2015-02-26 00:17:25 +000044 bool UseLineDirectives; ///< Use of line directives or line markers.
Justin Bogner0707fd02015-07-01 04:40:10 +000045 /// Tracks where inclusions that change the file are found.
46 std::map<unsigned, IncludedFile> FileIncludes;
47 /// Tracks where inclusions that import modules are found.
48 std::map<unsigned, const Module *> ModuleIncludes;
Richard Smithd1386302017-05-04 00:29:54 +000049 /// Tracks where inclusions that enter modules (in a module build) are found.
50 std::map<unsigned, const Module *> ModuleEntryIncludes;
Justin Bogner0707fd02015-07-01 04:40:10 +000051 /// Used transitively for building up the FileIncludes mapping over the
David Blaikied5321242012-06-06 18:52:13 +000052 /// various \c PPCallbacks callbacks.
Justin Bogner0707fd02015-07-01 04:40:10 +000053 SourceLocation LastInclusionLocation;
David Blaikied5321242012-06-06 18:52:13 +000054public:
Reid Kleckner1df0fea2015-02-26 00:17:25 +000055 InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers,
56 bool UseLineDirectives);
Richard Smithc7cacdc2017-04-29 00:54:03 +000057 void Process(FileID FileId, SrcMgr::CharacteristicKind FileType);
Argyrios Kyrtzidis17ff2e52013-07-26 15:32:04 +000058 void setPredefinesBuffer(const llvm::MemoryBuffer *Buf) {
59 PredefinesBuffer = Buf;
60 }
Reid Klecknere2793c02014-09-05 16:49:50 +000061 void detectMainFileEOL();
Richard Smithd1386302017-05-04 00:29:54 +000062 void handleModuleBegin(Token &Tok) {
63 assert(Tok.getKind() == tok::annot_module_begin);
64 ModuleEntryIncludes.insert({Tok.getLocation().getRawEncoding(),
65 (Module *)Tok.getAnnotationValue()});
66 }
David Blaikied5321242012-06-06 18:52:13 +000067private:
Craig Topperfb6b25b2014-03-15 04:29:04 +000068 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
69 SrcMgr::CharacteristicKind FileType,
70 FileID PrevFID) override;
Nikola Smiljanicfb891fc2015-05-12 11:48:05 +000071 void FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok,
Craig Topperfb6b25b2014-03-15 04:29:04 +000072 SrcMgr::CharacteristicKind FileType) override;
73 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
74 StringRef FileName, bool IsAngled,
75 CharSourceRange FilenameRange, const FileEntry *File,
76 StringRef SearchPath, StringRef RelativePath,
77 const Module *Imported) override;
Mehdi Amini99d1b292016-10-01 16:38:28 +000078 void WriteLineInfo(StringRef Filename, int Line,
David Blaikied5321242012-06-06 18:52:13 +000079 SrcMgr::CharacteristicKind FileType,
Reid Klecknere2793c02014-09-05 16:49:50 +000080 StringRef Extra = StringRef());
81 void WriteImplicitModuleImport(const Module *Mod);
David Blaikied5321242012-06-06 18:52:13 +000082 void OutputContentUpTo(const MemoryBuffer &FromFile,
83 unsigned &WriteFrom, unsigned WriteTo,
84 StringRef EOL, int &lines,
Alp Toker08c25002013-12-13 17:04:55 +000085 bool EnsureNewline);
David Blaikied5321242012-06-06 18:52:13 +000086 void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken,
87 const MemoryBuffer &FromFile, StringRef EOL,
88 unsigned &NextToWrite, int &Lines);
Benjamin Kramerb10e6152013-04-16 19:08:41 +000089 bool HandleHasInclude(FileID FileId, Lexer &RawLex,
90 const DirectoryLookup *Lookup, Token &Tok,
91 bool &FileExists);
Justin Bogner0707fd02015-07-01 04:40:10 +000092 const IncludedFile *FindIncludeAtLocation(SourceLocation Loc) const;
93 const Module *FindModuleAtLocation(SourceLocation Loc) const;
Richard Smithd1386302017-05-04 00:29:54 +000094 const Module *FindEnteredModule(SourceLocation Loc) const;
David Blaikied5321242012-06-06 18:52:13 +000095 StringRef NextIdentifierName(Lexer &RawLex, Token &RawToken);
96};
97
98} // end anonymous namespace
99
100/// Initializes an InclusionRewriter with a \p PP source and \p OS destination.
101InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS,
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000102 bool ShowLineMarkers,
103 bool UseLineDirectives)
Reid Klecknere2793c02014-09-05 16:49:50 +0000104 : PP(PP), SM(PP.getSourceManager()), OS(OS), MainEOL("\n"),
105 PredefinesBuffer(nullptr), ShowLineMarkers(ShowLineMarkers),
Eric Christopher8213f7f2015-02-26 00:29:54 +0000106 UseLineDirectives(UseLineDirectives),
Justin Bogner0707fd02015-07-01 04:40:10 +0000107 LastInclusionLocation(SourceLocation()) {}
David Blaikied5321242012-06-06 18:52:13 +0000108
109/// Write appropriate line information as either #line directives or GNU line
110/// markers depending on what mode we're in, including the \p Filename and
111/// \p Line we are located at, using the specified \p EOL line separator, and
112/// any \p Extra context specifiers in GNU line directives.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000113void InclusionRewriter::WriteLineInfo(StringRef Filename, int Line,
David Blaikied5321242012-06-06 18:52:13 +0000114 SrcMgr::CharacteristicKind FileType,
Reid Klecknere2793c02014-09-05 16:49:50 +0000115 StringRef Extra) {
David Blaikied5321242012-06-06 18:52:13 +0000116 if (!ShowLineMarkers)
117 return;
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000118 if (UseLineDirectives) {
Eli Friedman9fc443a2013-09-17 00:51:31 +0000119 OS << "#line" << ' ' << Line << ' ' << '"';
120 OS.write_escaped(Filename);
121 OS << '"';
David Blaikied5321242012-06-06 18:52:13 +0000122 } else {
123 // Use GNU linemarkers as described here:
124 // http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html
Eli Friedman80e45b82013-08-29 01:42:42 +0000125 OS << '#' << ' ' << Line << ' ' << '"';
126 OS.write_escaped(Filename);
127 OS << '"';
David Blaikied5321242012-06-06 18:52:13 +0000128 if (!Extra.empty())
129 OS << Extra;
130 if (FileType == SrcMgr::C_System)
131 // "`3' This indicates that the following text comes from a system header
132 // file, so certain warnings should be suppressed."
133 OS << " 3";
134 else if (FileType == SrcMgr::C_ExternCSystem)
135 // as above for `3', plus "`4' This indicates that the following text
136 // should be treated as being wrapped in an implicit extern "C" block."
137 OS << " 3 4";
138 }
Reid Klecknere2793c02014-09-05 16:49:50 +0000139 OS << MainEOL;
David Blaikied5321242012-06-06 18:52:13 +0000140}
141
Reid Klecknere2793c02014-09-05 16:49:50 +0000142void InclusionRewriter::WriteImplicitModuleImport(const Module *Mod) {
Richard Smithc51c38b2017-04-29 00:34:47 +0000143 OS << "#pragma clang module import " << Mod->getFullModuleName()
Reid Klecknere2793c02014-09-05 16:49:50 +0000144 << " /* clang -frewrite-includes: implicit import */" << MainEOL;
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000145}
146
David Blaikied5321242012-06-06 18:52:13 +0000147/// FileChanged - Whenever the preprocessor enters or exits a #include file
148/// it invokes this handler.
149void InclusionRewriter::FileChanged(SourceLocation Loc,
150 FileChangeReason Reason,
151 SrcMgr::CharacteristicKind NewFileType,
152 FileID) {
153 if (Reason != EnterFile)
154 return;
Justin Bogner0707fd02015-07-01 04:40:10 +0000155 if (LastInclusionLocation.isInvalid())
David Blaikied5321242012-06-06 18:52:13 +0000156 // we didn't reach this file (eg: the main file) via an inclusion directive
157 return;
Justin Bogner0707fd02015-07-01 04:40:10 +0000158 FileID Id = FullSourceLoc(Loc, SM).getFileID();
Justin Bogner879d4202015-07-01 04:53:19 +0000159 auto P = FileIncludes.insert(std::make_pair(
160 LastInclusionLocation.getRawEncoding(), IncludedFile(Id, NewFileType)));
Justin Bogner2510ba32015-07-01 05:41:50 +0000161 (void)P;
Justin Bogner0707fd02015-07-01 04:40:10 +0000162 assert(P.second && "Unexpected revisitation of the same include directive");
163 LastInclusionLocation = SourceLocation();
David Blaikied5321242012-06-06 18:52:13 +0000164}
165
166/// Called whenever an inclusion is skipped due to canonical header protection
167/// macros.
Nikola Smiljanicfb891fc2015-05-12 11:48:05 +0000168void InclusionRewriter::FileSkipped(const FileEntry &/*SkippedFile*/,
David Blaikied5321242012-06-06 18:52:13 +0000169 const Token &/*FilenameTok*/,
170 SrcMgr::CharacteristicKind /*FileType*/) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000171 assert(LastInclusionLocation.isValid() &&
Justin Bogner0707fd02015-07-01 04:40:10 +0000172 "A file, that wasn't found via an inclusion directive, was skipped");
173 LastInclusionLocation = SourceLocation();
David Blaikied5321242012-06-06 18:52:13 +0000174}
175
176/// This should be called whenever the preprocessor encounters include
177/// directives. It does not say whether the file has been included, but it
178/// provides more information about the directive (hash location instead
179/// of location inside the included file). It is assumed that the matching
180/// FileChanged() or FileSkipped() is called after this.
181void InclusionRewriter::InclusionDirective(SourceLocation HashLoc,
182 const Token &/*IncludeTok*/,
183 StringRef /*FileName*/,
184 bool /*IsAngled*/,
Argyrios Kyrtzidis4fcd2882012-09-27 01:42:07 +0000185 CharSourceRange /*FilenameRange*/,
David Blaikied5321242012-06-06 18:52:13 +0000186 const FileEntry * /*File*/,
David Blaikied5321242012-06-06 18:52:13 +0000187 StringRef /*SearchPath*/,
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000188 StringRef /*RelativePath*/,
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000189 const Module *Imported) {
Justin Bogner0707fd02015-07-01 04:40:10 +0000190 assert(LastInclusionLocation.isInvalid() &&
191 "Another inclusion directive was found before the previous one "
192 "was processed");
193 if (Imported) {
Justin Bogner879d4202015-07-01 04:53:19 +0000194 auto P = ModuleIncludes.insert(
195 std::make_pair(HashLoc.getRawEncoding(), Imported));
Justin Bogner2510ba32015-07-01 05:41:50 +0000196 (void)P;
Justin Bogner0707fd02015-07-01 04:40:10 +0000197 assert(P.second && "Unexpected revisitation of the same include directive");
198 } else
199 LastInclusionLocation = HashLoc;
David Blaikied5321242012-06-06 18:52:13 +0000200}
201
202/// Simple lookup for a SourceLocation (specifically one denoting the hash in
203/// an inclusion directive) in the map of inclusion information, FileChanges.
Justin Bogner0707fd02015-07-01 04:40:10 +0000204const InclusionRewriter::IncludedFile *
205InclusionRewriter::FindIncludeAtLocation(SourceLocation Loc) const {
206 const auto I = FileIncludes.find(Loc.getRawEncoding());
207 if (I != FileIncludes.end())
David Blaikied5321242012-06-06 18:52:13 +0000208 return &I->second;
Craig Topper8ae12032014-05-07 06:21:57 +0000209 return nullptr;
David Blaikied5321242012-06-06 18:52:13 +0000210}
211
Justin Bogner0707fd02015-07-01 04:40:10 +0000212/// Simple lookup for a SourceLocation (specifically one denoting the hash in
213/// an inclusion directive) in the map of module inclusion information.
214const Module *
215InclusionRewriter::FindModuleAtLocation(SourceLocation Loc) const {
216 const auto I = ModuleIncludes.find(Loc.getRawEncoding());
217 if (I != ModuleIncludes.end())
218 return I->second;
219 return nullptr;
220}
221
Richard Smithd1386302017-05-04 00:29:54 +0000222/// Simple lookup for a SourceLocation (specifically one denoting the hash in
223/// an inclusion directive) in the map of module entry information.
224const Module *
225InclusionRewriter::FindEnteredModule(SourceLocation Loc) const {
226 const auto I = ModuleEntryIncludes.find(Loc.getRawEncoding());
227 if (I != ModuleEntryIncludes.end())
228 return I->second;
229 return nullptr;
230}
231
David Blaikied5321242012-06-06 18:52:13 +0000232/// Detect the likely line ending style of \p FromFile by examining the first
233/// newline found within it.
234static StringRef DetectEOL(const MemoryBuffer &FromFile) {
Reid Klecknere2793c02014-09-05 16:49:50 +0000235 // Detect what line endings the file uses, so that added content does not mix
236 // the style. We need to check for "\r\n" first because "\n\r" will match
237 // "\r\n\r\n".
David Blaikied5321242012-06-06 18:52:13 +0000238 const char *Pos = strchr(FromFile.getBufferStart(), '\n');
Craig Topper8ae12032014-05-07 06:21:57 +0000239 if (!Pos)
David Blaikied5321242012-06-06 18:52:13 +0000240 return "\n";
David Blaikied5321242012-06-06 18:52:13 +0000241 if (Pos - 1 >= FromFile.getBufferStart() && Pos[-1] == '\r')
242 return "\r\n";
Reid Klecknere2793c02014-09-05 16:49:50 +0000243 if (Pos + 1 < FromFile.getBufferEnd() && Pos[1] == '\r')
244 return "\n\r";
David Blaikied5321242012-06-06 18:52:13 +0000245 return "\n";
246}
247
Reid Klecknere2793c02014-09-05 16:49:50 +0000248void InclusionRewriter::detectMainFileEOL() {
249 bool Invalid;
250 const MemoryBuffer &FromFile = *SM.getBuffer(SM.getMainFileID(), &Invalid);
251 assert(!Invalid);
252 if (Invalid)
253 return; // Should never happen, but whatever.
254 MainEOL = DetectEOL(FromFile);
255}
256
David Blaikied5321242012-06-06 18:52:13 +0000257/// Writes out bytes from \p FromFile, starting at \p NextToWrite and ending at
258/// \p WriteTo - 1.
259void InclusionRewriter::OutputContentUpTo(const MemoryBuffer &FromFile,
260 unsigned &WriteFrom, unsigned WriteTo,
Reid Klecknere2793c02014-09-05 16:49:50 +0000261 StringRef LocalEOL, int &Line,
David Blaikied5321242012-06-06 18:52:13 +0000262 bool EnsureNewline) {
263 if (WriteTo <= WriteFrom)
264 return;
Argyrios Kyrtzidis17ff2e52013-07-26 15:32:04 +0000265 if (&FromFile == PredefinesBuffer) {
266 // Ignore the #defines of the predefines buffer.
267 WriteFrom = WriteTo;
268 return;
269 }
Reid Klecknere2793c02014-09-05 16:49:50 +0000270
271 // If we would output half of a line ending, advance one character to output
272 // the whole line ending. All buffers are null terminated, so looking ahead
273 // one byte is safe.
274 if (LocalEOL.size() == 2 &&
275 LocalEOL[0] == (FromFile.getBufferStart() + WriteTo)[-1] &&
276 LocalEOL[1] == (FromFile.getBufferStart() + WriteTo)[0])
277 WriteTo++;
278
279 StringRef TextToWrite(FromFile.getBufferStart() + WriteFrom,
280 WriteTo - WriteFrom);
281
282 if (MainEOL == LocalEOL) {
283 OS << TextToWrite;
284 // count lines manually, it's faster than getPresumedLoc()
285 Line += TextToWrite.count(LocalEOL);
286 if (EnsureNewline && !TextToWrite.endswith(LocalEOL))
287 OS << MainEOL;
288 } else {
289 // Output the file one line at a time, rewriting the line endings as we go.
290 StringRef Rest = TextToWrite;
291 while (!Rest.empty()) {
292 StringRef LineText;
293 std::tie(LineText, Rest) = Rest.split(LocalEOL);
294 OS << LineText;
295 Line++;
296 if (!Rest.empty())
297 OS << MainEOL;
298 }
299 if (TextToWrite.endswith(LocalEOL) || EnsureNewline)
300 OS << MainEOL;
David Blaikied5321242012-06-06 18:52:13 +0000301 }
302 WriteFrom = WriteTo;
303}
304
305/// Print characters from \p FromFile starting at \p NextToWrite up until the
306/// inclusion directive at \p StartToken, then print out the inclusion
307/// inclusion directive disabled by a #if directive, updating \p NextToWrite
308/// and \p Line to track the number of source lines visited and the progress
309/// through the \p FromFile buffer.
310void InclusionRewriter::CommentOutDirective(Lexer &DirectiveLex,
311 const Token &StartToken,
312 const MemoryBuffer &FromFile,
Reid Klecknere2793c02014-09-05 16:49:50 +0000313 StringRef LocalEOL,
David Blaikied5321242012-06-06 18:52:13 +0000314 unsigned &NextToWrite, int &Line) {
315 OutputContentUpTo(FromFile, NextToWrite,
Reid Klecknere2793c02014-09-05 16:49:50 +0000316 SM.getFileOffset(StartToken.getLocation()), LocalEOL, Line,
317 false);
David Blaikied5321242012-06-06 18:52:13 +0000318 Token DirectiveToken;
319 do {
320 DirectiveLex.LexFromRawLexer(DirectiveToken);
321 } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof));
Lubos Lunak72cad682014-05-01 21:10:08 +0000322 if (&FromFile == PredefinesBuffer) {
323 // OutputContentUpTo() would not output anything anyway.
324 return;
325 }
Reid Klecknere2793c02014-09-05 16:49:50 +0000326 OS << "#if 0 /* expanded by -frewrite-includes */" << MainEOL;
David Blaikied5321242012-06-06 18:52:13 +0000327 OutputContentUpTo(FromFile, NextToWrite,
Reid Klecknere2793c02014-09-05 16:49:50 +0000328 SM.getFileOffset(DirectiveToken.getLocation()) +
329 DirectiveToken.getLength(),
330 LocalEOL, Line, true);
331 OS << "#endif /* expanded by -frewrite-includes */" << MainEOL;
David Blaikied5321242012-06-06 18:52:13 +0000332}
333
334/// Find the next identifier in the pragma directive specified by \p RawToken.
335StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex,
336 Token &RawToken) {
337 RawLex.LexFromRawLexer(RawToken);
338 if (RawToken.is(tok::raw_identifier))
339 PP.LookUpIdentifierInfo(RawToken);
340 if (RawToken.is(tok::identifier))
341 return RawToken.getIdentifierInfo()->getName();
342 return StringRef();
343}
344
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000345// Expand __has_include and __has_include_next if possible. If there's no
346// definitive answer return false.
347bool InclusionRewriter::HandleHasInclude(
348 FileID FileId, Lexer &RawLex, const DirectoryLookup *Lookup, Token &Tok,
349 bool &FileExists) {
350 // Lex the opening paren.
351 RawLex.LexFromRawLexer(Tok);
352 if (Tok.isNot(tok::l_paren))
353 return false;
354
355 RawLex.LexFromRawLexer(Tok);
356
357 SmallString<128> FilenameBuffer;
358 StringRef Filename;
359 // Since the raw lexer doesn't give us angle_literals we have to parse them
360 // ourselves.
361 // FIXME: What to do if the file name is a macro?
362 if (Tok.is(tok::less)) {
363 RawLex.LexFromRawLexer(Tok);
364
365 FilenameBuffer += '<';
366 do {
367 if (Tok.is(tok::eod)) // Sanity check.
368 return false;
369
370 if (Tok.is(tok::raw_identifier))
371 PP.LookUpIdentifierInfo(Tok);
372
373 // Get the string piece.
374 SmallVector<char, 128> TmpBuffer;
375 bool Invalid = false;
376 StringRef TmpName = PP.getSpelling(Tok, TmpBuffer, &Invalid);
377 if (Invalid)
378 return false;
379
380 FilenameBuffer += TmpName;
381
382 RawLex.LexFromRawLexer(Tok);
383 } while (Tok.isNot(tok::greater));
384
385 FilenameBuffer += '>';
386 Filename = FilenameBuffer;
387 } else {
388 if (Tok.isNot(tok::string_literal))
389 return false;
390
391 bool Invalid = false;
392 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
393 if (Invalid)
394 return false;
395 }
396
397 // Lex the closing paren.
398 RawLex.LexFromRawLexer(Tok);
399 if (Tok.isNot(tok::r_paren))
400 return false;
401
402 // Now ask HeaderInfo if it knows about the header.
403 // FIXME: Subframeworks aren't handled here. Do we care?
404 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
405 const DirectoryLookup *CurDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000406 const FileEntry *FileEnt = PP.getSourceManager().getFileEntryForID(FileId);
407 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 1>
408 Includers;
409 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Richard Smith3d5b48c2015-10-16 21:42:56 +0000410 // FIXME: Why don't we call PP.LookupFile here?
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000411 const FileEntry *File = PP.getHeaderSearchInfo().LookupFile(
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000412 Filename, SourceLocation(), isAngled, nullptr, CurDir, Includers, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000413 nullptr, nullptr, nullptr, nullptr);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000414
Craig Topper8ae12032014-05-07 06:21:57 +0000415 FileExists = File != nullptr;
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000416 return true;
417}
418
Benjamin Kramere2881572013-10-13 12:02:16 +0000419/// Use a raw lexer to analyze \p FileId, incrementally copying parts of it
David Blaikied5321242012-06-06 18:52:13 +0000420/// and including content of included files recursively.
Richard Smithc7cacdc2017-04-29 00:54:03 +0000421void InclusionRewriter::Process(FileID FileId,
422 SrcMgr::CharacteristicKind FileType) {
David Blaikied5321242012-06-06 18:52:13 +0000423 bool Invalid;
424 const MemoryBuffer &FromFile = *SM.getBuffer(FileId, &Invalid);
Justin Bogner0707fd02015-07-01 04:40:10 +0000425 assert(!Invalid && "Attempting to process invalid inclusion");
Mehdi Amini99d1b292016-10-01 16:38:28 +0000426 StringRef FileName = FromFile.getBufferIdentifier();
David Blaikied5321242012-06-06 18:52:13 +0000427 Lexer RawLex(FileId, &FromFile, PP.getSourceManager(), PP.getLangOpts());
428 RawLex.SetCommentRetentionState(false);
429
Reid Klecknere2793c02014-09-05 16:49:50 +0000430 StringRef LocalEOL = DetectEOL(FromFile);
David Blaikied5321242012-06-06 18:52:13 +0000431
Lubos Lunak10961c02014-05-01 13:50:44 +0000432 // Per the GNU docs: "1" indicates entering a new file.
Lubos Lunak72cad682014-05-01 21:10:08 +0000433 if (FileId == SM.getMainFileID() || FileId == PP.getPredefinesFileID())
Reid Klecknere2793c02014-09-05 16:49:50 +0000434 WriteLineInfo(FileName, 1, FileType, "");
Lubos Lunak10961c02014-05-01 13:50:44 +0000435 else
Reid Klecknere2793c02014-09-05 16:49:50 +0000436 WriteLineInfo(FileName, 1, FileType, " 1");
David Blaikied5321242012-06-06 18:52:13 +0000437
438 if (SM.getFileIDSize(FileId) == 0)
Richard Smithc7cacdc2017-04-29 00:54:03 +0000439 return;
David Blaikied5321242012-06-06 18:52:13 +0000440
Alp Toker3dfeafd2013-11-28 07:21:44 +0000441 // The next byte to be copied from the source file, which may be non-zero if
442 // the lexer handled a BOM.
Alp Toker52937ab2013-12-05 17:28:42 +0000443 unsigned NextToWrite = SM.getFileOffset(RawLex.getSourceLocation());
444 assert(SM.getLineNumber(FileId, NextToWrite) == 1);
David Blaikied5321242012-06-06 18:52:13 +0000445 int Line = 1; // The current input file line number.
446
447 Token RawToken;
448 RawLex.LexFromRawLexer(RawToken);
449
450 // TODO: Consider adding a switch that strips possibly unimportant content,
451 // such as comments, to reduce the size of repro files.
452 while (RawToken.isNot(tok::eof)) {
453 if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) {
454 RawLex.setParsingPreprocessorDirective(true);
455 Token HashToken = RawToken;
456 RawLex.LexFromRawLexer(RawToken);
457 if (RawToken.is(tok::raw_identifier))
458 PP.LookUpIdentifierInfo(RawToken);
Craig Topper8ae12032014-05-07 06:21:57 +0000459 if (RawToken.getIdentifierInfo() != nullptr) {
David Blaikied5321242012-06-06 18:52:13 +0000460 switch (RawToken.getIdentifierInfo()->getPPKeywordID()) {
461 case tok::pp_include:
462 case tok::pp_include_next:
463 case tok::pp_import: {
Reid Klecknere2793c02014-09-05 16:49:50 +0000464 CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL, NextToWrite,
David Blaikied5321242012-06-06 18:52:13 +0000465 Line);
Lubos Lunak4526b462014-05-01 21:11:57 +0000466 if (FileId != PP.getPredefinesFileID())
Reid Klecknere2793c02014-09-05 16:49:50 +0000467 WriteLineInfo(FileName, Line - 1, FileType, "");
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000468 StringRef LineInfoExtra;
Justin Bogner0707fd02015-07-01 04:40:10 +0000469 SourceLocation Loc = HashToken.getLocation();
Richard Smithc51c38b2017-04-29 00:34:47 +0000470 if (const Module *Mod = FindModuleAtLocation(Loc))
Justin Bogner0707fd02015-07-01 04:40:10 +0000471 WriteImplicitModuleImport(Mod);
472 else if (const IncludedFile *Inc = FindIncludeAtLocation(Loc)) {
Richard Smithd1386302017-05-04 00:29:54 +0000473 const Module *Mod = FindEnteredModule(Loc);
474 if (Mod)
475 OS << "#pragma clang module begin " << Mod->getFullModuleName()
476 << "\n";
477
Richard Smithc7cacdc2017-04-29 00:54:03 +0000478 // Include and recursively process the file.
479 Process(Inc->Id, Inc->FileType);
Richard Smithd1386302017-05-04 00:29:54 +0000480
481 if (Mod)
482 OS << "#pragma clang module end /*" << Mod->getFullModuleName()
483 << "*/\n";
484
Richard Smithc7cacdc2017-04-29 00:54:03 +0000485 // Add line marker to indicate we're returning from an included
486 // file.
487 LineInfoExtra = " 2";
Argyrios Kyrtzidiscf22d1f2013-04-10 01:53:50 +0000488 }
489 // fix up lineinfo (since commented out directive changed line
490 // numbers) for inclusions that were skipped due to header guards
Reid Klecknere2793c02014-09-05 16:49:50 +0000491 WriteLineInfo(FileName, Line, FileType, LineInfoExtra);
David Blaikied5321242012-06-06 18:52:13 +0000492 break;
493 }
494 case tok::pp_pragma: {
495 StringRef Identifier = NextIdentifierName(RawLex, RawToken);
496 if (Identifier == "clang" || Identifier == "GCC") {
497 if (NextIdentifierName(RawLex, RawToken) == "system_header") {
498 // keep the directive in, commented out
Reid Klecknere2793c02014-09-05 16:49:50 +0000499 CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL,
David Blaikied5321242012-06-06 18:52:13 +0000500 NextToWrite, Line);
501 // update our own type
502 FileType = SM.getFileCharacteristic(RawToken.getLocation());
Reid Klecknere2793c02014-09-05 16:49:50 +0000503 WriteLineInfo(FileName, Line, FileType);
David Blaikied5321242012-06-06 18:52:13 +0000504 }
505 } else if (Identifier == "once") {
506 // keep the directive in, commented out
Reid Klecknere2793c02014-09-05 16:49:50 +0000507 CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL,
David Blaikied5321242012-06-06 18:52:13 +0000508 NextToWrite, Line);
Reid Klecknere2793c02014-09-05 16:49:50 +0000509 WriteLineInfo(FileName, Line, FileType);
David Blaikied5321242012-06-06 18:52:13 +0000510 }
511 break;
512 }
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000513 case tok::pp_if:
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000514 case tok::pp_elif: {
515 bool elif = (RawToken.getIdentifierInfo()->getPPKeywordID() ==
516 tok::pp_elif);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000517 // Rewrite special builtin macros to avoid pulling in host details.
518 do {
519 // Walk over the directive.
520 RawLex.LexFromRawLexer(RawToken);
521 if (RawToken.is(tok::raw_identifier))
522 PP.LookUpIdentifierInfo(RawToken);
523
524 if (RawToken.is(tok::identifier)) {
525 bool HasFile;
526 SourceLocation Loc = RawToken.getLocation();
527
528 // Rewrite __has_include(x)
529 if (RawToken.getIdentifierInfo()->isStr("__has_include")) {
Craig Topper8ae12032014-05-07 06:21:57 +0000530 if (!HandleHasInclude(FileId, RawLex, nullptr, RawToken,
531 HasFile))
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000532 continue;
533 // Rewrite __has_include_next(x)
534 } else if (RawToken.getIdentifierInfo()->isStr(
535 "__has_include_next")) {
536 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
537 if (Lookup)
538 ++Lookup;
539
540 if (!HandleHasInclude(FileId, RawLex, Lookup, RawToken,
541 HasFile))
542 continue;
543 } else {
544 continue;
545 }
546 // Replace the macro with (0) or (1), followed by the commented
547 // out macro for reference.
548 OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(Loc),
Reid Klecknere2793c02014-09-05 16:49:50 +0000549 LocalEOL, Line, false);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000550 OS << '(' << (int) HasFile << ")/*";
551 OutputContentUpTo(FromFile, NextToWrite,
552 SM.getFileOffset(RawToken.getLocation()) +
Reid Klecknere2793c02014-09-05 16:49:50 +0000553 RawToken.getLength(),
554 LocalEOL, Line, false);
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000555 OS << "*/";
556 }
557 } while (RawToken.isNot(tok::eod));
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000558 if (elif) {
559 OutputContentUpTo(FromFile, NextToWrite,
560 SM.getFileOffset(RawToken.getLocation()) +
561 RawToken.getLength(),
Reid Klecknere2793c02014-09-05 16:49:50 +0000562 LocalEOL, Line, /*EnsureNewline=*/ true);
563 WriteLineInfo(FileName, Line, FileType);
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000564 }
Benjamin Kramerb10e6152013-04-16 19:08:41 +0000565 break;
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000566 }
567 case tok::pp_endif:
568 case tok::pp_else: {
569 // We surround every #include by #if 0 to comment it out, but that
570 // changes line numbers. These are fixed up right after that, but
571 // the whole #include could be inside a preprocessor conditional
572 // that is not processed. So it is necessary to fix the line
573 // numbers one the next line after each #else/#endif as well.
574 RawLex.SetKeepWhitespaceMode(true);
575 do {
576 RawLex.LexFromRawLexer(RawToken);
577 } while (RawToken.isNot(tok::eod) && RawToken.isNot(tok::eof));
Reid Klecknere2793c02014-09-05 16:49:50 +0000578 OutputContentUpTo(FromFile, NextToWrite,
579 SM.getFileOffset(RawToken.getLocation()) +
580 RawToken.getLength(),
581 LocalEOL, Line, /*EnsureNewline=*/ true);
582 WriteLineInfo(FileName, Line, FileType);
Lubos Lunak4c22f6a2013-07-20 14:23:27 +0000583 RawLex.SetKeepWhitespaceMode(false);
584 }
David Blaikied5321242012-06-06 18:52:13 +0000585 default:
586 break;
587 }
588 }
589 RawLex.setParsingPreprocessorDirective(false);
590 }
591 RawLex.LexFromRawLexer(RawToken);
592 }
593 OutputContentUpTo(FromFile, NextToWrite,
Reid Klecknere2793c02014-09-05 16:49:50 +0000594 SM.getFileOffset(SM.getLocForEndOfFile(FileId)), LocalEOL,
595 Line, /*EnsureNewline=*/true);
David Blaikied5321242012-06-06 18:52:13 +0000596}
597
David Blaikie619117a2012-06-14 17:36:01 +0000598/// InclusionRewriterInInput - Implement -frewrite-includes mode.
David Blaikied5321242012-06-06 18:52:13 +0000599void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS,
600 const PreprocessorOutputOptions &Opts) {
601 SourceManager &SM = PP.getSourceManager();
Reid Kleckner1df0fea2015-02-26 00:17:25 +0000602 InclusionRewriter *Rewrite = new InclusionRewriter(
603 PP, *OS, Opts.ShowLineMarkers, Opts.UseLineDirectives);
Reid Klecknere2793c02014-09-05 16:49:50 +0000604 Rewrite->detectMainFileEOL();
605
Craig Topperb8a70532014-09-10 04:53:53 +0000606 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Rewrite));
Lubos Lunak576a0412014-05-01 12:54:03 +0000607 PP.IgnorePragmas();
David Blaikied5321242012-06-06 18:52:13 +0000608
609 // First let the preprocessor process the entire file and call callbacks.
610 // Callbacks will record which #include's were actually performed.
611 PP.EnterMainSourceFile();
612 Token Tok;
613 // Only preprocessor directives matter here, so disable macro expansion
614 // everywhere else as an optimization.
615 // TODO: It would be even faster if the preprocessor could be switched
616 // to a mode where it would parse only preprocessor directives and comments,
617 // nothing else matters for parsing or processing.
618 PP.SetMacroExpansionOnlyInDirectives();
619 do {
620 PP.Lex(Tok);
Richard Smithd1386302017-05-04 00:29:54 +0000621 if (Tok.is(tok::annot_module_begin))
622 Rewrite->handleModuleBegin(Tok);
David Blaikied5321242012-06-06 18:52:13 +0000623 } while (Tok.isNot(tok::eof));
Argyrios Kyrtzidis17ff2e52013-07-26 15:32:04 +0000624 Rewrite->setPredefinesBuffer(SM.getBuffer(PP.getPredefinesFileID()));
625 Rewrite->Process(PP.getPredefinesFileID(), SrcMgr::C_User);
David Blaikied5321242012-06-06 18:52:13 +0000626 Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User);
627 OS->flush();
628}