10b57cec5SDimitry Andric //===--- InclusionRewriter.cpp - Rewrite includes into their expansions ---===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This code rewrites include invocations into their expansions. This gives you 100b57cec5SDimitry Andric // a file with all included files merged into it. 110b57cec5SDimitry Andric // 120b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 130b57cec5SDimitry Andric 140b57cec5SDimitry Andric #include "clang/Rewrite/Frontend/Rewriters.h" 150b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h" 160b57cec5SDimitry Andric #include "clang/Frontend/PreprocessorOutputOptions.h" 170b57cec5SDimitry Andric #include "clang/Lex/Pragma.h" 180b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h" 190b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h" 200b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 210b57cec5SDimitry Andric 220b57cec5SDimitry Andric using namespace clang; 230b57cec5SDimitry Andric using namespace llvm; 240b57cec5SDimitry Andric 250b57cec5SDimitry Andric namespace { 260b57cec5SDimitry Andric 270b57cec5SDimitry Andric class InclusionRewriter : public PPCallbacks { 280b57cec5SDimitry Andric /// Information about which #includes were actually performed, 290b57cec5SDimitry Andric /// created by preprocessor callbacks. 300b57cec5SDimitry Andric struct IncludedFile { 310b57cec5SDimitry Andric FileID Id; 320b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileType; 33*04eeddc0SDimitry Andric IncludedFile(FileID Id, SrcMgr::CharacteristicKind FileType) 34*04eeddc0SDimitry Andric : Id(Id), FileType(FileType) {} 350b57cec5SDimitry Andric }; 360b57cec5SDimitry Andric Preprocessor &PP; ///< Used to find inclusion directives. 370b57cec5SDimitry Andric SourceManager &SM; ///< Used to read and manage source files. 380b57cec5SDimitry Andric raw_ostream &OS; ///< The destination stream for rewritten contents. 390b57cec5SDimitry Andric StringRef MainEOL; ///< The line ending marker to use. 40e8d8bef9SDimitry Andric llvm::MemoryBufferRef PredefinesBuffer; ///< The preprocessor predefines. 410b57cec5SDimitry Andric bool ShowLineMarkers; ///< Show #line markers. 420b57cec5SDimitry Andric bool UseLineDirectives; ///< Use of line directives or line markers. 430b57cec5SDimitry Andric /// Tracks where inclusions that change the file are found. 44e8d8bef9SDimitry Andric std::map<SourceLocation, IncludedFile> FileIncludes; 450b57cec5SDimitry Andric /// Tracks where inclusions that import modules are found. 46e8d8bef9SDimitry Andric std::map<SourceLocation, const Module *> ModuleIncludes; 470b57cec5SDimitry Andric /// Tracks where inclusions that enter modules (in a module build) are found. 48e8d8bef9SDimitry Andric std::map<SourceLocation, const Module *> ModuleEntryIncludes; 49a7dea167SDimitry Andric /// Tracks where #if and #elif directives get evaluated and whether to true. 50e8d8bef9SDimitry Andric std::map<SourceLocation, bool> IfConditions; 510b57cec5SDimitry Andric /// Used transitively for building up the FileIncludes mapping over the 520b57cec5SDimitry Andric /// various \c PPCallbacks callbacks. 530b57cec5SDimitry Andric SourceLocation LastInclusionLocation; 540b57cec5SDimitry Andric public: 550b57cec5SDimitry Andric InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers, 560b57cec5SDimitry Andric bool UseLineDirectives); 57*04eeddc0SDimitry Andric void Process(FileID FileId, SrcMgr::CharacteristicKind FileType); 58e8d8bef9SDimitry Andric void setPredefinesBuffer(const llvm::MemoryBufferRef &Buf) { 590b57cec5SDimitry Andric PredefinesBuffer = Buf; 600b57cec5SDimitry Andric } 610b57cec5SDimitry Andric void detectMainFileEOL(); 620b57cec5SDimitry Andric void handleModuleBegin(Token &Tok) { 630b57cec5SDimitry Andric assert(Tok.getKind() == tok::annot_module_begin); 64e8d8bef9SDimitry Andric ModuleEntryIncludes.insert( 65e8d8bef9SDimitry Andric {Tok.getLocation(), (Module *)Tok.getAnnotationValue()}); 660b57cec5SDimitry Andric } 670b57cec5SDimitry Andric private: 680b57cec5SDimitry Andric void FileChanged(SourceLocation Loc, FileChangeReason Reason, 690b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileType, 700b57cec5SDimitry Andric FileID PrevFID) override; 71a7dea167SDimitry Andric void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok, 720b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileType) override; 730b57cec5SDimitry Andric void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, 740b57cec5SDimitry Andric StringRef FileName, bool IsAngled, 750b57cec5SDimitry Andric CharSourceRange FilenameRange, const FileEntry *File, 760b57cec5SDimitry Andric StringRef SearchPath, StringRef RelativePath, 770b57cec5SDimitry Andric const Module *Imported, 780b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileType) override; 79a7dea167SDimitry Andric void If(SourceLocation Loc, SourceRange ConditionRange, 80a7dea167SDimitry Andric ConditionValueKind ConditionValue) override; 81a7dea167SDimitry Andric void Elif(SourceLocation Loc, SourceRange ConditionRange, 82a7dea167SDimitry Andric ConditionValueKind ConditionValue, SourceLocation IfLoc) override; 830b57cec5SDimitry Andric void WriteLineInfo(StringRef Filename, int Line, 840b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileType, 850b57cec5SDimitry Andric StringRef Extra = StringRef()); 860b57cec5SDimitry Andric void WriteImplicitModuleImport(const Module *Mod); 87e8d8bef9SDimitry Andric void OutputContentUpTo(const MemoryBufferRef &FromFile, unsigned &WriteFrom, 88e8d8bef9SDimitry Andric unsigned WriteTo, StringRef EOL, int &lines, 890b57cec5SDimitry Andric bool EnsureNewline); 900b57cec5SDimitry Andric void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken, 91e8d8bef9SDimitry Andric const MemoryBufferRef &FromFile, StringRef EOL, 920b57cec5SDimitry Andric unsigned &NextToWrite, int &Lines); 930b57cec5SDimitry Andric const IncludedFile *FindIncludeAtLocation(SourceLocation Loc) const; 940b57cec5SDimitry Andric const Module *FindModuleAtLocation(SourceLocation Loc) const; 950b57cec5SDimitry Andric const Module *FindEnteredModule(SourceLocation Loc) const; 96a7dea167SDimitry Andric bool IsIfAtLocationTrue(SourceLocation Loc) const; 970b57cec5SDimitry Andric StringRef NextIdentifierName(Lexer &RawLex, Token &RawToken); 980b57cec5SDimitry Andric }; 990b57cec5SDimitry Andric 1000b57cec5SDimitry Andric } // end anonymous namespace 1010b57cec5SDimitry Andric 1020b57cec5SDimitry Andric /// Initializes an InclusionRewriter with a \p PP source and \p OS destination. 1030b57cec5SDimitry Andric InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS, 1040b57cec5SDimitry Andric bool ShowLineMarkers, 1050b57cec5SDimitry Andric bool UseLineDirectives) 1060b57cec5SDimitry Andric : PP(PP), SM(PP.getSourceManager()), OS(OS), MainEOL("\n"), 107e8d8bef9SDimitry Andric ShowLineMarkers(ShowLineMarkers), UseLineDirectives(UseLineDirectives), 1080b57cec5SDimitry Andric LastInclusionLocation(SourceLocation()) {} 1090b57cec5SDimitry Andric 1100b57cec5SDimitry Andric /// Write appropriate line information as either #line directives or GNU line 1110b57cec5SDimitry Andric /// markers depending on what mode we're in, including the \p Filename and 1120b57cec5SDimitry Andric /// \p Line we are located at, using the specified \p EOL line separator, and 1130b57cec5SDimitry Andric /// any \p Extra context specifiers in GNU line directives. 1140b57cec5SDimitry Andric void InclusionRewriter::WriteLineInfo(StringRef Filename, int Line, 1150b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileType, 1160b57cec5SDimitry Andric StringRef Extra) { 1170b57cec5SDimitry Andric if (!ShowLineMarkers) 1180b57cec5SDimitry Andric return; 1190b57cec5SDimitry Andric if (UseLineDirectives) { 1200b57cec5SDimitry Andric OS << "#line" << ' ' << Line << ' ' << '"'; 1210b57cec5SDimitry Andric OS.write_escaped(Filename); 1220b57cec5SDimitry Andric OS << '"'; 1230b57cec5SDimitry Andric } else { 1240b57cec5SDimitry Andric // Use GNU linemarkers as described here: 1250b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html 1260b57cec5SDimitry Andric OS << '#' << ' ' << Line << ' ' << '"'; 1270b57cec5SDimitry Andric OS.write_escaped(Filename); 1280b57cec5SDimitry Andric OS << '"'; 1290b57cec5SDimitry Andric if (!Extra.empty()) 1300b57cec5SDimitry Andric OS << Extra; 1310b57cec5SDimitry Andric if (FileType == SrcMgr::C_System) 1320b57cec5SDimitry Andric // "`3' This indicates that the following text comes from a system header 1330b57cec5SDimitry Andric // file, so certain warnings should be suppressed." 1340b57cec5SDimitry Andric OS << " 3"; 1350b57cec5SDimitry Andric else if (FileType == SrcMgr::C_ExternCSystem) 1360b57cec5SDimitry Andric // as above for `3', plus "`4' This indicates that the following text 1370b57cec5SDimitry Andric // should be treated as being wrapped in an implicit extern "C" block." 1380b57cec5SDimitry Andric OS << " 3 4"; 1390b57cec5SDimitry Andric } 1400b57cec5SDimitry Andric OS << MainEOL; 1410b57cec5SDimitry Andric } 1420b57cec5SDimitry Andric 1430b57cec5SDimitry Andric void InclusionRewriter::WriteImplicitModuleImport(const Module *Mod) { 1440b57cec5SDimitry Andric OS << "#pragma clang module import " << Mod->getFullModuleName(true) 1450b57cec5SDimitry Andric << " /* clang -frewrite-includes: implicit import */" << MainEOL; 1460b57cec5SDimitry Andric } 1470b57cec5SDimitry Andric 1480b57cec5SDimitry Andric /// FileChanged - Whenever the preprocessor enters or exits a #include file 1490b57cec5SDimitry Andric /// it invokes this handler. 1500b57cec5SDimitry Andric void InclusionRewriter::FileChanged(SourceLocation Loc, 1510b57cec5SDimitry Andric FileChangeReason Reason, 1520b57cec5SDimitry Andric SrcMgr::CharacteristicKind NewFileType, 1530b57cec5SDimitry Andric FileID) { 1540b57cec5SDimitry Andric if (Reason != EnterFile) 1550b57cec5SDimitry Andric return; 1560b57cec5SDimitry Andric if (LastInclusionLocation.isInvalid()) 1570b57cec5SDimitry Andric // we didn't reach this file (eg: the main file) via an inclusion directive 1580b57cec5SDimitry Andric return; 1590b57cec5SDimitry Andric FileID Id = FullSourceLoc(Loc, SM).getFileID(); 1600b57cec5SDimitry Andric auto P = FileIncludes.insert( 161*04eeddc0SDimitry Andric std::make_pair(LastInclusionLocation, IncludedFile(Id, NewFileType))); 1620b57cec5SDimitry Andric (void)P; 1630b57cec5SDimitry Andric assert(P.second && "Unexpected revisitation of the same include directive"); 1640b57cec5SDimitry Andric LastInclusionLocation = SourceLocation(); 1650b57cec5SDimitry Andric } 1660b57cec5SDimitry Andric 1670b57cec5SDimitry Andric /// Called whenever an inclusion is skipped due to canonical header protection 1680b57cec5SDimitry Andric /// macros. 169a7dea167SDimitry Andric void InclusionRewriter::FileSkipped(const FileEntryRef & /*SkippedFile*/, 1700b57cec5SDimitry Andric const Token & /*FilenameTok*/, 1710b57cec5SDimitry Andric SrcMgr::CharacteristicKind /*FileType*/) { 1720b57cec5SDimitry Andric assert(LastInclusionLocation.isValid() && 1730b57cec5SDimitry Andric "A file, that wasn't found via an inclusion directive, was skipped"); 1740b57cec5SDimitry Andric LastInclusionLocation = SourceLocation(); 1750b57cec5SDimitry Andric } 1760b57cec5SDimitry Andric 1770b57cec5SDimitry Andric /// This should be called whenever the preprocessor encounters include 1780b57cec5SDimitry Andric /// directives. It does not say whether the file has been included, but it 1790b57cec5SDimitry Andric /// provides more information about the directive (hash location instead 1800b57cec5SDimitry Andric /// of location inside the included file). It is assumed that the matching 1810b57cec5SDimitry Andric /// FileChanged() or FileSkipped() is called after this (or neither is 1820b57cec5SDimitry Andric /// called if this #include results in an error or does not textually include 1830b57cec5SDimitry Andric /// anything). 1840b57cec5SDimitry Andric void InclusionRewriter::InclusionDirective(SourceLocation HashLoc, 1850b57cec5SDimitry Andric const Token &/*IncludeTok*/, 1860b57cec5SDimitry Andric StringRef /*FileName*/, 1870b57cec5SDimitry Andric bool /*IsAngled*/, 1880b57cec5SDimitry Andric CharSourceRange /*FilenameRange*/, 1890b57cec5SDimitry Andric const FileEntry * /*File*/, 1900b57cec5SDimitry Andric StringRef /*SearchPath*/, 1910b57cec5SDimitry Andric StringRef /*RelativePath*/, 1920b57cec5SDimitry Andric const Module *Imported, 1930b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileType){ 1940b57cec5SDimitry Andric if (Imported) { 195e8d8bef9SDimitry Andric auto P = ModuleIncludes.insert(std::make_pair(HashLoc, Imported)); 1960b57cec5SDimitry Andric (void)P; 1970b57cec5SDimitry Andric assert(P.second && "Unexpected revisitation of the same include directive"); 1980b57cec5SDimitry Andric } else 1990b57cec5SDimitry Andric LastInclusionLocation = HashLoc; 2000b57cec5SDimitry Andric } 2010b57cec5SDimitry Andric 202a7dea167SDimitry Andric void InclusionRewriter::If(SourceLocation Loc, SourceRange ConditionRange, 203a7dea167SDimitry Andric ConditionValueKind ConditionValue) { 204e8d8bef9SDimitry Andric auto P = IfConditions.insert(std::make_pair(Loc, ConditionValue == CVK_True)); 205a7dea167SDimitry Andric (void)P; 206a7dea167SDimitry Andric assert(P.second && "Unexpected revisitation of the same if directive"); 207a7dea167SDimitry Andric } 208a7dea167SDimitry Andric 209a7dea167SDimitry Andric void InclusionRewriter::Elif(SourceLocation Loc, SourceRange ConditionRange, 210a7dea167SDimitry Andric ConditionValueKind ConditionValue, 211a7dea167SDimitry Andric SourceLocation IfLoc) { 212e8d8bef9SDimitry Andric auto P = IfConditions.insert(std::make_pair(Loc, ConditionValue == CVK_True)); 213a7dea167SDimitry Andric (void)P; 214a7dea167SDimitry Andric assert(P.second && "Unexpected revisitation of the same elif directive"); 215a7dea167SDimitry Andric } 216a7dea167SDimitry Andric 2170b57cec5SDimitry Andric /// Simple lookup for a SourceLocation (specifically one denoting the hash in 2180b57cec5SDimitry Andric /// an inclusion directive) in the map of inclusion information, FileChanges. 2190b57cec5SDimitry Andric const InclusionRewriter::IncludedFile * 2200b57cec5SDimitry Andric InclusionRewriter::FindIncludeAtLocation(SourceLocation Loc) const { 221e8d8bef9SDimitry Andric const auto I = FileIncludes.find(Loc); 2220b57cec5SDimitry Andric if (I != FileIncludes.end()) 2230b57cec5SDimitry Andric return &I->second; 2240b57cec5SDimitry Andric return nullptr; 2250b57cec5SDimitry Andric } 2260b57cec5SDimitry Andric 2270b57cec5SDimitry Andric /// Simple lookup for a SourceLocation (specifically one denoting the hash in 2280b57cec5SDimitry Andric /// an inclusion directive) in the map of module inclusion information. 2290b57cec5SDimitry Andric const Module * 2300b57cec5SDimitry Andric InclusionRewriter::FindModuleAtLocation(SourceLocation Loc) const { 231e8d8bef9SDimitry Andric const auto I = ModuleIncludes.find(Loc); 2320b57cec5SDimitry Andric if (I != ModuleIncludes.end()) 2330b57cec5SDimitry Andric return I->second; 2340b57cec5SDimitry Andric return nullptr; 2350b57cec5SDimitry Andric } 2360b57cec5SDimitry Andric 2370b57cec5SDimitry Andric /// Simple lookup for a SourceLocation (specifically one denoting the hash in 2380b57cec5SDimitry Andric /// an inclusion directive) in the map of module entry information. 2390b57cec5SDimitry Andric const Module * 2400b57cec5SDimitry Andric InclusionRewriter::FindEnteredModule(SourceLocation Loc) const { 241e8d8bef9SDimitry Andric const auto I = ModuleEntryIncludes.find(Loc); 2420b57cec5SDimitry Andric if (I != ModuleEntryIncludes.end()) 2430b57cec5SDimitry Andric return I->second; 2440b57cec5SDimitry Andric return nullptr; 2450b57cec5SDimitry Andric } 2460b57cec5SDimitry Andric 247a7dea167SDimitry Andric bool InclusionRewriter::IsIfAtLocationTrue(SourceLocation Loc) const { 248e8d8bef9SDimitry Andric const auto I = IfConditions.find(Loc); 249a7dea167SDimitry Andric if (I != IfConditions.end()) 250a7dea167SDimitry Andric return I->second; 251a7dea167SDimitry Andric return false; 252a7dea167SDimitry Andric } 253a7dea167SDimitry Andric 2540b57cec5SDimitry Andric void InclusionRewriter::detectMainFileEOL() { 255e8d8bef9SDimitry Andric Optional<MemoryBufferRef> FromFile = *SM.getBufferOrNone(SM.getMainFileID()); 256e8d8bef9SDimitry Andric assert(FromFile); 257e8d8bef9SDimitry Andric if (!FromFile) 2580b57cec5SDimitry Andric return; // Should never happen, but whatever. 259*04eeddc0SDimitry Andric MainEOL = FromFile->getBuffer().detectEOL(); 2600b57cec5SDimitry Andric } 2610b57cec5SDimitry Andric 2620b57cec5SDimitry Andric /// Writes out bytes from \p FromFile, starting at \p NextToWrite and ending at 2630b57cec5SDimitry Andric /// \p WriteTo - 1. 264e8d8bef9SDimitry Andric void InclusionRewriter::OutputContentUpTo(const MemoryBufferRef &FromFile, 2650b57cec5SDimitry Andric unsigned &WriteFrom, unsigned WriteTo, 2660b57cec5SDimitry Andric StringRef LocalEOL, int &Line, 2670b57cec5SDimitry Andric bool EnsureNewline) { 2680b57cec5SDimitry Andric if (WriteTo <= WriteFrom) 2690b57cec5SDimitry Andric return; 270e8d8bef9SDimitry Andric if (FromFile == PredefinesBuffer) { 2710b57cec5SDimitry Andric // Ignore the #defines of the predefines buffer. 2720b57cec5SDimitry Andric WriteFrom = WriteTo; 2730b57cec5SDimitry Andric return; 2740b57cec5SDimitry Andric } 2750b57cec5SDimitry Andric 2760b57cec5SDimitry Andric // If we would output half of a line ending, advance one character to output 2770b57cec5SDimitry Andric // the whole line ending. All buffers are null terminated, so looking ahead 2780b57cec5SDimitry Andric // one byte is safe. 2790b57cec5SDimitry Andric if (LocalEOL.size() == 2 && 2800b57cec5SDimitry Andric LocalEOL[0] == (FromFile.getBufferStart() + WriteTo)[-1] && 2810b57cec5SDimitry Andric LocalEOL[1] == (FromFile.getBufferStart() + WriteTo)[0]) 2820b57cec5SDimitry Andric WriteTo++; 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric StringRef TextToWrite(FromFile.getBufferStart() + WriteFrom, 2850b57cec5SDimitry Andric WriteTo - WriteFrom); 2860b57cec5SDimitry Andric 2870b57cec5SDimitry Andric if (MainEOL == LocalEOL) { 2880b57cec5SDimitry Andric OS << TextToWrite; 2890b57cec5SDimitry Andric // count lines manually, it's faster than getPresumedLoc() 2900b57cec5SDimitry Andric Line += TextToWrite.count(LocalEOL); 2910b57cec5SDimitry Andric if (EnsureNewline && !TextToWrite.endswith(LocalEOL)) 2920b57cec5SDimitry Andric OS << MainEOL; 2930b57cec5SDimitry Andric } else { 2940b57cec5SDimitry Andric // Output the file one line at a time, rewriting the line endings as we go. 2950b57cec5SDimitry Andric StringRef Rest = TextToWrite; 2960b57cec5SDimitry Andric while (!Rest.empty()) { 2970b57cec5SDimitry Andric StringRef LineText; 2980b57cec5SDimitry Andric std::tie(LineText, Rest) = Rest.split(LocalEOL); 2990b57cec5SDimitry Andric OS << LineText; 3000b57cec5SDimitry Andric Line++; 3010b57cec5SDimitry Andric if (!Rest.empty()) 3020b57cec5SDimitry Andric OS << MainEOL; 3030b57cec5SDimitry Andric } 3040b57cec5SDimitry Andric if (TextToWrite.endswith(LocalEOL) || EnsureNewline) 3050b57cec5SDimitry Andric OS << MainEOL; 3060b57cec5SDimitry Andric } 3070b57cec5SDimitry Andric WriteFrom = WriteTo; 3080b57cec5SDimitry Andric } 3090b57cec5SDimitry Andric 3100b57cec5SDimitry Andric /// Print characters from \p FromFile starting at \p NextToWrite up until the 3110b57cec5SDimitry Andric /// inclusion directive at \p StartToken, then print out the inclusion 3120b57cec5SDimitry Andric /// inclusion directive disabled by a #if directive, updating \p NextToWrite 3130b57cec5SDimitry Andric /// and \p Line to track the number of source lines visited and the progress 3140b57cec5SDimitry Andric /// through the \p FromFile buffer. 3150b57cec5SDimitry Andric void InclusionRewriter::CommentOutDirective(Lexer &DirectiveLex, 3160b57cec5SDimitry Andric const Token &StartToken, 317e8d8bef9SDimitry Andric const MemoryBufferRef &FromFile, 3180b57cec5SDimitry Andric StringRef LocalEOL, 3190b57cec5SDimitry Andric unsigned &NextToWrite, int &Line) { 3200b57cec5SDimitry Andric OutputContentUpTo(FromFile, NextToWrite, 3210b57cec5SDimitry Andric SM.getFileOffset(StartToken.getLocation()), LocalEOL, Line, 3220b57cec5SDimitry Andric false); 3230b57cec5SDimitry Andric Token DirectiveToken; 3240b57cec5SDimitry Andric do { 3250b57cec5SDimitry Andric DirectiveLex.LexFromRawLexer(DirectiveToken); 3260b57cec5SDimitry Andric } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof)); 327e8d8bef9SDimitry Andric if (FromFile == PredefinesBuffer) { 3280b57cec5SDimitry Andric // OutputContentUpTo() would not output anything anyway. 3290b57cec5SDimitry Andric return; 3300b57cec5SDimitry Andric } 3310b57cec5SDimitry Andric OS << "#if 0 /* expanded by -frewrite-includes */" << MainEOL; 3320b57cec5SDimitry Andric OutputContentUpTo(FromFile, NextToWrite, 3330b57cec5SDimitry Andric SM.getFileOffset(DirectiveToken.getLocation()) + 3340b57cec5SDimitry Andric DirectiveToken.getLength(), 3350b57cec5SDimitry Andric LocalEOL, Line, true); 3360b57cec5SDimitry Andric OS << "#endif /* expanded by -frewrite-includes */" << MainEOL; 3370b57cec5SDimitry Andric } 3380b57cec5SDimitry Andric 3390b57cec5SDimitry Andric /// Find the next identifier in the pragma directive specified by \p RawToken. 3400b57cec5SDimitry Andric StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex, 3410b57cec5SDimitry Andric Token &RawToken) { 3420b57cec5SDimitry Andric RawLex.LexFromRawLexer(RawToken); 3430b57cec5SDimitry Andric if (RawToken.is(tok::raw_identifier)) 3440b57cec5SDimitry Andric PP.LookUpIdentifierInfo(RawToken); 3450b57cec5SDimitry Andric if (RawToken.is(tok::identifier)) 3460b57cec5SDimitry Andric return RawToken.getIdentifierInfo()->getName(); 3470b57cec5SDimitry Andric return StringRef(); 3480b57cec5SDimitry Andric } 3490b57cec5SDimitry Andric 3500b57cec5SDimitry Andric /// Use a raw lexer to analyze \p FileId, incrementally copying parts of it 3510b57cec5SDimitry Andric /// and including content of included files recursively. 3520b57cec5SDimitry Andric void InclusionRewriter::Process(FileID FileId, 353*04eeddc0SDimitry Andric SrcMgr::CharacteristicKind FileType) { 354e8d8bef9SDimitry Andric MemoryBufferRef FromFile; 355e8d8bef9SDimitry Andric { 356e8d8bef9SDimitry Andric auto B = SM.getBufferOrNone(FileId); 357e8d8bef9SDimitry Andric assert(B && "Attempting to process invalid inclusion"); 358e8d8bef9SDimitry Andric if (B) 359e8d8bef9SDimitry Andric FromFile = *B; 360e8d8bef9SDimitry Andric } 3610b57cec5SDimitry Andric StringRef FileName = FromFile.getBufferIdentifier(); 362e8d8bef9SDimitry Andric Lexer RawLex(FileId, FromFile, PP.getSourceManager(), PP.getLangOpts()); 3630b57cec5SDimitry Andric RawLex.SetCommentRetentionState(false); 3640b57cec5SDimitry Andric 365*04eeddc0SDimitry Andric StringRef LocalEOL = FromFile.getBuffer().detectEOL(); 3660b57cec5SDimitry Andric 3670b57cec5SDimitry Andric // Per the GNU docs: "1" indicates entering a new file. 3680b57cec5SDimitry Andric if (FileId == SM.getMainFileID() || FileId == PP.getPredefinesFileID()) 3690b57cec5SDimitry Andric WriteLineInfo(FileName, 1, FileType, ""); 3700b57cec5SDimitry Andric else 3710b57cec5SDimitry Andric WriteLineInfo(FileName, 1, FileType, " 1"); 3720b57cec5SDimitry Andric 3730b57cec5SDimitry Andric if (SM.getFileIDSize(FileId) == 0) 3740b57cec5SDimitry Andric return; 3750b57cec5SDimitry Andric 3760b57cec5SDimitry Andric // The next byte to be copied from the source file, which may be non-zero if 3770b57cec5SDimitry Andric // the lexer handled a BOM. 3780b57cec5SDimitry Andric unsigned NextToWrite = SM.getFileOffset(RawLex.getSourceLocation()); 3790b57cec5SDimitry Andric assert(SM.getLineNumber(FileId, NextToWrite) == 1); 3800b57cec5SDimitry Andric int Line = 1; // The current input file line number. 3810b57cec5SDimitry Andric 3820b57cec5SDimitry Andric Token RawToken; 3830b57cec5SDimitry Andric RawLex.LexFromRawLexer(RawToken); 3840b57cec5SDimitry Andric 3850b57cec5SDimitry Andric // TODO: Consider adding a switch that strips possibly unimportant content, 3860b57cec5SDimitry Andric // such as comments, to reduce the size of repro files. 3870b57cec5SDimitry Andric while (RawToken.isNot(tok::eof)) { 3880b57cec5SDimitry Andric if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) { 3890b57cec5SDimitry Andric RawLex.setParsingPreprocessorDirective(true); 3900b57cec5SDimitry Andric Token HashToken = RawToken; 3910b57cec5SDimitry Andric RawLex.LexFromRawLexer(RawToken); 3920b57cec5SDimitry Andric if (RawToken.is(tok::raw_identifier)) 3930b57cec5SDimitry Andric PP.LookUpIdentifierInfo(RawToken); 3940b57cec5SDimitry Andric if (RawToken.getIdentifierInfo() != nullptr) { 3950b57cec5SDimitry Andric switch (RawToken.getIdentifierInfo()->getPPKeywordID()) { 3960b57cec5SDimitry Andric case tok::pp_include: 3970b57cec5SDimitry Andric case tok::pp_include_next: 3980b57cec5SDimitry Andric case tok::pp_import: { 3990b57cec5SDimitry Andric CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL, NextToWrite, 4000b57cec5SDimitry Andric Line); 4010b57cec5SDimitry Andric if (FileId != PP.getPredefinesFileID()) 4020b57cec5SDimitry Andric WriteLineInfo(FileName, Line - 1, FileType, ""); 4030b57cec5SDimitry Andric StringRef LineInfoExtra; 4040b57cec5SDimitry Andric SourceLocation Loc = HashToken.getLocation(); 4050b57cec5SDimitry Andric if (const Module *Mod = FindModuleAtLocation(Loc)) 4060b57cec5SDimitry Andric WriteImplicitModuleImport(Mod); 4070b57cec5SDimitry Andric else if (const IncludedFile *Inc = FindIncludeAtLocation(Loc)) { 4080b57cec5SDimitry Andric const Module *Mod = FindEnteredModule(Loc); 4090b57cec5SDimitry Andric if (Mod) 4100b57cec5SDimitry Andric OS << "#pragma clang module begin " 4110b57cec5SDimitry Andric << Mod->getFullModuleName(true) << "\n"; 4120b57cec5SDimitry Andric 4130b57cec5SDimitry Andric // Include and recursively process the file. 414*04eeddc0SDimitry Andric Process(Inc->Id, Inc->FileType); 4150b57cec5SDimitry Andric 4160b57cec5SDimitry Andric if (Mod) 4170b57cec5SDimitry Andric OS << "#pragma clang module end /*" 4180b57cec5SDimitry Andric << Mod->getFullModuleName(true) << "*/\n"; 4190b57cec5SDimitry Andric 4200b57cec5SDimitry Andric // Add line marker to indicate we're returning from an included 4210b57cec5SDimitry Andric // file. 4220b57cec5SDimitry Andric LineInfoExtra = " 2"; 4230b57cec5SDimitry Andric } 4240b57cec5SDimitry Andric // fix up lineinfo (since commented out directive changed line 4250b57cec5SDimitry Andric // numbers) for inclusions that were skipped due to header guards 4260b57cec5SDimitry Andric WriteLineInfo(FileName, Line, FileType, LineInfoExtra); 4270b57cec5SDimitry Andric break; 4280b57cec5SDimitry Andric } 4290b57cec5SDimitry Andric case tok::pp_pragma: { 4300b57cec5SDimitry Andric StringRef Identifier = NextIdentifierName(RawLex, RawToken); 4310b57cec5SDimitry Andric if (Identifier == "clang" || Identifier == "GCC") { 4320b57cec5SDimitry Andric if (NextIdentifierName(RawLex, RawToken) == "system_header") { 4330b57cec5SDimitry Andric // keep the directive in, commented out 4340b57cec5SDimitry Andric CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL, 4350b57cec5SDimitry Andric NextToWrite, Line); 4360b57cec5SDimitry Andric // update our own type 4370b57cec5SDimitry Andric FileType = SM.getFileCharacteristic(RawToken.getLocation()); 4380b57cec5SDimitry Andric WriteLineInfo(FileName, Line, FileType); 4390b57cec5SDimitry Andric } 4400b57cec5SDimitry Andric } else if (Identifier == "once") { 4410b57cec5SDimitry Andric // keep the directive in, commented out 4420b57cec5SDimitry Andric CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL, 4430b57cec5SDimitry Andric NextToWrite, Line); 4440b57cec5SDimitry Andric WriteLineInfo(FileName, Line, FileType); 4450b57cec5SDimitry Andric } 4460b57cec5SDimitry Andric break; 4470b57cec5SDimitry Andric } 4480b57cec5SDimitry Andric case tok::pp_if: 4490b57cec5SDimitry Andric case tok::pp_elif: { 4500b57cec5SDimitry Andric bool elif = (RawToken.getIdentifierInfo()->getPPKeywordID() == 4510b57cec5SDimitry Andric tok::pp_elif); 452a7dea167SDimitry Andric bool isTrue = IsIfAtLocationTrue(RawToken.getLocation()); 4530b57cec5SDimitry Andric OutputContentUpTo(FromFile, NextToWrite, 454a7dea167SDimitry Andric SM.getFileOffset(HashToken.getLocation()), 455a7dea167SDimitry Andric LocalEOL, Line, /*EnsureNewline=*/true); 456a7dea167SDimitry Andric do { 457a7dea167SDimitry Andric RawLex.LexFromRawLexer(RawToken); 458a7dea167SDimitry Andric } while (!RawToken.is(tok::eod) && RawToken.isNot(tok::eof)); 459a7dea167SDimitry Andric // We need to disable the old condition, but that is tricky. 460a7dea167SDimitry Andric // Trying to comment it out can easily lead to comment nesting. 461a7dea167SDimitry Andric // So instead make the condition harmless by making it enclose 462a7dea167SDimitry Andric // and empty block. Moreover, put it itself inside an #if 0 block 463a7dea167SDimitry Andric // to disable it from getting evaluated (e.g. __has_include_next 464a7dea167SDimitry Andric // warns if used from the primary source file). 465a7dea167SDimitry Andric OS << "#if 0 /* disabled by -frewrite-includes */" << MainEOL; 4660b57cec5SDimitry Andric if (elif) { 467a7dea167SDimitry Andric OS << "#if 0" << MainEOL; 468a7dea167SDimitry Andric } 4690b57cec5SDimitry Andric OutputContentUpTo(FromFile, NextToWrite, 4700b57cec5SDimitry Andric SM.getFileOffset(RawToken.getLocation()) + 4710b57cec5SDimitry Andric RawToken.getLength(), 4720b57cec5SDimitry Andric LocalEOL, Line, /*EnsureNewline=*/true); 473a7dea167SDimitry Andric // Close the empty block and the disabling block. 474a7dea167SDimitry Andric OS << "#endif" << MainEOL; 475a7dea167SDimitry Andric OS << "#endif /* disabled by -frewrite-includes */" << MainEOL; 476a7dea167SDimitry Andric OS << (elif ? "#elif " : "#if ") << (isTrue ? "1" : "0") 477a7dea167SDimitry Andric << " /* evaluated by -frewrite-includes */" << MainEOL; 4780b57cec5SDimitry Andric WriteLineInfo(FileName, Line, FileType); 4790b57cec5SDimitry Andric break; 4800b57cec5SDimitry Andric } 4810b57cec5SDimitry Andric case tok::pp_endif: 4820b57cec5SDimitry Andric case tok::pp_else: { 4830b57cec5SDimitry Andric // We surround every #include by #if 0 to comment it out, but that 4840b57cec5SDimitry Andric // changes line numbers. These are fixed up right after that, but 4850b57cec5SDimitry Andric // the whole #include could be inside a preprocessor conditional 4860b57cec5SDimitry Andric // that is not processed. So it is necessary to fix the line 4870b57cec5SDimitry Andric // numbers one the next line after each #else/#endif as well. 4880b57cec5SDimitry Andric RawLex.SetKeepWhitespaceMode(true); 4890b57cec5SDimitry Andric do { 4900b57cec5SDimitry Andric RawLex.LexFromRawLexer(RawToken); 4910b57cec5SDimitry Andric } while (RawToken.isNot(tok::eod) && RawToken.isNot(tok::eof)); 4920b57cec5SDimitry Andric OutputContentUpTo(FromFile, NextToWrite, 4930b57cec5SDimitry Andric SM.getFileOffset(RawToken.getLocation()) + 4940b57cec5SDimitry Andric RawToken.getLength(), 4950b57cec5SDimitry Andric LocalEOL, Line, /*EnsureNewline=*/ true); 4960b57cec5SDimitry Andric WriteLineInfo(FileName, Line, FileType); 4970b57cec5SDimitry Andric RawLex.SetKeepWhitespaceMode(false); 4980b57cec5SDimitry Andric break; 4990b57cec5SDimitry Andric } 5000b57cec5SDimitry Andric default: 5010b57cec5SDimitry Andric break; 5020b57cec5SDimitry Andric } 5030b57cec5SDimitry Andric } 5040b57cec5SDimitry Andric RawLex.setParsingPreprocessorDirective(false); 5050b57cec5SDimitry Andric } 5060b57cec5SDimitry Andric RawLex.LexFromRawLexer(RawToken); 5070b57cec5SDimitry Andric } 5080b57cec5SDimitry Andric OutputContentUpTo(FromFile, NextToWrite, 5090b57cec5SDimitry Andric SM.getFileOffset(SM.getLocForEndOfFile(FileId)), LocalEOL, 5100b57cec5SDimitry Andric Line, /*EnsureNewline=*/true); 5110b57cec5SDimitry Andric } 5120b57cec5SDimitry Andric 5130b57cec5SDimitry Andric /// InclusionRewriterInInput - Implement -frewrite-includes mode. 5140b57cec5SDimitry Andric void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS, 5150b57cec5SDimitry Andric const PreprocessorOutputOptions &Opts) { 5160b57cec5SDimitry Andric SourceManager &SM = PP.getSourceManager(); 5170b57cec5SDimitry Andric InclusionRewriter *Rewrite = new InclusionRewriter( 5180b57cec5SDimitry Andric PP, *OS, Opts.ShowLineMarkers, Opts.UseLineDirectives); 5190b57cec5SDimitry Andric Rewrite->detectMainFileEOL(); 5200b57cec5SDimitry Andric 5210b57cec5SDimitry Andric PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Rewrite)); 5220b57cec5SDimitry Andric PP.IgnorePragmas(); 5230b57cec5SDimitry Andric 5240b57cec5SDimitry Andric // First let the preprocessor process the entire file and call callbacks. 5250b57cec5SDimitry Andric // Callbacks will record which #include's were actually performed. 5260b57cec5SDimitry Andric PP.EnterMainSourceFile(); 5270b57cec5SDimitry Andric Token Tok; 5280b57cec5SDimitry Andric // Only preprocessor directives matter here, so disable macro expansion 5290b57cec5SDimitry Andric // everywhere else as an optimization. 5300b57cec5SDimitry Andric // TODO: It would be even faster if the preprocessor could be switched 5310b57cec5SDimitry Andric // to a mode where it would parse only preprocessor directives and comments, 5320b57cec5SDimitry Andric // nothing else matters for parsing or processing. 5330b57cec5SDimitry Andric PP.SetMacroExpansionOnlyInDirectives(); 5340b57cec5SDimitry Andric do { 5350b57cec5SDimitry Andric PP.Lex(Tok); 5360b57cec5SDimitry Andric if (Tok.is(tok::annot_module_begin)) 5370b57cec5SDimitry Andric Rewrite->handleModuleBegin(Tok); 5380b57cec5SDimitry Andric } while (Tok.isNot(tok::eof)); 539e8d8bef9SDimitry Andric Rewrite->setPredefinesBuffer(SM.getBufferOrFake(PP.getPredefinesFileID())); 540*04eeddc0SDimitry Andric Rewrite->Process(PP.getPredefinesFileID(), SrcMgr::C_User); 541*04eeddc0SDimitry Andric Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User); 5420b57cec5SDimitry Andric OS->flush(); 5430b57cec5SDimitry Andric } 544