xref: /src/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
122989816SDimitry Andric //===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===//
2ec2b103cSEd Schouten //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ec2b103cSEd Schouten //
7ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
8ec2b103cSEd Schouten //
9ec2b103cSEd Schouten //  This file implements the Preprocessor interface.
10ec2b103cSEd Schouten //
11ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
12ec2b103cSEd Schouten //
13ec2b103cSEd Schouten // Options to support:
14ec2b103cSEd Schouten //   -H       - Print the name of each header file used.
15ec2b103cSEd Schouten //   -d[DNI] - Dump various things.
16ec2b103cSEd Schouten //   -fworking-directory - #line's with preprocessor's working dir.
17ec2b103cSEd Schouten //   -fpreprocessed
18ec2b103cSEd Schouten //   -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
19ec2b103cSEd Schouten //   -W*
20ec2b103cSEd Schouten //   -w
21ec2b103cSEd Schouten //
22ec2b103cSEd Schouten // Messages to emit:
23ec2b103cSEd Schouten //   "Multiple include guards may be useful for:\n"
24ec2b103cSEd Schouten //
25ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
26ec2b103cSEd Schouten 
27ec2b103cSEd Schouten #include "clang/Lex/Preprocessor.h"
28706b4fc4SDimitry Andric #include "clang/Basic/Builtins.h"
29809500fcSDimitry Andric #include "clang/Basic/FileManager.h"
3006d4ba38SDimitry Andric #include "clang/Basic/FileSystemStatCache.h"
31461a67faSDimitry Andric #include "clang/Basic/IdentifierTable.h"
32461a67faSDimitry Andric #include "clang/Basic/LLVM.h"
33461a67faSDimitry Andric #include "clang/Basic/LangOptions.h"
34461a67faSDimitry Andric #include "clang/Basic/Module.h"
35461a67faSDimitry Andric #include "clang/Basic/SourceLocation.h"
36809500fcSDimitry Andric #include "clang/Basic/SourceManager.h"
37809500fcSDimitry Andric #include "clang/Basic/TargetInfo.h"
38809500fcSDimitry Andric #include "clang/Lex/CodeCompletionHandler.h"
39ee791ddeSRoman Divacky #include "clang/Lex/ExternalPreprocessorSource.h"
40ec2b103cSEd Schouten #include "clang/Lex/HeaderSearch.h"
41809500fcSDimitry Andric #include "clang/Lex/LexDiagnostic.h"
42461a67faSDimitry Andric #include "clang/Lex/Lexer.h"
43809500fcSDimitry Andric #include "clang/Lex/LiteralSupport.h"
449f4dbff6SDimitry Andric #include "clang/Lex/MacroArgs.h"
45ec2b103cSEd Schouten #include "clang/Lex/MacroInfo.h"
46809500fcSDimitry Andric #include "clang/Lex/ModuleLoader.h"
47ec2b103cSEd Schouten #include "clang/Lex/Pragma.h"
48c0c7bca4SRoman Divacky #include "clang/Lex/PreprocessingRecord.h"
49461a67faSDimitry Andric #include "clang/Lex/PreprocessorLexer.h"
50809500fcSDimitry Andric #include "clang/Lex/PreprocessorOptions.h"
51ec2b103cSEd Schouten #include "clang/Lex/ScratchBuffer.h"
52461a67faSDimitry Andric #include "clang/Lex/Token.h"
53461a67faSDimitry Andric #include "clang/Lex/TokenLexer.h"
54bab175ecSDimitry Andric #include "llvm/ADT/APInt.h"
55461a67faSDimitry Andric #include "llvm/ADT/ArrayRef.h"
56bab175ecSDimitry Andric #include "llvm/ADT/DenseMap.h"
57706b4fc4SDimitry Andric #include "llvm/ADT/STLExtras.h"
589f4dbff6SDimitry Andric #include "llvm/ADT/SmallString.h"
59bab175ecSDimitry Andric #include "llvm/ADT/SmallVector.h"
60bab175ecSDimitry Andric #include "llvm/ADT/StringRef.h"
61ac9a064cSDimitry Andric #include "llvm/ADT/iterator_range.h"
62809500fcSDimitry Andric #include "llvm/Support/Capacity.h"
63bab175ecSDimitry Andric #include "llvm/Support/ErrorHandling.h"
64ec2b103cSEd Schouten #include "llvm/Support/MemoryBuffer.h"
654c8b2481SRoman Divacky #include "llvm/Support/raw_ostream.h"
66bab175ecSDimitry Andric #include <algorithm>
67bab175ecSDimitry Andric #include <cassert>
68bab175ecSDimitry Andric #include <memory>
69e3b55780SDimitry Andric #include <optional>
70bab175ecSDimitry Andric #include <string>
712b6b257fSDimitry Andric #include <utility>
72bab175ecSDimitry Andric #include <vector>
73bab175ecSDimitry Andric 
74ec2b103cSEd Schouten using namespace clang;
75ec2b103cSEd Schouten 
76ac9a064cSDimitry Andric /// Minimum distance between two check points, in tokens.
77ac9a064cSDimitry Andric static constexpr unsigned CheckPointStepSize = 1024;
78ac9a064cSDimitry Andric 
79bab175ecSDimitry Andric LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
802b6b257fSDimitry Andric 
81461a67faSDimitry Andric ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
82ec2b103cSEd Schouten 
Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,DiagnosticsEngine & diags,const LangOptions & opts,SourceManager & SM,HeaderSearch & Headers,ModuleLoader & TheModuleLoader,IdentifierInfoLookup * IILookup,bool OwnsHeaders,TranslationUnitKind TUKind)836694ed09SDimitry Andric Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
84b1c73532SDimitry Andric                            DiagnosticsEngine &diags, const LangOptions &opts,
8522989816SDimitry Andric                            SourceManager &SM, HeaderSearch &Headers,
8622989816SDimitry Andric                            ModuleLoader &TheModuleLoader,
87809500fcSDimitry Andric                            IdentifierInfoLookup *IILookup, bool OwnsHeaders,
889f4dbff6SDimitry Andric                            TranslationUnitKind TUKind)
89461a67faSDimitry Andric     : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
9022989816SDimitry Andric       FileMgr(Headers.getFileMgr()), SourceMgr(SM),
9148675466SDimitry Andric       ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
9248675466SDimitry Andric       TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
9348675466SDimitry Andric       // As the language options may have not been loaded yet (when
9448675466SDimitry Andric       // deserializing an ASTUnit), adding keywords to the identifier table is
9548675466SDimitry Andric       // deferred to Preprocessor::Initialize().
9648675466SDimitry Andric       Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
9748675466SDimitry Andric       TUKind(TUKind), SkipMainFilePreamble(0, true),
98461a67faSDimitry Andric       CurSubmoduleState(&NullSubmoduleState) {
99b3d5a323SRoman Divacky   OwnsHeaderSearch = OwnsHeaders;
100ec2b103cSEd Schouten 
10156d91b49SDimitry Andric   // Default to discarding comments.
10256d91b49SDimitry Andric   KeepComments = false;
10356d91b49SDimitry Andric   KeepMacroComments = false;
10456d91b49SDimitry Andric   SuppressIncludeNotFoundError = false;
10556d91b49SDimitry Andric 
10656d91b49SDimitry Andric   // Macro expansion is enabled.
10756d91b49SDimitry Andric   DisableMacroExpansion = false;
10856d91b49SDimitry Andric   MacroExpansionInDirectivesOverride = false;
10956d91b49SDimitry Andric   InMacroArgs = false;
11022989816SDimitry Andric   ArgMacro = nullptr;
11156d91b49SDimitry Andric   InMacroArgPreExpansion = false;
11256d91b49SDimitry Andric   NumCachedTokenLexers = 0;
11356d91b49SDimitry Andric   PragmasEnabled = true;
114809500fcSDimitry Andric   ParsingIfOrElifDirective = false;
115809500fcSDimitry Andric   PreprocessedOutput = false;
11656d91b49SDimitry Andric 
11756d91b49SDimitry Andric   // We haven't read anything from the external source.
11856d91b49SDimitry Andric   ReadMacrosFromExternalSource = false;
11956d91b49SDimitry Andric 
120706b4fc4SDimitry Andric   BuiltinInfo = std::make_unique<Builtin::Context>();
121706b4fc4SDimitry Andric 
122461a67faSDimitry Andric   // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
123461a67faSDimitry Andric   // a macro. They get unpoisoned where it is allowed.
12456d91b49SDimitry Andric   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
12556d91b49SDimitry Andric   SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
126461a67faSDimitry Andric   (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
127461a67faSDimitry Andric   SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
12856d91b49SDimitry Andric 
12956d91b49SDimitry Andric   // Initialize the pragma handlers.
13056d91b49SDimitry Andric   RegisterBuiltinPragmas();
13156d91b49SDimitry Andric 
13256d91b49SDimitry Andric   // Initialize builtin macros like __LINE__ and friends.
13356d91b49SDimitry Andric   RegisterBuiltinMacros();
13456d91b49SDimitry Andric 
13556d91b49SDimitry Andric   if(LangOpts.Borland) {
13656d91b49SDimitry Andric     Ident__exception_info        = getIdentifierInfo("_exception_info");
13756d91b49SDimitry Andric     Ident___exception_info       = getIdentifierInfo("__exception_info");
13856d91b49SDimitry Andric     Ident_GetExceptionInfo       = getIdentifierInfo("GetExceptionInformation");
13956d91b49SDimitry Andric     Ident__exception_code        = getIdentifierInfo("_exception_code");
14056d91b49SDimitry Andric     Ident___exception_code       = getIdentifierInfo("__exception_code");
14156d91b49SDimitry Andric     Ident_GetExceptionCode       = getIdentifierInfo("GetExceptionCode");
14256d91b49SDimitry Andric     Ident__abnormal_termination  = getIdentifierInfo("_abnormal_termination");
14356d91b49SDimitry Andric     Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
14456d91b49SDimitry Andric     Ident_AbnormalTermination    = getIdentifierInfo("AbnormalTermination");
14556d91b49SDimitry Andric   } else {
1469f4dbff6SDimitry Andric     Ident__exception_info = Ident__exception_code = nullptr;
1479f4dbff6SDimitry Andric     Ident__abnormal_termination = Ident___exception_info = nullptr;
1489f4dbff6SDimitry Andric     Ident___exception_code = Ident___abnormal_termination = nullptr;
1499f4dbff6SDimitry Andric     Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
1509f4dbff6SDimitry Andric     Ident_AbnormalTermination = nullptr;
15101af97d3SDimitry Andric   }
152550ae89aSDimitry Andric 
153b1c73532SDimitry Andric   // Default incremental processing to -fincremental-extensions, clients can
154b1c73532SDimitry Andric   // override with `enableIncrementalProcessing` if desired.
155b1c73532SDimitry Andric   IncrementalProcessing = LangOpts.IncrementalExtensions;
156b1c73532SDimitry Andric 
157676fbe81SDimitry Andric   // If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
158676fbe81SDimitry Andric   if (usingPCHWithPragmaHdrStop())
159676fbe81SDimitry Andric     SkippingUntilPragmaHdrStop = true;
160676fbe81SDimitry Andric 
16148675466SDimitry Andric   // If using a PCH with a through header, start skipping tokens.
16248675466SDimitry Andric   if (!this->PPOpts->PCHThroughHeader.empty() &&
16348675466SDimitry Andric       !this->PPOpts->ImplicitPCHInclude.empty())
16448675466SDimitry Andric     SkippingUntilPCHThroughHeader = true;
16548675466SDimitry Andric 
166550ae89aSDimitry Andric   if (this->PPOpts->GeneratePreamble)
167550ae89aSDimitry Andric     PreambleConditionalStack.startRecording();
168519fc96cSDimitry Andric 
169cfca06d7SDimitry Andric   MaxTokens = LangOpts.MaxTokens;
170ec2b103cSEd Schouten }
171ec2b103cSEd Schouten 
~Preprocessor()172ec2b103cSEd Schouten Preprocessor::~Preprocessor() {
173ec2b103cSEd Schouten   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
174ec2b103cSEd Schouten 
1759f4dbff6SDimitry Andric   IncludeMacroStack.clear();
176ec2b103cSEd Schouten 
177ec2b103cSEd Schouten   // Free any cached macro expanders.
1789f4dbff6SDimitry Andric   // This populates MacroArgCache, so all TokenLexers need to be destroyed
1799f4dbff6SDimitry Andric   // before the code below that frees up the MacroArgCache list.
18006d4ba38SDimitry Andric   std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
1819f4dbff6SDimitry Andric   CurTokenLexer.reset();
182ec2b103cSEd Schouten 
18334d02d0bSRoman Divacky   // Free any cached MacroArgs.
18434d02d0bSRoman Divacky   for (MacroArgs *ArgList = MacroArgCache; ArgList;)
18534d02d0bSRoman Divacky     ArgList = ArgList->deallocate();
18634d02d0bSRoman Divacky 
187b3d5a323SRoman Divacky   // Delete the header search info, if we own it.
188b3d5a323SRoman Divacky   if (OwnsHeaderSearch)
189b3d5a323SRoman Divacky     delete &HeaderInfo;
190ec2b103cSEd Schouten }
191ec2b103cSEd Schouten 
Initialize(const TargetInfo & Target,const TargetInfo * AuxTarget)19245b53394SDimitry Andric void Preprocessor::Initialize(const TargetInfo &Target,
19345b53394SDimitry Andric                               const TargetInfo *AuxTarget) {
19436981b17SDimitry Andric   assert((!this->Target || this->Target == &Target) &&
19536981b17SDimitry Andric          "Invalid override of target information");
19636981b17SDimitry Andric   this->Target = &Target;
19736981b17SDimitry Andric 
19845b53394SDimitry Andric   assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
19945b53394SDimitry Andric          "Invalid override of aux target information.");
20045b53394SDimitry Andric   this->AuxTarget = AuxTarget;
20145b53394SDimitry Andric 
20236981b17SDimitry Andric   // Initialize information about built-ins.
203706b4fc4SDimitry Andric   BuiltinInfo->InitializeTarget(Target, AuxTarget);
204dbe13110SDimitry Andric   HeaderInfo.setTarget(Target);
20548675466SDimitry Andric 
20648675466SDimitry Andric   // Populate the identifier table with info about keywords for the current language.
20748675466SDimitry Andric   Identifiers.AddKeywords(LangOpts);
208145449b1SDimitry Andric 
209145449b1SDimitry Andric   // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.
210145449b1SDimitry Andric   setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
211145449b1SDimitry Andric 
212145449b1SDimitry Andric   if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
213145449b1SDimitry Andric     // Use setting from TargetInfo.
214145449b1SDimitry Andric     setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());
215145449b1SDimitry Andric   else
216145449b1SDimitry Andric     // Set initial value of __FLT_EVAL_METHOD__ from the command line.
217145449b1SDimitry Andric     setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
21836981b17SDimitry Andric }
21936981b17SDimitry Andric 
InitializeForModelFile()22006d4ba38SDimitry Andric void Preprocessor::InitializeForModelFile() {
22106d4ba38SDimitry Andric   NumEnteredSourceFiles = 0;
22206d4ba38SDimitry Andric 
22306d4ba38SDimitry Andric   // Reset pragmas
22406d4ba38SDimitry Andric   PragmaHandlersBackup = std::move(PragmaHandlers);
225519fc96cSDimitry Andric   PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
22606d4ba38SDimitry Andric   RegisterBuiltinPragmas();
22706d4ba38SDimitry Andric 
22806d4ba38SDimitry Andric   // Reset PredefinesFileID
22906d4ba38SDimitry Andric   PredefinesFileID = FileID();
23006d4ba38SDimitry Andric }
23106d4ba38SDimitry Andric 
FinalizeForModelFile()23206d4ba38SDimitry Andric void Preprocessor::FinalizeForModelFile() {
23306d4ba38SDimitry Andric   NumEnteredSourceFiles = 1;
23406d4ba38SDimitry Andric 
23506d4ba38SDimitry Andric   PragmaHandlers = std::move(PragmaHandlersBackup);
23606d4ba38SDimitry Andric }
23706d4ba38SDimitry Andric 
DumpToken(const Token & Tok,bool DumpFlags) const238ec2b103cSEd Schouten void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
239145449b1SDimitry Andric   llvm::errs() << tok::getTokenName(Tok.getKind());
240145449b1SDimitry Andric 
241145449b1SDimitry Andric   if (!Tok.isAnnotation())
242145449b1SDimitry Andric     llvm::errs() << " '" << getSpelling(Tok) << "'";
243ec2b103cSEd Schouten 
244ec2b103cSEd Schouten   if (!DumpFlags) return;
245ec2b103cSEd Schouten 
2464c8b2481SRoman Divacky   llvm::errs() << "\t";
247ec2b103cSEd Schouten   if (Tok.isAtStartOfLine())
2484c8b2481SRoman Divacky     llvm::errs() << " [StartOfLine]";
249ec2b103cSEd Schouten   if (Tok.hasLeadingSpace())
2504c8b2481SRoman Divacky     llvm::errs() << " [LeadingSpace]";
251ec2b103cSEd Schouten   if (Tok.isExpandDisabled())
2524c8b2481SRoman Divacky     llvm::errs() << " [ExpandDisabled]";
253ec2b103cSEd Schouten   if (Tok.needsCleaning()) {
254ec2b103cSEd Schouten     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
25536981b17SDimitry Andric     llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
256ec2b103cSEd Schouten                  << "']";
257ec2b103cSEd Schouten   }
258ec2b103cSEd Schouten 
2594c8b2481SRoman Divacky   llvm::errs() << "\tLoc=<";
260ec2b103cSEd Schouten   DumpLocation(Tok.getLocation());
2614c8b2481SRoman Divacky   llvm::errs() << ">";
262ec2b103cSEd Schouten }
263ec2b103cSEd Schouten 
DumpLocation(SourceLocation Loc) const264ec2b103cSEd Schouten void Preprocessor::DumpLocation(SourceLocation Loc) const {
265676fbe81SDimitry Andric   Loc.print(llvm::errs(), SourceMgr);
266ec2b103cSEd Schouten }
267ec2b103cSEd Schouten 
DumpMacro(const MacroInfo & MI) const268ec2b103cSEd Schouten void Preprocessor::DumpMacro(const MacroInfo &MI) const {
2694c8b2481SRoman Divacky   llvm::errs() << "MACRO: ";
270ec2b103cSEd Schouten   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
271ec2b103cSEd Schouten     DumpToken(MI.getReplacementToken(i));
2724c8b2481SRoman Divacky     llvm::errs() << "  ";
273ec2b103cSEd Schouten   }
2744c8b2481SRoman Divacky   llvm::errs() << "\n";
275ec2b103cSEd Schouten }
276ec2b103cSEd Schouten 
PrintStats()277ec2b103cSEd Schouten void Preprocessor::PrintStats() {
2784c8b2481SRoman Divacky   llvm::errs() << "\n*** Preprocessor Stats:\n";
2794c8b2481SRoman Divacky   llvm::errs() << NumDirectives << " directives found:\n";
2804c8b2481SRoman Divacky   llvm::errs() << "  " << NumDefined << " #define.\n";
2814c8b2481SRoman Divacky   llvm::errs() << "  " << NumUndefined << " #undef.\n";
2824c8b2481SRoman Divacky   llvm::errs() << "  #include/#include_next/#import:\n";
2834c8b2481SRoman Divacky   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
2844c8b2481SRoman Divacky   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
2854c8b2481SRoman Divacky   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
286344a3780SDimitry Andric   llvm::errs() << "  " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";
2874c8b2481SRoman Divacky   llvm::errs() << "  " << NumEndif << " #endif.\n";
2884c8b2481SRoman Divacky   llvm::errs() << "  " << NumPragma << " #pragma.\n";
2894c8b2481SRoman Divacky   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
290ec2b103cSEd Schouten 
2914c8b2481SRoman Divacky   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
292ec2b103cSEd Schouten              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
293ec2b103cSEd Schouten              << NumFastMacroExpanded << " on the fast path.\n";
2944c8b2481SRoman Divacky   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
295ec2b103cSEd Schouten              << " token paste (##) operations performed, "
296ec2b103cSEd Schouten              << NumFastTokenPaste << " on the fast path.\n";
29756d91b49SDimitry Andric 
29856d91b49SDimitry Andric   llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
29956d91b49SDimitry Andric 
30056d91b49SDimitry Andric   llvm::errs() << "\n  BumpPtr: " << BP.getTotalMemory();
30156d91b49SDimitry Andric   llvm::errs() << "\n  Macro Expanded Tokens: "
30256d91b49SDimitry Andric                << llvm::capacity_in_bytes(MacroExpandedTokens);
30356d91b49SDimitry Andric   llvm::errs() << "\n  Predefines Buffer: " << Predefines.capacity();
3045e20cdd8SDimitry Andric   // FIXME: List information for all submodules.
3055e20cdd8SDimitry Andric   llvm::errs() << "\n  Macros: "
3065e20cdd8SDimitry Andric                << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
30756d91b49SDimitry Andric   llvm::errs() << "\n  #pragma push_macro Info: "
30856d91b49SDimitry Andric                << llvm::capacity_in_bytes(PragmaPushMacroInfo);
30956d91b49SDimitry Andric   llvm::errs() << "\n  Poison Reasons: "
31056d91b49SDimitry Andric                << llvm::capacity_in_bytes(PoisonReasons);
31156d91b49SDimitry Andric   llvm::errs() << "\n  Comment Handlers: "
31256d91b49SDimitry Andric                << llvm::capacity_in_bytes(CommentHandlers) << "\n";
313ec2b103cSEd Schouten }
314ec2b103cSEd Schouten 
315ee791ddeSRoman Divacky Preprocessor::macro_iterator
macro_begin(bool IncludeExternalMacros) const316ee791ddeSRoman Divacky Preprocessor::macro_begin(bool IncludeExternalMacros) const {
317ee791ddeSRoman Divacky   if (IncludeExternalMacros && ExternalSource &&
318ee791ddeSRoman Divacky       !ReadMacrosFromExternalSource) {
319ee791ddeSRoman Divacky     ReadMacrosFromExternalSource = true;
320ee791ddeSRoman Divacky     ExternalSource->ReadDefinedMacros();
321ee791ddeSRoman Divacky   }
322ee791ddeSRoman Divacky 
323c192b3dcSDimitry Andric   // Make sure we cover all macros in visible modules.
324c192b3dcSDimitry Andric   for (const ModuleMacro &Macro : ModuleMacros)
325c192b3dcSDimitry Andric     CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
326c192b3dcSDimitry Andric 
3275e20cdd8SDimitry Andric   return CurSubmoduleState->Macros.begin();
328ee791ddeSRoman Divacky }
329ee791ddeSRoman Divacky 
getTotalMemory() const330180abc3dSDimitry Andric size_t Preprocessor::getTotalMemory() const {
33136981b17SDimitry Andric   return BP.getTotalMemory()
33236981b17SDimitry Andric     + llvm::capacity_in_bytes(MacroExpandedTokens)
33336981b17SDimitry Andric     + Predefines.capacity() /* Predefines buffer. */
3345e20cdd8SDimitry Andric     // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
3355e20cdd8SDimitry Andric     // and ModuleMacros.
3365e20cdd8SDimitry Andric     + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
33736981b17SDimitry Andric     + llvm::capacity_in_bytes(PragmaPushMacroInfo)
33836981b17SDimitry Andric     + llvm::capacity_in_bytes(PoisonReasons)
33936981b17SDimitry Andric     + llvm::capacity_in_bytes(CommentHandlers);
340180abc3dSDimitry Andric }
341180abc3dSDimitry Andric 
342ee791ddeSRoman Divacky Preprocessor::macro_iterator
macro_end(bool IncludeExternalMacros) const343ee791ddeSRoman Divacky Preprocessor::macro_end(bool IncludeExternalMacros) const {
344ee791ddeSRoman Divacky   if (IncludeExternalMacros && ExternalSource &&
345ee791ddeSRoman Divacky       !ReadMacrosFromExternalSource) {
346ee791ddeSRoman Divacky     ReadMacrosFromExternalSource = true;
347ee791ddeSRoman Divacky     ExternalSource->ReadDefinedMacros();
348ee791ddeSRoman Divacky   }
349ee791ddeSRoman Divacky 
3505e20cdd8SDimitry Andric   return CurSubmoduleState->Macros.end();
351ee791ddeSRoman Divacky }
352ee791ddeSRoman Divacky 
35348675466SDimitry Andric /// Compares macro tokens with a specified token value sequence.
MacroDefinitionEquals(const MacroInfo * MI,ArrayRef<TokenValue> Tokens)35413cc256eSDimitry Andric static bool MacroDefinitionEquals(const MacroInfo *MI,
355809500fcSDimitry Andric                                   ArrayRef<TokenValue> Tokens) {
35613cc256eSDimitry Andric   return Tokens.size() == MI->getNumTokens() &&
35713cc256eSDimitry Andric       std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
35813cc256eSDimitry Andric }
35913cc256eSDimitry Andric 
getLastMacroWithSpelling(SourceLocation Loc,ArrayRef<TokenValue> Tokens) const36013cc256eSDimitry Andric StringRef Preprocessor::getLastMacroWithSpelling(
36113cc256eSDimitry Andric                                     SourceLocation Loc,
36213cc256eSDimitry Andric                                     ArrayRef<TokenValue> Tokens) const {
36313cc256eSDimitry Andric   SourceLocation BestLocation;
36413cc256eSDimitry Andric   StringRef BestSpelling;
36513cc256eSDimitry Andric   for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
36613cc256eSDimitry Andric        I != E; ++I) {
367809500fcSDimitry Andric     const MacroDirective::DefInfo
3685e20cdd8SDimitry Andric       Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
3695e20cdd8SDimitry Andric     if (!Def || !Def.getMacroInfo())
3705e20cdd8SDimitry Andric       continue;
3715e20cdd8SDimitry Andric     if (!Def.getMacroInfo()->isObjectLike())
37213cc256eSDimitry Andric       continue;
373809500fcSDimitry Andric     if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
37413cc256eSDimitry Andric       continue;
375809500fcSDimitry Andric     SourceLocation Location = Def.getLocation();
37613cc256eSDimitry Andric     // Choose the macro defined latest.
37713cc256eSDimitry Andric     if (BestLocation.isInvalid() ||
37813cc256eSDimitry Andric         (Location.isValid() &&
37913cc256eSDimitry Andric          SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
38013cc256eSDimitry Andric       BestLocation = Location;
38113cc256eSDimitry Andric       BestSpelling = I->first->getName();
38213cc256eSDimitry Andric     }
38313cc256eSDimitry Andric   }
38413cc256eSDimitry Andric   return BestSpelling;
38513cc256eSDimitry Andric }
38613cc256eSDimitry Andric 
recomputeCurLexerKind()387dbe13110SDimitry Andric void Preprocessor::recomputeCurLexerKind() {
388dbe13110SDimitry Andric   if (CurLexer)
389b1c73532SDimitry Andric     CurLexerCallback = CurLexer->isDependencyDirectivesLexer()
390145449b1SDimitry Andric                            ? CLK_DependencyDirectivesLexer
391145449b1SDimitry Andric                            : CLK_Lexer;
392dbe13110SDimitry Andric   else if (CurTokenLexer)
393b1c73532SDimitry Andric     CurLexerCallback = CLK_TokenLexer;
394dbe13110SDimitry Andric   else
395b1c73532SDimitry Andric     CurLexerCallback = CLK_CachingLexer;
396dbe13110SDimitry Andric }
397dbe13110SDimitry Andric 
SetCodeCompletionPoint(FileEntryRef File,unsigned CompleteLine,unsigned CompleteColumn)398b1c73532SDimitry Andric bool Preprocessor::SetCodeCompletionPoint(FileEntryRef File,
39936981b17SDimitry Andric                                           unsigned CompleteLine,
40036981b17SDimitry Andric                                           unsigned CompleteColumn) {
40136981b17SDimitry Andric   assert(CompleteLine && CompleteColumn && "Starts from 1:1");
40236981b17SDimitry Andric   assert(!CodeCompletionFile && "Already set");
40336981b17SDimitry Andric 
40434d02d0bSRoman Divacky   // Load the actual file's contents.
405e3b55780SDimitry Andric   std::optional<llvm::MemoryBufferRef> Buffer =
406b60736ecSDimitry Andric       SourceMgr.getMemoryBufferForFileOrNone(File);
407b60736ecSDimitry Andric   if (!Buffer)
40834d02d0bSRoman Divacky     return true;
40934d02d0bSRoman Divacky 
41034d02d0bSRoman Divacky   // Find the byte position of the truncation point.
41134d02d0bSRoman Divacky   const char *Position = Buffer->getBufferStart();
41236981b17SDimitry Andric   for (unsigned Line = 1; Line < CompleteLine; ++Line) {
41334d02d0bSRoman Divacky     for (; *Position; ++Position) {
41434d02d0bSRoman Divacky       if (*Position != '\r' && *Position != '\n')
41534d02d0bSRoman Divacky         continue;
41634d02d0bSRoman Divacky 
41734d02d0bSRoman Divacky       // Eat \r\n or \n\r as a single line.
41834d02d0bSRoman Divacky       if ((Position[1] == '\r' || Position[1] == '\n') &&
41934d02d0bSRoman Divacky           Position[0] != Position[1])
42034d02d0bSRoman Divacky         ++Position;
42134d02d0bSRoman Divacky       ++Position;
42234d02d0bSRoman Divacky       break;
42334d02d0bSRoman Divacky     }
42434d02d0bSRoman Divacky   }
42534d02d0bSRoman Divacky 
42636981b17SDimitry Andric   Position += CompleteColumn - 1;
42734d02d0bSRoman Divacky 
42806d4ba38SDimitry Andric   // If pointing inside the preamble, adjust the position at the beginning of
42906d4ba38SDimitry Andric   // the file after the preamble.
43006d4ba38SDimitry Andric   if (SkipMainFilePreamble.first &&
43106d4ba38SDimitry Andric       SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
43206d4ba38SDimitry Andric     if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
43306d4ba38SDimitry Andric       Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
43406d4ba38SDimitry Andric   }
43506d4ba38SDimitry Andric 
43606d4ba38SDimitry Andric   if (Position > Buffer->getBufferEnd())
43706d4ba38SDimitry Andric     Position = Buffer->getBufferEnd();
43806d4ba38SDimitry Andric 
43936981b17SDimitry Andric   CodeCompletionFile = File;
44036981b17SDimitry Andric   CodeCompletionOffset = Position - Buffer->getBufferStart();
44136981b17SDimitry Andric 
4426252156dSDimitry Andric   auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
4436252156dSDimitry Andric       Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
4446252156dSDimitry Andric   char *NewBuf = NewBuffer->getBufferStart();
44536981b17SDimitry Andric   char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
44636981b17SDimitry Andric   *NewPos = '\0';
44736981b17SDimitry Andric   std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
44806d4ba38SDimitry Andric   SourceMgr.overrideFileContents(File, std::move(NewBuffer));
44934d02d0bSRoman Divacky 
45034d02d0bSRoman Divacky   return false;
45134d02d0bSRoman Divacky }
45234d02d0bSRoman Divacky 
CodeCompleteIncludedFile(llvm::StringRef Dir,bool IsAngled)453676fbe81SDimitry Andric void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
454676fbe81SDimitry Andric                                             bool IsAngled) {
455344a3780SDimitry Andric   setCodeCompletionReached();
456676fbe81SDimitry Andric   if (CodeComplete)
457676fbe81SDimitry Andric     CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
458676fbe81SDimitry Andric }
459676fbe81SDimitry Andric 
CodeCompleteNaturalLanguage()4603d1dcd9bSDimitry Andric void Preprocessor::CodeCompleteNaturalLanguage() {
461344a3780SDimitry Andric   setCodeCompletionReached();
4623d1dcd9bSDimitry Andric   if (CodeComplete)
4633d1dcd9bSDimitry Andric     CodeComplete->CodeCompleteNaturalLanguage();
4643d1dcd9bSDimitry Andric }
4653d1dcd9bSDimitry Andric 
46679ade4e0SRoman Divacky /// getSpelling - This method is used to get the spelling of a token into a
46779ade4e0SRoman Divacky /// SmallVector. Note that the returned StringRef may not point to the
46879ade4e0SRoman Divacky /// supplied buffer if a copy can be avoided.
getSpelling(const Token & Tok,SmallVectorImpl<char> & Buffer,bool * Invalid) const46936981b17SDimitry Andric StringRef Preprocessor::getSpelling(const Token &Tok,
47036981b17SDimitry Andric                                           SmallVectorImpl<char> &Buffer,
4714a37f65fSRoman Divacky                                           bool *Invalid) const {
472bca07a45SDimitry Andric   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
473809500fcSDimitry Andric   if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
47479ade4e0SRoman Divacky     // Try the fast path.
47579ade4e0SRoman Divacky     if (const IdentifierInfo *II = Tok.getIdentifierInfo())
47679ade4e0SRoman Divacky       return II->getName();
477bca07a45SDimitry Andric   }
47879ade4e0SRoman Divacky 
47979ade4e0SRoman Divacky   // Resize the buffer if we need to copy into it.
48079ade4e0SRoman Divacky   if (Tok.needsCleaning())
48179ade4e0SRoman Divacky     Buffer.resize(Tok.getLength());
48279ade4e0SRoman Divacky 
48379ade4e0SRoman Divacky   const char *Ptr = Buffer.data();
4844a37f65fSRoman Divacky   unsigned Len = getSpelling(Tok, Ptr, Invalid);
48536981b17SDimitry Andric   return StringRef(Ptr, Len);
48679ade4e0SRoman Divacky }
48779ade4e0SRoman Divacky 
488ec2b103cSEd Schouten /// CreateString - Plop the specified string into a scratch buffer and return a
489ec2b103cSEd Schouten /// location for it.  If specified, the source location provides a source
490ec2b103cSEd Schouten /// location for the token.
CreateString(StringRef Str,Token & Tok,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd)49113cc256eSDimitry Andric void Preprocessor::CreateString(StringRef Str, Token &Tok,
49236981b17SDimitry Andric                                 SourceLocation ExpansionLocStart,
49336981b17SDimitry Andric                                 SourceLocation ExpansionLocEnd) {
49413cc256eSDimitry Andric   Tok.setLength(Str.size());
495ec2b103cSEd Schouten 
496ec2b103cSEd Schouten   const char *DestPtr;
49713cc256eSDimitry Andric   SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
498ec2b103cSEd Schouten 
49936981b17SDimitry Andric   if (ExpansionLocStart.isValid())
50036981b17SDimitry Andric     Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
50113cc256eSDimitry Andric                                        ExpansionLocEnd, Str.size());
502ec2b103cSEd Schouten   Tok.setLocation(Loc);
503ec2b103cSEd Schouten 
504bca07a45SDimitry Andric   // If this is a raw identifier or a literal token, set the pointer data.
505bca07a45SDimitry Andric   if (Tok.is(tok::raw_identifier))
506bca07a45SDimitry Andric     Tok.setRawIdentifierData(DestPtr);
507bca07a45SDimitry Andric   else if (Tok.isLiteral())
508ec2b103cSEd Schouten     Tok.setLiteralData(DestPtr);
509ec2b103cSEd Schouten }
510ec2b103cSEd Schouten 
SplitToken(SourceLocation Loc,unsigned Length)51148675466SDimitry Andric SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
51248675466SDimitry Andric   auto &SM = getSourceManager();
51348675466SDimitry Andric   SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
51448675466SDimitry Andric   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
51548675466SDimitry Andric   bool Invalid = false;
51648675466SDimitry Andric   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
51748675466SDimitry Andric   if (Invalid)
51848675466SDimitry Andric     return SourceLocation();
51948675466SDimitry Andric 
52048675466SDimitry Andric   // FIXME: We could consider re-using spelling for tokens we see repeatedly.
52148675466SDimitry Andric   const char *DestPtr;
52248675466SDimitry Andric   SourceLocation Spelling =
52348675466SDimitry Andric       ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
52448675466SDimitry Andric   return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
52548675466SDimitry Andric }
52648675466SDimitry Andric 
getCurrentModule()527dbe13110SDimitry Andric Module *Preprocessor::getCurrentModule() {
528bab175ecSDimitry Andric   if (!getLangOpts().isCompilingModule())
5299f4dbff6SDimitry Andric     return nullptr;
530ec2b103cSEd Schouten 
531dbe13110SDimitry Andric   return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
532dbe13110SDimitry Andric }
533ec2b103cSEd Schouten 
getCurrentModuleImplementation()534e3b55780SDimitry Andric Module *Preprocessor::getCurrentModuleImplementation() {
535e3b55780SDimitry Andric   if (!getLangOpts().isCompilingModuleImplementation())
536e3b55780SDimitry Andric     return nullptr;
537e3b55780SDimitry Andric 
538e3b55780SDimitry Andric   return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);
539e3b55780SDimitry Andric }
540e3b55780SDimitry Andric 
541ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
542ec2b103cSEd Schouten // Preprocessor Initialization Methods
543ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
544ec2b103cSEd Schouten 
545ec2b103cSEd Schouten /// EnterMainSourceFile - Enter the specified FileID as the main source file,
546ec2b103cSEd Schouten /// which implicitly adds the builtin defines etc.
EnterMainSourceFile()5470883ccd9SRoman Divacky void Preprocessor::EnterMainSourceFile() {
548ec2b103cSEd Schouten   // We do not allow the preprocessor to reenter the main file.  Doing so will
549ec2b103cSEd Schouten   // cause FileID's to accumulate information from both runs (e.g. #line
550ec2b103cSEd Schouten   // information) and predefined macros aren't guaranteed to be set properly.
551ec2b103cSEd Schouten   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
552ec2b103cSEd Schouten   FileID MainFileID = SourceMgr.getMainFileID();
553ec2b103cSEd Schouten 
554dbe13110SDimitry Andric   // If MainFileID is loaded it means we loaded an AST file, no need to enter
555dbe13110SDimitry Andric   // a main file.
556dbe13110SDimitry Andric   if (!SourceMgr.isLoadedFileID(MainFileID)) {
557ec2b103cSEd Schouten     // Enter the main file source buffer.
5589f4dbff6SDimitry Andric     EnterSourceFile(MainFileID, nullptr, SourceLocation());
559ec2b103cSEd Schouten 
5603d1dcd9bSDimitry Andric     // If we've been asked to skip bytes in the main file (e.g., as part of a
5613d1dcd9bSDimitry Andric     // precompiled preamble), do so now.
5623d1dcd9bSDimitry Andric     if (SkipMainFilePreamble.first > 0)
563461a67faSDimitry Andric       CurLexer->SetByteOffset(SkipMainFilePreamble.first,
5643d1dcd9bSDimitry Andric                               SkipMainFilePreamble.second);
5653d1dcd9bSDimitry Andric 
566ec2b103cSEd Schouten     // Tell the header info that the main file was entered.  If the file is later
567ec2b103cSEd Schouten     // #imported, it won't be re-entered.
568b1c73532SDimitry Andric     if (OptionalFileEntryRef FE = SourceMgr.getFileEntryRefForID(MainFileID))
569b1c73532SDimitry Andric       markIncluded(*FE);
570dbe13110SDimitry Andric   }
571ec2b103cSEd Schouten 
572abe15e55SRoman Divacky   // Preprocess Predefines to populate the initial preprocessor state.
57306d4ba38SDimitry Andric   std::unique_ptr<llvm::MemoryBuffer> SB =
57460bfabcdSRoman Divacky     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
5753d1dcd9bSDimitry Andric   assert(SB && "Cannot create predefined source buffer");
57606d4ba38SDimitry Andric   FileID FID = SourceMgr.createFileID(std::move(SB));
57745b53394SDimitry Andric   assert(FID.isValid() && "Could not create FileID for predefines?");
578809500fcSDimitry Andric   setPredefinesFileID(FID);
579ec2b103cSEd Schouten 
580ec2b103cSEd Schouten   // Start parsing the predefines.
5819f4dbff6SDimitry Andric   EnterSourceFile(FID, nullptr, SourceLocation());
58248675466SDimitry Andric 
58348675466SDimitry Andric   if (!PPOpts->PCHThroughHeader.empty()) {
58448675466SDimitry Andric     // Lookup and save the FileID for the through header. If it isn't found
58548675466SDimitry Andric     // in the search path, it's a fatal error.
586e3b55780SDimitry Andric     OptionalFileEntryRef File = LookupFile(
58748675466SDimitry Andric         SourceLocation(), PPOpts->PCHThroughHeader,
5886f8fc217SDimitry Andric         /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
5896f8fc217SDimitry Andric         /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
59022989816SDimitry Andric         /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
59122989816SDimitry Andric         /*IsFrameworkFound=*/nullptr);
59248675466SDimitry Andric     if (!File) {
59348675466SDimitry Andric       Diag(SourceLocation(), diag::err_pp_through_header_not_found)
59448675466SDimitry Andric           << PPOpts->PCHThroughHeader;
59548675466SDimitry Andric       return;
59648675466SDimitry Andric     }
59748675466SDimitry Andric     setPCHThroughHeaderFileID(
598519fc96cSDimitry Andric         SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
59948675466SDimitry Andric   }
60048675466SDimitry Andric 
60148675466SDimitry Andric   // Skip tokens from the Predefines and if needed the main file.
602676fbe81SDimitry Andric   if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
603676fbe81SDimitry Andric       (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
604676fbe81SDimitry Andric     SkipTokensWhileUsingPCH();
60548675466SDimitry Andric }
60648675466SDimitry Andric 
setPCHThroughHeaderFileID(FileID FID)60748675466SDimitry Andric void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
60848675466SDimitry Andric   assert(PCHThroughHeaderFileID.isInvalid() &&
60948675466SDimitry Andric          "PCHThroughHeaderFileID already set!");
61048675466SDimitry Andric   PCHThroughHeaderFileID = FID;
61148675466SDimitry Andric }
61248675466SDimitry Andric 
isPCHThroughHeader(const FileEntry * FE)61348675466SDimitry Andric bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
61448675466SDimitry Andric   assert(PCHThroughHeaderFileID.isValid() &&
61548675466SDimitry Andric          "Invalid PCH through header FileID");
61648675466SDimitry Andric   return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
61748675466SDimitry Andric }
61848675466SDimitry Andric 
creatingPCHWithThroughHeader()61948675466SDimitry Andric bool Preprocessor::creatingPCHWithThroughHeader() {
62048675466SDimitry Andric   return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
62148675466SDimitry Andric          PCHThroughHeaderFileID.isValid();
62248675466SDimitry Andric }
62348675466SDimitry Andric 
usingPCHWithThroughHeader()62448675466SDimitry Andric bool Preprocessor::usingPCHWithThroughHeader() {
62548675466SDimitry Andric   return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
62648675466SDimitry Andric          PCHThroughHeaderFileID.isValid();
62748675466SDimitry Andric }
62848675466SDimitry Andric 
creatingPCHWithPragmaHdrStop()629676fbe81SDimitry Andric bool Preprocessor::creatingPCHWithPragmaHdrStop() {
630676fbe81SDimitry Andric   return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
631676fbe81SDimitry Andric }
632676fbe81SDimitry Andric 
usingPCHWithPragmaHdrStop()633676fbe81SDimitry Andric bool Preprocessor::usingPCHWithPragmaHdrStop() {
634676fbe81SDimitry Andric   return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
635676fbe81SDimitry Andric }
636676fbe81SDimitry Andric 
637676fbe81SDimitry Andric /// Skip tokens until after the #include of the through header or
638676fbe81SDimitry Andric /// until after a #pragma hdrstop is seen. Tokens in the predefines file
639676fbe81SDimitry Andric /// and the main file may be skipped. If the end of the predefines file
640676fbe81SDimitry Andric /// is reached, skipping continues into the main file. If the end of the
641676fbe81SDimitry Andric /// main file is reached, it's a fatal error.
SkipTokensWhileUsingPCH()642676fbe81SDimitry Andric void Preprocessor::SkipTokensWhileUsingPCH() {
64348675466SDimitry Andric   bool ReachedMainFileEOF = false;
644676fbe81SDimitry Andric   bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
645676fbe81SDimitry Andric   bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
64648675466SDimitry Andric   Token Tok;
64748675466SDimitry Andric   while (true) {
64822989816SDimitry Andric     bool InPredefines =
64922989816SDimitry Andric         (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
650b1c73532SDimitry Andric     CurLexerCallback(*this, Tok);
65148675466SDimitry Andric     if (Tok.is(tok::eof) && !InPredefines) {
65248675466SDimitry Andric       ReachedMainFileEOF = true;
65348675466SDimitry Andric       break;
65448675466SDimitry Andric     }
655676fbe81SDimitry Andric     if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
656676fbe81SDimitry Andric       break;
657676fbe81SDimitry Andric     if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
65848675466SDimitry Andric       break;
65948675466SDimitry Andric   }
660676fbe81SDimitry Andric   if (ReachedMainFileEOF) {
661676fbe81SDimitry Andric     if (UsingPCHThroughHeader)
66248675466SDimitry Andric       Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
66348675466SDimitry Andric           << PPOpts->PCHThroughHeader << 1;
664676fbe81SDimitry Andric     else if (!PPOpts->PCHWithHdrStopCreate)
665676fbe81SDimitry Andric       Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
666676fbe81SDimitry Andric   }
6678746d127SDimitry Andric }
668550ae89aSDimitry Andric 
replayPreambleConditionalStack()6698746d127SDimitry Andric void Preprocessor::replayPreambleConditionalStack() {
670550ae89aSDimitry Andric   // Restore the conditional stack from the preamble, if there is one.
671550ae89aSDimitry Andric   if (PreambleConditionalStack.isReplaying()) {
672a75fa8aaSDimitry Andric     assert(CurPPLexer &&
673a75fa8aaSDimitry Andric            "CurPPLexer is null when calling replayPreambleConditionalStack.");
674550ae89aSDimitry Andric     CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
675550ae89aSDimitry Andric     PreambleConditionalStack.doneReplaying();
676461a67faSDimitry Andric     if (PreambleConditionalStack.reachedEOFWhileSkipping())
677461a67faSDimitry Andric       SkipExcludedConditionalBlock(
678461a67faSDimitry Andric           PreambleConditionalStack.SkipInfo->HashTokenLoc,
679461a67faSDimitry Andric           PreambleConditionalStack.SkipInfo->IfTokenLoc,
680461a67faSDimitry Andric           PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
681461a67faSDimitry Andric           PreambleConditionalStack.SkipInfo->FoundElse,
682461a67faSDimitry Andric           PreambleConditionalStack.SkipInfo->ElseLoc);
683550ae89aSDimitry Andric   }
684ec2b103cSEd Schouten }
685ec2b103cSEd Schouten 
EndSourceFile()68611d2b2d2SRoman Divacky void Preprocessor::EndSourceFile() {
68711d2b2d2SRoman Divacky   // Notify the client that we reached the end of the source file.
68811d2b2d2SRoman Divacky   if (Callbacks)
68911d2b2d2SRoman Divacky     Callbacks->EndOfMainFile();
69011d2b2d2SRoman Divacky }
691ec2b103cSEd Schouten 
692ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
693ec2b103cSEd Schouten // Lexer Event Handling.
694ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
695ec2b103cSEd Schouten 
696bca07a45SDimitry Andric /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
697bca07a45SDimitry Andric /// identifier information for the token and install it into the token,
698bca07a45SDimitry Andric /// updating the token kind accordingly.
LookUpIdentifierInfo(Token & Identifier) const699bca07a45SDimitry Andric IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
7009f4dbff6SDimitry Andric   assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
701ec2b103cSEd Schouten 
702ec2b103cSEd Schouten   // Look up this token, see if it is a macro, or if it is a language keyword.
703ec2b103cSEd Schouten   IdentifierInfo *II;
704809500fcSDimitry Andric   if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
705ec2b103cSEd Schouten     // No cleaning needed, just use the characters from the lexed buffer.
7069f4dbff6SDimitry Andric     II = getIdentifierInfo(Identifier.getRawIdentifier());
707ec2b103cSEd Schouten   } else {
708ec2b103cSEd Schouten     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
709dbe13110SDimitry Andric     SmallString<64> IdentifierBuffer;
71036981b17SDimitry Andric     StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
711809500fcSDimitry Andric 
712809500fcSDimitry Andric     if (Identifier.hasUCN()) {
713809500fcSDimitry Andric       SmallString<64> UCNIdentifierBuffer;
714809500fcSDimitry Andric       expandUCNs(UCNIdentifierBuffer, CleanedStr);
715809500fcSDimitry Andric       II = getIdentifierInfo(UCNIdentifierBuffer);
716809500fcSDimitry Andric     } else {
71779ade4e0SRoman Divacky       II = getIdentifierInfo(CleanedStr);
718ec2b103cSEd Schouten     }
719809500fcSDimitry Andric   }
720bca07a45SDimitry Andric 
721bca07a45SDimitry Andric   // Update the token info (identifier info and appropriate token kind).
722344a3780SDimitry Andric   // FIXME: the raw_identifier may contain leading whitespace which is removed
723344a3780SDimitry Andric   // from the cleaned identifier token. The SourceLocation should be updated to
724344a3780SDimitry Andric   // refer to the non-whitespace character. For instance, the text "\\\nB" (a
725344a3780SDimitry Andric   // line continuation before 'B') is parsed as a single tok::raw_identifier and
726344a3780SDimitry Andric   // is cleaned to tok::identifier "B". After cleaning the token's length is
727344a3780SDimitry Andric   // still 3 and the SourceLocation refers to the location of the backslash.
728ec2b103cSEd Schouten   Identifier.setIdentifierInfo(II);
729bca07a45SDimitry Andric   Identifier.setKind(II->getTokenID());
730bca07a45SDimitry Andric 
731ec2b103cSEd Schouten   return II;
732ec2b103cSEd Schouten }
733ec2b103cSEd Schouten 
SetPoisonReason(IdentifierInfo * II,unsigned DiagID)73401af97d3SDimitry Andric void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
73501af97d3SDimitry Andric   PoisonReasons[II] = DiagID;
73601af97d3SDimitry Andric }
73701af97d3SDimitry Andric 
PoisonSEHIdentifiers(bool Poison)73801af97d3SDimitry Andric void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
73901af97d3SDimitry Andric   assert(Ident__exception_code && Ident__exception_info);
74001af97d3SDimitry Andric   assert(Ident___exception_code && Ident___exception_info);
74101af97d3SDimitry Andric   Ident__exception_code->setIsPoisoned(Poison);
74201af97d3SDimitry Andric   Ident___exception_code->setIsPoisoned(Poison);
74301af97d3SDimitry Andric   Ident_GetExceptionCode->setIsPoisoned(Poison);
74401af97d3SDimitry Andric   Ident__exception_info->setIsPoisoned(Poison);
74501af97d3SDimitry Andric   Ident___exception_info->setIsPoisoned(Poison);
74601af97d3SDimitry Andric   Ident_GetExceptionInfo->setIsPoisoned(Poison);
74701af97d3SDimitry Andric   Ident__abnormal_termination->setIsPoisoned(Poison);
74801af97d3SDimitry Andric   Ident___abnormal_termination->setIsPoisoned(Poison);
74901af97d3SDimitry Andric   Ident_AbnormalTermination->setIsPoisoned(Poison);
75001af97d3SDimitry Andric }
75101af97d3SDimitry Andric 
HandlePoisonedIdentifier(Token & Identifier)75201af97d3SDimitry Andric void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
75301af97d3SDimitry Andric   assert(Identifier.getIdentifierInfo() &&
75401af97d3SDimitry Andric          "Can't handle identifiers without identifier info!");
75501af97d3SDimitry Andric   llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
75601af97d3SDimitry Andric     PoisonReasons.find(Identifier.getIdentifierInfo());
75701af97d3SDimitry Andric   if(it == PoisonReasons.end())
75801af97d3SDimitry Andric     Diag(Identifier, diag::err_pp_used_poisoned_id);
75901af97d3SDimitry Andric   else
76001af97d3SDimitry Andric     Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
76101af97d3SDimitry Andric }
762ec2b103cSEd Schouten 
updateOutOfDateIdentifier(const IdentifierInfo & II) const763ac9a064cSDimitry Andric void Preprocessor::updateOutOfDateIdentifier(const IdentifierInfo &II) const {
764bab175ecSDimitry Andric   assert(II.isOutOfDate() && "not out of date");
765bab175ecSDimitry Andric   getExternalSource()->updateOutOfDateIdentifier(II);
766bab175ecSDimitry Andric }
767bab175ecSDimitry Andric 
768ec2b103cSEd Schouten /// HandleIdentifier - This callback is invoked when the lexer reads an
769ec2b103cSEd Schouten /// identifier.  This callback looks up the identifier in the map and/or
770ec2b103cSEd Schouten /// potentially macro expands it or turns it into a named token (like 'for').
771ec2b103cSEd Schouten ///
772ec2b103cSEd Schouten /// Note that callers of this method are guarded by checking the
773ec2b103cSEd Schouten /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
774ec2b103cSEd Schouten /// IdentifierInfo methods that compute these properties will need to change to
775ec2b103cSEd Schouten /// match.
HandleIdentifier(Token & Identifier)776bfef3995SDimitry Andric bool Preprocessor::HandleIdentifier(Token &Identifier) {
777ec2b103cSEd Schouten   assert(Identifier.getIdentifierInfo() &&
778ec2b103cSEd Schouten          "Can't handle identifiers without identifier info!");
779ec2b103cSEd Schouten 
780ec2b103cSEd Schouten   IdentifierInfo &II = *Identifier.getIdentifierInfo();
781ec2b103cSEd Schouten 
782dbe13110SDimitry Andric   // If the information about this identifier is out of date, update it from
783dbe13110SDimitry Andric   // the external source.
78456d91b49SDimitry Andric   // We have to treat __VA_ARGS__ in a special way, since it gets
78556d91b49SDimitry Andric   // serialized with isPoisoned = true, but our preprocessor may have
78656d91b49SDimitry Andric   // unpoisoned it if we're defining a C99 macro.
787dbe13110SDimitry Andric   if (II.isOutOfDate()) {
78856d91b49SDimitry Andric     bool CurrentIsPoisoned = false;
789461a67faSDimitry Andric     const bool IsSpecialVariadicMacro =
790461a67faSDimitry Andric         &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
791461a67faSDimitry Andric     if (IsSpecialVariadicMacro)
792461a67faSDimitry Andric       CurrentIsPoisoned = II.isPoisoned();
79356d91b49SDimitry Andric 
794bab175ecSDimitry Andric     updateOutOfDateIdentifier(II);
795dbe13110SDimitry Andric     Identifier.setKind(II.getTokenID());
79656d91b49SDimitry Andric 
797461a67faSDimitry Andric     if (IsSpecialVariadicMacro)
79856d91b49SDimitry Andric       II.setIsPoisoned(CurrentIsPoisoned);
799dbe13110SDimitry Andric   }
800dbe13110SDimitry Andric 
801ec2b103cSEd Schouten   // If this identifier was poisoned, and if it was not produced from a macro
802ec2b103cSEd Schouten   // expansion, emit an error.
803ec2b103cSEd Schouten   if (II.isPoisoned() && CurPPLexer) {
80401af97d3SDimitry Andric     HandlePoisonedIdentifier(Identifier);
805ec2b103cSEd Schouten   }
806ec2b103cSEd Schouten 
807ec2b103cSEd Schouten   // If this is a macro to be expanded, do it.
808b1c73532SDimitry Andric   if (const MacroDefinition MD = getMacroDefinition(&II)) {
809b1c73532SDimitry Andric     const auto *MI = MD.getMacroInfo();
8105e20cdd8SDimitry Andric     assert(MI && "macro definition with no macro info?");
811dbe13110SDimitry Andric     if (!DisableMacroExpansion) {
812809500fcSDimitry Andric       if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
813bfef3995SDimitry Andric         // C99 6.10.3p10: If the preprocessing token immediately after the
814bfef3995SDimitry Andric         // macro name isn't a '(', this macro should not be expanded.
815bfef3995SDimitry Andric         if (!MI->isFunctionLike() || isNextPPTokenLParen())
816bfef3995SDimitry Andric           return HandleMacroExpandedIdentifier(Identifier, MD);
817ec2b103cSEd Schouten       } else {
818ec2b103cSEd Schouten         // C99 6.10.3.4p2 says that a disabled macro may never again be
819ec2b103cSEd Schouten         // expanded, even if it's in a context where it could be expanded in the
820ec2b103cSEd Schouten         // future.
821ec2b103cSEd Schouten         Identifier.setFlag(Token::DisableExpand);
822809500fcSDimitry Andric         if (MI->isObjectLike() || isNextPPTokenLParen())
823dbe13110SDimitry Andric           Diag(Identifier, diag::pp_disabled_macro_expansion);
824ec2b103cSEd Schouten       }
825ec2b103cSEd Schouten     }
826ec2b103cSEd Schouten   }
827ec2b103cSEd Schouten 
8285e20cdd8SDimitry Andric   // If this identifier is a keyword in a newer Standard or proposed Standard,
8295e20cdd8SDimitry Andric   // produce a warning. Don't warn if we're not considering macro expansion,
8305e20cdd8SDimitry Andric   // since this identifier might be the name of a macro.
83136981b17SDimitry Andric   // FIXME: This warning is disabled in cases where it shouldn't be, like
83236981b17SDimitry Andric   //   "#define constexpr constexpr", "int constexpr;"
8335e20cdd8SDimitry Andric   if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
834e3b55780SDimitry Andric     Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))
8355e20cdd8SDimitry Andric         << II.getName();
83636981b17SDimitry Andric     // Don't diagnose this keyword again in this translation unit.
8375e20cdd8SDimitry Andric     II.setIsFutureCompatKeyword(false);
83836981b17SDimitry Andric   }
83936981b17SDimitry Andric 
840ec2b103cSEd Schouten   // If this is an extension token, diagnose its use.
841ec2b103cSEd Schouten   // We avoid diagnosing tokens that originate from macro definitions.
842ec2b103cSEd Schouten   // FIXME: This warning is disabled in cases where it shouldn't be,
843ec2b103cSEd Schouten   // like "#define TY typeof", "TY(1) x".
844ec2b103cSEd Schouten   if (II.isExtensionToken() && !DisableMacroExpansion)
845ec2b103cSEd Schouten     Diag(Identifier, diag::ext_token_used);
84636981b17SDimitry Andric 
847bfef3995SDimitry Andric   // If this is the 'import' contextual keyword following an '@', note
848dbe13110SDimitry Andric   // that the next token indicates a module name.
849dbe13110SDimitry Andric   //
850809500fcSDimitry Andric   // Note that we do not treat 'import' as a contextual
851dbe13110SDimitry Andric   // keyword when we're in a caching lexer, because caching lexers only get
852dbe13110SDimitry Andric   // used in contexts where import declarations are disallowed.
853bab175ecSDimitry Andric   //
8547fa27ce4SDimitry Andric   // Likewise if this is the standard C++ import keyword.
855bab175ecSDimitry Andric   if (((LastTokenWasAt && II.isModulesImport()) ||
856bab175ecSDimitry Andric        Identifier.is(tok::kw_import)) &&
857bab175ecSDimitry Andric       !InMacroArgs && !DisableMacroExpansion &&
85806d4ba38SDimitry Andric       (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
859b1c73532SDimitry Andric       CurLexerCallback != CLK_CachingLexer) {
86036981b17SDimitry Andric     ModuleImportLoc = Identifier.getLocation();
861e3b55780SDimitry Andric     NamedModuleImportPath.clear();
8627fa27ce4SDimitry Andric     IsAtImport = true;
863dbe13110SDimitry Andric     ModuleImportExpectsIdentifier = true;
864b1c73532SDimitry Andric     CurLexerCallback = CLK_LexAfterModuleImport;
86536981b17SDimitry Andric   }
866bfef3995SDimitry Andric   return true;
86736981b17SDimitry Andric }
86836981b17SDimitry Andric 
Lex(Token & Result)869bfef3995SDimitry Andric void Preprocessor::Lex(Token &Result) {
87022989816SDimitry Andric   ++LexLevel;
87122989816SDimitry Andric 
87245b53394SDimitry Andric   // We loop here until a lex function returns a token; this avoids recursion.
873b1c73532SDimitry Andric   while (!CurLexerCallback(*this, Result))
874b1c73532SDimitry Andric     ;
875bfef3995SDimitry Andric 
876cfca06d7SDimitry Andric   if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
877cfca06d7SDimitry Andric     return;
878cfca06d7SDimitry Andric 
87948675466SDimitry Andric   if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
88048675466SDimitry Andric     // Remember the identifier before code completion token.
881bab175ecSDimitry Andric     setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
882676fbe81SDimitry Andric     setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
88348675466SDimitry Andric     // Set IdenfitierInfo to null to avoid confusing code that handles both
88448675466SDimitry Andric     // identifiers and completion tokens.
88548675466SDimitry Andric     Result.setIdentifierInfo(nullptr);
88648675466SDimitry Andric   }
887bab175ecSDimitry Andric 
888e3b55780SDimitry Andric   // Update StdCXXImportSeqState to track our position within a C++20 import-seq
88922989816SDimitry Andric   // if this token is being produced as a result of phase 4 of translation.
8901f917f69SDimitry Andric   // Update TrackGMFState to decide if we are currently in a Global Module
891e3b55780SDimitry Andric   // Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state
892e3b55780SDimitry Andric   // depends on the prevailing StdCXXImportSeq state in two cases.
89322989816SDimitry Andric   if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
89422989816SDimitry Andric       !Result.getFlag(Token::IsReinjected)) {
89522989816SDimitry Andric     switch (Result.getKind()) {
89622989816SDimitry Andric     case tok::l_paren: case tok::l_square: case tok::l_brace:
897e3b55780SDimitry Andric       StdCXXImportSeqState.handleOpenBracket();
89822989816SDimitry Andric       break;
89922989816SDimitry Andric     case tok::r_paren: case tok::r_square:
900e3b55780SDimitry Andric       StdCXXImportSeqState.handleCloseBracket();
90122989816SDimitry Andric       break;
90222989816SDimitry Andric     case tok::r_brace:
903e3b55780SDimitry Andric       StdCXXImportSeqState.handleCloseBrace();
90422989816SDimitry Andric       break;
9051f917f69SDimitry Andric     // This token is injected to represent the translation of '#include "a.h"'
9061f917f69SDimitry Andric     // into "import a.h;". Mimic the notional ';'.
9071f917f69SDimitry Andric     case tok::annot_module_include:
90822989816SDimitry Andric     case tok::semi:
9091f917f69SDimitry Andric       TrackGMFState.handleSemi();
910e3b55780SDimitry Andric       StdCXXImportSeqState.handleSemi();
9117fa27ce4SDimitry Andric       ModuleDeclState.handleSemi();
91222989816SDimitry Andric       break;
91322989816SDimitry Andric     case tok::header_name:
91422989816SDimitry Andric     case tok::annot_header_unit:
915e3b55780SDimitry Andric       StdCXXImportSeqState.handleHeaderName();
91622989816SDimitry Andric       break;
91722989816SDimitry Andric     case tok::kw_export:
9181f917f69SDimitry Andric       TrackGMFState.handleExport();
919e3b55780SDimitry Andric       StdCXXImportSeqState.handleExport();
9207fa27ce4SDimitry Andric       ModuleDeclState.handleExport();
9217fa27ce4SDimitry Andric       break;
9227fa27ce4SDimitry Andric     case tok::colon:
9237fa27ce4SDimitry Andric       ModuleDeclState.handleColon();
9247fa27ce4SDimitry Andric       break;
9257fa27ce4SDimitry Andric     case tok::period:
9267fa27ce4SDimitry Andric       ModuleDeclState.handlePeriod();
92722989816SDimitry Andric       break;
92822989816SDimitry Andric     case tok::identifier:
929b1c73532SDimitry Andric       // Check "import" and "module" when there is no open bracket. The two
930b1c73532SDimitry Andric       // identifiers are not meaningful with open brackets.
931b1c73532SDimitry Andric       if (StdCXXImportSeqState.atTopLevel()) {
93222989816SDimitry Andric         if (Result.getIdentifierInfo()->isModulesImport()) {
933e3b55780SDimitry Andric           TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());
934e3b55780SDimitry Andric           StdCXXImportSeqState.handleImport();
935e3b55780SDimitry Andric           if (StdCXXImportSeqState.afterImportSeq()) {
93622989816SDimitry Andric             ModuleImportLoc = Result.getLocation();
937e3b55780SDimitry Andric             NamedModuleImportPath.clear();
9387fa27ce4SDimitry Andric             IsAtImport = false;
93922989816SDimitry Andric             ModuleImportExpectsIdentifier = true;
940b1c73532SDimitry Andric             CurLexerCallback = CLK_LexAfterModuleImport;
941bfef3995SDimitry Andric           }
94222989816SDimitry Andric           break;
9431f917f69SDimitry Andric         } else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) {
944e3b55780SDimitry Andric           TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());
9457fa27ce4SDimitry Andric           ModuleDeclState.handleModule();
9467fa27ce4SDimitry Andric           break;
947b1c73532SDimitry Andric         }
948b1c73532SDimitry Andric       }
9497fa27ce4SDimitry Andric       ModuleDeclState.handleIdentifier(Result.getIdentifierInfo());
9507fa27ce4SDimitry Andric       if (ModuleDeclState.isModuleCandidate())
9511f917f69SDimitry Andric         break;
952e3b55780SDimitry Andric       [[fallthrough]];
95322989816SDimitry Andric     default:
9541f917f69SDimitry Andric       TrackGMFState.handleMisc();
955e3b55780SDimitry Andric       StdCXXImportSeqState.handleMisc();
9567fa27ce4SDimitry Andric       ModuleDeclState.handleMisc();
95722989816SDimitry Andric       break;
95822989816SDimitry Andric     }
95922989816SDimitry Andric   }
96022989816SDimitry Andric 
961ac9a064cSDimitry Andric   if (CurLexer && ++CheckPointCounter == CheckPointStepSize) {
962ac9a064cSDimitry Andric     CheckPoints[CurLexer->getFileID()].push_back(CurLexer->BufferPtr);
963ac9a064cSDimitry Andric     CheckPointCounter = 0;
964ac9a064cSDimitry Andric   }
965ac9a064cSDimitry Andric 
96622989816SDimitry Andric   LastTokenWasAt = Result.is(tok::at);
96722989816SDimitry Andric   --LexLevel;
968cfca06d7SDimitry Andric 
969b60736ecSDimitry Andric   if ((LexLevel == 0 || PreprocessToken) &&
970b60736ecSDimitry Andric       !Result.getFlag(Token::IsReinjected)) {
971b60736ecSDimitry Andric     if (LexLevel == 0)
972cfca06d7SDimitry Andric       ++TokenCount;
973cfca06d7SDimitry Andric     if (OnToken)
97422989816SDimitry Andric       OnToken(Result);
97522989816SDimitry Andric   }
976cfca06d7SDimitry Andric }
97722989816SDimitry Andric 
LexTokensUntilEOF(std::vector<Token> * Tokens)978b1c73532SDimitry Andric void Preprocessor::LexTokensUntilEOF(std::vector<Token> *Tokens) {
979b1c73532SDimitry Andric   while (1) {
980b1c73532SDimitry Andric     Token Tok;
981b1c73532SDimitry Andric     Lex(Tok);
982b1c73532SDimitry Andric     if (Tok.isOneOf(tok::unknown, tok::eof, tok::eod,
983b1c73532SDimitry Andric                     tok::annot_repl_input_end))
984b1c73532SDimitry Andric       break;
985b1c73532SDimitry Andric     if (Tokens != nullptr)
986b1c73532SDimitry Andric       Tokens->push_back(Tok);
987b1c73532SDimitry Andric   }
988b1c73532SDimitry Andric }
989b1c73532SDimitry Andric 
99022989816SDimitry Andric /// Lex a header-name token (including one formed from header-name-tokens if
991ac9a064cSDimitry Andric /// \p AllowMacroExpansion is \c true).
99222989816SDimitry Andric ///
99322989816SDimitry Andric /// \param FilenameTok Filled in with the next token. On success, this will
99422989816SDimitry Andric ///        be either a header_name token. On failure, it will be whatever other
99522989816SDimitry Andric ///        token was found instead.
99622989816SDimitry Andric /// \param AllowMacroExpansion If \c true, allow the header name to be formed
99722989816SDimitry Andric ///        by macro expansion (concatenating tokens as necessary if the first
99822989816SDimitry Andric ///        token is a '<').
99922989816SDimitry Andric /// \return \c true if we reached EOD or EOF while looking for a > token in
100022989816SDimitry Andric ///         a concatenated header name and diagnosed it. \c false otherwise.
LexHeaderName(Token & FilenameTok,bool AllowMacroExpansion)100122989816SDimitry Andric bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
100222989816SDimitry Andric   // Lex using header-name tokenization rules if tokens are being lexed from
100322989816SDimitry Andric   // a file. Just grab a token normally if we're in a macro expansion.
100422989816SDimitry Andric   if (CurPPLexer)
100522989816SDimitry Andric     CurPPLexer->LexIncludeFilename(FilenameTok);
100622989816SDimitry Andric   else
100722989816SDimitry Andric     Lex(FilenameTok);
100822989816SDimitry Andric 
100922989816SDimitry Andric   // This could be a <foo/bar.h> file coming from a macro expansion.  In this
101022989816SDimitry Andric   // case, glue the tokens together into an angle_string_literal token.
101122989816SDimitry Andric   SmallString<128> FilenameBuffer;
101222989816SDimitry Andric   if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
101322989816SDimitry Andric     bool StartOfLine = FilenameTok.isAtStartOfLine();
101422989816SDimitry Andric     bool LeadingSpace = FilenameTok.hasLeadingSpace();
101522989816SDimitry Andric     bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
101622989816SDimitry Andric 
101722989816SDimitry Andric     SourceLocation Start = FilenameTok.getLocation();
101822989816SDimitry Andric     SourceLocation End;
101922989816SDimitry Andric     FilenameBuffer.push_back('<');
102022989816SDimitry Andric 
102122989816SDimitry Andric     // Consume tokens until we find a '>'.
102222989816SDimitry Andric     // FIXME: A header-name could be formed starting or ending with an
102322989816SDimitry Andric     // alternative token. It's not clear whether that's ill-formed in all
102422989816SDimitry Andric     // cases.
102522989816SDimitry Andric     while (FilenameTok.isNot(tok::greater)) {
102622989816SDimitry Andric       Lex(FilenameTok);
102722989816SDimitry Andric       if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
102822989816SDimitry Andric         Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
102922989816SDimitry Andric         Diag(Start, diag::note_matching) << tok::less;
103022989816SDimitry Andric         return true;
103122989816SDimitry Andric       }
103222989816SDimitry Andric 
103322989816SDimitry Andric       End = FilenameTok.getLocation();
103422989816SDimitry Andric 
103522989816SDimitry Andric       // FIXME: Provide code completion for #includes.
103622989816SDimitry Andric       if (FilenameTok.is(tok::code_completion)) {
103722989816SDimitry Andric         setCodeCompletionReached();
103822989816SDimitry Andric         Lex(FilenameTok);
103922989816SDimitry Andric         continue;
104022989816SDimitry Andric       }
104122989816SDimitry Andric 
104222989816SDimitry Andric       // Append the spelling of this token to the buffer. If there was a space
104322989816SDimitry Andric       // before it, add it now.
104422989816SDimitry Andric       if (FilenameTok.hasLeadingSpace())
104522989816SDimitry Andric         FilenameBuffer.push_back(' ');
104622989816SDimitry Andric 
104722989816SDimitry Andric       // Get the spelling of the token, directly into FilenameBuffer if
104822989816SDimitry Andric       // possible.
104922989816SDimitry Andric       size_t PreAppendSize = FilenameBuffer.size();
105022989816SDimitry Andric       FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
105122989816SDimitry Andric 
105222989816SDimitry Andric       const char *BufPtr = &FilenameBuffer[PreAppendSize];
105322989816SDimitry Andric       unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
105422989816SDimitry Andric 
105522989816SDimitry Andric       // If the token was spelled somewhere else, copy it into FilenameBuffer.
105622989816SDimitry Andric       if (BufPtr != &FilenameBuffer[PreAppendSize])
105722989816SDimitry Andric         memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
105822989816SDimitry Andric 
105922989816SDimitry Andric       // Resize FilenameBuffer to the correct size.
106022989816SDimitry Andric       if (FilenameTok.getLength() != ActualLen)
106122989816SDimitry Andric         FilenameBuffer.resize(PreAppendSize + ActualLen);
106222989816SDimitry Andric     }
106322989816SDimitry Andric 
106422989816SDimitry Andric     FilenameTok.startToken();
106522989816SDimitry Andric     FilenameTok.setKind(tok::header_name);
106622989816SDimitry Andric     FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
106722989816SDimitry Andric     FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
106822989816SDimitry Andric     FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
106922989816SDimitry Andric     CreateString(FilenameBuffer, FilenameTok, Start, End);
107022989816SDimitry Andric   } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
107122989816SDimitry Andric     // Convert a string-literal token of the form " h-char-sequence "
107222989816SDimitry Andric     // (produced by macro expansion) into a header-name token.
107322989816SDimitry Andric     //
107422989816SDimitry Andric     // The rules for header-names don't quite match the rules for
107522989816SDimitry Andric     // string-literals, but all the places where they differ result in
107622989816SDimitry Andric     // undefined behavior, so we can and do treat them the same.
107722989816SDimitry Andric     //
107822989816SDimitry Andric     // A string-literal with a prefix or suffix is not translated into a
107922989816SDimitry Andric     // header-name. This could theoretically be observable via the C++20
108022989816SDimitry Andric     // context-sensitive header-name formation rules.
108122989816SDimitry Andric     StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
108222989816SDimitry Andric     if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
108322989816SDimitry Andric       FilenameTok.setKind(tok::header_name);
108422989816SDimitry Andric   }
108522989816SDimitry Andric 
108622989816SDimitry Andric   return false;
108722989816SDimitry Andric }
108822989816SDimitry Andric 
108922989816SDimitry Andric /// Collect the tokens of a C++20 pp-import-suffix.
CollectPpImportSuffix(SmallVectorImpl<Token> & Toks)109022989816SDimitry Andric void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {
109122989816SDimitry Andric   // FIXME: For error recovery, consider recognizing attribute syntax here
109222989816SDimitry Andric   // and terminating / diagnosing a missing semicolon if we find anything
109322989816SDimitry Andric   // else? (Can we leave that to the parser?)
109422989816SDimitry Andric   unsigned BracketDepth = 0;
109522989816SDimitry Andric   while (true) {
109622989816SDimitry Andric     Toks.emplace_back();
109722989816SDimitry Andric     Lex(Toks.back());
109822989816SDimitry Andric 
109922989816SDimitry Andric     switch (Toks.back().getKind()) {
110022989816SDimitry Andric     case tok::l_paren: case tok::l_square: case tok::l_brace:
110122989816SDimitry Andric       ++BracketDepth;
110222989816SDimitry Andric       break;
110322989816SDimitry Andric 
110422989816SDimitry Andric     case tok::r_paren: case tok::r_square: case tok::r_brace:
110522989816SDimitry Andric       if (BracketDepth == 0)
110622989816SDimitry Andric         return;
110722989816SDimitry Andric       --BracketDepth;
110822989816SDimitry Andric       break;
110922989816SDimitry Andric 
111022989816SDimitry Andric     case tok::semi:
111122989816SDimitry Andric       if (BracketDepth == 0)
111222989816SDimitry Andric         return;
111322989816SDimitry Andric     break;
111422989816SDimitry Andric 
111522989816SDimitry Andric     case tok::eof:
111622989816SDimitry Andric       return;
111722989816SDimitry Andric 
111822989816SDimitry Andric     default:
111922989816SDimitry Andric       break;
112022989816SDimitry Andric     }
112122989816SDimitry Andric   }
112222989816SDimitry Andric }
112322989816SDimitry Andric 
1124bfef3995SDimitry Andric 
112548675466SDimitry Andric /// Lex a token following the 'import' contextual keyword.
1126dbe13110SDimitry Andric ///
112722989816SDimitry Andric ///     pp-import: [C++20]
112822989816SDimitry Andric ///           import header-name pp-import-suffix[opt] ;
112922989816SDimitry Andric ///           import header-name-tokens pp-import-suffix[opt] ;
113022989816SDimitry Andric /// [ObjC]    @ import module-name ;
113122989816SDimitry Andric /// [Clang]   import module-name ;
113222989816SDimitry Andric ///
113322989816SDimitry Andric ///     header-name-tokens:
113422989816SDimitry Andric ///           string-literal
113522989816SDimitry Andric ///           < [any sequence of preprocessing-tokens other than >] >
113622989816SDimitry Andric ///
113722989816SDimitry Andric ///     module-name:
113822989816SDimitry Andric ///           module-name-qualifier[opt] identifier
113922989816SDimitry Andric ///
114022989816SDimitry Andric ///     module-name-qualifier
114122989816SDimitry Andric ///           module-name-qualifier[opt] identifier .
114222989816SDimitry Andric ///
114322989816SDimitry Andric /// We respond to a pp-import by importing macros from the named module.
LexAfterModuleImport(Token & Result)114422989816SDimitry Andric bool Preprocessor::LexAfterModuleImport(Token &Result) {
114536981b17SDimitry Andric   // Figure out what kind of lexer we actually have.
1146dbe13110SDimitry Andric   recomputeCurLexerKind();
114736981b17SDimitry Andric 
114822989816SDimitry Andric   // Lex the next token. The header-name lexing rules are used at the start of
114922989816SDimitry Andric   // a pp-import.
115022989816SDimitry Andric   //
115122989816SDimitry Andric   // For now, we only support header-name imports in C++20 mode.
115222989816SDimitry Andric   // FIXME: Should we allow this in all language modes that support an import
115322989816SDimitry Andric   // declaration as an extension?
1154e3b55780SDimitry Andric   if (NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
115522989816SDimitry Andric     if (LexHeaderName(Result))
115622989816SDimitry Andric       return true;
11577fa27ce4SDimitry Andric 
11587fa27ce4SDimitry Andric     if (Result.is(tok::colon) && ModuleDeclState.isNamedModule()) {
11597fa27ce4SDimitry Andric       std::string Name = ModuleDeclState.getPrimaryName().str();
11607fa27ce4SDimitry Andric       Name += ":";
11617fa27ce4SDimitry Andric       NamedModuleImportPath.push_back(
11627fa27ce4SDimitry Andric           {getIdentifierInfo(Name), Result.getLocation()});
1163b1c73532SDimitry Andric       CurLexerCallback = CLK_LexAfterModuleImport;
11647fa27ce4SDimitry Andric       return true;
11657fa27ce4SDimitry Andric     }
116622989816SDimitry Andric   } else {
116736981b17SDimitry Andric     Lex(Result);
116822989816SDimitry Andric   }
116922989816SDimitry Andric 
117022989816SDimitry Andric   // Allocate a holding buffer for a sequence of tokens and introduce it into
117122989816SDimitry Andric   // the token stream.
117222989816SDimitry Andric   auto EnterTokens = [this](ArrayRef<Token> Toks) {
1173519fc96cSDimitry Andric     auto ToksCopy = std::make_unique<Token[]>(Toks.size());
117422989816SDimitry Andric     std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
117522989816SDimitry Andric     EnterTokenStream(std::move(ToksCopy), Toks.size(),
117622989816SDimitry Andric                      /*DisableMacroExpansion*/ true, /*IsReinject*/ false);
117722989816SDimitry Andric   };
117822989816SDimitry Andric 
11797fa27ce4SDimitry Andric   bool ImportingHeader = Result.is(tok::header_name);
118022989816SDimitry Andric   // Check for a header-name.
118122989816SDimitry Andric   SmallVector<Token, 32> Suffix;
11827fa27ce4SDimitry Andric   if (ImportingHeader) {
118322989816SDimitry Andric     // Enter the header-name token into the token stream; a Lex action cannot
118422989816SDimitry Andric     // both return a token and cache tokens (doing so would corrupt the token
118522989816SDimitry Andric     // cache if the call to Lex comes from CachingLex / PeekAhead).
118622989816SDimitry Andric     Suffix.push_back(Result);
118722989816SDimitry Andric 
118822989816SDimitry Andric     // Consume the pp-import-suffix and expand any macros in it now. We'll add
118922989816SDimitry Andric     // it back into the token stream later.
119022989816SDimitry Andric     CollectPpImportSuffix(Suffix);
119122989816SDimitry Andric     if (Suffix.back().isNot(tok::semi)) {
119222989816SDimitry Andric       // This is not a pp-import after all.
119322989816SDimitry Andric       EnterTokens(Suffix);
119422989816SDimitry Andric       return false;
119522989816SDimitry Andric     }
119622989816SDimitry Andric 
119722989816SDimitry Andric     // C++2a [cpp.module]p1:
119822989816SDimitry Andric     //   The ';' preprocessing-token terminating a pp-import shall not have
119922989816SDimitry Andric     //   been produced by macro replacement.
120022989816SDimitry Andric     SourceLocation SemiLoc = Suffix.back().getLocation();
120122989816SDimitry Andric     if (SemiLoc.isMacroID())
120222989816SDimitry Andric       Diag(SemiLoc, diag::err_header_import_semi_in_macro);
120322989816SDimitry Andric 
120422989816SDimitry Andric     // Reconstitute the import token.
120522989816SDimitry Andric     Token ImportTok;
120622989816SDimitry Andric     ImportTok.startToken();
120722989816SDimitry Andric     ImportTok.setKind(tok::kw_import);
120822989816SDimitry Andric     ImportTok.setLocation(ModuleImportLoc);
120922989816SDimitry Andric     ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
121022989816SDimitry Andric     ImportTok.setLength(6);
121122989816SDimitry Andric 
121222989816SDimitry Andric     auto Action = HandleHeaderIncludeOrImport(
121322989816SDimitry Andric         /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
121422989816SDimitry Andric     switch (Action.Kind) {
121522989816SDimitry Andric     case ImportAction::None:
121622989816SDimitry Andric       break;
121722989816SDimitry Andric 
121822989816SDimitry Andric     case ImportAction::ModuleBegin:
121922989816SDimitry Andric       // Let the parser know we're textually entering the module.
122022989816SDimitry Andric       Suffix.emplace_back();
122122989816SDimitry Andric       Suffix.back().startToken();
122222989816SDimitry Andric       Suffix.back().setKind(tok::annot_module_begin);
122322989816SDimitry Andric       Suffix.back().setLocation(SemiLoc);
122422989816SDimitry Andric       Suffix.back().setAnnotationEndLoc(SemiLoc);
122522989816SDimitry Andric       Suffix.back().setAnnotationValue(Action.ModuleForHeader);
1226e3b55780SDimitry Andric       [[fallthrough]];
122722989816SDimitry Andric 
122822989816SDimitry Andric     case ImportAction::ModuleImport:
12291f917f69SDimitry Andric     case ImportAction::HeaderUnitImport:
123022989816SDimitry Andric     case ImportAction::SkippedModuleImport:
123122989816SDimitry Andric       // We chose to import (or textually enter) the file. Convert the
123222989816SDimitry Andric       // header-name token into a header unit annotation token.
123322989816SDimitry Andric       Suffix[0].setKind(tok::annot_header_unit);
123422989816SDimitry Andric       Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
123522989816SDimitry Andric       Suffix[0].setAnnotationValue(Action.ModuleForHeader);
123622989816SDimitry Andric       // FIXME: Call the moduleImport callback?
123722989816SDimitry Andric       break;
1238cfca06d7SDimitry Andric     case ImportAction::Failure:
1239cfca06d7SDimitry Andric       assert(TheModuleLoader.HadFatalFailure &&
1240cfca06d7SDimitry Andric              "This should be an early exit only to a fatal error");
1241cfca06d7SDimitry Andric       Result.setKind(tok::eof);
1242cfca06d7SDimitry Andric       CurLexer->cutOffLexing();
1243cfca06d7SDimitry Andric       EnterTokens(Suffix);
1244cfca06d7SDimitry Andric       return true;
124522989816SDimitry Andric     }
124622989816SDimitry Andric 
124722989816SDimitry Andric     EnterTokens(Suffix);
124822989816SDimitry Andric     return false;
124922989816SDimitry Andric   }
125036981b17SDimitry Andric 
125136981b17SDimitry Andric   // The token sequence
125236981b17SDimitry Andric   //
1253dbe13110SDimitry Andric   //   import identifier (. identifier)*
125436981b17SDimitry Andric   //
1255dbe13110SDimitry Andric   // indicates a module import directive. We already saw the 'import'
1256dbe13110SDimitry Andric   // contextual keyword, so now we're looking for the identifiers.
1257dbe13110SDimitry Andric   if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
1258dbe13110SDimitry Andric     // We expected to see an identifier here, and we did; continue handling
1259dbe13110SDimitry Andric     // identifiers.
12607fa27ce4SDimitry Andric     NamedModuleImportPath.push_back(
12617fa27ce4SDimitry Andric         std::make_pair(Result.getIdentifierInfo(), Result.getLocation()));
1262dbe13110SDimitry Andric     ModuleImportExpectsIdentifier = false;
1263b1c73532SDimitry Andric     CurLexerCallback = CLK_LexAfterModuleImport;
126422989816SDimitry Andric     return true;
1265dbe13110SDimitry Andric   }
126636981b17SDimitry Andric 
1267dbe13110SDimitry Andric   // If we're expecting a '.' or a ';', and we got a '.', then wait until we
1268bab175ecSDimitry Andric   // see the next identifier. (We can also see a '[[' that begins an
12697fa27ce4SDimitry Andric   // attribute-specifier-seq here under the Standard C++ Modules.)
1270dbe13110SDimitry Andric   if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
1271dbe13110SDimitry Andric     ModuleImportExpectsIdentifier = true;
1272b1c73532SDimitry Andric     CurLexerCallback = CLK_LexAfterModuleImport;
127322989816SDimitry Andric     return true;
1274dbe13110SDimitry Andric   }
1275dbe13110SDimitry Andric 
127622989816SDimitry Andric   // If we didn't recognize a module name at all, this is not a (valid) import.
1277e3b55780SDimitry Andric   if (NamedModuleImportPath.empty() || Result.is(tok::eof))
127822989816SDimitry Andric     return true;
127922989816SDimitry Andric 
128022989816SDimitry Andric   // Consume the pp-import-suffix and expand any macros in it now, if we're not
128122989816SDimitry Andric   // at the semicolon already.
128222989816SDimitry Andric   SourceLocation SemiLoc = Result.getLocation();
128322989816SDimitry Andric   if (Result.isNot(tok::semi)) {
128422989816SDimitry Andric     Suffix.push_back(Result);
128522989816SDimitry Andric     CollectPpImportSuffix(Suffix);
128622989816SDimitry Andric     if (Suffix.back().isNot(tok::semi)) {
128722989816SDimitry Andric       // This is not an import after all.
128822989816SDimitry Andric       EnterTokens(Suffix);
128922989816SDimitry Andric       return false;
129022989816SDimitry Andric     }
129122989816SDimitry Andric     SemiLoc = Suffix.back().getLocation();
129222989816SDimitry Andric   }
129322989816SDimitry Andric 
12947fa27ce4SDimitry Andric   // Under the standard C++ Modules, the dot is just part of the module name,
12957fa27ce4SDimitry Andric   // and not a real hierarchy separator. Flatten such module names now.
1296bab175ecSDimitry Andric   //
1297bab175ecSDimitry Andric   // FIXME: Is this the right level to be performing this transformation?
1298bab175ecSDimitry Andric   std::string FlatModuleName;
12997fa27ce4SDimitry Andric   if (getLangOpts().CPlusPlusModules) {
1300e3b55780SDimitry Andric     for (auto &Piece : NamedModuleImportPath) {
13017fa27ce4SDimitry Andric       // If the FlatModuleName ends with colon, it implies it is a partition.
13027fa27ce4SDimitry Andric       if (!FlatModuleName.empty() && FlatModuleName.back() != ':')
1303bab175ecSDimitry Andric         FlatModuleName += ".";
1304bab175ecSDimitry Andric       FlatModuleName += Piece.first->getName();
1305bab175ecSDimitry Andric     }
1306e3b55780SDimitry Andric     SourceLocation FirstPathLoc = NamedModuleImportPath[0].second;
1307e3b55780SDimitry Andric     NamedModuleImportPath.clear();
1308e3b55780SDimitry Andric     NamedModuleImportPath.push_back(
1309bab175ecSDimitry Andric         std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
1310bab175ecSDimitry Andric   }
1311bab175ecSDimitry Andric 
131206d4ba38SDimitry Andric   Module *Imported = nullptr;
13137fa27ce4SDimitry Andric   // We don't/shouldn't load the standard c++20 modules when preprocessing.
13147fa27ce4SDimitry Andric   if (getLangOpts().Modules && !isInImportingCXXNamedModules()) {
131506d4ba38SDimitry Andric     Imported = TheModuleLoader.loadModule(ModuleImportLoc,
1316e3b55780SDimitry Andric                                           NamedModuleImportPath,
13175e20cdd8SDimitry Andric                                           Module::Hidden,
131822989816SDimitry Andric                                           /*IsInclusionDirective=*/false);
13195e20cdd8SDimitry Andric     if (Imported)
132022989816SDimitry Andric       makeModuleVisible(Imported, SemiLoc);
13215e20cdd8SDimitry Andric   }
13227fa27ce4SDimitry Andric 
132322989816SDimitry Andric   if (Callbacks)
1324e3b55780SDimitry Andric     Callbacks->moduleImport(ModuleImportLoc, NamedModuleImportPath, Imported);
132522989816SDimitry Andric 
132622989816SDimitry Andric   if (!Suffix.empty()) {
132722989816SDimitry Andric     EnterTokens(Suffix);
132822989816SDimitry Andric     return false;
132913cc256eSDimitry Andric   }
133022989816SDimitry Andric   return true;
1331ec2b103cSEd Schouten }
13325362a71cSEd Schouten 
makeModuleVisible(Module * M,SourceLocation Loc)13335e20cdd8SDimitry Andric void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
13345e20cdd8SDimitry Andric   CurSubmoduleState->VisibleModules.setVisible(
13355e20cdd8SDimitry Andric       M, Loc, [](Module *) {},
13365e20cdd8SDimitry Andric       [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
13375e20cdd8SDimitry Andric         // FIXME: Include the path in the diagnostic.
13385e20cdd8SDimitry Andric         // FIXME: Include the import location for the conflicting module.
13395e20cdd8SDimitry Andric         Diag(ModuleImportLoc, diag::warn_module_conflict)
13405e20cdd8SDimitry Andric             << Path[0]->getFullModuleName()
13415e20cdd8SDimitry Andric             << Conflict->getFullModuleName()
13425e20cdd8SDimitry Andric             << Message;
13435e20cdd8SDimitry Andric       });
13445e20cdd8SDimitry Andric 
13455e20cdd8SDimitry Andric   // Add this module to the imports list of the currently-built submodule.
13465e20cdd8SDimitry Andric   if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
13475e20cdd8SDimitry Andric     BuildingSubmoduleStack.back().M->Imports.insert(M);
13485e20cdd8SDimitry Andric }
13495e20cdd8SDimitry Andric 
FinishLexStringLiteral(Token & Result,std::string & String,const char * DiagnosticTag,bool AllowMacroExpansion)1350809500fcSDimitry Andric bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
1351809500fcSDimitry Andric                                           const char *DiagnosticTag,
1352809500fcSDimitry Andric                                           bool AllowMacroExpansion) {
1353809500fcSDimitry Andric   // We need at least one string literal.
1354809500fcSDimitry Andric   if (Result.isNot(tok::string_literal)) {
1355809500fcSDimitry Andric     Diag(Result, diag::err_expected_string_literal)
1356809500fcSDimitry Andric       << /*Source='in...'*/0 << DiagnosticTag;
1357809500fcSDimitry Andric     return false;
1358809500fcSDimitry Andric   }
1359809500fcSDimitry Andric 
1360809500fcSDimitry Andric   // Lex string literal tokens, optionally with macro expansion.
1361809500fcSDimitry Andric   SmallVector<Token, 4> StrToks;
1362809500fcSDimitry Andric   do {
1363809500fcSDimitry Andric     StrToks.push_back(Result);
1364809500fcSDimitry Andric 
1365809500fcSDimitry Andric     if (Result.hasUDSuffix())
1366809500fcSDimitry Andric       Diag(Result, diag::err_invalid_string_udl);
1367809500fcSDimitry Andric 
1368809500fcSDimitry Andric     if (AllowMacroExpansion)
1369809500fcSDimitry Andric       Lex(Result);
1370809500fcSDimitry Andric     else
1371809500fcSDimitry Andric       LexUnexpandedToken(Result);
1372809500fcSDimitry Andric   } while (Result.is(tok::string_literal));
1373809500fcSDimitry Andric 
1374809500fcSDimitry Andric   // Concatenate and parse the strings.
13759f4dbff6SDimitry Andric   StringLiteralParser Literal(StrToks, *this);
1376145449b1SDimitry Andric   assert(Literal.isOrdinary() && "Didn't allow wide strings in");
1377809500fcSDimitry Andric 
1378809500fcSDimitry Andric   if (Literal.hadError)
1379809500fcSDimitry Andric     return false;
1380809500fcSDimitry Andric 
1381809500fcSDimitry Andric   if (Literal.Pascal) {
1382809500fcSDimitry Andric     Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1383809500fcSDimitry Andric       << /*Source='in...'*/0 << DiagnosticTag;
1384809500fcSDimitry Andric     return false;
1385809500fcSDimitry Andric   }
1386809500fcSDimitry Andric 
1387cfca06d7SDimitry Andric   String = std::string(Literal.GetString());
1388809500fcSDimitry Andric   return true;
1389809500fcSDimitry Andric }
1390809500fcSDimitry Andric 
parseSimpleIntegerLiteral(Token & Tok,uint64_t & Value)13919f4dbff6SDimitry Andric bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
13929f4dbff6SDimitry Andric   assert(Tok.is(tok::numeric_constant));
13939f4dbff6SDimitry Andric   SmallString<8> IntegerBuffer;
13949f4dbff6SDimitry Andric   bool NumberInvalid = false;
13959f4dbff6SDimitry Andric   StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
13969f4dbff6SDimitry Andric   if (NumberInvalid)
13979f4dbff6SDimitry Andric     return false;
1398cfca06d7SDimitry Andric   NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
1399cfca06d7SDimitry Andric                                getLangOpts(), getTargetInfo(),
1400cfca06d7SDimitry Andric                                getDiagnostics());
14019f4dbff6SDimitry Andric   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
14029f4dbff6SDimitry Andric     return false;
14039f4dbff6SDimitry Andric   llvm::APInt APVal(64, 0);
14049f4dbff6SDimitry Andric   if (Literal.GetIntegerValue(APVal))
14059f4dbff6SDimitry Andric     return false;
14069f4dbff6SDimitry Andric   Lex(Tok);
14079f4dbff6SDimitry Andric   Value = APVal.getLimitedValue();
14089f4dbff6SDimitry Andric   return true;
14099f4dbff6SDimitry Andric }
14109f4dbff6SDimitry Andric 
addCommentHandler(CommentHandler * Handler)141156d91b49SDimitry Andric void Preprocessor::addCommentHandler(CommentHandler *Handler) {
14125362a71cSEd Schouten   assert(Handler && "NULL comment handler");
1413c0981da4SDimitry Andric   assert(!llvm::is_contained(CommentHandlers, Handler) &&
141422989816SDimitry Andric          "Comment handler already registered");
14155362a71cSEd Schouten   CommentHandlers.push_back(Handler);
14165362a71cSEd Schouten }
14175362a71cSEd Schouten 
removeCommentHandler(CommentHandler * Handler)141856d91b49SDimitry Andric void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
1419461a67faSDimitry Andric   std::vector<CommentHandler *>::iterator Pos =
142022989816SDimitry Andric       llvm::find(CommentHandlers, Handler);
14215362a71cSEd Schouten   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
14225362a71cSEd Schouten   CommentHandlers.erase(Pos);
14235362a71cSEd Schouten }
14245362a71cSEd Schouten 
HandleComment(Token & result,SourceRange Comment)14255044f5c8SRoman Divacky bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
14265044f5c8SRoman Divacky   bool AnyPendingTokens = false;
14275362a71cSEd Schouten   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
14285362a71cSEd Schouten        HEnd = CommentHandlers.end();
14295044f5c8SRoman Divacky        H != HEnd; ++H) {
14305044f5c8SRoman Divacky     if ((*H)->HandleComment(*this, Comment))
14315044f5c8SRoman Divacky       AnyPendingTokens = true;
14325044f5c8SRoman Divacky   }
14335044f5c8SRoman Divacky   if (!AnyPendingTokens || getCommentRetentionState())
14345044f5c8SRoman Divacky     return false;
14355044f5c8SRoman Divacky   Lex(result);
14365044f5c8SRoman Divacky   return true;
14375362a71cSEd Schouten }
14385362a71cSEd Schouten 
emitMacroDeprecationWarning(const Token & Identifier) const1439c0981da4SDimitry Andric void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
1440c0981da4SDimitry Andric   const MacroAnnotations &A =
1441c0981da4SDimitry Andric       getMacroAnnotations(Identifier.getIdentifierInfo());
1442c0981da4SDimitry Andric   assert(A.DeprecationInfo &&
1443c0981da4SDimitry Andric          "Macro deprecation warning without recorded annotation!");
1444c0981da4SDimitry Andric   const MacroAnnotationInfo &Info = *A.DeprecationInfo;
1445c0981da4SDimitry Andric   if (Info.Message.empty())
1446c0981da4SDimitry Andric     Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1447c0981da4SDimitry Andric         << Identifier.getIdentifierInfo() << 0;
1448c0981da4SDimitry Andric   else
1449c0981da4SDimitry Andric     Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1450c0981da4SDimitry Andric         << Identifier.getIdentifierInfo() << 1 << Info.Message;
1451c0981da4SDimitry Andric   Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
1452c0981da4SDimitry Andric }
1453c0981da4SDimitry Andric 
emitRestrictExpansionWarning(const Token & Identifier) const1454c0981da4SDimitry Andric void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
1455c0981da4SDimitry Andric   const MacroAnnotations &A =
1456c0981da4SDimitry Andric       getMacroAnnotations(Identifier.getIdentifierInfo());
1457c0981da4SDimitry Andric   assert(A.RestrictExpansionInfo &&
1458c0981da4SDimitry Andric          "Macro restricted expansion warning without recorded annotation!");
1459c0981da4SDimitry Andric   const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
1460c0981da4SDimitry Andric   if (Info.Message.empty())
1461c0981da4SDimitry Andric     Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1462c0981da4SDimitry Andric         << Identifier.getIdentifierInfo() << 0;
1463c0981da4SDimitry Andric   else
1464c0981da4SDimitry Andric     Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1465c0981da4SDimitry Andric         << Identifier.getIdentifierInfo() << 1 << Info.Message;
1466c0981da4SDimitry Andric   Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
1467c0981da4SDimitry Andric }
1468c0981da4SDimitry Andric 
emitRestrictInfNaNWarning(const Token & Identifier,unsigned DiagSelection) const14694df029ccSDimitry Andric void Preprocessor::emitRestrictInfNaNWarning(const Token &Identifier,
14704df029ccSDimitry Andric                                              unsigned DiagSelection) const {
14714df029ccSDimitry Andric   Diag(Identifier, diag::warn_fp_nan_inf_when_disabled) << DiagSelection << 1;
14724df029ccSDimitry Andric }
14734df029ccSDimitry Andric 
emitFinalMacroWarning(const Token & Identifier,bool IsUndef) const1474c0981da4SDimitry Andric void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
1475c0981da4SDimitry Andric                                          bool IsUndef) const {
1476c0981da4SDimitry Andric   const MacroAnnotations &A =
1477c0981da4SDimitry Andric       getMacroAnnotations(Identifier.getIdentifierInfo());
1478c0981da4SDimitry Andric   assert(A.FinalAnnotationLoc &&
1479c0981da4SDimitry Andric          "Final macro warning without recorded annotation!");
1480c0981da4SDimitry Andric 
1481c0981da4SDimitry Andric   Diag(Identifier, diag::warn_pragma_final_macro)
1482c0981da4SDimitry Andric       << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
1483c0981da4SDimitry Andric   Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
1484c0981da4SDimitry Andric }
1485c0981da4SDimitry Andric 
isSafeBufferOptOut(const SourceManager & SourceMgr,const SourceLocation & Loc) const14867fa27ce4SDimitry Andric bool Preprocessor::isSafeBufferOptOut(const SourceManager &SourceMgr,
14877fa27ce4SDimitry Andric                                       const SourceLocation &Loc) const {
1488ac9a064cSDimitry Andric   // The lambda that tests if a `Loc` is in an opt-out region given one opt-out
1489ac9a064cSDimitry Andric   // region map:
1490ac9a064cSDimitry Andric   auto TestInMap = [&SourceMgr](const SafeBufferOptOutRegionsTy &Map,
1491ac9a064cSDimitry Andric                                 const SourceLocation &Loc) -> bool {
14927fa27ce4SDimitry Andric     // Try to find a region in `SafeBufferOptOutMap` where `Loc` is in:
14937fa27ce4SDimitry Andric     auto FirstRegionEndingAfterLoc = llvm::partition_point(
1494ac9a064cSDimitry Andric         Map, [&SourceMgr,
14957fa27ce4SDimitry Andric               &Loc](const std::pair<SourceLocation, SourceLocation> &Region) {
14967fa27ce4SDimitry Andric           return SourceMgr.isBeforeInTranslationUnit(Region.second, Loc);
14977fa27ce4SDimitry Andric         });
14987fa27ce4SDimitry Andric 
1499ac9a064cSDimitry Andric     if (FirstRegionEndingAfterLoc != Map.end()) {
15007fa27ce4SDimitry Andric       // To test if the start location of the found region precedes `Loc`:
1501ac9a064cSDimitry Andric       return SourceMgr.isBeforeInTranslationUnit(
1502ac9a064cSDimitry Andric           FirstRegionEndingAfterLoc->first, Loc);
15037fa27ce4SDimitry Andric     }
15047fa27ce4SDimitry Andric     // If we do not find a region whose end location passes `Loc`, we want to
15057fa27ce4SDimitry Andric     // check if the current region is still open:
1506ac9a064cSDimitry Andric     if (!Map.empty() && Map.back().first == Map.back().second)
1507ac9a064cSDimitry Andric       return SourceMgr.isBeforeInTranslationUnit(Map.back().first, Loc);
1508ac9a064cSDimitry Andric     return false;
1509ac9a064cSDimitry Andric   };
1510ac9a064cSDimitry Andric 
1511ac9a064cSDimitry Andric   // What the following does:
1512ac9a064cSDimitry Andric   //
1513ac9a064cSDimitry Andric   // If `Loc` belongs to the local TU, we just look up `SafeBufferOptOutMap`.
1514ac9a064cSDimitry Andric   // Otherwise, `Loc` is from a loaded AST.  We look up the
1515ac9a064cSDimitry Andric   // `LoadedSafeBufferOptOutMap` first to get the opt-out region map of the
1516ac9a064cSDimitry Andric   // loaded AST where `Loc` is at.  Then we find if `Loc` is in an opt-out
1517ac9a064cSDimitry Andric   // region w.r.t. the region map.  If the region map is absent, it means there
1518ac9a064cSDimitry Andric   // is no opt-out pragma in that loaded AST.
1519ac9a064cSDimitry Andric   //
1520ac9a064cSDimitry Andric   // Opt-out pragmas in the local TU or a loaded AST is not visible to another
1521ac9a064cSDimitry Andric   // one of them.  That means if you put the pragmas around a `#include
1522ac9a064cSDimitry Andric   // "module.h"`, where module.h is a module, it is not actually suppressing
1523ac9a064cSDimitry Andric   // warnings in module.h.  This is fine because warnings in module.h will be
1524ac9a064cSDimitry Andric   // reported when module.h is compiled in isolation and nothing in module.h
1525ac9a064cSDimitry Andric   // will be analyzed ever again.  So you will not see warnings from the file
1526ac9a064cSDimitry Andric   // that imports module.h anyway. And you can't even do the same thing for PCHs
1527ac9a064cSDimitry Andric   //  because they can only be included from the command line.
1528ac9a064cSDimitry Andric 
1529ac9a064cSDimitry Andric   if (SourceMgr.isLocalSourceLocation(Loc))
1530ac9a064cSDimitry Andric     return TestInMap(SafeBufferOptOutMap, Loc);
1531ac9a064cSDimitry Andric 
1532ac9a064cSDimitry Andric   const SafeBufferOptOutRegionsTy *LoadedRegions =
1533ac9a064cSDimitry Andric       LoadedSafeBufferOptOutMap.lookupLoadedOptOutMap(Loc, SourceMgr);
1534ac9a064cSDimitry Andric 
1535ac9a064cSDimitry Andric   if (LoadedRegions)
1536ac9a064cSDimitry Andric     return TestInMap(*LoadedRegions, Loc);
15377fa27ce4SDimitry Andric   return false;
15387fa27ce4SDimitry Andric }
15397fa27ce4SDimitry Andric 
enterOrExitSafeBufferOptOutRegion(bool isEnter,const SourceLocation & Loc)15407fa27ce4SDimitry Andric bool Preprocessor::enterOrExitSafeBufferOptOutRegion(
15417fa27ce4SDimitry Andric     bool isEnter, const SourceLocation &Loc) {
15427fa27ce4SDimitry Andric   if (isEnter) {
15437fa27ce4SDimitry Andric     if (isPPInSafeBufferOptOutRegion())
15447fa27ce4SDimitry Andric       return true; // invalid enter action
15457fa27ce4SDimitry Andric     InSafeBufferOptOutRegion = true;
15467fa27ce4SDimitry Andric     CurrentSafeBufferOptOutStart = Loc;
15477fa27ce4SDimitry Andric 
15487fa27ce4SDimitry Andric     // To set the start location of a new region:
15497fa27ce4SDimitry Andric 
15507fa27ce4SDimitry Andric     if (!SafeBufferOptOutMap.empty()) {
15517fa27ce4SDimitry Andric       [[maybe_unused]] auto *PrevRegion = &SafeBufferOptOutMap.back();
15527fa27ce4SDimitry Andric       assert(PrevRegion->first != PrevRegion->second &&
15537fa27ce4SDimitry Andric              "Shall not begin a safe buffer opt-out region before closing the "
15547fa27ce4SDimitry Andric              "previous one.");
15557fa27ce4SDimitry Andric     }
15567fa27ce4SDimitry Andric     // If the start location equals to the end location, we call the region a
15577fa27ce4SDimitry Andric     // open region or a unclosed region (i.e., end location has not been set
15587fa27ce4SDimitry Andric     // yet).
15597fa27ce4SDimitry Andric     SafeBufferOptOutMap.emplace_back(Loc, Loc);
15607fa27ce4SDimitry Andric   } else {
15617fa27ce4SDimitry Andric     if (!isPPInSafeBufferOptOutRegion())
15627fa27ce4SDimitry Andric       return true; // invalid enter action
15637fa27ce4SDimitry Andric     InSafeBufferOptOutRegion = false;
15647fa27ce4SDimitry Andric 
15657fa27ce4SDimitry Andric     // To set the end location of the current open region:
15667fa27ce4SDimitry Andric 
15677fa27ce4SDimitry Andric     assert(!SafeBufferOptOutMap.empty() &&
15687fa27ce4SDimitry Andric            "Misordered safe buffer opt-out regions");
15697fa27ce4SDimitry Andric     auto *CurrRegion = &SafeBufferOptOutMap.back();
15707fa27ce4SDimitry Andric     assert(CurrRegion->first == CurrRegion->second &&
15717fa27ce4SDimitry Andric            "Set end location to a closed safe buffer opt-out region");
15727fa27ce4SDimitry Andric     CurrRegion->second = Loc;
15737fa27ce4SDimitry Andric   }
15747fa27ce4SDimitry Andric   return false;
15757fa27ce4SDimitry Andric }
15767fa27ce4SDimitry Andric 
isPPInSafeBufferOptOutRegion()15777fa27ce4SDimitry Andric bool Preprocessor::isPPInSafeBufferOptOutRegion() {
15787fa27ce4SDimitry Andric   return InSafeBufferOptOutRegion;
15797fa27ce4SDimitry Andric }
isPPInSafeBufferOptOutRegion(SourceLocation & StartLoc)15807fa27ce4SDimitry Andric bool Preprocessor::isPPInSafeBufferOptOutRegion(SourceLocation &StartLoc) {
15817fa27ce4SDimitry Andric   StartLoc = CurrentSafeBufferOptOutStart;
15827fa27ce4SDimitry Andric   return InSafeBufferOptOutRegion;
15837fa27ce4SDimitry Andric }
15847fa27ce4SDimitry Andric 
1585ac9a064cSDimitry Andric SmallVector<SourceLocation, 64>
serializeSafeBufferOptOutMap() const1586ac9a064cSDimitry Andric Preprocessor::serializeSafeBufferOptOutMap() const {
1587ac9a064cSDimitry Andric   assert(!InSafeBufferOptOutRegion &&
1588ac9a064cSDimitry Andric          "Attempt to serialize safe buffer opt-out regions before file being "
1589ac9a064cSDimitry Andric          "completely preprocessed");
1590ac9a064cSDimitry Andric 
1591ac9a064cSDimitry Andric   SmallVector<SourceLocation, 64> SrcSeq;
1592ac9a064cSDimitry Andric 
1593ac9a064cSDimitry Andric   for (const auto &[begin, end] : SafeBufferOptOutMap) {
1594ac9a064cSDimitry Andric     SrcSeq.push_back(begin);
1595ac9a064cSDimitry Andric     SrcSeq.push_back(end);
1596ac9a064cSDimitry Andric   }
1597ac9a064cSDimitry Andric   // Only `SafeBufferOptOutMap` gets serialized. No need to serialize
1598ac9a064cSDimitry Andric   // `LoadedSafeBufferOptOutMap` because if this TU loads a pch/module, every
1599ac9a064cSDimitry Andric   // pch/module in the pch-chain/module-DAG will be loaded one by one in order.
1600ac9a064cSDimitry Andric   // It means that for each loading pch/module m, it just needs to load m's own
1601ac9a064cSDimitry Andric   // `SafeBufferOptOutMap`.
1602ac9a064cSDimitry Andric   return SrcSeq;
1603ac9a064cSDimitry Andric }
1604ac9a064cSDimitry Andric 
setDeserializedSafeBufferOptOutMap(const SmallVectorImpl<SourceLocation> & SourceLocations)1605ac9a064cSDimitry Andric bool Preprocessor::setDeserializedSafeBufferOptOutMap(
1606ac9a064cSDimitry Andric     const SmallVectorImpl<SourceLocation> &SourceLocations) {
1607ac9a064cSDimitry Andric   if (SourceLocations.size() == 0)
1608ac9a064cSDimitry Andric     return false;
1609ac9a064cSDimitry Andric 
1610ac9a064cSDimitry Andric   assert(SourceLocations.size() % 2 == 0 &&
1611ac9a064cSDimitry Andric          "ill-formed SourceLocation sequence");
1612ac9a064cSDimitry Andric 
1613ac9a064cSDimitry Andric   auto It = SourceLocations.begin();
1614ac9a064cSDimitry Andric   SafeBufferOptOutRegionsTy &Regions =
1615ac9a064cSDimitry Andric       LoadedSafeBufferOptOutMap.findAndConsLoadedOptOutMap(*It, SourceMgr);
1616ac9a064cSDimitry Andric 
1617ac9a064cSDimitry Andric   do {
1618ac9a064cSDimitry Andric     SourceLocation Begin = *It++;
1619ac9a064cSDimitry Andric     SourceLocation End = *It++;
1620ac9a064cSDimitry Andric 
1621ac9a064cSDimitry Andric     Regions.emplace_back(Begin, End);
1622ac9a064cSDimitry Andric   } while (It != SourceLocations.end());
1623ac9a064cSDimitry Andric   return true;
1624ac9a064cSDimitry Andric }
1625ac9a064cSDimitry Andric 
1626461a67faSDimitry Andric ModuleLoader::~ModuleLoader() = default;
162736981b17SDimitry Andric 
1628461a67faSDimitry Andric CommentHandler::~CommentHandler() = default;
1629c0c7bca4SRoman Divacky 
1630b60736ecSDimitry Andric EmptylineHandler::~EmptylineHandler() = default;
1631b60736ecSDimitry Andric 
1632461a67faSDimitry Andric CodeCompletionHandler::~CodeCompletionHandler() = default;
16333d1dcd9bSDimitry Andric 
createPreprocessingRecord()1634809500fcSDimitry Andric void Preprocessor::createPreprocessingRecord() {
1635c0c7bca4SRoman Divacky   if (Record)
1636c0c7bca4SRoman Divacky     return;
1637c0c7bca4SRoman Divacky 
1638809500fcSDimitry Andric   Record = new PreprocessingRecord(getSourceManager());
163906d4ba38SDimitry Andric   addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
1640c0c7bca4SRoman Divacky }
1641ac9a064cSDimitry Andric 
getCheckPoint(FileID FID,const char * Start) const1642ac9a064cSDimitry Andric const char *Preprocessor::getCheckPoint(FileID FID, const char *Start) const {
1643ac9a064cSDimitry Andric   if (auto It = CheckPoints.find(FID); It != CheckPoints.end()) {
1644ac9a064cSDimitry Andric     const SmallVector<const char *> &FileCheckPoints = It->second;
1645ac9a064cSDimitry Andric     const char *Last = nullptr;
1646ac9a064cSDimitry Andric     // FIXME: Do better than a linear search.
1647ac9a064cSDimitry Andric     for (const char *P : FileCheckPoints) {
1648ac9a064cSDimitry Andric       if (P > Start)
1649ac9a064cSDimitry Andric         break;
1650ac9a064cSDimitry Andric       Last = P;
1651ac9a064cSDimitry Andric     }
1652ac9a064cSDimitry Andric     return Last;
1653ac9a064cSDimitry Andric   }
1654ac9a064cSDimitry Andric 
1655ac9a064cSDimitry Andric   return nullptr;
1656ac9a064cSDimitry Andric }
1657