1 //===--- 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 15 #include "clang/Rewrite/Frontend/Rewriters.h" 16 #include "clang/Basic/SourceManager.h" 17 #include "clang/Frontend/PreprocessorOutputOptions.h" 18 #include "clang/Lex/HeaderSearch.h" 19 #include "clang/Lex/Pragma.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "llvm/ADT/SmallString.h" 22 #include "llvm/Support/raw_ostream.h" 23 24 using namespace clang; 25 using namespace llvm; 26 27 namespace { 28 29 class InclusionRewriter : public PPCallbacks { 30 /// Information about which #includes were actually performed, 31 /// created by preprocessor callbacks. 32 struct IncludedFile { 33 FileID Id; 34 SrcMgr::CharacteristicKind FileType; 35 const DirectoryLookup *DirLookup; 36 IncludedFile(FileID Id, SrcMgr::CharacteristicKind FileType, 37 const DirectoryLookup *DirLookup) 38 : Id(Id), FileType(FileType), DirLookup(DirLookup) {} 39 }; 40 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. 43 StringRef MainEOL; ///< The line ending marker to use. 44 const llvm::MemoryBuffer *PredefinesBuffer; ///< The preprocessor predefines. 45 bool ShowLineMarkers; ///< Show #line markers. 46 bool UseLineDirectives; ///< Use of line directives or line markers. 47 /// Tracks where inclusions that change the file are found. 48 std::map<unsigned, IncludedFile> FileIncludes; 49 /// Tracks where inclusions that import modules are found. 50 std::map<unsigned, const Module *> ModuleIncludes; 51 /// Tracks where inclusions that enter modules (in a module build) are found. 52 std::map<unsigned, const Module *> ModuleEntryIncludes; 53 /// Used transitively for building up the FileIncludes mapping over the 54 /// various \c PPCallbacks callbacks. 55 SourceLocation LastInclusionLocation; 56 public: 57 InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers, 58 bool UseLineDirectives); 59 void Process(FileID FileId, SrcMgr::CharacteristicKind FileType, 60 const DirectoryLookup *DirLookup); 61 void setPredefinesBuffer(const llvm::MemoryBuffer *Buf) { 62 PredefinesBuffer = Buf; 63 } 64 void detectMainFileEOL(); 65 void handleModuleBegin(Token &Tok) { 66 assert(Tok.getKind() == tok::annot_module_begin); 67 ModuleEntryIncludes.insert({Tok.getLocation().getRawEncoding(), 68 (Module *)Tok.getAnnotationValue()}); 69 } 70 private: 71 void FileChanged(SourceLocation Loc, FileChangeReason Reason, 72 SrcMgr::CharacteristicKind FileType, 73 FileID PrevFID) override; 74 void FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok, 75 SrcMgr::CharacteristicKind FileType) override; 76 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, 77 StringRef FileName, bool IsAngled, 78 CharSourceRange FilenameRange, const FileEntry *File, 79 StringRef SearchPath, StringRef RelativePath, 80 const Module *Imported) override; 81 void WriteLineInfo(StringRef Filename, int Line, 82 SrcMgr::CharacteristicKind FileType, 83 StringRef Extra = StringRef()); 84 void WriteImplicitModuleImport(const Module *Mod); 85 void OutputContentUpTo(const MemoryBuffer &FromFile, 86 unsigned &WriteFrom, unsigned WriteTo, 87 StringRef EOL, int &lines, 88 bool EnsureNewline); 89 void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken, 90 const MemoryBuffer &FromFile, StringRef EOL, 91 unsigned &NextToWrite, int &Lines); 92 bool HandleHasInclude(FileID FileId, Lexer &RawLex, 93 const DirectoryLookup *Lookup, Token &Tok, 94 bool &FileExists); 95 const IncludedFile *FindIncludeAtLocation(SourceLocation Loc) const; 96 const Module *FindModuleAtLocation(SourceLocation Loc) const; 97 const Module *FindEnteredModule(SourceLocation Loc) const; 98 StringRef NextIdentifierName(Lexer &RawLex, Token &RawToken); 99 }; 100 101 } // end anonymous namespace 102 103 /// Initializes an InclusionRewriter with a \p PP source and \p OS destination. 104 InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS, 105 bool ShowLineMarkers, 106 bool UseLineDirectives) 107 : PP(PP), SM(PP.getSourceManager()), OS(OS), MainEOL("\n"), 108 PredefinesBuffer(nullptr), ShowLineMarkers(ShowLineMarkers), 109 UseLineDirectives(UseLineDirectives), 110 LastInclusionLocation(SourceLocation()) {} 111 112 /// Write appropriate line information as either #line directives or GNU line 113 /// markers depending on what mode we're in, including the \p Filename and 114 /// \p Line we are located at, using the specified \p EOL line separator, and 115 /// any \p Extra context specifiers in GNU line directives. 116 void InclusionRewriter::WriteLineInfo(StringRef Filename, int Line, 117 SrcMgr::CharacteristicKind FileType, 118 StringRef Extra) { 119 if (!ShowLineMarkers) 120 return; 121 if (UseLineDirectives) { 122 OS << "#line" << ' ' << Line << ' ' << '"'; 123 OS.write_escaped(Filename); 124 OS << '"'; 125 } else { 126 // Use GNU linemarkers as described here: 127 // http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html 128 OS << '#' << ' ' << Line << ' ' << '"'; 129 OS.write_escaped(Filename); 130 OS << '"'; 131 if (!Extra.empty()) 132 OS << Extra; 133 if (FileType == SrcMgr::C_System) 134 // "`3' This indicates that the following text comes from a system header 135 // file, so certain warnings should be suppressed." 136 OS << " 3"; 137 else if (FileType == SrcMgr::C_ExternCSystem) 138 // as above for `3', plus "`4' This indicates that the following text 139 // should be treated as being wrapped in an implicit extern "C" block." 140 OS << " 3 4"; 141 } 142 OS << MainEOL; 143 } 144 145 void InclusionRewriter::WriteImplicitModuleImport(const Module *Mod) { 146 OS << "#pragma clang module import " << Mod->getFullModuleName(true) 147 << " /* clang -frewrite-includes: implicit import */" << MainEOL; 148 } 149 150 /// FileChanged - Whenever the preprocessor enters or exits a #include file 151 /// it invokes this handler. 152 void InclusionRewriter::FileChanged(SourceLocation Loc, 153 FileChangeReason Reason, 154 SrcMgr::CharacteristicKind NewFileType, 155 FileID) { 156 if (Reason != EnterFile) 157 return; 158 if (LastInclusionLocation.isInvalid()) 159 // we didn't reach this file (eg: the main file) via an inclusion directive 160 return; 161 FileID Id = FullSourceLoc(Loc, SM).getFileID(); 162 auto P = FileIncludes.insert( 163 std::make_pair(LastInclusionLocation.getRawEncoding(), 164 IncludedFile(Id, NewFileType, PP.GetCurDirLookup()))); 165 (void)P; 166 assert(P.second && "Unexpected revisitation of the same include directive"); 167 LastInclusionLocation = SourceLocation(); 168 } 169 170 /// Called whenever an inclusion is skipped due to canonical header protection 171 /// macros. 172 void InclusionRewriter::FileSkipped(const FileEntry &/*SkippedFile*/, 173 const Token &/*FilenameTok*/, 174 SrcMgr::CharacteristicKind /*FileType*/) { 175 assert(LastInclusionLocation.isValid() && 176 "A file, that wasn't found via an inclusion directive, was skipped"); 177 LastInclusionLocation = SourceLocation(); 178 } 179 180 /// This should be called whenever the preprocessor encounters include 181 /// directives. It does not say whether the file has been included, but it 182 /// provides more information about the directive (hash location instead 183 /// of location inside the included file). It is assumed that the matching 184 /// FileChanged() or FileSkipped() is called after this (or neither is 185 /// called if this #include results in an error or does not textually include 186 /// anything). 187 void InclusionRewriter::InclusionDirective(SourceLocation HashLoc, 188 const Token &/*IncludeTok*/, 189 StringRef /*FileName*/, 190 bool /*IsAngled*/, 191 CharSourceRange /*FilenameRange*/, 192 const FileEntry * /*File*/, 193 StringRef /*SearchPath*/, 194 StringRef /*RelativePath*/, 195 const Module *Imported) { 196 if (Imported) { 197 auto P = ModuleIncludes.insert( 198 std::make_pair(HashLoc.getRawEncoding(), Imported)); 199 (void)P; 200 assert(P.second && "Unexpected revisitation of the same include directive"); 201 } else 202 LastInclusionLocation = HashLoc; 203 } 204 205 /// Simple lookup for a SourceLocation (specifically one denoting the hash in 206 /// an inclusion directive) in the map of inclusion information, FileChanges. 207 const InclusionRewriter::IncludedFile * 208 InclusionRewriter::FindIncludeAtLocation(SourceLocation Loc) const { 209 const auto I = FileIncludes.find(Loc.getRawEncoding()); 210 if (I != FileIncludes.end()) 211 return &I->second; 212 return nullptr; 213 } 214 215 /// Simple lookup for a SourceLocation (specifically one denoting the hash in 216 /// an inclusion directive) in the map of module inclusion information. 217 const Module * 218 InclusionRewriter::FindModuleAtLocation(SourceLocation Loc) const { 219 const auto I = ModuleIncludes.find(Loc.getRawEncoding()); 220 if (I != ModuleIncludes.end()) 221 return I->second; 222 return nullptr; 223 } 224 225 /// Simple lookup for a SourceLocation (specifically one denoting the hash in 226 /// an inclusion directive) in the map of module entry information. 227 const Module * 228 InclusionRewriter::FindEnteredModule(SourceLocation Loc) const { 229 const auto I = ModuleEntryIncludes.find(Loc.getRawEncoding()); 230 if (I != ModuleEntryIncludes.end()) 231 return I->second; 232 return nullptr; 233 } 234 235 /// Detect the likely line ending style of \p FromFile by examining the first 236 /// newline found within it. 237 static StringRef DetectEOL(const MemoryBuffer &FromFile) { 238 // Detect what line endings the file uses, so that added content does not mix 239 // the style. We need to check for "\r\n" first because "\n\r" will match 240 // "\r\n\r\n". 241 const char *Pos = strchr(FromFile.getBufferStart(), '\n'); 242 if (!Pos) 243 return "\n"; 244 if (Pos - 1 >= FromFile.getBufferStart() && Pos[-1] == '\r') 245 return "\r\n"; 246 if (Pos + 1 < FromFile.getBufferEnd() && Pos[1] == '\r') 247 return "\n\r"; 248 return "\n"; 249 } 250 251 void InclusionRewriter::detectMainFileEOL() { 252 bool Invalid; 253 const MemoryBuffer &FromFile = *SM.getBuffer(SM.getMainFileID(), &Invalid); 254 assert(!Invalid); 255 if (Invalid) 256 return; // Should never happen, but whatever. 257 MainEOL = DetectEOL(FromFile); 258 } 259 260 /// Writes out bytes from \p FromFile, starting at \p NextToWrite and ending at 261 /// \p WriteTo - 1. 262 void InclusionRewriter::OutputContentUpTo(const MemoryBuffer &FromFile, 263 unsigned &WriteFrom, unsigned WriteTo, 264 StringRef LocalEOL, int &Line, 265 bool EnsureNewline) { 266 if (WriteTo <= WriteFrom) 267 return; 268 if (&FromFile == PredefinesBuffer) { 269 // Ignore the #defines of the predefines buffer. 270 WriteFrom = WriteTo; 271 return; 272 } 273 274 // If we would output half of a line ending, advance one character to output 275 // the whole line ending. All buffers are null terminated, so looking ahead 276 // one byte is safe. 277 if (LocalEOL.size() == 2 && 278 LocalEOL[0] == (FromFile.getBufferStart() + WriteTo)[-1] && 279 LocalEOL[1] == (FromFile.getBufferStart() + WriteTo)[0]) 280 WriteTo++; 281 282 StringRef TextToWrite(FromFile.getBufferStart() + WriteFrom, 283 WriteTo - WriteFrom); 284 285 if (MainEOL == LocalEOL) { 286 OS << TextToWrite; 287 // count lines manually, it's faster than getPresumedLoc() 288 Line += TextToWrite.count(LocalEOL); 289 if (EnsureNewline && !TextToWrite.endswith(LocalEOL)) 290 OS << MainEOL; 291 } else { 292 // Output the file one line at a time, rewriting the line endings as we go. 293 StringRef Rest = TextToWrite; 294 while (!Rest.empty()) { 295 StringRef LineText; 296 std::tie(LineText, Rest) = Rest.split(LocalEOL); 297 OS << LineText; 298 Line++; 299 if (!Rest.empty()) 300 OS << MainEOL; 301 } 302 if (TextToWrite.endswith(LocalEOL) || EnsureNewline) 303 OS << MainEOL; 304 } 305 WriteFrom = WriteTo; 306 } 307 308 /// Print characters from \p FromFile starting at \p NextToWrite up until the 309 /// inclusion directive at \p StartToken, then print out the inclusion 310 /// inclusion directive disabled by a #if directive, updating \p NextToWrite 311 /// and \p Line to track the number of source lines visited and the progress 312 /// through the \p FromFile buffer. 313 void InclusionRewriter::CommentOutDirective(Lexer &DirectiveLex, 314 const Token &StartToken, 315 const MemoryBuffer &FromFile, 316 StringRef LocalEOL, 317 unsigned &NextToWrite, int &Line) { 318 OutputContentUpTo(FromFile, NextToWrite, 319 SM.getFileOffset(StartToken.getLocation()), LocalEOL, Line, 320 false); 321 Token DirectiveToken; 322 do { 323 DirectiveLex.LexFromRawLexer(DirectiveToken); 324 } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof)); 325 if (&FromFile == PredefinesBuffer) { 326 // OutputContentUpTo() would not output anything anyway. 327 return; 328 } 329 OS << "#if 0 /* expanded by -frewrite-includes */" << MainEOL; 330 OutputContentUpTo(FromFile, NextToWrite, 331 SM.getFileOffset(DirectiveToken.getLocation()) + 332 DirectiveToken.getLength(), 333 LocalEOL, Line, true); 334 OS << "#endif /* expanded by -frewrite-includes */" << MainEOL; 335 } 336 337 /// Find the next identifier in the pragma directive specified by \p RawToken. 338 StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex, 339 Token &RawToken) { 340 RawLex.LexFromRawLexer(RawToken); 341 if (RawToken.is(tok::raw_identifier)) 342 PP.LookUpIdentifierInfo(RawToken); 343 if (RawToken.is(tok::identifier)) 344 return RawToken.getIdentifierInfo()->getName(); 345 return StringRef(); 346 } 347 348 // Expand __has_include and __has_include_next if possible. If there's no 349 // definitive answer return false. 350 bool InclusionRewriter::HandleHasInclude( 351 FileID FileId, Lexer &RawLex, const DirectoryLookup *Lookup, Token &Tok, 352 bool &FileExists) { 353 // Lex the opening paren. 354 RawLex.LexFromRawLexer(Tok); 355 if (Tok.isNot(tok::l_paren)) 356 return false; 357 358 RawLex.LexFromRawLexer(Tok); 359 360 SmallString<128> FilenameBuffer; 361 StringRef Filename; 362 // Since the raw lexer doesn't give us angle_literals we have to parse them 363 // ourselves. 364 // FIXME: What to do if the file name is a macro? 365 if (Tok.is(tok::less)) { 366 RawLex.LexFromRawLexer(Tok); 367 368 FilenameBuffer += '<'; 369 do { 370 if (Tok.is(tok::eod)) // Sanity check. 371 return false; 372 373 if (Tok.is(tok::raw_identifier)) 374 PP.LookUpIdentifierInfo(Tok); 375 376 // Get the string piece. 377 SmallVector<char, 128> TmpBuffer; 378 bool Invalid = false; 379 StringRef TmpName = PP.getSpelling(Tok, TmpBuffer, &Invalid); 380 if (Invalid) 381 return false; 382 383 FilenameBuffer += TmpName; 384 385 RawLex.LexFromRawLexer(Tok); 386 } while (Tok.isNot(tok::greater)); 387 388 FilenameBuffer += '>'; 389 Filename = FilenameBuffer; 390 } else { 391 if (Tok.isNot(tok::string_literal)) 392 return false; 393 394 bool Invalid = false; 395 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid); 396 if (Invalid) 397 return false; 398 } 399 400 // Lex the closing paren. 401 RawLex.LexFromRawLexer(Tok); 402 if (Tok.isNot(tok::r_paren)) 403 return false; 404 405 // Now ask HeaderInfo if it knows about the header. 406 // FIXME: Subframeworks aren't handled here. Do we care? 407 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename); 408 const DirectoryLookup *CurDir; 409 const FileEntry *FileEnt = PP.getSourceManager().getFileEntryForID(FileId); 410 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 1> 411 Includers; 412 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir())); 413 // FIXME: Why don't we call PP.LookupFile here? 414 const FileEntry *File = PP.getHeaderSearchInfo().LookupFile( 415 Filename, SourceLocation(), isAngled, Lookup, CurDir, Includers, nullptr, 416 nullptr, nullptr, nullptr, nullptr); 417 418 FileExists = File != nullptr; 419 return true; 420 } 421 422 /// Use a raw lexer to analyze \p FileId, incrementally copying parts of it 423 /// and including content of included files recursively. 424 void InclusionRewriter::Process(FileID FileId, 425 SrcMgr::CharacteristicKind FileType, 426 const DirectoryLookup *DirLookup) { 427 bool Invalid; 428 const MemoryBuffer &FromFile = *SM.getBuffer(FileId, &Invalid); 429 assert(!Invalid && "Attempting to process invalid inclusion"); 430 StringRef FileName = FromFile.getBufferIdentifier(); 431 Lexer RawLex(FileId, &FromFile, PP.getSourceManager(), PP.getLangOpts()); 432 RawLex.SetCommentRetentionState(false); 433 434 StringRef LocalEOL = DetectEOL(FromFile); 435 436 // Per the GNU docs: "1" indicates entering a new file. 437 if (FileId == SM.getMainFileID() || FileId == PP.getPredefinesFileID()) 438 WriteLineInfo(FileName, 1, FileType, ""); 439 else 440 WriteLineInfo(FileName, 1, FileType, " 1"); 441 442 if (SM.getFileIDSize(FileId) == 0) 443 return; 444 445 // The next byte to be copied from the source file, which may be non-zero if 446 // the lexer handled a BOM. 447 unsigned NextToWrite = SM.getFileOffset(RawLex.getSourceLocation()); 448 assert(SM.getLineNumber(FileId, NextToWrite) == 1); 449 int Line = 1; // The current input file line number. 450 451 Token RawToken; 452 RawLex.LexFromRawLexer(RawToken); 453 454 // TODO: Consider adding a switch that strips possibly unimportant content, 455 // such as comments, to reduce the size of repro files. 456 while (RawToken.isNot(tok::eof)) { 457 if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) { 458 RawLex.setParsingPreprocessorDirective(true); 459 Token HashToken = RawToken; 460 RawLex.LexFromRawLexer(RawToken); 461 if (RawToken.is(tok::raw_identifier)) 462 PP.LookUpIdentifierInfo(RawToken); 463 if (RawToken.getIdentifierInfo() != nullptr) { 464 switch (RawToken.getIdentifierInfo()->getPPKeywordID()) { 465 case tok::pp_include: 466 case tok::pp_include_next: 467 case tok::pp_import: { 468 CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL, NextToWrite, 469 Line); 470 if (FileId != PP.getPredefinesFileID()) 471 WriteLineInfo(FileName, Line - 1, FileType, ""); 472 StringRef LineInfoExtra; 473 SourceLocation Loc = HashToken.getLocation(); 474 if (const Module *Mod = FindModuleAtLocation(Loc)) 475 WriteImplicitModuleImport(Mod); 476 else if (const IncludedFile *Inc = FindIncludeAtLocation(Loc)) { 477 const Module *Mod = FindEnteredModule(Loc); 478 if (Mod) 479 OS << "#pragma clang module begin " 480 << Mod->getFullModuleName(true) << "\n"; 481 482 // Include and recursively process the file. 483 Process(Inc->Id, Inc->FileType, Inc->DirLookup); 484 485 if (Mod) 486 OS << "#pragma clang module end /*" 487 << Mod->getFullModuleName(true) << "*/\n"; 488 489 // Add line marker to indicate we're returning from an included 490 // file. 491 LineInfoExtra = " 2"; 492 } 493 // fix up lineinfo (since commented out directive changed line 494 // numbers) for inclusions that were skipped due to header guards 495 WriteLineInfo(FileName, Line, FileType, LineInfoExtra); 496 break; 497 } 498 case tok::pp_pragma: { 499 StringRef Identifier = NextIdentifierName(RawLex, RawToken); 500 if (Identifier == "clang" || Identifier == "GCC") { 501 if (NextIdentifierName(RawLex, RawToken) == "system_header") { 502 // keep the directive in, commented out 503 CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL, 504 NextToWrite, Line); 505 // update our own type 506 FileType = SM.getFileCharacteristic(RawToken.getLocation()); 507 WriteLineInfo(FileName, Line, FileType); 508 } 509 } else if (Identifier == "once") { 510 // keep the directive in, commented out 511 CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL, 512 NextToWrite, Line); 513 WriteLineInfo(FileName, Line, FileType); 514 } 515 break; 516 } 517 case tok::pp_if: 518 case tok::pp_elif: { 519 bool elif = (RawToken.getIdentifierInfo()->getPPKeywordID() == 520 tok::pp_elif); 521 // Rewrite special builtin macros to avoid pulling in host details. 522 do { 523 // Walk over the directive. 524 RawLex.LexFromRawLexer(RawToken); 525 if (RawToken.is(tok::raw_identifier)) 526 PP.LookUpIdentifierInfo(RawToken); 527 528 if (RawToken.is(tok::identifier)) { 529 bool HasFile; 530 SourceLocation Loc = RawToken.getLocation(); 531 532 // Rewrite __has_include(x) 533 if (RawToken.getIdentifierInfo()->isStr("__has_include")) { 534 if (!HandleHasInclude(FileId, RawLex, nullptr, RawToken, 535 HasFile)) 536 continue; 537 // Rewrite __has_include_next(x) 538 } else if (RawToken.getIdentifierInfo()->isStr( 539 "__has_include_next")) { 540 if (DirLookup) 541 ++DirLookup; 542 543 if (!HandleHasInclude(FileId, RawLex, DirLookup, RawToken, 544 HasFile)) 545 continue; 546 } else { 547 continue; 548 } 549 // Replace the macro with (0) or (1), followed by the commented 550 // out macro for reference. 551 OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(Loc), 552 LocalEOL, Line, false); 553 OS << '(' << (int) HasFile << ")/*"; 554 OutputContentUpTo(FromFile, NextToWrite, 555 SM.getFileOffset(RawToken.getLocation()) + 556 RawToken.getLength(), 557 LocalEOL, Line, false); 558 OS << "*/"; 559 } 560 } while (RawToken.isNot(tok::eod)); 561 if (elif) { 562 OutputContentUpTo(FromFile, NextToWrite, 563 SM.getFileOffset(RawToken.getLocation()) + 564 RawToken.getLength(), 565 LocalEOL, Line, /*EnsureNewline=*/ true); 566 WriteLineInfo(FileName, Line, FileType); 567 } 568 break; 569 } 570 case tok::pp_endif: 571 case tok::pp_else: { 572 // We surround every #include by #if 0 to comment it out, but that 573 // changes line numbers. These are fixed up right after that, but 574 // the whole #include could be inside a preprocessor conditional 575 // that is not processed. So it is necessary to fix the line 576 // numbers one the next line after each #else/#endif as well. 577 RawLex.SetKeepWhitespaceMode(true); 578 do { 579 RawLex.LexFromRawLexer(RawToken); 580 } while (RawToken.isNot(tok::eod) && RawToken.isNot(tok::eof)); 581 OutputContentUpTo(FromFile, NextToWrite, 582 SM.getFileOffset(RawToken.getLocation()) + 583 RawToken.getLength(), 584 LocalEOL, Line, /*EnsureNewline=*/ true); 585 WriteLineInfo(FileName, Line, FileType); 586 RawLex.SetKeepWhitespaceMode(false); 587 } 588 default: 589 break; 590 } 591 } 592 RawLex.setParsingPreprocessorDirective(false); 593 } 594 RawLex.LexFromRawLexer(RawToken); 595 } 596 OutputContentUpTo(FromFile, NextToWrite, 597 SM.getFileOffset(SM.getLocForEndOfFile(FileId)), LocalEOL, 598 Line, /*EnsureNewline=*/true); 599 } 600 601 /// InclusionRewriterInInput - Implement -frewrite-includes mode. 602 void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS, 603 const PreprocessorOutputOptions &Opts) { 604 SourceManager &SM = PP.getSourceManager(); 605 InclusionRewriter *Rewrite = new InclusionRewriter( 606 PP, *OS, Opts.ShowLineMarkers, Opts.UseLineDirectives); 607 Rewrite->detectMainFileEOL(); 608 609 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Rewrite)); 610 PP.IgnorePragmas(); 611 612 // First let the preprocessor process the entire file and call callbacks. 613 // Callbacks will record which #include's were actually performed. 614 PP.EnterMainSourceFile(); 615 Token Tok; 616 // Only preprocessor directives matter here, so disable macro expansion 617 // everywhere else as an optimization. 618 // TODO: It would be even faster if the preprocessor could be switched 619 // to a mode where it would parse only preprocessor directives and comments, 620 // nothing else matters for parsing or processing. 621 PP.SetMacroExpansionOnlyInDirectives(); 622 do { 623 PP.Lex(Tok); 624 if (Tok.is(tok::annot_module_begin)) 625 Rewrite->handleModuleBegin(Tok); 626 } while (Tok.isNot(tok::eof)); 627 Rewrite->setPredefinesBuffer(SM.getBuffer(PP.getPredefinesFileID())); 628 Rewrite->Process(PP.getPredefinesFileID(), SrcMgr::C_User, nullptr); 629 Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User, nullptr); 630 OS->flush(); 631 } 632