xref: /freebsd/contrib/llvm-project/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
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"
21*bdd1243dSDimitry Andric #include <optional>
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric using namespace clang;
240b57cec5SDimitry Andric using namespace llvm;
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric namespace {
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric class InclusionRewriter : public PPCallbacks {
290b57cec5SDimitry Andric   /// Information about which #includes were actually performed,
300b57cec5SDimitry Andric   /// created by preprocessor callbacks.
310b57cec5SDimitry Andric   struct IncludedFile {
320b57cec5SDimitry Andric     FileID Id;
330b57cec5SDimitry Andric     SrcMgr::CharacteristicKind FileType;
3404eeddc0SDimitry Andric     IncludedFile(FileID Id, SrcMgr::CharacteristicKind FileType)
3504eeddc0SDimitry Andric         : Id(Id), FileType(FileType) {}
360b57cec5SDimitry Andric   };
370b57cec5SDimitry Andric   Preprocessor &PP; ///< Used to find inclusion directives.
380b57cec5SDimitry Andric   SourceManager &SM; ///< Used to read and manage source files.
390b57cec5SDimitry Andric   raw_ostream &OS; ///< The destination stream for rewritten contents.
400b57cec5SDimitry Andric   StringRef MainEOL; ///< The line ending marker to use.
41e8d8bef9SDimitry Andric   llvm::MemoryBufferRef PredefinesBuffer; ///< The preprocessor predefines.
420b57cec5SDimitry Andric   bool ShowLineMarkers; ///< Show #line markers.
430b57cec5SDimitry Andric   bool UseLineDirectives; ///< Use of line directives or line markers.
440b57cec5SDimitry Andric   /// Tracks where inclusions that change the file are found.
45e8d8bef9SDimitry Andric   std::map<SourceLocation, IncludedFile> FileIncludes;
460b57cec5SDimitry Andric   /// Tracks where inclusions that import modules are found.
47e8d8bef9SDimitry Andric   std::map<SourceLocation, const Module *> ModuleIncludes;
480b57cec5SDimitry Andric   /// Tracks where inclusions that enter modules (in a module build) are found.
49e8d8bef9SDimitry Andric   std::map<SourceLocation, const Module *> ModuleEntryIncludes;
50a7dea167SDimitry Andric   /// Tracks where #if and #elif directives get evaluated and whether to true.
51e8d8bef9SDimitry Andric   std::map<SourceLocation, bool> IfConditions;
520b57cec5SDimitry Andric   /// Used transitively for building up the FileIncludes mapping over the
530b57cec5SDimitry Andric   /// various \c PPCallbacks callbacks.
540b57cec5SDimitry Andric   SourceLocation LastInclusionLocation;
550b57cec5SDimitry Andric public:
560b57cec5SDimitry Andric   InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers,
570b57cec5SDimitry Andric                     bool UseLineDirectives);
5804eeddc0SDimitry Andric   void Process(FileID FileId, SrcMgr::CharacteristicKind FileType);
59e8d8bef9SDimitry Andric   void setPredefinesBuffer(const llvm::MemoryBufferRef &Buf) {
600b57cec5SDimitry Andric     PredefinesBuffer = Buf;
610b57cec5SDimitry Andric   }
620b57cec5SDimitry Andric   void detectMainFileEOL();
630b57cec5SDimitry Andric   void handleModuleBegin(Token &Tok) {
640b57cec5SDimitry Andric     assert(Tok.getKind() == tok::annot_module_begin);
65e8d8bef9SDimitry Andric     ModuleEntryIncludes.insert(
66e8d8bef9SDimitry Andric         {Tok.getLocation(), (Module *)Tok.getAnnotationValue()});
670b57cec5SDimitry Andric   }
680b57cec5SDimitry Andric private:
690b57cec5SDimitry Andric   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
700b57cec5SDimitry Andric                    SrcMgr::CharacteristicKind FileType,
710b57cec5SDimitry Andric                    FileID PrevFID) override;
72a7dea167SDimitry Andric   void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
730b57cec5SDimitry Andric                    SrcMgr::CharacteristicKind FileType) override;
740b57cec5SDimitry Andric   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
750b57cec5SDimitry Andric                           StringRef FileName, bool IsAngled,
7681ad6265SDimitry Andric                           CharSourceRange FilenameRange,
77*bdd1243dSDimitry Andric                           OptionalFileEntryRef File, StringRef SearchPath,
7881ad6265SDimitry Andric                           StringRef RelativePath, const Module *Imported,
790b57cec5SDimitry Andric                           SrcMgr::CharacteristicKind FileType) override;
80a7dea167SDimitry Andric   void If(SourceLocation Loc, SourceRange ConditionRange,
81a7dea167SDimitry Andric           ConditionValueKind ConditionValue) override;
82a7dea167SDimitry Andric   void Elif(SourceLocation Loc, SourceRange ConditionRange,
83a7dea167SDimitry Andric             ConditionValueKind ConditionValue, SourceLocation IfLoc) override;
840b57cec5SDimitry Andric   void WriteLineInfo(StringRef Filename, int Line,
850b57cec5SDimitry Andric                      SrcMgr::CharacteristicKind FileType,
860b57cec5SDimitry Andric                      StringRef Extra = StringRef());
870b57cec5SDimitry Andric   void WriteImplicitModuleImport(const Module *Mod);
88e8d8bef9SDimitry Andric   void OutputContentUpTo(const MemoryBufferRef &FromFile, unsigned &WriteFrom,
89e8d8bef9SDimitry Andric                          unsigned WriteTo, StringRef EOL, int &lines,
900b57cec5SDimitry Andric                          bool EnsureNewline);
910b57cec5SDimitry Andric   void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken,
92e8d8bef9SDimitry Andric                            const MemoryBufferRef &FromFile, StringRef EOL,
930b57cec5SDimitry Andric                            unsigned &NextToWrite, int &Lines);
940b57cec5SDimitry Andric   const IncludedFile *FindIncludeAtLocation(SourceLocation Loc) const;
950b57cec5SDimitry Andric   const Module *FindModuleAtLocation(SourceLocation Loc) const;
960b57cec5SDimitry Andric   const Module *FindEnteredModule(SourceLocation Loc) const;
97a7dea167SDimitry Andric   bool IsIfAtLocationTrue(SourceLocation Loc) const;
980b57cec5SDimitry Andric   StringRef NextIdentifierName(Lexer &RawLex, Token &RawToken);
990b57cec5SDimitry Andric };
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric }  // end anonymous namespace
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric /// Initializes an InclusionRewriter with a \p PP source and \p OS destination.
1040b57cec5SDimitry Andric InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS,
1050b57cec5SDimitry Andric                                      bool ShowLineMarkers,
1060b57cec5SDimitry Andric                                      bool UseLineDirectives)
1070b57cec5SDimitry Andric     : PP(PP), SM(PP.getSourceManager()), OS(OS), MainEOL("\n"),
108e8d8bef9SDimitry Andric       ShowLineMarkers(ShowLineMarkers), UseLineDirectives(UseLineDirectives),
1090b57cec5SDimitry Andric       LastInclusionLocation(SourceLocation()) {}
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric /// Write appropriate line information as either #line directives or GNU line
1120b57cec5SDimitry Andric /// markers depending on what mode we're in, including the \p Filename and
1130b57cec5SDimitry Andric /// \p Line we are located at, using the specified \p EOL line separator, and
1140b57cec5SDimitry Andric /// any \p Extra context specifiers in GNU line directives.
1150b57cec5SDimitry Andric void InclusionRewriter::WriteLineInfo(StringRef Filename, int Line,
1160b57cec5SDimitry Andric                                       SrcMgr::CharacteristicKind FileType,
1170b57cec5SDimitry Andric                                       StringRef Extra) {
1180b57cec5SDimitry Andric   if (!ShowLineMarkers)
1190b57cec5SDimitry Andric     return;
1200b57cec5SDimitry Andric   if (UseLineDirectives) {
1210b57cec5SDimitry Andric     OS << "#line" << ' ' << Line << ' ' << '"';
1220b57cec5SDimitry Andric     OS.write_escaped(Filename);
1230b57cec5SDimitry Andric     OS << '"';
1240b57cec5SDimitry Andric   } else {
1250b57cec5SDimitry Andric     // Use GNU linemarkers as described here:
1260b57cec5SDimitry Andric     // http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html
1270b57cec5SDimitry Andric     OS << '#' << ' ' << Line << ' ' << '"';
1280b57cec5SDimitry Andric     OS.write_escaped(Filename);
1290b57cec5SDimitry Andric     OS << '"';
1300b57cec5SDimitry Andric     if (!Extra.empty())
1310b57cec5SDimitry Andric       OS << Extra;
1320b57cec5SDimitry Andric     if (FileType == SrcMgr::C_System)
1330b57cec5SDimitry Andric       // "`3' This indicates that the following text comes from a system header
1340b57cec5SDimitry Andric       // file, so certain warnings should be suppressed."
1350b57cec5SDimitry Andric       OS << " 3";
1360b57cec5SDimitry Andric     else if (FileType == SrcMgr::C_ExternCSystem)
1370b57cec5SDimitry Andric       // as above for `3', plus "`4' This indicates that the following text
1380b57cec5SDimitry Andric       // should be treated as being wrapped in an implicit extern "C" block."
1390b57cec5SDimitry Andric       OS << " 3 4";
1400b57cec5SDimitry Andric   }
1410b57cec5SDimitry Andric   OS << MainEOL;
1420b57cec5SDimitry Andric }
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric void InclusionRewriter::WriteImplicitModuleImport(const Module *Mod) {
1450b57cec5SDimitry Andric   OS << "#pragma clang module import " << Mod->getFullModuleName(true)
1460b57cec5SDimitry Andric      << " /* clang -frewrite-includes: implicit import */" << MainEOL;
1470b57cec5SDimitry Andric }
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric /// FileChanged - Whenever the preprocessor enters or exits a #include file
1500b57cec5SDimitry Andric /// it invokes this handler.
1510b57cec5SDimitry Andric void InclusionRewriter::FileChanged(SourceLocation Loc,
1520b57cec5SDimitry Andric                                     FileChangeReason Reason,
1530b57cec5SDimitry Andric                                     SrcMgr::CharacteristicKind NewFileType,
1540b57cec5SDimitry Andric                                     FileID) {
1550b57cec5SDimitry Andric   if (Reason != EnterFile)
1560b57cec5SDimitry Andric     return;
1570b57cec5SDimitry Andric   if (LastInclusionLocation.isInvalid())
1580b57cec5SDimitry Andric     // we didn't reach this file (eg: the main file) via an inclusion directive
1590b57cec5SDimitry Andric     return;
1600b57cec5SDimitry Andric   FileID Id = FullSourceLoc(Loc, SM).getFileID();
1610b57cec5SDimitry Andric   auto P = FileIncludes.insert(
16204eeddc0SDimitry Andric       std::make_pair(LastInclusionLocation, IncludedFile(Id, NewFileType)));
1630b57cec5SDimitry Andric   (void)P;
1640b57cec5SDimitry Andric   assert(P.second && "Unexpected revisitation of the same include directive");
1650b57cec5SDimitry Andric   LastInclusionLocation = SourceLocation();
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric /// Called whenever an inclusion is skipped due to canonical header protection
1690b57cec5SDimitry Andric /// macros.
170a7dea167SDimitry Andric void InclusionRewriter::FileSkipped(const FileEntryRef & /*SkippedFile*/,
1710b57cec5SDimitry Andric                                     const Token & /*FilenameTok*/,
1720b57cec5SDimitry Andric                                     SrcMgr::CharacteristicKind /*FileType*/) {
1730b57cec5SDimitry Andric   assert(LastInclusionLocation.isValid() &&
1740b57cec5SDimitry Andric          "A file, that wasn't found via an inclusion directive, was skipped");
1750b57cec5SDimitry Andric   LastInclusionLocation = SourceLocation();
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric /// This should be called whenever the preprocessor encounters include
1790b57cec5SDimitry Andric /// directives. It does not say whether the file has been included, but it
1800b57cec5SDimitry Andric /// provides more information about the directive (hash location instead
1810b57cec5SDimitry Andric /// of location inside the included file). It is assumed that the matching
1820b57cec5SDimitry Andric /// FileChanged() or FileSkipped() is called after this (or neither is
1830b57cec5SDimitry Andric /// called if this #include results in an error or does not textually include
1840b57cec5SDimitry Andric /// anything).
185*bdd1243dSDimitry Andric void InclusionRewriter::InclusionDirective(
186*bdd1243dSDimitry Andric     SourceLocation HashLoc, const Token & /*IncludeTok*/,
187*bdd1243dSDimitry Andric     StringRef /*FileName*/, bool /*IsAngled*/,
188*bdd1243dSDimitry Andric     CharSourceRange /*FilenameRange*/, OptionalFileEntryRef /*File*/,
189*bdd1243dSDimitry Andric     StringRef /*SearchPath*/, StringRef /*RelativePath*/,
190*bdd1243dSDimitry Andric     const Module *Imported, SrcMgr::CharacteristicKind FileType) {
1910b57cec5SDimitry Andric   if (Imported) {
192e8d8bef9SDimitry Andric     auto P = ModuleIncludes.insert(std::make_pair(HashLoc, Imported));
1930b57cec5SDimitry Andric     (void)P;
1940b57cec5SDimitry Andric     assert(P.second && "Unexpected revisitation of the same include directive");
1950b57cec5SDimitry Andric   } else
1960b57cec5SDimitry Andric     LastInclusionLocation = HashLoc;
1970b57cec5SDimitry Andric }
1980b57cec5SDimitry Andric 
199a7dea167SDimitry Andric void InclusionRewriter::If(SourceLocation Loc, SourceRange ConditionRange,
200a7dea167SDimitry Andric                            ConditionValueKind ConditionValue) {
201e8d8bef9SDimitry Andric   auto P = IfConditions.insert(std::make_pair(Loc, ConditionValue == CVK_True));
202a7dea167SDimitry Andric   (void)P;
203a7dea167SDimitry Andric   assert(P.second && "Unexpected revisitation of the same if directive");
204a7dea167SDimitry Andric }
205a7dea167SDimitry Andric 
206a7dea167SDimitry Andric void InclusionRewriter::Elif(SourceLocation Loc, SourceRange ConditionRange,
207a7dea167SDimitry Andric                              ConditionValueKind ConditionValue,
208a7dea167SDimitry Andric                              SourceLocation IfLoc) {
209e8d8bef9SDimitry Andric   auto P = IfConditions.insert(std::make_pair(Loc, ConditionValue == CVK_True));
210a7dea167SDimitry Andric   (void)P;
211a7dea167SDimitry Andric   assert(P.second && "Unexpected revisitation of the same elif directive");
212a7dea167SDimitry Andric }
213a7dea167SDimitry Andric 
2140b57cec5SDimitry Andric /// Simple lookup for a SourceLocation (specifically one denoting the hash in
2150b57cec5SDimitry Andric /// an inclusion directive) in the map of inclusion information, FileChanges.
2160b57cec5SDimitry Andric const InclusionRewriter::IncludedFile *
2170b57cec5SDimitry Andric InclusionRewriter::FindIncludeAtLocation(SourceLocation Loc) const {
218e8d8bef9SDimitry Andric   const auto I = FileIncludes.find(Loc);
2190b57cec5SDimitry Andric   if (I != FileIncludes.end())
2200b57cec5SDimitry Andric     return &I->second;
2210b57cec5SDimitry Andric   return nullptr;
2220b57cec5SDimitry Andric }
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric /// Simple lookup for a SourceLocation (specifically one denoting the hash in
2250b57cec5SDimitry Andric /// an inclusion directive) in the map of module inclusion information.
2260b57cec5SDimitry Andric const Module *
2270b57cec5SDimitry Andric InclusionRewriter::FindModuleAtLocation(SourceLocation Loc) const {
228e8d8bef9SDimitry Andric   const auto I = ModuleIncludes.find(Loc);
2290b57cec5SDimitry Andric   if (I != ModuleIncludes.end())
2300b57cec5SDimitry Andric     return I->second;
2310b57cec5SDimitry Andric   return nullptr;
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric /// Simple lookup for a SourceLocation (specifically one denoting the hash in
2350b57cec5SDimitry Andric /// an inclusion directive) in the map of module entry information.
2360b57cec5SDimitry Andric const Module *
2370b57cec5SDimitry Andric InclusionRewriter::FindEnteredModule(SourceLocation Loc) const {
238e8d8bef9SDimitry Andric   const auto I = ModuleEntryIncludes.find(Loc);
2390b57cec5SDimitry Andric   if (I != ModuleEntryIncludes.end())
2400b57cec5SDimitry Andric     return I->second;
2410b57cec5SDimitry Andric   return nullptr;
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric 
244a7dea167SDimitry Andric bool InclusionRewriter::IsIfAtLocationTrue(SourceLocation Loc) const {
245e8d8bef9SDimitry Andric   const auto I = IfConditions.find(Loc);
246a7dea167SDimitry Andric   if (I != IfConditions.end())
247a7dea167SDimitry Andric     return I->second;
248a7dea167SDimitry Andric   return false;
249a7dea167SDimitry Andric }
250a7dea167SDimitry Andric 
2510b57cec5SDimitry Andric void InclusionRewriter::detectMainFileEOL() {
252*bdd1243dSDimitry Andric   std::optional<MemoryBufferRef> FromFile =
253*bdd1243dSDimitry Andric       *SM.getBufferOrNone(SM.getMainFileID());
254e8d8bef9SDimitry Andric   assert(FromFile);
255e8d8bef9SDimitry Andric   if (!FromFile)
2560b57cec5SDimitry Andric     return; // Should never happen, but whatever.
25704eeddc0SDimitry Andric   MainEOL = FromFile->getBuffer().detectEOL();
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric /// Writes out bytes from \p FromFile, starting at \p NextToWrite and ending at
2610b57cec5SDimitry Andric /// \p WriteTo - 1.
262e8d8bef9SDimitry Andric void InclusionRewriter::OutputContentUpTo(const MemoryBufferRef &FromFile,
2630b57cec5SDimitry Andric                                           unsigned &WriteFrom, unsigned WriteTo,
2640b57cec5SDimitry Andric                                           StringRef LocalEOL, int &Line,
2650b57cec5SDimitry Andric                                           bool EnsureNewline) {
2660b57cec5SDimitry Andric   if (WriteTo <= WriteFrom)
2670b57cec5SDimitry Andric     return;
268e8d8bef9SDimitry Andric   if (FromFile == PredefinesBuffer) {
2690b57cec5SDimitry Andric     // Ignore the #defines of the predefines buffer.
2700b57cec5SDimitry Andric     WriteFrom = WriteTo;
2710b57cec5SDimitry Andric     return;
2720b57cec5SDimitry Andric   }
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric   // If we would output half of a line ending, advance one character to output
2750b57cec5SDimitry Andric   // the whole line ending.  All buffers are null terminated, so looking ahead
2760b57cec5SDimitry Andric   // one byte is safe.
2770b57cec5SDimitry Andric   if (LocalEOL.size() == 2 &&
2780b57cec5SDimitry Andric       LocalEOL[0] == (FromFile.getBufferStart() + WriteTo)[-1] &&
2790b57cec5SDimitry Andric       LocalEOL[1] == (FromFile.getBufferStart() + WriteTo)[0])
2800b57cec5SDimitry Andric     WriteTo++;
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   StringRef TextToWrite(FromFile.getBufferStart() + WriteFrom,
2830b57cec5SDimitry Andric                         WriteTo - WriteFrom);
284*bdd1243dSDimitry Andric   // count lines manually, it's faster than getPresumedLoc()
285*bdd1243dSDimitry Andric   Line += TextToWrite.count(LocalEOL);
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   if (MainEOL == LocalEOL) {
2880b57cec5SDimitry Andric     OS << TextToWrite;
2890b57cec5SDimitry Andric   } else {
2900b57cec5SDimitry Andric     // Output the file one line at a time, rewriting the line endings as we go.
2910b57cec5SDimitry Andric     StringRef Rest = TextToWrite;
2920b57cec5SDimitry Andric     while (!Rest.empty()) {
293*bdd1243dSDimitry Andric       // Identify and output the next line excluding an EOL sequence if present.
294*bdd1243dSDimitry Andric       size_t Idx = Rest.find(LocalEOL);
295*bdd1243dSDimitry Andric       StringRef LineText = Rest.substr(0, Idx);
2960b57cec5SDimitry Andric       OS << LineText;
297*bdd1243dSDimitry Andric       if (Idx != StringRef::npos) {
298*bdd1243dSDimitry Andric         // An EOL sequence was present, output the EOL sequence for the
299*bdd1243dSDimitry Andric         // main source file and skip past the local EOL sequence.
3000b57cec5SDimitry Andric         OS << MainEOL;
301*bdd1243dSDimitry Andric         Idx += LocalEOL.size();
3020b57cec5SDimitry Andric       }
303*bdd1243dSDimitry Andric       // Strip the line just handled. If Idx is npos or matches the end of the
304*bdd1243dSDimitry Andric       // text, Rest will be set to an empty string and the loop will terminate.
305*bdd1243dSDimitry Andric       Rest = Rest.substr(Idx);
306*bdd1243dSDimitry Andric     }
307*bdd1243dSDimitry Andric   }
308*bdd1243dSDimitry Andric   if (EnsureNewline && !TextToWrite.endswith(LocalEOL))
3090b57cec5SDimitry Andric     OS << MainEOL;
310*bdd1243dSDimitry Andric 
3110b57cec5SDimitry Andric   WriteFrom = WriteTo;
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric /// Print characters from \p FromFile starting at \p NextToWrite up until the
3150b57cec5SDimitry Andric /// inclusion directive at \p StartToken, then print out the inclusion
3160b57cec5SDimitry Andric /// inclusion directive disabled by a #if directive, updating \p NextToWrite
3170b57cec5SDimitry Andric /// and \p Line to track the number of source lines visited and the progress
3180b57cec5SDimitry Andric /// through the \p FromFile buffer.
3190b57cec5SDimitry Andric void InclusionRewriter::CommentOutDirective(Lexer &DirectiveLex,
3200b57cec5SDimitry Andric                                             const Token &StartToken,
321e8d8bef9SDimitry Andric                                             const MemoryBufferRef &FromFile,
3220b57cec5SDimitry Andric                                             StringRef LocalEOL,
3230b57cec5SDimitry Andric                                             unsigned &NextToWrite, int &Line) {
3240b57cec5SDimitry Andric   OutputContentUpTo(FromFile, NextToWrite,
3250b57cec5SDimitry Andric                     SM.getFileOffset(StartToken.getLocation()), LocalEOL, Line,
3260b57cec5SDimitry Andric                     false);
3270b57cec5SDimitry Andric   Token DirectiveToken;
3280b57cec5SDimitry Andric   do {
3290b57cec5SDimitry Andric     DirectiveLex.LexFromRawLexer(DirectiveToken);
3300b57cec5SDimitry Andric   } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof));
331e8d8bef9SDimitry Andric   if (FromFile == PredefinesBuffer) {
3320b57cec5SDimitry Andric     // OutputContentUpTo() would not output anything anyway.
3330b57cec5SDimitry Andric     return;
3340b57cec5SDimitry Andric   }
3350b57cec5SDimitry Andric   OS << "#if 0 /* expanded by -frewrite-includes */" << MainEOL;
3360b57cec5SDimitry Andric   OutputContentUpTo(FromFile, NextToWrite,
3370b57cec5SDimitry Andric                     SM.getFileOffset(DirectiveToken.getLocation()) +
3380b57cec5SDimitry Andric                         DirectiveToken.getLength(),
3390b57cec5SDimitry Andric                     LocalEOL, Line, true);
3400b57cec5SDimitry Andric   OS << "#endif /* expanded by -frewrite-includes */" << MainEOL;
3410b57cec5SDimitry Andric }
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric /// Find the next identifier in the pragma directive specified by \p RawToken.
3440b57cec5SDimitry Andric StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex,
3450b57cec5SDimitry Andric                                                 Token &RawToken) {
3460b57cec5SDimitry Andric   RawLex.LexFromRawLexer(RawToken);
3470b57cec5SDimitry Andric   if (RawToken.is(tok::raw_identifier))
3480b57cec5SDimitry Andric     PP.LookUpIdentifierInfo(RawToken);
3490b57cec5SDimitry Andric   if (RawToken.is(tok::identifier))
3500b57cec5SDimitry Andric     return RawToken.getIdentifierInfo()->getName();
3510b57cec5SDimitry Andric   return StringRef();
3520b57cec5SDimitry Andric }
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric /// Use a raw lexer to analyze \p FileId, incrementally copying parts of it
3550b57cec5SDimitry Andric /// and including content of included files recursively.
3560b57cec5SDimitry Andric void InclusionRewriter::Process(FileID FileId,
35704eeddc0SDimitry Andric                                 SrcMgr::CharacteristicKind FileType) {
358e8d8bef9SDimitry Andric   MemoryBufferRef FromFile;
359e8d8bef9SDimitry Andric   {
360e8d8bef9SDimitry Andric     auto B = SM.getBufferOrNone(FileId);
361e8d8bef9SDimitry Andric     assert(B && "Attempting to process invalid inclusion");
362e8d8bef9SDimitry Andric     if (B)
363e8d8bef9SDimitry Andric       FromFile = *B;
364e8d8bef9SDimitry Andric   }
3650b57cec5SDimitry Andric   StringRef FileName = FromFile.getBufferIdentifier();
366e8d8bef9SDimitry Andric   Lexer RawLex(FileId, FromFile, PP.getSourceManager(), PP.getLangOpts());
3670b57cec5SDimitry Andric   RawLex.SetCommentRetentionState(false);
3680b57cec5SDimitry Andric 
36904eeddc0SDimitry Andric   StringRef LocalEOL = FromFile.getBuffer().detectEOL();
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   // Per the GNU docs: "1" indicates entering a new file.
3720b57cec5SDimitry Andric   if (FileId == SM.getMainFileID() || FileId == PP.getPredefinesFileID())
3730b57cec5SDimitry Andric     WriteLineInfo(FileName, 1, FileType, "");
3740b57cec5SDimitry Andric   else
3750b57cec5SDimitry Andric     WriteLineInfo(FileName, 1, FileType, " 1");
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   if (SM.getFileIDSize(FileId) == 0)
3780b57cec5SDimitry Andric     return;
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   // The next byte to be copied from the source file, which may be non-zero if
3810b57cec5SDimitry Andric   // the lexer handled a BOM.
3820b57cec5SDimitry Andric   unsigned NextToWrite = SM.getFileOffset(RawLex.getSourceLocation());
3830b57cec5SDimitry Andric   assert(SM.getLineNumber(FileId, NextToWrite) == 1);
3840b57cec5SDimitry Andric   int Line = 1; // The current input file line number.
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   Token RawToken;
3870b57cec5SDimitry Andric   RawLex.LexFromRawLexer(RawToken);
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric   // TODO: Consider adding a switch that strips possibly unimportant content,
3900b57cec5SDimitry Andric   // such as comments, to reduce the size of repro files.
3910b57cec5SDimitry Andric   while (RawToken.isNot(tok::eof)) {
3920b57cec5SDimitry Andric     if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) {
3930b57cec5SDimitry Andric       RawLex.setParsingPreprocessorDirective(true);
3940b57cec5SDimitry Andric       Token HashToken = RawToken;
3950b57cec5SDimitry Andric       RawLex.LexFromRawLexer(RawToken);
3960b57cec5SDimitry Andric       if (RawToken.is(tok::raw_identifier))
3970b57cec5SDimitry Andric         PP.LookUpIdentifierInfo(RawToken);
3980b57cec5SDimitry Andric       if (RawToken.getIdentifierInfo() != nullptr) {
3990b57cec5SDimitry Andric         switch (RawToken.getIdentifierInfo()->getPPKeywordID()) {
4000b57cec5SDimitry Andric           case tok::pp_include:
4010b57cec5SDimitry Andric           case tok::pp_include_next:
4020b57cec5SDimitry Andric           case tok::pp_import: {
4030b57cec5SDimitry Andric             CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL, NextToWrite,
4040b57cec5SDimitry Andric               Line);
4050b57cec5SDimitry Andric             if (FileId != PP.getPredefinesFileID())
4060b57cec5SDimitry Andric               WriteLineInfo(FileName, Line - 1, FileType, "");
4070b57cec5SDimitry Andric             StringRef LineInfoExtra;
4080b57cec5SDimitry Andric             SourceLocation Loc = HashToken.getLocation();
4090b57cec5SDimitry Andric             if (const Module *Mod = FindModuleAtLocation(Loc))
4100b57cec5SDimitry Andric               WriteImplicitModuleImport(Mod);
4110b57cec5SDimitry Andric             else if (const IncludedFile *Inc = FindIncludeAtLocation(Loc)) {
4120b57cec5SDimitry Andric               const Module *Mod = FindEnteredModule(Loc);
4130b57cec5SDimitry Andric               if (Mod)
4140b57cec5SDimitry Andric                 OS << "#pragma clang module begin "
4150b57cec5SDimitry Andric                    << Mod->getFullModuleName(true) << "\n";
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric               // Include and recursively process the file.
41804eeddc0SDimitry Andric               Process(Inc->Id, Inc->FileType);
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric               if (Mod)
4210b57cec5SDimitry Andric                 OS << "#pragma clang module end /*"
4220b57cec5SDimitry Andric                    << Mod->getFullModuleName(true) << "*/\n";
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric               // Add line marker to indicate we're returning from an included
4250b57cec5SDimitry Andric               // file.
4260b57cec5SDimitry Andric               LineInfoExtra = " 2";
4270b57cec5SDimitry Andric             }
4280b57cec5SDimitry Andric             // fix up lineinfo (since commented out directive changed line
4290b57cec5SDimitry Andric             // numbers) for inclusions that were skipped due to header guards
4300b57cec5SDimitry Andric             WriteLineInfo(FileName, Line, FileType, LineInfoExtra);
4310b57cec5SDimitry Andric             break;
4320b57cec5SDimitry Andric           }
4330b57cec5SDimitry Andric           case tok::pp_pragma: {
4340b57cec5SDimitry Andric             StringRef Identifier = NextIdentifierName(RawLex, RawToken);
4350b57cec5SDimitry Andric             if (Identifier == "clang" || Identifier == "GCC") {
4360b57cec5SDimitry Andric               if (NextIdentifierName(RawLex, RawToken) == "system_header") {
4370b57cec5SDimitry Andric                 // keep the directive in, commented out
4380b57cec5SDimitry Andric                 CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL,
4390b57cec5SDimitry Andric                   NextToWrite, Line);
4400b57cec5SDimitry Andric                 // update our own type
4410b57cec5SDimitry Andric                 FileType = SM.getFileCharacteristic(RawToken.getLocation());
4420b57cec5SDimitry Andric                 WriteLineInfo(FileName, Line, FileType);
4430b57cec5SDimitry Andric               }
4440b57cec5SDimitry Andric             } else if (Identifier == "once") {
4450b57cec5SDimitry Andric               // keep the directive in, commented out
4460b57cec5SDimitry Andric               CommentOutDirective(RawLex, HashToken, FromFile, LocalEOL,
4470b57cec5SDimitry Andric                 NextToWrite, Line);
4480b57cec5SDimitry Andric               WriteLineInfo(FileName, Line, FileType);
4490b57cec5SDimitry Andric             }
4500b57cec5SDimitry Andric             break;
4510b57cec5SDimitry Andric           }
4520b57cec5SDimitry Andric           case tok::pp_if:
4530b57cec5SDimitry Andric           case tok::pp_elif: {
4540b57cec5SDimitry Andric             bool elif = (RawToken.getIdentifierInfo()->getPPKeywordID() ==
4550b57cec5SDimitry Andric                          tok::pp_elif);
456a7dea167SDimitry Andric             bool isTrue = IsIfAtLocationTrue(RawToken.getLocation());
4570b57cec5SDimitry Andric             OutputContentUpTo(FromFile, NextToWrite,
458a7dea167SDimitry Andric                               SM.getFileOffset(HashToken.getLocation()),
459a7dea167SDimitry Andric                               LocalEOL, Line, /*EnsureNewline=*/true);
460a7dea167SDimitry Andric             do {
461a7dea167SDimitry Andric               RawLex.LexFromRawLexer(RawToken);
462a7dea167SDimitry Andric             } while (!RawToken.is(tok::eod) && RawToken.isNot(tok::eof));
463a7dea167SDimitry Andric             // We need to disable the old condition, but that is tricky.
464a7dea167SDimitry Andric             // Trying to comment it out can easily lead to comment nesting.
465a7dea167SDimitry Andric             // So instead make the condition harmless by making it enclose
466a7dea167SDimitry Andric             // and empty block. Moreover, put it itself inside an #if 0 block
467a7dea167SDimitry Andric             // to disable it from getting evaluated (e.g. __has_include_next
468a7dea167SDimitry Andric             // warns if used from the primary source file).
469a7dea167SDimitry Andric             OS << "#if 0 /* disabled by -frewrite-includes */" << MainEOL;
4700b57cec5SDimitry Andric             if (elif) {
471a7dea167SDimitry Andric               OS << "#if 0" << MainEOL;
472a7dea167SDimitry Andric             }
4730b57cec5SDimitry Andric             OutputContentUpTo(FromFile, NextToWrite,
4740b57cec5SDimitry Andric                               SM.getFileOffset(RawToken.getLocation()) +
4750b57cec5SDimitry Andric                                   RawToken.getLength(),
4760b57cec5SDimitry Andric                               LocalEOL, Line, /*EnsureNewline=*/true);
477a7dea167SDimitry Andric             // Close the empty block and the disabling block.
478a7dea167SDimitry Andric             OS << "#endif" << MainEOL;
479a7dea167SDimitry Andric             OS << "#endif /* disabled by -frewrite-includes */" << MainEOL;
480a7dea167SDimitry Andric             OS << (elif ? "#elif " : "#if ") << (isTrue ? "1" : "0")
481a7dea167SDimitry Andric                << " /* evaluated by -frewrite-includes */" << MainEOL;
4820b57cec5SDimitry Andric             WriteLineInfo(FileName, Line, FileType);
4830b57cec5SDimitry Andric             break;
4840b57cec5SDimitry Andric           }
4850b57cec5SDimitry Andric           case tok::pp_endif:
4860b57cec5SDimitry Andric           case tok::pp_else: {
4870b57cec5SDimitry Andric             // We surround every #include by #if 0 to comment it out, but that
4880b57cec5SDimitry Andric             // changes line numbers. These are fixed up right after that, but
4890b57cec5SDimitry Andric             // the whole #include could be inside a preprocessor conditional
4900b57cec5SDimitry Andric             // that is not processed. So it is necessary to fix the line
4910b57cec5SDimitry Andric             // numbers one the next line after each #else/#endif as well.
4920b57cec5SDimitry Andric             RawLex.SetKeepWhitespaceMode(true);
4930b57cec5SDimitry Andric             do {
4940b57cec5SDimitry Andric               RawLex.LexFromRawLexer(RawToken);
4950b57cec5SDimitry Andric             } while (RawToken.isNot(tok::eod) && RawToken.isNot(tok::eof));
4960b57cec5SDimitry Andric             OutputContentUpTo(FromFile, NextToWrite,
4970b57cec5SDimitry Andric                               SM.getFileOffset(RawToken.getLocation()) +
4980b57cec5SDimitry Andric                                   RawToken.getLength(),
4990b57cec5SDimitry Andric                               LocalEOL, Line, /*EnsureNewline=*/ true);
5000b57cec5SDimitry Andric             WriteLineInfo(FileName, Line, FileType);
5010b57cec5SDimitry Andric             RawLex.SetKeepWhitespaceMode(false);
5020b57cec5SDimitry Andric             break;
5030b57cec5SDimitry Andric           }
5040b57cec5SDimitry Andric           default:
5050b57cec5SDimitry Andric             break;
5060b57cec5SDimitry Andric         }
5070b57cec5SDimitry Andric       }
5080b57cec5SDimitry Andric       RawLex.setParsingPreprocessorDirective(false);
5090b57cec5SDimitry Andric     }
5100b57cec5SDimitry Andric     RawLex.LexFromRawLexer(RawToken);
5110b57cec5SDimitry Andric   }
5120b57cec5SDimitry Andric   OutputContentUpTo(FromFile, NextToWrite,
5130b57cec5SDimitry Andric                     SM.getFileOffset(SM.getLocForEndOfFile(FileId)), LocalEOL,
5140b57cec5SDimitry Andric                     Line, /*EnsureNewline=*/true);
5150b57cec5SDimitry Andric }
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric /// InclusionRewriterInInput - Implement -frewrite-includes mode.
5180b57cec5SDimitry Andric void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS,
5190b57cec5SDimitry Andric                                    const PreprocessorOutputOptions &Opts) {
5200b57cec5SDimitry Andric   SourceManager &SM = PP.getSourceManager();
5210b57cec5SDimitry Andric   InclusionRewriter *Rewrite = new InclusionRewriter(
5220b57cec5SDimitry Andric       PP, *OS, Opts.ShowLineMarkers, Opts.UseLineDirectives);
5230b57cec5SDimitry Andric   Rewrite->detectMainFileEOL();
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Rewrite));
5260b57cec5SDimitry Andric   PP.IgnorePragmas();
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   // First let the preprocessor process the entire file and call callbacks.
5290b57cec5SDimitry Andric   // Callbacks will record which #include's were actually performed.
5300b57cec5SDimitry Andric   PP.EnterMainSourceFile();
5310b57cec5SDimitry Andric   Token Tok;
5320b57cec5SDimitry Andric   // Only preprocessor directives matter here, so disable macro expansion
5330b57cec5SDimitry Andric   // everywhere else as an optimization.
5340b57cec5SDimitry Andric   // TODO: It would be even faster if the preprocessor could be switched
5350b57cec5SDimitry Andric   // to a mode where it would parse only preprocessor directives and comments,
5360b57cec5SDimitry Andric   // nothing else matters for parsing or processing.
5370b57cec5SDimitry Andric   PP.SetMacroExpansionOnlyInDirectives();
5380b57cec5SDimitry Andric   do {
5390b57cec5SDimitry Andric     PP.Lex(Tok);
5400b57cec5SDimitry Andric     if (Tok.is(tok::annot_module_begin))
5410b57cec5SDimitry Andric       Rewrite->handleModuleBegin(Tok);
5420b57cec5SDimitry Andric   } while (Tok.isNot(tok::eof));
543e8d8bef9SDimitry Andric   Rewrite->setPredefinesBuffer(SM.getBufferOrFake(PP.getPredefinesFileID()));
54404eeddc0SDimitry Andric   Rewrite->Process(PP.getPredefinesFileID(), SrcMgr::C_User);
54504eeddc0SDimitry Andric   Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User);
5460b57cec5SDimitry Andric   OS->flush();
5470b57cec5SDimitry Andric }
548