xref: /aosp_15_r20/external/clang/lib/Lex/Preprocessor.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li //  This file implements the Preprocessor interface.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li //
14*67e74705SXin Li // Options to support:
15*67e74705SXin Li //   -H       - Print the name of each header file used.
16*67e74705SXin Li //   -d[DNI] - Dump various things.
17*67e74705SXin Li //   -fworking-directory - #line's with preprocessor's working dir.
18*67e74705SXin Li //   -fpreprocessed
19*67e74705SXin Li //   -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20*67e74705SXin Li //   -W*
21*67e74705SXin Li //   -w
22*67e74705SXin Li //
23*67e74705SXin Li // Messages to emit:
24*67e74705SXin Li //   "Multiple include guards may be useful for:\n"
25*67e74705SXin Li //
26*67e74705SXin Li //===----------------------------------------------------------------------===//
27*67e74705SXin Li 
28*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
29*67e74705SXin Li #include "clang/Basic/FileManager.h"
30*67e74705SXin Li #include "clang/Basic/FileSystemStatCache.h"
31*67e74705SXin Li #include "clang/Basic/SourceManager.h"
32*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
33*67e74705SXin Li #include "clang/Lex/CodeCompletionHandler.h"
34*67e74705SXin Li #include "clang/Lex/ExternalPreprocessorSource.h"
35*67e74705SXin Li #include "clang/Lex/HeaderSearch.h"
36*67e74705SXin Li #include "clang/Lex/LexDiagnostic.h"
37*67e74705SXin Li #include "clang/Lex/LiteralSupport.h"
38*67e74705SXin Li #include "clang/Lex/MacroArgs.h"
39*67e74705SXin Li #include "clang/Lex/MacroInfo.h"
40*67e74705SXin Li #include "clang/Lex/ModuleLoader.h"
41*67e74705SXin Li #include "clang/Lex/PTHManager.h"
42*67e74705SXin Li #include "clang/Lex/Pragma.h"
43*67e74705SXin Li #include "clang/Lex/PreprocessingRecord.h"
44*67e74705SXin Li #include "clang/Lex/PreprocessorOptions.h"
45*67e74705SXin Li #include "clang/Lex/ScratchBuffer.h"
46*67e74705SXin Li #include "llvm/ADT/APFloat.h"
47*67e74705SXin Li #include "llvm/ADT/STLExtras.h"
48*67e74705SXin Li #include "llvm/ADT/SmallString.h"
49*67e74705SXin Li #include "llvm/ADT/StringExtras.h"
50*67e74705SXin Li #include "llvm/Support/Capacity.h"
51*67e74705SXin Li #include "llvm/Support/ConvertUTF.h"
52*67e74705SXin Li #include "llvm/Support/MemoryBuffer.h"
53*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
54*67e74705SXin Li #include <utility>
55*67e74705SXin Li using namespace clang;
56*67e74705SXin Li 
57*67e74705SXin Li template class llvm::Registry<clang::PragmaHandler>;
58*67e74705SXin Li 
59*67e74705SXin Li //===----------------------------------------------------------------------===//
~ExternalPreprocessorSource()60*67e74705SXin Li ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
61*67e74705SXin Li 
Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,DiagnosticsEngine & diags,LangOptions & opts,SourceManager & SM,HeaderSearch & Headers,ModuleLoader & TheModuleLoader,IdentifierInfoLookup * IILookup,bool OwnsHeaders,TranslationUnitKind TUKind)62*67e74705SXin Li Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
63*67e74705SXin Li                            DiagnosticsEngine &diags, LangOptions &opts,
64*67e74705SXin Li                            SourceManager &SM, HeaderSearch &Headers,
65*67e74705SXin Li                            ModuleLoader &TheModuleLoader,
66*67e74705SXin Li                            IdentifierInfoLookup *IILookup, bool OwnsHeaders,
67*67e74705SXin Li                            TranslationUnitKind TUKind)
68*67e74705SXin Li     : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts), Target(nullptr),
69*67e74705SXin Li       AuxTarget(nullptr), FileMgr(Headers.getFileMgr()), SourceMgr(SM),
70*67e74705SXin Li       ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
71*67e74705SXin Li       TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
72*67e74705SXin Li       Identifiers(opts, IILookup),
73*67e74705SXin Li       PragmaHandlers(new PragmaNamespace(StringRef())),
74*67e74705SXin Li       IncrementalProcessing(false), TUKind(TUKind), CodeComplete(nullptr),
75*67e74705SXin Li       CodeCompletionFile(nullptr), CodeCompletionOffset(0),
76*67e74705SXin Li       LastTokenWasAt(false), ModuleImportExpectsIdentifier(false),
77*67e74705SXin Li       CodeCompletionReached(0), MainFileDir(nullptr),
78*67e74705SXin Li       SkipMainFilePreamble(0, true), CurPPLexer(nullptr), CurDirLookup(nullptr),
79*67e74705SXin Li       CurLexerKind(CLK_Lexer), CurSubmodule(nullptr), Callbacks(nullptr),
80*67e74705SXin Li       CurSubmoduleState(&NullSubmoduleState), MacroArgCache(nullptr),
81*67e74705SXin Li       Record(nullptr), MIChainHead(nullptr), DeserialMIChainHead(nullptr) {
82*67e74705SXin Li   OwnsHeaderSearch = OwnsHeaders;
83*67e74705SXin Li 
84*67e74705SXin Li   CounterValue = 0; // __COUNTER__ starts at 0.
85*67e74705SXin Li 
86*67e74705SXin Li   // Clear stats.
87*67e74705SXin Li   NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
88*67e74705SXin Li   NumIf = NumElse = NumEndif = 0;
89*67e74705SXin Li   NumEnteredSourceFiles = 0;
90*67e74705SXin Li   NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
91*67e74705SXin Li   NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
92*67e74705SXin Li   MaxIncludeStackDepth = 0;
93*67e74705SXin Li   NumSkipped = 0;
94*67e74705SXin Li 
95*67e74705SXin Li   // Default to discarding comments.
96*67e74705SXin Li   KeepComments = false;
97*67e74705SXin Li   KeepMacroComments = false;
98*67e74705SXin Li   SuppressIncludeNotFoundError = false;
99*67e74705SXin Li 
100*67e74705SXin Li   // Macro expansion is enabled.
101*67e74705SXin Li   DisableMacroExpansion = false;
102*67e74705SXin Li   MacroExpansionInDirectivesOverride = false;
103*67e74705SXin Li   InMacroArgs = false;
104*67e74705SXin Li   InMacroArgPreExpansion = false;
105*67e74705SXin Li   NumCachedTokenLexers = 0;
106*67e74705SXin Li   PragmasEnabled = true;
107*67e74705SXin Li   ParsingIfOrElifDirective = false;
108*67e74705SXin Li   PreprocessedOutput = false;
109*67e74705SXin Li 
110*67e74705SXin Li   CachedLexPos = 0;
111*67e74705SXin Li 
112*67e74705SXin Li   // We haven't read anything from the external source.
113*67e74705SXin Li   ReadMacrosFromExternalSource = false;
114*67e74705SXin Li 
115*67e74705SXin Li   // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
116*67e74705SXin Li   // This gets unpoisoned where it is allowed.
117*67e74705SXin Li   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
118*67e74705SXin Li   SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
119*67e74705SXin Li 
120*67e74705SXin Li   // Initialize the pragma handlers.
121*67e74705SXin Li   RegisterBuiltinPragmas();
122*67e74705SXin Li 
123*67e74705SXin Li   // Initialize builtin macros like __LINE__ and friends.
124*67e74705SXin Li   RegisterBuiltinMacros();
125*67e74705SXin Li 
126*67e74705SXin Li   if(LangOpts.Borland) {
127*67e74705SXin Li     Ident__exception_info        = getIdentifierInfo("_exception_info");
128*67e74705SXin Li     Ident___exception_info       = getIdentifierInfo("__exception_info");
129*67e74705SXin Li     Ident_GetExceptionInfo       = getIdentifierInfo("GetExceptionInformation");
130*67e74705SXin Li     Ident__exception_code        = getIdentifierInfo("_exception_code");
131*67e74705SXin Li     Ident___exception_code       = getIdentifierInfo("__exception_code");
132*67e74705SXin Li     Ident_GetExceptionCode       = getIdentifierInfo("GetExceptionCode");
133*67e74705SXin Li     Ident__abnormal_termination  = getIdentifierInfo("_abnormal_termination");
134*67e74705SXin Li     Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
135*67e74705SXin Li     Ident_AbnormalTermination    = getIdentifierInfo("AbnormalTermination");
136*67e74705SXin Li   } else {
137*67e74705SXin Li     Ident__exception_info = Ident__exception_code = nullptr;
138*67e74705SXin Li     Ident__abnormal_termination = Ident___exception_info = nullptr;
139*67e74705SXin Li     Ident___exception_code = Ident___abnormal_termination = nullptr;
140*67e74705SXin Li     Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
141*67e74705SXin Li     Ident_AbnormalTermination = nullptr;
142*67e74705SXin Li   }
143*67e74705SXin Li }
144*67e74705SXin Li 
~Preprocessor()145*67e74705SXin Li Preprocessor::~Preprocessor() {
146*67e74705SXin Li   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
147*67e74705SXin Li 
148*67e74705SXin Li   IncludeMacroStack.clear();
149*67e74705SXin Li 
150*67e74705SXin Li   // Destroy any macro definitions.
151*67e74705SXin Li   while (MacroInfoChain *I = MIChainHead) {
152*67e74705SXin Li     MIChainHead = I->Next;
153*67e74705SXin Li     I->~MacroInfoChain();
154*67e74705SXin Li   }
155*67e74705SXin Li 
156*67e74705SXin Li   // Free any cached macro expanders.
157*67e74705SXin Li   // This populates MacroArgCache, so all TokenLexers need to be destroyed
158*67e74705SXin Li   // before the code below that frees up the MacroArgCache list.
159*67e74705SXin Li   std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
160*67e74705SXin Li   CurTokenLexer.reset();
161*67e74705SXin Li 
162*67e74705SXin Li   while (DeserializedMacroInfoChain *I = DeserialMIChainHead) {
163*67e74705SXin Li     DeserialMIChainHead = I->Next;
164*67e74705SXin Li     I->~DeserializedMacroInfoChain();
165*67e74705SXin Li   }
166*67e74705SXin Li 
167*67e74705SXin Li   // Free any cached MacroArgs.
168*67e74705SXin Li   for (MacroArgs *ArgList = MacroArgCache; ArgList;)
169*67e74705SXin Li     ArgList = ArgList->deallocate();
170*67e74705SXin Li 
171*67e74705SXin Li   // Delete the header search info, if we own it.
172*67e74705SXin Li   if (OwnsHeaderSearch)
173*67e74705SXin Li     delete &HeaderInfo;
174*67e74705SXin Li }
175*67e74705SXin Li 
Initialize(const TargetInfo & Target,const TargetInfo * AuxTarget)176*67e74705SXin Li void Preprocessor::Initialize(const TargetInfo &Target,
177*67e74705SXin Li                               const TargetInfo *AuxTarget) {
178*67e74705SXin Li   assert((!this->Target || this->Target == &Target) &&
179*67e74705SXin Li          "Invalid override of target information");
180*67e74705SXin Li   this->Target = &Target;
181*67e74705SXin Li 
182*67e74705SXin Li   assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
183*67e74705SXin Li          "Invalid override of aux target information.");
184*67e74705SXin Li   this->AuxTarget = AuxTarget;
185*67e74705SXin Li 
186*67e74705SXin Li   // Initialize information about built-ins.
187*67e74705SXin Li   BuiltinInfo.InitializeTarget(Target, AuxTarget);
188*67e74705SXin Li   HeaderInfo.setTarget(Target);
189*67e74705SXin Li }
190*67e74705SXin Li 
InitializeForModelFile()191*67e74705SXin Li void Preprocessor::InitializeForModelFile() {
192*67e74705SXin Li   NumEnteredSourceFiles = 0;
193*67e74705SXin Li 
194*67e74705SXin Li   // Reset pragmas
195*67e74705SXin Li   PragmaHandlersBackup = std::move(PragmaHandlers);
196*67e74705SXin Li   PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
197*67e74705SXin Li   RegisterBuiltinPragmas();
198*67e74705SXin Li 
199*67e74705SXin Li   // Reset PredefinesFileID
200*67e74705SXin Li   PredefinesFileID = FileID();
201*67e74705SXin Li }
202*67e74705SXin Li 
FinalizeForModelFile()203*67e74705SXin Li void Preprocessor::FinalizeForModelFile() {
204*67e74705SXin Li   NumEnteredSourceFiles = 1;
205*67e74705SXin Li 
206*67e74705SXin Li   PragmaHandlers = std::move(PragmaHandlersBackup);
207*67e74705SXin Li }
208*67e74705SXin Li 
setPTHManager(PTHManager * pm)209*67e74705SXin Li void Preprocessor::setPTHManager(PTHManager* pm) {
210*67e74705SXin Li   PTH.reset(pm);
211*67e74705SXin Li   FileMgr.addStatCache(PTH->createStatCache());
212*67e74705SXin Li }
213*67e74705SXin Li 
DumpToken(const Token & Tok,bool DumpFlags) const214*67e74705SXin Li void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
215*67e74705SXin Li   llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
216*67e74705SXin Li                << getSpelling(Tok) << "'";
217*67e74705SXin Li 
218*67e74705SXin Li   if (!DumpFlags) return;
219*67e74705SXin Li 
220*67e74705SXin Li   llvm::errs() << "\t";
221*67e74705SXin Li   if (Tok.isAtStartOfLine())
222*67e74705SXin Li     llvm::errs() << " [StartOfLine]";
223*67e74705SXin Li   if (Tok.hasLeadingSpace())
224*67e74705SXin Li     llvm::errs() << " [LeadingSpace]";
225*67e74705SXin Li   if (Tok.isExpandDisabled())
226*67e74705SXin Li     llvm::errs() << " [ExpandDisabled]";
227*67e74705SXin Li   if (Tok.needsCleaning()) {
228*67e74705SXin Li     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
229*67e74705SXin Li     llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
230*67e74705SXin Li                  << "']";
231*67e74705SXin Li   }
232*67e74705SXin Li 
233*67e74705SXin Li   llvm::errs() << "\tLoc=<";
234*67e74705SXin Li   DumpLocation(Tok.getLocation());
235*67e74705SXin Li   llvm::errs() << ">";
236*67e74705SXin Li }
237*67e74705SXin Li 
DumpLocation(SourceLocation Loc) const238*67e74705SXin Li void Preprocessor::DumpLocation(SourceLocation Loc) const {
239*67e74705SXin Li   Loc.dump(SourceMgr);
240*67e74705SXin Li }
241*67e74705SXin Li 
DumpMacro(const MacroInfo & MI) const242*67e74705SXin Li void Preprocessor::DumpMacro(const MacroInfo &MI) const {
243*67e74705SXin Li   llvm::errs() << "MACRO: ";
244*67e74705SXin Li   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
245*67e74705SXin Li     DumpToken(MI.getReplacementToken(i));
246*67e74705SXin Li     llvm::errs() << "  ";
247*67e74705SXin Li   }
248*67e74705SXin Li   llvm::errs() << "\n";
249*67e74705SXin Li }
250*67e74705SXin Li 
PrintStats()251*67e74705SXin Li void Preprocessor::PrintStats() {
252*67e74705SXin Li   llvm::errs() << "\n*** Preprocessor Stats:\n";
253*67e74705SXin Li   llvm::errs() << NumDirectives << " directives found:\n";
254*67e74705SXin Li   llvm::errs() << "  " << NumDefined << " #define.\n";
255*67e74705SXin Li   llvm::errs() << "  " << NumUndefined << " #undef.\n";
256*67e74705SXin Li   llvm::errs() << "  #include/#include_next/#import:\n";
257*67e74705SXin Li   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
258*67e74705SXin Li   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
259*67e74705SXin Li   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
260*67e74705SXin Li   llvm::errs() << "  " << NumElse << " #else/#elif.\n";
261*67e74705SXin Li   llvm::errs() << "  " << NumEndif << " #endif.\n";
262*67e74705SXin Li   llvm::errs() << "  " << NumPragma << " #pragma.\n";
263*67e74705SXin Li   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
264*67e74705SXin Li 
265*67e74705SXin Li   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
266*67e74705SXin Li              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
267*67e74705SXin Li              << NumFastMacroExpanded << " on the fast path.\n";
268*67e74705SXin Li   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
269*67e74705SXin Li              << " token paste (##) operations performed, "
270*67e74705SXin Li              << NumFastTokenPaste << " on the fast path.\n";
271*67e74705SXin Li 
272*67e74705SXin Li   llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
273*67e74705SXin Li 
274*67e74705SXin Li   llvm::errs() << "\n  BumpPtr: " << BP.getTotalMemory();
275*67e74705SXin Li   llvm::errs() << "\n  Macro Expanded Tokens: "
276*67e74705SXin Li                << llvm::capacity_in_bytes(MacroExpandedTokens);
277*67e74705SXin Li   llvm::errs() << "\n  Predefines Buffer: " << Predefines.capacity();
278*67e74705SXin Li   // FIXME: List information for all submodules.
279*67e74705SXin Li   llvm::errs() << "\n  Macros: "
280*67e74705SXin Li                << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
281*67e74705SXin Li   llvm::errs() << "\n  #pragma push_macro Info: "
282*67e74705SXin Li                << llvm::capacity_in_bytes(PragmaPushMacroInfo);
283*67e74705SXin Li   llvm::errs() << "\n  Poison Reasons: "
284*67e74705SXin Li                << llvm::capacity_in_bytes(PoisonReasons);
285*67e74705SXin Li   llvm::errs() << "\n  Comment Handlers: "
286*67e74705SXin Li                << llvm::capacity_in_bytes(CommentHandlers) << "\n";
287*67e74705SXin Li }
288*67e74705SXin Li 
289*67e74705SXin Li Preprocessor::macro_iterator
macro_begin(bool IncludeExternalMacros) const290*67e74705SXin Li Preprocessor::macro_begin(bool IncludeExternalMacros) const {
291*67e74705SXin Li   if (IncludeExternalMacros && ExternalSource &&
292*67e74705SXin Li       !ReadMacrosFromExternalSource) {
293*67e74705SXin Li     ReadMacrosFromExternalSource = true;
294*67e74705SXin Li     ExternalSource->ReadDefinedMacros();
295*67e74705SXin Li   }
296*67e74705SXin Li 
297*67e74705SXin Li   // Make sure we cover all macros in visible modules.
298*67e74705SXin Li   for (const ModuleMacro &Macro : ModuleMacros)
299*67e74705SXin Li     CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
300*67e74705SXin Li 
301*67e74705SXin Li   return CurSubmoduleState->Macros.begin();
302*67e74705SXin Li }
303*67e74705SXin Li 
getTotalMemory() const304*67e74705SXin Li size_t Preprocessor::getTotalMemory() const {
305*67e74705SXin Li   return BP.getTotalMemory()
306*67e74705SXin Li     + llvm::capacity_in_bytes(MacroExpandedTokens)
307*67e74705SXin Li     + Predefines.capacity() /* Predefines buffer. */
308*67e74705SXin Li     // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
309*67e74705SXin Li     // and ModuleMacros.
310*67e74705SXin Li     + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
311*67e74705SXin Li     + llvm::capacity_in_bytes(PragmaPushMacroInfo)
312*67e74705SXin Li     + llvm::capacity_in_bytes(PoisonReasons)
313*67e74705SXin Li     + llvm::capacity_in_bytes(CommentHandlers);
314*67e74705SXin Li }
315*67e74705SXin Li 
316*67e74705SXin Li Preprocessor::macro_iterator
macro_end(bool IncludeExternalMacros) const317*67e74705SXin Li Preprocessor::macro_end(bool IncludeExternalMacros) const {
318*67e74705SXin Li   if (IncludeExternalMacros && ExternalSource &&
319*67e74705SXin Li       !ReadMacrosFromExternalSource) {
320*67e74705SXin Li     ReadMacrosFromExternalSource = true;
321*67e74705SXin Li     ExternalSource->ReadDefinedMacros();
322*67e74705SXin Li   }
323*67e74705SXin Li 
324*67e74705SXin Li   return CurSubmoduleState->Macros.end();
325*67e74705SXin Li }
326*67e74705SXin Li 
327*67e74705SXin Li /// \brief Compares macro tokens with a specified token value sequence.
MacroDefinitionEquals(const MacroInfo * MI,ArrayRef<TokenValue> Tokens)328*67e74705SXin Li static bool MacroDefinitionEquals(const MacroInfo *MI,
329*67e74705SXin Li                                   ArrayRef<TokenValue> Tokens) {
330*67e74705SXin Li   return Tokens.size() == MI->getNumTokens() &&
331*67e74705SXin Li       std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
332*67e74705SXin Li }
333*67e74705SXin Li 
getLastMacroWithSpelling(SourceLocation Loc,ArrayRef<TokenValue> Tokens) const334*67e74705SXin Li StringRef Preprocessor::getLastMacroWithSpelling(
335*67e74705SXin Li                                     SourceLocation Loc,
336*67e74705SXin Li                                     ArrayRef<TokenValue> Tokens) const {
337*67e74705SXin Li   SourceLocation BestLocation;
338*67e74705SXin Li   StringRef BestSpelling;
339*67e74705SXin Li   for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
340*67e74705SXin Li        I != E; ++I) {
341*67e74705SXin Li     const MacroDirective::DefInfo
342*67e74705SXin Li       Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
343*67e74705SXin Li     if (!Def || !Def.getMacroInfo())
344*67e74705SXin Li       continue;
345*67e74705SXin Li     if (!Def.getMacroInfo()->isObjectLike())
346*67e74705SXin Li       continue;
347*67e74705SXin Li     if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
348*67e74705SXin Li       continue;
349*67e74705SXin Li     SourceLocation Location = Def.getLocation();
350*67e74705SXin Li     // Choose the macro defined latest.
351*67e74705SXin Li     if (BestLocation.isInvalid() ||
352*67e74705SXin Li         (Location.isValid() &&
353*67e74705SXin Li          SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
354*67e74705SXin Li       BestLocation = Location;
355*67e74705SXin Li       BestSpelling = I->first->getName();
356*67e74705SXin Li     }
357*67e74705SXin Li   }
358*67e74705SXin Li   return BestSpelling;
359*67e74705SXin Li }
360*67e74705SXin Li 
recomputeCurLexerKind()361*67e74705SXin Li void Preprocessor::recomputeCurLexerKind() {
362*67e74705SXin Li   if (CurLexer)
363*67e74705SXin Li     CurLexerKind = CLK_Lexer;
364*67e74705SXin Li   else if (CurPTHLexer)
365*67e74705SXin Li     CurLexerKind = CLK_PTHLexer;
366*67e74705SXin Li   else if (CurTokenLexer)
367*67e74705SXin Li     CurLexerKind = CLK_TokenLexer;
368*67e74705SXin Li   else
369*67e74705SXin Li     CurLexerKind = CLK_CachingLexer;
370*67e74705SXin Li }
371*67e74705SXin Li 
SetCodeCompletionPoint(const FileEntry * File,unsigned CompleteLine,unsigned CompleteColumn)372*67e74705SXin Li bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
373*67e74705SXin Li                                           unsigned CompleteLine,
374*67e74705SXin Li                                           unsigned CompleteColumn) {
375*67e74705SXin Li   assert(File);
376*67e74705SXin Li   assert(CompleteLine && CompleteColumn && "Starts from 1:1");
377*67e74705SXin Li   assert(!CodeCompletionFile && "Already set");
378*67e74705SXin Li 
379*67e74705SXin Li   using llvm::MemoryBuffer;
380*67e74705SXin Li 
381*67e74705SXin Li   // Load the actual file's contents.
382*67e74705SXin Li   bool Invalid = false;
383*67e74705SXin Li   const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
384*67e74705SXin Li   if (Invalid)
385*67e74705SXin Li     return true;
386*67e74705SXin Li 
387*67e74705SXin Li   // Find the byte position of the truncation point.
388*67e74705SXin Li   const char *Position = Buffer->getBufferStart();
389*67e74705SXin Li   for (unsigned Line = 1; Line < CompleteLine; ++Line) {
390*67e74705SXin Li     for (; *Position; ++Position) {
391*67e74705SXin Li       if (*Position != '\r' && *Position != '\n')
392*67e74705SXin Li         continue;
393*67e74705SXin Li 
394*67e74705SXin Li       // Eat \r\n or \n\r as a single line.
395*67e74705SXin Li       if ((Position[1] == '\r' || Position[1] == '\n') &&
396*67e74705SXin Li           Position[0] != Position[1])
397*67e74705SXin Li         ++Position;
398*67e74705SXin Li       ++Position;
399*67e74705SXin Li       break;
400*67e74705SXin Li     }
401*67e74705SXin Li   }
402*67e74705SXin Li 
403*67e74705SXin Li   Position += CompleteColumn - 1;
404*67e74705SXin Li 
405*67e74705SXin Li   // If pointing inside the preamble, adjust the position at the beginning of
406*67e74705SXin Li   // the file after the preamble.
407*67e74705SXin Li   if (SkipMainFilePreamble.first &&
408*67e74705SXin Li       SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
409*67e74705SXin Li     if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
410*67e74705SXin Li       Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
411*67e74705SXin Li   }
412*67e74705SXin Li 
413*67e74705SXin Li   if (Position > Buffer->getBufferEnd())
414*67e74705SXin Li     Position = Buffer->getBufferEnd();
415*67e74705SXin Li 
416*67e74705SXin Li   CodeCompletionFile = File;
417*67e74705SXin Li   CodeCompletionOffset = Position - Buffer->getBufferStart();
418*67e74705SXin Li 
419*67e74705SXin Li   std::unique_ptr<MemoryBuffer> NewBuffer =
420*67e74705SXin Li       MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
421*67e74705SXin Li                                           Buffer->getBufferIdentifier());
422*67e74705SXin Li   char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
423*67e74705SXin Li   char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
424*67e74705SXin Li   *NewPos = '\0';
425*67e74705SXin Li   std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
426*67e74705SXin Li   SourceMgr.overrideFileContents(File, std::move(NewBuffer));
427*67e74705SXin Li 
428*67e74705SXin Li   return false;
429*67e74705SXin Li }
430*67e74705SXin Li 
CodeCompleteNaturalLanguage()431*67e74705SXin Li void Preprocessor::CodeCompleteNaturalLanguage() {
432*67e74705SXin Li   if (CodeComplete)
433*67e74705SXin Li     CodeComplete->CodeCompleteNaturalLanguage();
434*67e74705SXin Li   setCodeCompletionReached();
435*67e74705SXin Li }
436*67e74705SXin Li 
437*67e74705SXin Li /// getSpelling - This method is used to get the spelling of a token into a
438*67e74705SXin Li /// SmallVector. Note that the returned StringRef may not point to the
439*67e74705SXin Li /// supplied buffer if a copy can be avoided.
getSpelling(const Token & Tok,SmallVectorImpl<char> & Buffer,bool * Invalid) const440*67e74705SXin Li StringRef Preprocessor::getSpelling(const Token &Tok,
441*67e74705SXin Li                                           SmallVectorImpl<char> &Buffer,
442*67e74705SXin Li                                           bool *Invalid) const {
443*67e74705SXin Li   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
444*67e74705SXin Li   if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
445*67e74705SXin Li     // Try the fast path.
446*67e74705SXin Li     if (const IdentifierInfo *II = Tok.getIdentifierInfo())
447*67e74705SXin Li       return II->getName();
448*67e74705SXin Li   }
449*67e74705SXin Li 
450*67e74705SXin Li   // Resize the buffer if we need to copy into it.
451*67e74705SXin Li   if (Tok.needsCleaning())
452*67e74705SXin Li     Buffer.resize(Tok.getLength());
453*67e74705SXin Li 
454*67e74705SXin Li   const char *Ptr = Buffer.data();
455*67e74705SXin Li   unsigned Len = getSpelling(Tok, Ptr, Invalid);
456*67e74705SXin Li   return StringRef(Ptr, Len);
457*67e74705SXin Li }
458*67e74705SXin Li 
459*67e74705SXin Li /// CreateString - Plop the specified string into a scratch buffer and return a
460*67e74705SXin Li /// location for it.  If specified, the source location provides a source
461*67e74705SXin Li /// location for the token.
CreateString(StringRef Str,Token & Tok,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd)462*67e74705SXin Li void Preprocessor::CreateString(StringRef Str, Token &Tok,
463*67e74705SXin Li                                 SourceLocation ExpansionLocStart,
464*67e74705SXin Li                                 SourceLocation ExpansionLocEnd) {
465*67e74705SXin Li   Tok.setLength(Str.size());
466*67e74705SXin Li 
467*67e74705SXin Li   const char *DestPtr;
468*67e74705SXin Li   SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
469*67e74705SXin Li 
470*67e74705SXin Li   if (ExpansionLocStart.isValid())
471*67e74705SXin Li     Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
472*67e74705SXin Li                                        ExpansionLocEnd, Str.size());
473*67e74705SXin Li   Tok.setLocation(Loc);
474*67e74705SXin Li 
475*67e74705SXin Li   // If this is a raw identifier or a literal token, set the pointer data.
476*67e74705SXin Li   if (Tok.is(tok::raw_identifier))
477*67e74705SXin Li     Tok.setRawIdentifierData(DestPtr);
478*67e74705SXin Li   else if (Tok.isLiteral())
479*67e74705SXin Li     Tok.setLiteralData(DestPtr);
480*67e74705SXin Li }
481*67e74705SXin Li 
getCurrentModule()482*67e74705SXin Li Module *Preprocessor::getCurrentModule() {
483*67e74705SXin Li   if (!getLangOpts().CompilingModule)
484*67e74705SXin Li     return nullptr;
485*67e74705SXin Li 
486*67e74705SXin Li   return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
487*67e74705SXin Li }
488*67e74705SXin Li 
489*67e74705SXin Li //===----------------------------------------------------------------------===//
490*67e74705SXin Li // Preprocessor Initialization Methods
491*67e74705SXin Li //===----------------------------------------------------------------------===//
492*67e74705SXin Li 
493*67e74705SXin Li 
494*67e74705SXin Li /// EnterMainSourceFile - Enter the specified FileID as the main source file,
495*67e74705SXin Li /// which implicitly adds the builtin defines etc.
EnterMainSourceFile()496*67e74705SXin Li void Preprocessor::EnterMainSourceFile() {
497*67e74705SXin Li   // We do not allow the preprocessor to reenter the main file.  Doing so will
498*67e74705SXin Li   // cause FileID's to accumulate information from both runs (e.g. #line
499*67e74705SXin Li   // information) and predefined macros aren't guaranteed to be set properly.
500*67e74705SXin Li   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
501*67e74705SXin Li   FileID MainFileID = SourceMgr.getMainFileID();
502*67e74705SXin Li 
503*67e74705SXin Li   // If MainFileID is loaded it means we loaded an AST file, no need to enter
504*67e74705SXin Li   // a main file.
505*67e74705SXin Li   if (!SourceMgr.isLoadedFileID(MainFileID)) {
506*67e74705SXin Li     // Enter the main file source buffer.
507*67e74705SXin Li     EnterSourceFile(MainFileID, nullptr, SourceLocation());
508*67e74705SXin Li 
509*67e74705SXin Li     // If we've been asked to skip bytes in the main file (e.g., as part of a
510*67e74705SXin Li     // precompiled preamble), do so now.
511*67e74705SXin Li     if (SkipMainFilePreamble.first > 0)
512*67e74705SXin Li       CurLexer->SkipBytes(SkipMainFilePreamble.first,
513*67e74705SXin Li                           SkipMainFilePreamble.second);
514*67e74705SXin Li 
515*67e74705SXin Li     // Tell the header info that the main file was entered.  If the file is later
516*67e74705SXin Li     // #imported, it won't be re-entered.
517*67e74705SXin Li     if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
518*67e74705SXin Li       HeaderInfo.IncrementIncludeCount(FE);
519*67e74705SXin Li   }
520*67e74705SXin Li 
521*67e74705SXin Li   // Preprocess Predefines to populate the initial preprocessor state.
522*67e74705SXin Li   std::unique_ptr<llvm::MemoryBuffer> SB =
523*67e74705SXin Li     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
524*67e74705SXin Li   assert(SB && "Cannot create predefined source buffer");
525*67e74705SXin Li   FileID FID = SourceMgr.createFileID(std::move(SB));
526*67e74705SXin Li   assert(FID.isValid() && "Could not create FileID for predefines?");
527*67e74705SXin Li   setPredefinesFileID(FID);
528*67e74705SXin Li 
529*67e74705SXin Li   // Start parsing the predefines.
530*67e74705SXin Li   EnterSourceFile(FID, nullptr, SourceLocation());
531*67e74705SXin Li }
532*67e74705SXin Li 
EndSourceFile()533*67e74705SXin Li void Preprocessor::EndSourceFile() {
534*67e74705SXin Li   // Notify the client that we reached the end of the source file.
535*67e74705SXin Li   if (Callbacks)
536*67e74705SXin Li     Callbacks->EndOfMainFile();
537*67e74705SXin Li }
538*67e74705SXin Li 
539*67e74705SXin Li //===----------------------------------------------------------------------===//
540*67e74705SXin Li // Lexer Event Handling.
541*67e74705SXin Li //===----------------------------------------------------------------------===//
542*67e74705SXin Li 
543*67e74705SXin Li /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
544*67e74705SXin Li /// identifier information for the token and install it into the token,
545*67e74705SXin Li /// updating the token kind accordingly.
LookUpIdentifierInfo(Token & Identifier) const546*67e74705SXin Li IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
547*67e74705SXin Li   assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
548*67e74705SXin Li 
549*67e74705SXin Li   // Look up this token, see if it is a macro, or if it is a language keyword.
550*67e74705SXin Li   IdentifierInfo *II;
551*67e74705SXin Li   if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
552*67e74705SXin Li     // No cleaning needed, just use the characters from the lexed buffer.
553*67e74705SXin Li     II = getIdentifierInfo(Identifier.getRawIdentifier());
554*67e74705SXin Li   } else {
555*67e74705SXin Li     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
556*67e74705SXin Li     SmallString<64> IdentifierBuffer;
557*67e74705SXin Li     StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
558*67e74705SXin Li 
559*67e74705SXin Li     if (Identifier.hasUCN()) {
560*67e74705SXin Li       SmallString<64> UCNIdentifierBuffer;
561*67e74705SXin Li       expandUCNs(UCNIdentifierBuffer, CleanedStr);
562*67e74705SXin Li       II = getIdentifierInfo(UCNIdentifierBuffer);
563*67e74705SXin Li     } else {
564*67e74705SXin Li       II = getIdentifierInfo(CleanedStr);
565*67e74705SXin Li     }
566*67e74705SXin Li   }
567*67e74705SXin Li 
568*67e74705SXin Li   // Update the token info (identifier info and appropriate token kind).
569*67e74705SXin Li   Identifier.setIdentifierInfo(II);
570*67e74705SXin Li   Identifier.setKind(II->getTokenID());
571*67e74705SXin Li 
572*67e74705SXin Li   return II;
573*67e74705SXin Li }
574*67e74705SXin Li 
SetPoisonReason(IdentifierInfo * II,unsigned DiagID)575*67e74705SXin Li void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
576*67e74705SXin Li   PoisonReasons[II] = DiagID;
577*67e74705SXin Li }
578*67e74705SXin Li 
PoisonSEHIdentifiers(bool Poison)579*67e74705SXin Li void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
580*67e74705SXin Li   assert(Ident__exception_code && Ident__exception_info);
581*67e74705SXin Li   assert(Ident___exception_code && Ident___exception_info);
582*67e74705SXin Li   Ident__exception_code->setIsPoisoned(Poison);
583*67e74705SXin Li   Ident___exception_code->setIsPoisoned(Poison);
584*67e74705SXin Li   Ident_GetExceptionCode->setIsPoisoned(Poison);
585*67e74705SXin Li   Ident__exception_info->setIsPoisoned(Poison);
586*67e74705SXin Li   Ident___exception_info->setIsPoisoned(Poison);
587*67e74705SXin Li   Ident_GetExceptionInfo->setIsPoisoned(Poison);
588*67e74705SXin Li   Ident__abnormal_termination->setIsPoisoned(Poison);
589*67e74705SXin Li   Ident___abnormal_termination->setIsPoisoned(Poison);
590*67e74705SXin Li   Ident_AbnormalTermination->setIsPoisoned(Poison);
591*67e74705SXin Li }
592*67e74705SXin Li 
HandlePoisonedIdentifier(Token & Identifier)593*67e74705SXin Li void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
594*67e74705SXin Li   assert(Identifier.getIdentifierInfo() &&
595*67e74705SXin Li          "Can't handle identifiers without identifier info!");
596*67e74705SXin Li   llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
597*67e74705SXin Li     PoisonReasons.find(Identifier.getIdentifierInfo());
598*67e74705SXin Li   if(it == PoisonReasons.end())
599*67e74705SXin Li     Diag(Identifier, diag::err_pp_used_poisoned_id);
600*67e74705SXin Li   else
601*67e74705SXin Li     Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
602*67e74705SXin Li }
603*67e74705SXin Li 
604*67e74705SXin Li /// \brief Returns a diagnostic message kind for reporting a future keyword as
605*67e74705SXin Li /// appropriate for the identifier and specified language.
getFutureCompatDiagKind(const IdentifierInfo & II,const LangOptions & LangOpts)606*67e74705SXin Li static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
607*67e74705SXin Li                                           const LangOptions &LangOpts) {
608*67e74705SXin Li   assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
609*67e74705SXin Li 
610*67e74705SXin Li   if (LangOpts.CPlusPlus)
611*67e74705SXin Li     return llvm::StringSwitch<diag::kind>(II.getName())
612*67e74705SXin Li #define CXX11_KEYWORD(NAME, FLAGS)                                             \
613*67e74705SXin Li         .Case(#NAME, diag::warn_cxx11_keyword)
614*67e74705SXin Li #include "clang/Basic/TokenKinds.def"
615*67e74705SXin Li         ;
616*67e74705SXin Li 
617*67e74705SXin Li   llvm_unreachable(
618*67e74705SXin Li       "Keyword not known to come from a newer Standard or proposed Standard");
619*67e74705SXin Li }
620*67e74705SXin Li 
621*67e74705SXin Li /// HandleIdentifier - This callback is invoked when the lexer reads an
622*67e74705SXin Li /// identifier.  This callback looks up the identifier in the map and/or
623*67e74705SXin Li /// potentially macro expands it or turns it into a named token (like 'for').
624*67e74705SXin Li ///
625*67e74705SXin Li /// Note that callers of this method are guarded by checking the
626*67e74705SXin Li /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
627*67e74705SXin Li /// IdentifierInfo methods that compute these properties will need to change to
628*67e74705SXin Li /// match.
HandleIdentifier(Token & Identifier)629*67e74705SXin Li bool Preprocessor::HandleIdentifier(Token &Identifier) {
630*67e74705SXin Li   assert(Identifier.getIdentifierInfo() &&
631*67e74705SXin Li          "Can't handle identifiers without identifier info!");
632*67e74705SXin Li 
633*67e74705SXin Li   IdentifierInfo &II = *Identifier.getIdentifierInfo();
634*67e74705SXin Li 
635*67e74705SXin Li   // If the information about this identifier is out of date, update it from
636*67e74705SXin Li   // the external source.
637*67e74705SXin Li   // We have to treat __VA_ARGS__ in a special way, since it gets
638*67e74705SXin Li   // serialized with isPoisoned = true, but our preprocessor may have
639*67e74705SXin Li   // unpoisoned it if we're defining a C99 macro.
640*67e74705SXin Li   if (II.isOutOfDate()) {
641*67e74705SXin Li     bool CurrentIsPoisoned = false;
642*67e74705SXin Li     if (&II == Ident__VA_ARGS__)
643*67e74705SXin Li       CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
644*67e74705SXin Li 
645*67e74705SXin Li     ExternalSource->updateOutOfDateIdentifier(II);
646*67e74705SXin Li     Identifier.setKind(II.getTokenID());
647*67e74705SXin Li 
648*67e74705SXin Li     if (&II == Ident__VA_ARGS__)
649*67e74705SXin Li       II.setIsPoisoned(CurrentIsPoisoned);
650*67e74705SXin Li   }
651*67e74705SXin Li 
652*67e74705SXin Li   // If this identifier was poisoned, and if it was not produced from a macro
653*67e74705SXin Li   // expansion, emit an error.
654*67e74705SXin Li   if (II.isPoisoned() && CurPPLexer) {
655*67e74705SXin Li     HandlePoisonedIdentifier(Identifier);
656*67e74705SXin Li   }
657*67e74705SXin Li 
658*67e74705SXin Li   // If this is a macro to be expanded, do it.
659*67e74705SXin Li   if (MacroDefinition MD = getMacroDefinition(&II)) {
660*67e74705SXin Li     auto *MI = MD.getMacroInfo();
661*67e74705SXin Li     assert(MI && "macro definition with no macro info?");
662*67e74705SXin Li     if (!DisableMacroExpansion) {
663*67e74705SXin Li       if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
664*67e74705SXin Li         // C99 6.10.3p10: If the preprocessing token immediately after the
665*67e74705SXin Li         // macro name isn't a '(', this macro should not be expanded.
666*67e74705SXin Li         if (!MI->isFunctionLike() || isNextPPTokenLParen())
667*67e74705SXin Li           return HandleMacroExpandedIdentifier(Identifier, MD);
668*67e74705SXin Li       } else {
669*67e74705SXin Li         // C99 6.10.3.4p2 says that a disabled macro may never again be
670*67e74705SXin Li         // expanded, even if it's in a context where it could be expanded in the
671*67e74705SXin Li         // future.
672*67e74705SXin Li         Identifier.setFlag(Token::DisableExpand);
673*67e74705SXin Li         if (MI->isObjectLike() || isNextPPTokenLParen())
674*67e74705SXin Li           Diag(Identifier, diag::pp_disabled_macro_expansion);
675*67e74705SXin Li       }
676*67e74705SXin Li     }
677*67e74705SXin Li   }
678*67e74705SXin Li 
679*67e74705SXin Li   // If this identifier is a keyword in a newer Standard or proposed Standard,
680*67e74705SXin Li   // produce a warning. Don't warn if we're not considering macro expansion,
681*67e74705SXin Li   // since this identifier might be the name of a macro.
682*67e74705SXin Li   // FIXME: This warning is disabled in cases where it shouldn't be, like
683*67e74705SXin Li   //   "#define constexpr constexpr", "int constexpr;"
684*67e74705SXin Li   if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
685*67e74705SXin Li     Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
686*67e74705SXin Li         << II.getName();
687*67e74705SXin Li     // Don't diagnose this keyword again in this translation unit.
688*67e74705SXin Li     II.setIsFutureCompatKeyword(false);
689*67e74705SXin Li   }
690*67e74705SXin Li 
691*67e74705SXin Li   // C++ 2.11p2: If this is an alternative representation of a C++ operator,
692*67e74705SXin Li   // then we act as if it is the actual operator and not the textual
693*67e74705SXin Li   // representation of it.
694*67e74705SXin Li   if (II.isCPlusPlusOperatorKeyword())
695*67e74705SXin Li     Identifier.setIdentifierInfo(nullptr);
696*67e74705SXin Li 
697*67e74705SXin Li   // If this is an extension token, diagnose its use.
698*67e74705SXin Li   // We avoid diagnosing tokens that originate from macro definitions.
699*67e74705SXin Li   // FIXME: This warning is disabled in cases where it shouldn't be,
700*67e74705SXin Li   // like "#define TY typeof", "TY(1) x".
701*67e74705SXin Li   if (II.isExtensionToken() && !DisableMacroExpansion)
702*67e74705SXin Li     Diag(Identifier, diag::ext_token_used);
703*67e74705SXin Li 
704*67e74705SXin Li   // If this is the 'import' contextual keyword following an '@', note
705*67e74705SXin Li   // that the next token indicates a module name.
706*67e74705SXin Li   //
707*67e74705SXin Li   // Note that we do not treat 'import' as a contextual
708*67e74705SXin Li   // keyword when we're in a caching lexer, because caching lexers only get
709*67e74705SXin Li   // used in contexts where import declarations are disallowed.
710*67e74705SXin Li   if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
711*67e74705SXin Li       !DisableMacroExpansion &&
712*67e74705SXin Li       (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
713*67e74705SXin Li       CurLexerKind != CLK_CachingLexer) {
714*67e74705SXin Li     ModuleImportLoc = Identifier.getLocation();
715*67e74705SXin Li     ModuleImportPath.clear();
716*67e74705SXin Li     ModuleImportExpectsIdentifier = true;
717*67e74705SXin Li     CurLexerKind = CLK_LexAfterModuleImport;
718*67e74705SXin Li   }
719*67e74705SXin Li   return true;
720*67e74705SXin Li }
721*67e74705SXin Li 
Lex(Token & Result)722*67e74705SXin Li void Preprocessor::Lex(Token &Result) {
723*67e74705SXin Li   // We loop here until a lex function returns a token; this avoids recursion.
724*67e74705SXin Li   bool ReturnedToken;
725*67e74705SXin Li   do {
726*67e74705SXin Li     switch (CurLexerKind) {
727*67e74705SXin Li     case CLK_Lexer:
728*67e74705SXin Li       ReturnedToken = CurLexer->Lex(Result);
729*67e74705SXin Li       break;
730*67e74705SXin Li     case CLK_PTHLexer:
731*67e74705SXin Li       ReturnedToken = CurPTHLexer->Lex(Result);
732*67e74705SXin Li       break;
733*67e74705SXin Li     case CLK_TokenLexer:
734*67e74705SXin Li       ReturnedToken = CurTokenLexer->Lex(Result);
735*67e74705SXin Li       break;
736*67e74705SXin Li     case CLK_CachingLexer:
737*67e74705SXin Li       CachingLex(Result);
738*67e74705SXin Li       ReturnedToken = true;
739*67e74705SXin Li       break;
740*67e74705SXin Li     case CLK_LexAfterModuleImport:
741*67e74705SXin Li       LexAfterModuleImport(Result);
742*67e74705SXin Li       ReturnedToken = true;
743*67e74705SXin Li       break;
744*67e74705SXin Li     }
745*67e74705SXin Li   } while (!ReturnedToken);
746*67e74705SXin Li 
747*67e74705SXin Li   LastTokenWasAt = Result.is(tok::at);
748*67e74705SXin Li }
749*67e74705SXin Li 
750*67e74705SXin Li 
751*67e74705SXin Li /// \brief Lex a token following the 'import' contextual keyword.
752*67e74705SXin Li ///
LexAfterModuleImport(Token & Result)753*67e74705SXin Li void Preprocessor::LexAfterModuleImport(Token &Result) {
754*67e74705SXin Li   // Figure out what kind of lexer we actually have.
755*67e74705SXin Li   recomputeCurLexerKind();
756*67e74705SXin Li 
757*67e74705SXin Li   // Lex the next token.
758*67e74705SXin Li   Lex(Result);
759*67e74705SXin Li 
760*67e74705SXin Li   // The token sequence
761*67e74705SXin Li   //
762*67e74705SXin Li   //   import identifier (. identifier)*
763*67e74705SXin Li   //
764*67e74705SXin Li   // indicates a module import directive. We already saw the 'import'
765*67e74705SXin Li   // contextual keyword, so now we're looking for the identifiers.
766*67e74705SXin Li   if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
767*67e74705SXin Li     // We expected to see an identifier here, and we did; continue handling
768*67e74705SXin Li     // identifiers.
769*67e74705SXin Li     ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
770*67e74705SXin Li                                               Result.getLocation()));
771*67e74705SXin Li     ModuleImportExpectsIdentifier = false;
772*67e74705SXin Li     CurLexerKind = CLK_LexAfterModuleImport;
773*67e74705SXin Li     return;
774*67e74705SXin Li   }
775*67e74705SXin Li 
776*67e74705SXin Li   // If we're expecting a '.' or a ';', and we got a '.', then wait until we
777*67e74705SXin Li   // see the next identifier.
778*67e74705SXin Li   if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
779*67e74705SXin Li     ModuleImportExpectsIdentifier = true;
780*67e74705SXin Li     CurLexerKind = CLK_LexAfterModuleImport;
781*67e74705SXin Li     return;
782*67e74705SXin Li   }
783*67e74705SXin Li 
784*67e74705SXin Li   // If we have a non-empty module path, load the named module.
785*67e74705SXin Li   if (!ModuleImportPath.empty()) {
786*67e74705SXin Li     Module *Imported = nullptr;
787*67e74705SXin Li     if (getLangOpts().Modules) {
788*67e74705SXin Li       Imported = TheModuleLoader.loadModule(ModuleImportLoc,
789*67e74705SXin Li                                             ModuleImportPath,
790*67e74705SXin Li                                             Module::Hidden,
791*67e74705SXin Li                                             /*IsIncludeDirective=*/false);
792*67e74705SXin Li       if (Imported)
793*67e74705SXin Li         makeModuleVisible(Imported, ModuleImportLoc);
794*67e74705SXin Li     }
795*67e74705SXin Li     if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
796*67e74705SXin Li       Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
797*67e74705SXin Li   }
798*67e74705SXin Li }
799*67e74705SXin Li 
makeModuleVisible(Module * M,SourceLocation Loc)800*67e74705SXin Li void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
801*67e74705SXin Li   CurSubmoduleState->VisibleModules.setVisible(
802*67e74705SXin Li       M, Loc, [](Module *) {},
803*67e74705SXin Li       [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
804*67e74705SXin Li         // FIXME: Include the path in the diagnostic.
805*67e74705SXin Li         // FIXME: Include the import location for the conflicting module.
806*67e74705SXin Li         Diag(ModuleImportLoc, diag::warn_module_conflict)
807*67e74705SXin Li             << Path[0]->getFullModuleName()
808*67e74705SXin Li             << Conflict->getFullModuleName()
809*67e74705SXin Li             << Message;
810*67e74705SXin Li       });
811*67e74705SXin Li 
812*67e74705SXin Li   // Add this module to the imports list of the currently-built submodule.
813*67e74705SXin Li   if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
814*67e74705SXin Li     BuildingSubmoduleStack.back().M->Imports.insert(M);
815*67e74705SXin Li }
816*67e74705SXin Li 
FinishLexStringLiteral(Token & Result,std::string & String,const char * DiagnosticTag,bool AllowMacroExpansion)817*67e74705SXin Li bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
818*67e74705SXin Li                                           const char *DiagnosticTag,
819*67e74705SXin Li                                           bool AllowMacroExpansion) {
820*67e74705SXin Li   // We need at least one string literal.
821*67e74705SXin Li   if (Result.isNot(tok::string_literal)) {
822*67e74705SXin Li     Diag(Result, diag::err_expected_string_literal)
823*67e74705SXin Li       << /*Source='in...'*/0 << DiagnosticTag;
824*67e74705SXin Li     return false;
825*67e74705SXin Li   }
826*67e74705SXin Li 
827*67e74705SXin Li   // Lex string literal tokens, optionally with macro expansion.
828*67e74705SXin Li   SmallVector<Token, 4> StrToks;
829*67e74705SXin Li   do {
830*67e74705SXin Li     StrToks.push_back(Result);
831*67e74705SXin Li 
832*67e74705SXin Li     if (Result.hasUDSuffix())
833*67e74705SXin Li       Diag(Result, diag::err_invalid_string_udl);
834*67e74705SXin Li 
835*67e74705SXin Li     if (AllowMacroExpansion)
836*67e74705SXin Li       Lex(Result);
837*67e74705SXin Li     else
838*67e74705SXin Li       LexUnexpandedToken(Result);
839*67e74705SXin Li   } while (Result.is(tok::string_literal));
840*67e74705SXin Li 
841*67e74705SXin Li   // Concatenate and parse the strings.
842*67e74705SXin Li   StringLiteralParser Literal(StrToks, *this);
843*67e74705SXin Li   assert(Literal.isAscii() && "Didn't allow wide strings in");
844*67e74705SXin Li 
845*67e74705SXin Li   if (Literal.hadError)
846*67e74705SXin Li     return false;
847*67e74705SXin Li 
848*67e74705SXin Li   if (Literal.Pascal) {
849*67e74705SXin Li     Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
850*67e74705SXin Li       << /*Source='in...'*/0 << DiagnosticTag;
851*67e74705SXin Li     return false;
852*67e74705SXin Li   }
853*67e74705SXin Li 
854*67e74705SXin Li   String = Literal.GetString();
855*67e74705SXin Li   return true;
856*67e74705SXin Li }
857*67e74705SXin Li 
parseSimpleIntegerLiteral(Token & Tok,uint64_t & Value)858*67e74705SXin Li bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
859*67e74705SXin Li   assert(Tok.is(tok::numeric_constant));
860*67e74705SXin Li   SmallString<8> IntegerBuffer;
861*67e74705SXin Li   bool NumberInvalid = false;
862*67e74705SXin Li   StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
863*67e74705SXin Li   if (NumberInvalid)
864*67e74705SXin Li     return false;
865*67e74705SXin Li   NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
866*67e74705SXin Li   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
867*67e74705SXin Li     return false;
868*67e74705SXin Li   llvm::APInt APVal(64, 0);
869*67e74705SXin Li   if (Literal.GetIntegerValue(APVal))
870*67e74705SXin Li     return false;
871*67e74705SXin Li   Lex(Tok);
872*67e74705SXin Li   Value = APVal.getLimitedValue();
873*67e74705SXin Li   return true;
874*67e74705SXin Li }
875*67e74705SXin Li 
addCommentHandler(CommentHandler * Handler)876*67e74705SXin Li void Preprocessor::addCommentHandler(CommentHandler *Handler) {
877*67e74705SXin Li   assert(Handler && "NULL comment handler");
878*67e74705SXin Li   assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
879*67e74705SXin Li          CommentHandlers.end() && "Comment handler already registered");
880*67e74705SXin Li   CommentHandlers.push_back(Handler);
881*67e74705SXin Li }
882*67e74705SXin Li 
removeCommentHandler(CommentHandler * Handler)883*67e74705SXin Li void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
884*67e74705SXin Li   std::vector<CommentHandler *>::iterator Pos
885*67e74705SXin Li   = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
886*67e74705SXin Li   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
887*67e74705SXin Li   CommentHandlers.erase(Pos);
888*67e74705SXin Li }
889*67e74705SXin Li 
HandleComment(Token & result,SourceRange Comment)890*67e74705SXin Li bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
891*67e74705SXin Li   bool AnyPendingTokens = false;
892*67e74705SXin Li   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
893*67e74705SXin Li        HEnd = CommentHandlers.end();
894*67e74705SXin Li        H != HEnd; ++H) {
895*67e74705SXin Li     if ((*H)->HandleComment(*this, Comment))
896*67e74705SXin Li       AnyPendingTokens = true;
897*67e74705SXin Li   }
898*67e74705SXin Li   if (!AnyPendingTokens || getCommentRetentionState())
899*67e74705SXin Li     return false;
900*67e74705SXin Li   Lex(result);
901*67e74705SXin Li   return true;
902*67e74705SXin Li }
903*67e74705SXin Li 
~ModuleLoader()904*67e74705SXin Li ModuleLoader::~ModuleLoader() { }
905*67e74705SXin Li 
~CommentHandler()906*67e74705SXin Li CommentHandler::~CommentHandler() { }
907*67e74705SXin Li 
~CodeCompletionHandler()908*67e74705SXin Li CodeCompletionHandler::~CodeCompletionHandler() { }
909*67e74705SXin Li 
createPreprocessingRecord()910*67e74705SXin Li void Preprocessor::createPreprocessingRecord() {
911*67e74705SXin Li   if (Record)
912*67e74705SXin Li     return;
913*67e74705SXin Li 
914*67e74705SXin Li   Record = new PreprocessingRecord(getSourceManager());
915*67e74705SXin Li   addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
916*67e74705SXin Li }
917