xref: /llvm-project/clang/lib/Lex/Preprocessor.cpp (revision a9a60f20e6cc80855864b8f559073bc31f34554b)
1 //===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the Preprocessor interface.
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 // Options to support:
14 //   -H       - Print the name of each header file used.
15 //   -d[DNI] - Dump various things.
16 //   -fworking-directory - #line's with preprocessor's working dir.
17 //   -fpreprocessed
18 //   -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
19 //   -W*
20 //   -w
21 //
22 // Messages to emit:
23 //   "Multiple include guards may be useful for:\n"
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/FileSystemStatCache.h"
31 #include "clang/Basic/IdentifierTable.h"
32 #include "clang/Basic/LLVM.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/Module.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Lex/CodeCompletionHandler.h"
39 #include "clang/Lex/ExternalPreprocessorSource.h"
40 #include "clang/Lex/HeaderSearch.h"
41 #include "clang/Lex/LexDiagnostic.h"
42 #include "clang/Lex/Lexer.h"
43 #include "clang/Lex/LiteralSupport.h"
44 #include "clang/Lex/MacroArgs.h"
45 #include "clang/Lex/MacroInfo.h"
46 #include "clang/Lex/ModuleLoader.h"
47 #include "clang/Lex/Pragma.h"
48 #include "clang/Lex/PreprocessingRecord.h"
49 #include "clang/Lex/PreprocessorLexer.h"
50 #include "clang/Lex/PreprocessorOptions.h"
51 #include "clang/Lex/ScratchBuffer.h"
52 #include "clang/Lex/Token.h"
53 #include "clang/Lex/TokenLexer.h"
54 #include "llvm/ADT/APInt.h"
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/ADT/DenseMap.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallString.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/StringRef.h"
61 #include "llvm/ADT/StringSwitch.h"
62 #include "llvm/Support/Capacity.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/MemoryBuffer.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <memory>
69 #include <string>
70 #include <utility>
71 #include <vector>
72 
73 using namespace clang;
74 
75 LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
76 
77 ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
78 
79 Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
80                            DiagnosticsEngine &diags, LangOptions &opts,
81                            SourceManager &SM, HeaderSearch &Headers,
82                            ModuleLoader &TheModuleLoader,
83                            IdentifierInfoLookup *IILookup, bool OwnsHeaders,
84                            TranslationUnitKind TUKind)
85     : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
86       FileMgr(Headers.getFileMgr()), SourceMgr(SM),
87       ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
88       TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
89       // As the language options may have not been loaded yet (when
90       // deserializing an ASTUnit), adding keywords to the identifier table is
91       // deferred to Preprocessor::Initialize().
92       Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
93       TUKind(TUKind), SkipMainFilePreamble(0, true),
94       CurSubmoduleState(&NullSubmoduleState) {
95   OwnsHeaderSearch = OwnsHeaders;
96 
97   // Default to discarding comments.
98   KeepComments = false;
99   KeepMacroComments = false;
100   SuppressIncludeNotFoundError = false;
101 
102   // Macro expansion is enabled.
103   DisableMacroExpansion = false;
104   MacroExpansionInDirectivesOverride = false;
105   InMacroArgs = false;
106   ArgMacro = nullptr;
107   InMacroArgPreExpansion = false;
108   NumCachedTokenLexers = 0;
109   PragmasEnabled = true;
110   ParsingIfOrElifDirective = false;
111   PreprocessedOutput = false;
112 
113   // We haven't read anything from the external source.
114   ReadMacrosFromExternalSource = false;
115 
116   BuiltinInfo = std::make_unique<Builtin::Context>();
117 
118   // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
119   // a macro. They get unpoisoned where it is allowed.
120   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
121   SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
122   (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
123   SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
124 
125   // Initialize the pragma handlers.
126   RegisterBuiltinPragmas();
127 
128   // Initialize builtin macros like __LINE__ and friends.
129   RegisterBuiltinMacros();
130 
131   if(LangOpts.Borland) {
132     Ident__exception_info        = getIdentifierInfo("_exception_info");
133     Ident___exception_info       = getIdentifierInfo("__exception_info");
134     Ident_GetExceptionInfo       = getIdentifierInfo("GetExceptionInformation");
135     Ident__exception_code        = getIdentifierInfo("_exception_code");
136     Ident___exception_code       = getIdentifierInfo("__exception_code");
137     Ident_GetExceptionCode       = getIdentifierInfo("GetExceptionCode");
138     Ident__abnormal_termination  = getIdentifierInfo("_abnormal_termination");
139     Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
140     Ident_AbnormalTermination    = getIdentifierInfo("AbnormalTermination");
141   } else {
142     Ident__exception_info = Ident__exception_code = nullptr;
143     Ident__abnormal_termination = Ident___exception_info = nullptr;
144     Ident___exception_code = Ident___abnormal_termination = nullptr;
145     Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
146     Ident_AbnormalTermination = nullptr;
147   }
148 
149   // If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
150   if (usingPCHWithPragmaHdrStop())
151     SkippingUntilPragmaHdrStop = true;
152 
153   // If using a PCH with a through header, start skipping tokens.
154   if (!this->PPOpts->PCHThroughHeader.empty() &&
155       !this->PPOpts->ImplicitPCHInclude.empty())
156     SkippingUntilPCHThroughHeader = true;
157 
158   if (this->PPOpts->GeneratePreamble)
159     PreambleConditionalStack.startRecording();
160 
161   MaxTokens = LangOpts.MaxTokens;
162 }
163 
164 Preprocessor::~Preprocessor() {
165   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
166 
167   IncludeMacroStack.clear();
168 
169   // Destroy any macro definitions.
170   while (MacroInfoChain *I = MIChainHead) {
171     MIChainHead = I->Next;
172     I->~MacroInfoChain();
173   }
174 
175   // Free any cached macro expanders.
176   // This populates MacroArgCache, so all TokenLexers need to be destroyed
177   // before the code below that frees up the MacroArgCache list.
178   std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
179   CurTokenLexer.reset();
180 
181   // Free any cached MacroArgs.
182   for (MacroArgs *ArgList = MacroArgCache; ArgList;)
183     ArgList = ArgList->deallocate();
184 
185   // Delete the header search info, if we own it.
186   if (OwnsHeaderSearch)
187     delete &HeaderInfo;
188 }
189 
190 void Preprocessor::Initialize(const TargetInfo &Target,
191                               const TargetInfo *AuxTarget) {
192   assert((!this->Target || this->Target == &Target) &&
193          "Invalid override of target information");
194   this->Target = &Target;
195 
196   assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
197          "Invalid override of aux target information.");
198   this->AuxTarget = AuxTarget;
199 
200   // Initialize information about built-ins.
201   BuiltinInfo->InitializeTarget(Target, AuxTarget);
202   HeaderInfo.setTarget(Target);
203 
204   // Populate the identifier table with info about keywords for the current language.
205   Identifiers.AddKeywords(LangOpts);
206 
207   // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.
208   setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
209 }
210 
211 void Preprocessor::InitializeForModelFile() {
212   NumEnteredSourceFiles = 0;
213 
214   // Reset pragmas
215   PragmaHandlersBackup = std::move(PragmaHandlers);
216   PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
217   RegisterBuiltinPragmas();
218 
219   // Reset PredefinesFileID
220   PredefinesFileID = FileID();
221 }
222 
223 void Preprocessor::FinalizeForModelFile() {
224   NumEnteredSourceFiles = 1;
225 
226   PragmaHandlers = std::move(PragmaHandlersBackup);
227 }
228 
229 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
230   llvm::errs() << tok::getTokenName(Tok.getKind());
231 
232   if (!Tok.isAnnotation())
233     llvm::errs() << " '" << getSpelling(Tok) << "'";
234 
235   if (!DumpFlags) return;
236 
237   llvm::errs() << "\t";
238   if (Tok.isAtStartOfLine())
239     llvm::errs() << " [StartOfLine]";
240   if (Tok.hasLeadingSpace())
241     llvm::errs() << " [LeadingSpace]";
242   if (Tok.isExpandDisabled())
243     llvm::errs() << " [ExpandDisabled]";
244   if (Tok.needsCleaning()) {
245     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
246     llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
247                  << "']";
248   }
249 
250   llvm::errs() << "\tLoc=<";
251   DumpLocation(Tok.getLocation());
252   llvm::errs() << ">";
253 }
254 
255 void Preprocessor::DumpLocation(SourceLocation Loc) const {
256   Loc.print(llvm::errs(), SourceMgr);
257 }
258 
259 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
260   llvm::errs() << "MACRO: ";
261   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
262     DumpToken(MI.getReplacementToken(i));
263     llvm::errs() << "  ";
264   }
265   llvm::errs() << "\n";
266 }
267 
268 void Preprocessor::PrintStats() {
269   llvm::errs() << "\n*** Preprocessor Stats:\n";
270   llvm::errs() << NumDirectives << " directives found:\n";
271   llvm::errs() << "  " << NumDefined << " #define.\n";
272   llvm::errs() << "  " << NumUndefined << " #undef.\n";
273   llvm::errs() << "  #include/#include_next/#import:\n";
274   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
275   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
276   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
277   llvm::errs() << "  " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";
278   llvm::errs() << "  " << NumEndif << " #endif.\n";
279   llvm::errs() << "  " << NumPragma << " #pragma.\n";
280   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
281 
282   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
283              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
284              << NumFastMacroExpanded << " on the fast path.\n";
285   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
286              << " token paste (##) operations performed, "
287              << NumFastTokenPaste << " on the fast path.\n";
288 
289   llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
290 
291   llvm::errs() << "\n  BumpPtr: " << BP.getTotalMemory();
292   llvm::errs() << "\n  Macro Expanded Tokens: "
293                << llvm::capacity_in_bytes(MacroExpandedTokens);
294   llvm::errs() << "\n  Predefines Buffer: " << Predefines.capacity();
295   // FIXME: List information for all submodules.
296   llvm::errs() << "\n  Macros: "
297                << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
298   llvm::errs() << "\n  #pragma push_macro Info: "
299                << llvm::capacity_in_bytes(PragmaPushMacroInfo);
300   llvm::errs() << "\n  Poison Reasons: "
301                << llvm::capacity_in_bytes(PoisonReasons);
302   llvm::errs() << "\n  Comment Handlers: "
303                << llvm::capacity_in_bytes(CommentHandlers) << "\n";
304 }
305 
306 Preprocessor::macro_iterator
307 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
308   if (IncludeExternalMacros && ExternalSource &&
309       !ReadMacrosFromExternalSource) {
310     ReadMacrosFromExternalSource = true;
311     ExternalSource->ReadDefinedMacros();
312   }
313 
314   // Make sure we cover all macros in visible modules.
315   for (const ModuleMacro &Macro : ModuleMacros)
316     CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
317 
318   return CurSubmoduleState->Macros.begin();
319 }
320 
321 size_t Preprocessor::getTotalMemory() const {
322   return BP.getTotalMemory()
323     + llvm::capacity_in_bytes(MacroExpandedTokens)
324     + Predefines.capacity() /* Predefines buffer. */
325     // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
326     // and ModuleMacros.
327     + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
328     + llvm::capacity_in_bytes(PragmaPushMacroInfo)
329     + llvm::capacity_in_bytes(PoisonReasons)
330     + llvm::capacity_in_bytes(CommentHandlers);
331 }
332 
333 Preprocessor::macro_iterator
334 Preprocessor::macro_end(bool IncludeExternalMacros) const {
335   if (IncludeExternalMacros && ExternalSource &&
336       !ReadMacrosFromExternalSource) {
337     ReadMacrosFromExternalSource = true;
338     ExternalSource->ReadDefinedMacros();
339   }
340 
341   return CurSubmoduleState->Macros.end();
342 }
343 
344 /// Compares macro tokens with a specified token value sequence.
345 static bool MacroDefinitionEquals(const MacroInfo *MI,
346                                   ArrayRef<TokenValue> Tokens) {
347   return Tokens.size() == MI->getNumTokens() &&
348       std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
349 }
350 
351 StringRef Preprocessor::getLastMacroWithSpelling(
352                                     SourceLocation Loc,
353                                     ArrayRef<TokenValue> Tokens) const {
354   SourceLocation BestLocation;
355   StringRef BestSpelling;
356   for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
357        I != E; ++I) {
358     const MacroDirective::DefInfo
359       Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
360     if (!Def || !Def.getMacroInfo())
361       continue;
362     if (!Def.getMacroInfo()->isObjectLike())
363       continue;
364     if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
365       continue;
366     SourceLocation Location = Def.getLocation();
367     // Choose the macro defined latest.
368     if (BestLocation.isInvalid() ||
369         (Location.isValid() &&
370          SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
371       BestLocation = Location;
372       BestSpelling = I->first->getName();
373     }
374   }
375   return BestSpelling;
376 }
377 
378 void Preprocessor::recomputeCurLexerKind() {
379   if (CurLexer)
380     CurLexerKind = CurLexer->isDependencyDirectivesLexer()
381                        ? CLK_DependencyDirectivesLexer
382                        : CLK_Lexer;
383   else if (CurTokenLexer)
384     CurLexerKind = CLK_TokenLexer;
385   else
386     CurLexerKind = CLK_CachingLexer;
387 }
388 
389 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
390                                           unsigned CompleteLine,
391                                           unsigned CompleteColumn) {
392   assert(File);
393   assert(CompleteLine && CompleteColumn && "Starts from 1:1");
394   assert(!CodeCompletionFile && "Already set");
395 
396   // Load the actual file's contents.
397   Optional<llvm::MemoryBufferRef> Buffer =
398       SourceMgr.getMemoryBufferForFileOrNone(File);
399   if (!Buffer)
400     return true;
401 
402   // Find the byte position of the truncation point.
403   const char *Position = Buffer->getBufferStart();
404   for (unsigned Line = 1; Line < CompleteLine; ++Line) {
405     for (; *Position; ++Position) {
406       if (*Position != '\r' && *Position != '\n')
407         continue;
408 
409       // Eat \r\n or \n\r as a single line.
410       if ((Position[1] == '\r' || Position[1] == '\n') &&
411           Position[0] != Position[1])
412         ++Position;
413       ++Position;
414       break;
415     }
416   }
417 
418   Position += CompleteColumn - 1;
419 
420   // If pointing inside the preamble, adjust the position at the beginning of
421   // the file after the preamble.
422   if (SkipMainFilePreamble.first &&
423       SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
424     if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
425       Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
426   }
427 
428   if (Position > Buffer->getBufferEnd())
429     Position = Buffer->getBufferEnd();
430 
431   CodeCompletionFile = File;
432   CodeCompletionOffset = Position - Buffer->getBufferStart();
433 
434   auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
435       Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
436   char *NewBuf = NewBuffer->getBufferStart();
437   char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
438   *NewPos = '\0';
439   std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
440   SourceMgr.overrideFileContents(File, std::move(NewBuffer));
441 
442   return false;
443 }
444 
445 void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
446                                             bool IsAngled) {
447   setCodeCompletionReached();
448   if (CodeComplete)
449     CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
450 }
451 
452 void Preprocessor::CodeCompleteNaturalLanguage() {
453   setCodeCompletionReached();
454   if (CodeComplete)
455     CodeComplete->CodeCompleteNaturalLanguage();
456 }
457 
458 /// getSpelling - This method is used to get the spelling of a token into a
459 /// SmallVector. Note that the returned StringRef may not point to the
460 /// supplied buffer if a copy can be avoided.
461 StringRef Preprocessor::getSpelling(const Token &Tok,
462                                           SmallVectorImpl<char> &Buffer,
463                                           bool *Invalid) const {
464   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
465   if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
466     // Try the fast path.
467     if (const IdentifierInfo *II = Tok.getIdentifierInfo())
468       return II->getName();
469   }
470 
471   // Resize the buffer if we need to copy into it.
472   if (Tok.needsCleaning())
473     Buffer.resize(Tok.getLength());
474 
475   const char *Ptr = Buffer.data();
476   unsigned Len = getSpelling(Tok, Ptr, Invalid);
477   return StringRef(Ptr, Len);
478 }
479 
480 /// CreateString - Plop the specified string into a scratch buffer and return a
481 /// location for it.  If specified, the source location provides a source
482 /// location for the token.
483 void Preprocessor::CreateString(StringRef Str, Token &Tok,
484                                 SourceLocation ExpansionLocStart,
485                                 SourceLocation ExpansionLocEnd) {
486   Tok.setLength(Str.size());
487 
488   const char *DestPtr;
489   SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
490 
491   if (ExpansionLocStart.isValid())
492     Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
493                                        ExpansionLocEnd, Str.size());
494   Tok.setLocation(Loc);
495 
496   // If this is a raw identifier or a literal token, set the pointer data.
497   if (Tok.is(tok::raw_identifier))
498     Tok.setRawIdentifierData(DestPtr);
499   else if (Tok.isLiteral())
500     Tok.setLiteralData(DestPtr);
501 }
502 
503 SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
504   auto &SM = getSourceManager();
505   SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
506   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
507   bool Invalid = false;
508   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
509   if (Invalid)
510     return SourceLocation();
511 
512   // FIXME: We could consider re-using spelling for tokens we see repeatedly.
513   const char *DestPtr;
514   SourceLocation Spelling =
515       ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
516   return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
517 }
518 
519 Module *Preprocessor::getCurrentModule() {
520   if (!getLangOpts().isCompilingModule())
521     return nullptr;
522 
523   return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
524 }
525 
526 //===----------------------------------------------------------------------===//
527 // Preprocessor Initialization Methods
528 //===----------------------------------------------------------------------===//
529 
530 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
531 /// which implicitly adds the builtin defines etc.
532 void Preprocessor::EnterMainSourceFile() {
533   // We do not allow the preprocessor to reenter the main file.  Doing so will
534   // cause FileID's to accumulate information from both runs (e.g. #line
535   // information) and predefined macros aren't guaranteed to be set properly.
536   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
537   FileID MainFileID = SourceMgr.getMainFileID();
538 
539   // If MainFileID is loaded it means we loaded an AST file, no need to enter
540   // a main file.
541   if (!SourceMgr.isLoadedFileID(MainFileID)) {
542     // Enter the main file source buffer.
543     EnterSourceFile(MainFileID, nullptr, SourceLocation());
544 
545     // If we've been asked to skip bytes in the main file (e.g., as part of a
546     // precompiled preamble), do so now.
547     if (SkipMainFilePreamble.first > 0)
548       CurLexer->SetByteOffset(SkipMainFilePreamble.first,
549                               SkipMainFilePreamble.second);
550 
551     // Tell the header info that the main file was entered.  If the file is later
552     // #imported, it won't be re-entered.
553     if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
554       markIncluded(FE);
555   }
556 
557   // Preprocess Predefines to populate the initial preprocessor state.
558   std::unique_ptr<llvm::MemoryBuffer> SB =
559     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
560   assert(SB && "Cannot create predefined source buffer");
561   FileID FID = SourceMgr.createFileID(std::move(SB));
562   assert(FID.isValid() && "Could not create FileID for predefines?");
563   setPredefinesFileID(FID);
564 
565   // Start parsing the predefines.
566   EnterSourceFile(FID, nullptr, SourceLocation());
567 
568   if (!PPOpts->PCHThroughHeader.empty()) {
569     // Lookup and save the FileID for the through header. If it isn't found
570     // in the search path, it's a fatal error.
571     Optional<FileEntryRef> File = LookupFile(
572         SourceLocation(), PPOpts->PCHThroughHeader,
573         /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
574         /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
575         /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
576         /*IsFrameworkFound=*/nullptr);
577     if (!File) {
578       Diag(SourceLocation(), diag::err_pp_through_header_not_found)
579           << PPOpts->PCHThroughHeader;
580       return;
581     }
582     setPCHThroughHeaderFileID(
583         SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
584   }
585 
586   // Skip tokens from the Predefines and if needed the main file.
587   if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
588       (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
589     SkipTokensWhileUsingPCH();
590 }
591 
592 void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
593   assert(PCHThroughHeaderFileID.isInvalid() &&
594          "PCHThroughHeaderFileID already set!");
595   PCHThroughHeaderFileID = FID;
596 }
597 
598 bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
599   assert(PCHThroughHeaderFileID.isValid() &&
600          "Invalid PCH through header FileID");
601   return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
602 }
603 
604 bool Preprocessor::creatingPCHWithThroughHeader() {
605   return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
606          PCHThroughHeaderFileID.isValid();
607 }
608 
609 bool Preprocessor::usingPCHWithThroughHeader() {
610   return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
611          PCHThroughHeaderFileID.isValid();
612 }
613 
614 bool Preprocessor::creatingPCHWithPragmaHdrStop() {
615   return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
616 }
617 
618 bool Preprocessor::usingPCHWithPragmaHdrStop() {
619   return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
620 }
621 
622 /// Skip tokens until after the #include of the through header or
623 /// until after a #pragma hdrstop is seen. Tokens in the predefines file
624 /// and the main file may be skipped. If the end of the predefines file
625 /// is reached, skipping continues into the main file. If the end of the
626 /// main file is reached, it's a fatal error.
627 void Preprocessor::SkipTokensWhileUsingPCH() {
628   bool ReachedMainFileEOF = false;
629   bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
630   bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
631   Token Tok;
632   while (true) {
633     bool InPredefines =
634         (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
635     switch (CurLexerKind) {
636     case CLK_Lexer:
637       CurLexer->Lex(Tok);
638      break;
639     case CLK_TokenLexer:
640       CurTokenLexer->Lex(Tok);
641       break;
642     case CLK_CachingLexer:
643       CachingLex(Tok);
644       break;
645     case CLK_DependencyDirectivesLexer:
646       CurLexer->LexDependencyDirectiveToken(Tok);
647       break;
648     case CLK_LexAfterModuleImport:
649       LexAfterModuleImport(Tok);
650       break;
651     }
652     if (Tok.is(tok::eof) && !InPredefines) {
653       ReachedMainFileEOF = true;
654       break;
655     }
656     if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
657       break;
658     if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
659       break;
660   }
661   if (ReachedMainFileEOF) {
662     if (UsingPCHThroughHeader)
663       Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
664           << PPOpts->PCHThroughHeader << 1;
665     else if (!PPOpts->PCHWithHdrStopCreate)
666       Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
667   }
668 }
669 
670 void Preprocessor::replayPreambleConditionalStack() {
671   // Restore the conditional stack from the preamble, if there is one.
672   if (PreambleConditionalStack.isReplaying()) {
673     assert(CurPPLexer &&
674            "CurPPLexer is null when calling replayPreambleConditionalStack.");
675     CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
676     PreambleConditionalStack.doneReplaying();
677     if (PreambleConditionalStack.reachedEOFWhileSkipping())
678       SkipExcludedConditionalBlock(
679           PreambleConditionalStack.SkipInfo->HashTokenLoc,
680           PreambleConditionalStack.SkipInfo->IfTokenLoc,
681           PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
682           PreambleConditionalStack.SkipInfo->FoundElse,
683           PreambleConditionalStack.SkipInfo->ElseLoc);
684   }
685 }
686 
687 void Preprocessor::EndSourceFile() {
688   // Notify the client that we reached the end of the source file.
689   if (Callbacks)
690     Callbacks->EndOfMainFile();
691 }
692 
693 //===----------------------------------------------------------------------===//
694 // Lexer Event Handling.
695 //===----------------------------------------------------------------------===//
696 
697 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
698 /// identifier information for the token and install it into the token,
699 /// updating the token kind accordingly.
700 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
701   assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
702 
703   // Look up this token, see if it is a macro, or if it is a language keyword.
704   IdentifierInfo *II;
705   if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
706     // No cleaning needed, just use the characters from the lexed buffer.
707     II = getIdentifierInfo(Identifier.getRawIdentifier());
708   } else {
709     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
710     SmallString<64> IdentifierBuffer;
711     StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
712 
713     if (Identifier.hasUCN()) {
714       SmallString<64> UCNIdentifierBuffer;
715       expandUCNs(UCNIdentifierBuffer, CleanedStr);
716       II = getIdentifierInfo(UCNIdentifierBuffer);
717     } else {
718       II = getIdentifierInfo(CleanedStr);
719     }
720   }
721 
722   // Update the token info (identifier info and appropriate token kind).
723   // FIXME: the raw_identifier may contain leading whitespace which is removed
724   // from the cleaned identifier token. The SourceLocation should be updated to
725   // refer to the non-whitespace character. For instance, the text "\\\nB" (a
726   // line continuation before 'B') is parsed as a single tok::raw_identifier and
727   // is cleaned to tok::identifier "B". After cleaning the token's length is
728   // still 3 and the SourceLocation refers to the location of the backslash.
729   Identifier.setIdentifierInfo(II);
730   Identifier.setKind(II->getTokenID());
731 
732   return II;
733 }
734 
735 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
736   PoisonReasons[II] = DiagID;
737 }
738 
739 void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
740   assert(Ident__exception_code && Ident__exception_info);
741   assert(Ident___exception_code && Ident___exception_info);
742   Ident__exception_code->setIsPoisoned(Poison);
743   Ident___exception_code->setIsPoisoned(Poison);
744   Ident_GetExceptionCode->setIsPoisoned(Poison);
745   Ident__exception_info->setIsPoisoned(Poison);
746   Ident___exception_info->setIsPoisoned(Poison);
747   Ident_GetExceptionInfo->setIsPoisoned(Poison);
748   Ident__abnormal_termination->setIsPoisoned(Poison);
749   Ident___abnormal_termination->setIsPoisoned(Poison);
750   Ident_AbnormalTermination->setIsPoisoned(Poison);
751 }
752 
753 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
754   assert(Identifier.getIdentifierInfo() &&
755          "Can't handle identifiers without identifier info!");
756   llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
757     PoisonReasons.find(Identifier.getIdentifierInfo());
758   if(it == PoisonReasons.end())
759     Diag(Identifier, diag::err_pp_used_poisoned_id);
760   else
761     Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
762 }
763 
764 /// Returns a diagnostic message kind for reporting a future keyword as
765 /// appropriate for the identifier and specified language.
766 static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
767                                           const LangOptions &LangOpts) {
768   assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
769 
770   if (LangOpts.CPlusPlus)
771     return llvm::StringSwitch<diag::kind>(II.getName())
772 #define CXX11_KEYWORD(NAME, FLAGS)                                             \
773         .Case(#NAME, diag::warn_cxx11_keyword)
774 #define CXX20_KEYWORD(NAME, FLAGS)                                             \
775         .Case(#NAME, diag::warn_cxx20_keyword)
776 #include "clang/Basic/TokenKinds.def"
777         // char8_t is not modeled as a CXX20_KEYWORD because it's not
778         // unconditionally enabled in C++20 mode. (It can be disabled
779         // by -fno-char8_t.)
780         .Case("char8_t", diag::warn_cxx20_keyword)
781         ;
782 
783   llvm_unreachable(
784       "Keyword not known to come from a newer Standard or proposed Standard");
785 }
786 
787 void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
788   assert(II.isOutOfDate() && "not out of date");
789   getExternalSource()->updateOutOfDateIdentifier(II);
790 }
791 
792 /// HandleIdentifier - This callback is invoked when the lexer reads an
793 /// identifier.  This callback looks up the identifier in the map and/or
794 /// potentially macro expands it or turns it into a named token (like 'for').
795 ///
796 /// Note that callers of this method are guarded by checking the
797 /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
798 /// IdentifierInfo methods that compute these properties will need to change to
799 /// match.
800 bool Preprocessor::HandleIdentifier(Token &Identifier) {
801   assert(Identifier.getIdentifierInfo() &&
802          "Can't handle identifiers without identifier info!");
803 
804   IdentifierInfo &II = *Identifier.getIdentifierInfo();
805 
806   // If the information about this identifier is out of date, update it from
807   // the external source.
808   // We have to treat __VA_ARGS__ in a special way, since it gets
809   // serialized with isPoisoned = true, but our preprocessor may have
810   // unpoisoned it if we're defining a C99 macro.
811   if (II.isOutOfDate()) {
812     bool CurrentIsPoisoned = false;
813     const bool IsSpecialVariadicMacro =
814         &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
815     if (IsSpecialVariadicMacro)
816       CurrentIsPoisoned = II.isPoisoned();
817 
818     updateOutOfDateIdentifier(II);
819     Identifier.setKind(II.getTokenID());
820 
821     if (IsSpecialVariadicMacro)
822       II.setIsPoisoned(CurrentIsPoisoned);
823   }
824 
825   // If this identifier was poisoned, and if it was not produced from a macro
826   // expansion, emit an error.
827   if (II.isPoisoned() && CurPPLexer) {
828     HandlePoisonedIdentifier(Identifier);
829   }
830 
831   // If this is a macro to be expanded, do it.
832   if (MacroDefinition MD = getMacroDefinition(&II)) {
833     auto *MI = MD.getMacroInfo();
834     assert(MI && "macro definition with no macro info?");
835     if (!DisableMacroExpansion) {
836       if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
837         // C99 6.10.3p10: If the preprocessing token immediately after the
838         // macro name isn't a '(', this macro should not be expanded.
839         if (!MI->isFunctionLike() || isNextPPTokenLParen())
840           return HandleMacroExpandedIdentifier(Identifier, MD);
841       } else {
842         // C99 6.10.3.4p2 says that a disabled macro may never again be
843         // expanded, even if it's in a context where it could be expanded in the
844         // future.
845         Identifier.setFlag(Token::DisableExpand);
846         if (MI->isObjectLike() || isNextPPTokenLParen())
847           Diag(Identifier, diag::pp_disabled_macro_expansion);
848       }
849     }
850   }
851 
852   // If this identifier is a keyword in a newer Standard or proposed Standard,
853   // produce a warning. Don't warn if we're not considering macro expansion,
854   // since this identifier might be the name of a macro.
855   // FIXME: This warning is disabled in cases where it shouldn't be, like
856   //   "#define constexpr constexpr", "int constexpr;"
857   if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
858     Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
859         << II.getName();
860     // Don't diagnose this keyword again in this translation unit.
861     II.setIsFutureCompatKeyword(false);
862   }
863 
864   // If this is an extension token, diagnose its use.
865   // We avoid diagnosing tokens that originate from macro definitions.
866   // FIXME: This warning is disabled in cases where it shouldn't be,
867   // like "#define TY typeof", "TY(1) x".
868   if (II.isExtensionToken() && !DisableMacroExpansion)
869     Diag(Identifier, diag::ext_token_used);
870 
871   // If this is the 'import' contextual keyword following an '@', note
872   // that the next token indicates a module name.
873   //
874   // Note that we do not treat 'import' as a contextual
875   // keyword when we're in a caching lexer, because caching lexers only get
876   // used in contexts where import declarations are disallowed.
877   //
878   // Likewise if this is the C++ Modules TS import keyword.
879   if (((LastTokenWasAt && II.isModulesImport()) ||
880        Identifier.is(tok::kw_import)) &&
881       !InMacroArgs && !DisableMacroExpansion &&
882       (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
883       CurLexerKind != CLK_CachingLexer) {
884     ModuleImportLoc = Identifier.getLocation();
885     ModuleImportPath.clear();
886     ModuleImportExpectsIdentifier = true;
887     CurLexerKind = CLK_LexAfterModuleImport;
888   }
889   return true;
890 }
891 
892 void Preprocessor::Lex(Token &Result) {
893   ++LexLevel;
894 
895   // We loop here until a lex function returns a token; this avoids recursion.
896   bool ReturnedToken;
897   do {
898     switch (CurLexerKind) {
899     case CLK_Lexer:
900       ReturnedToken = CurLexer->Lex(Result);
901       break;
902     case CLK_TokenLexer:
903       ReturnedToken = CurTokenLexer->Lex(Result);
904       break;
905     case CLK_CachingLexer:
906       CachingLex(Result);
907       ReturnedToken = true;
908       break;
909     case CLK_DependencyDirectivesLexer:
910       ReturnedToken = CurLexer->LexDependencyDirectiveToken(Result);
911       break;
912     case CLK_LexAfterModuleImport:
913       ReturnedToken = LexAfterModuleImport(Result);
914       break;
915     }
916   } while (!ReturnedToken);
917 
918   if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
919     return;
920 
921   if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
922     // Remember the identifier before code completion token.
923     setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
924     setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
925     // Set IdenfitierInfo to null to avoid confusing code that handles both
926     // identifiers and completion tokens.
927     Result.setIdentifierInfo(nullptr);
928   }
929 
930   // Update ImportSeqState to track our position within a C++20 import-seq
931   // if this token is being produced as a result of phase 4 of translation.
932   if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
933       !Result.getFlag(Token::IsReinjected)) {
934     switch (Result.getKind()) {
935     case tok::l_paren: case tok::l_square: case tok::l_brace:
936       ImportSeqState.handleOpenBracket();
937       break;
938     case tok::r_paren: case tok::r_square:
939       ImportSeqState.handleCloseBracket();
940       break;
941     case tok::r_brace:
942       ImportSeqState.handleCloseBrace();
943       break;
944     case tok::semi:
945       ImportSeqState.handleSemi();
946       break;
947     case tok::header_name:
948     case tok::annot_header_unit:
949       ImportSeqState.handleHeaderName();
950       break;
951     case tok::kw_export:
952       ImportSeqState.handleExport();
953       break;
954     case tok::identifier:
955       if (Result.getIdentifierInfo()->isModulesImport()) {
956         ImportSeqState.handleImport();
957         if (ImportSeqState.afterImportSeq()) {
958           ModuleImportLoc = Result.getLocation();
959           ModuleImportPath.clear();
960           ModuleImportExpectsIdentifier = true;
961           CurLexerKind = CLK_LexAfterModuleImport;
962         }
963         break;
964       }
965       LLVM_FALLTHROUGH;
966     default:
967       ImportSeqState.handleMisc();
968       break;
969     }
970   }
971 
972   LastTokenWasAt = Result.is(tok::at);
973   --LexLevel;
974 
975   if ((LexLevel == 0 || PreprocessToken) &&
976       !Result.getFlag(Token::IsReinjected)) {
977     if (LexLevel == 0)
978       ++TokenCount;
979     if (OnToken)
980       OnToken(Result);
981   }
982 }
983 
984 /// Lex a header-name token (including one formed from header-name-tokens if
985 /// \p AllowConcatenation is \c true).
986 ///
987 /// \param FilenameTok Filled in with the next token. On success, this will
988 ///        be either a header_name token. On failure, it will be whatever other
989 ///        token was found instead.
990 /// \param AllowMacroExpansion If \c true, allow the header name to be formed
991 ///        by macro expansion (concatenating tokens as necessary if the first
992 ///        token is a '<').
993 /// \return \c true if we reached EOD or EOF while looking for a > token in
994 ///         a concatenated header name and diagnosed it. \c false otherwise.
995 bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
996   // Lex using header-name tokenization rules if tokens are being lexed from
997   // a file. Just grab a token normally if we're in a macro expansion.
998   if (CurPPLexer)
999     CurPPLexer->LexIncludeFilename(FilenameTok);
1000   else
1001     Lex(FilenameTok);
1002 
1003   // This could be a <foo/bar.h> file coming from a macro expansion.  In this
1004   // case, glue the tokens together into an angle_string_literal token.
1005   SmallString<128> FilenameBuffer;
1006   if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
1007     bool StartOfLine = FilenameTok.isAtStartOfLine();
1008     bool LeadingSpace = FilenameTok.hasLeadingSpace();
1009     bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
1010 
1011     SourceLocation Start = FilenameTok.getLocation();
1012     SourceLocation End;
1013     FilenameBuffer.push_back('<');
1014 
1015     // Consume tokens until we find a '>'.
1016     // FIXME: A header-name could be formed starting or ending with an
1017     // alternative token. It's not clear whether that's ill-formed in all
1018     // cases.
1019     while (FilenameTok.isNot(tok::greater)) {
1020       Lex(FilenameTok);
1021       if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
1022         Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
1023         Diag(Start, diag::note_matching) << tok::less;
1024         return true;
1025       }
1026 
1027       End = FilenameTok.getLocation();
1028 
1029       // FIXME: Provide code completion for #includes.
1030       if (FilenameTok.is(tok::code_completion)) {
1031         setCodeCompletionReached();
1032         Lex(FilenameTok);
1033         continue;
1034       }
1035 
1036       // Append the spelling of this token to the buffer. If there was a space
1037       // before it, add it now.
1038       if (FilenameTok.hasLeadingSpace())
1039         FilenameBuffer.push_back(' ');
1040 
1041       // Get the spelling of the token, directly into FilenameBuffer if
1042       // possible.
1043       size_t PreAppendSize = FilenameBuffer.size();
1044       FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
1045 
1046       const char *BufPtr = &FilenameBuffer[PreAppendSize];
1047       unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
1048 
1049       // If the token was spelled somewhere else, copy it into FilenameBuffer.
1050       if (BufPtr != &FilenameBuffer[PreAppendSize])
1051         memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1052 
1053       // Resize FilenameBuffer to the correct size.
1054       if (FilenameTok.getLength() != ActualLen)
1055         FilenameBuffer.resize(PreAppendSize + ActualLen);
1056     }
1057 
1058     FilenameTok.startToken();
1059     FilenameTok.setKind(tok::header_name);
1060     FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
1061     FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
1062     FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
1063     CreateString(FilenameBuffer, FilenameTok, Start, End);
1064   } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
1065     // Convert a string-literal token of the form " h-char-sequence "
1066     // (produced by macro expansion) into a header-name token.
1067     //
1068     // The rules for header-names don't quite match the rules for
1069     // string-literals, but all the places where they differ result in
1070     // undefined behavior, so we can and do treat them the same.
1071     //
1072     // A string-literal with a prefix or suffix is not translated into a
1073     // header-name. This could theoretically be observable via the C++20
1074     // context-sensitive header-name formation rules.
1075     StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
1076     if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
1077       FilenameTok.setKind(tok::header_name);
1078   }
1079 
1080   return false;
1081 }
1082 
1083 /// Collect the tokens of a C++20 pp-import-suffix.
1084 void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {
1085   // FIXME: For error recovery, consider recognizing attribute syntax here
1086   // and terminating / diagnosing a missing semicolon if we find anything
1087   // else? (Can we leave that to the parser?)
1088   unsigned BracketDepth = 0;
1089   while (true) {
1090     Toks.emplace_back();
1091     Lex(Toks.back());
1092 
1093     switch (Toks.back().getKind()) {
1094     case tok::l_paren: case tok::l_square: case tok::l_brace:
1095       ++BracketDepth;
1096       break;
1097 
1098     case tok::r_paren: case tok::r_square: case tok::r_brace:
1099       if (BracketDepth == 0)
1100         return;
1101       --BracketDepth;
1102       break;
1103 
1104     case tok::semi:
1105       if (BracketDepth == 0)
1106         return;
1107     break;
1108 
1109     case tok::eof:
1110       return;
1111 
1112     default:
1113       break;
1114     }
1115   }
1116 }
1117 
1118 
1119 /// Lex a token following the 'import' contextual keyword.
1120 ///
1121 ///     pp-import: [C++20]
1122 ///           import header-name pp-import-suffix[opt] ;
1123 ///           import header-name-tokens pp-import-suffix[opt] ;
1124 /// [ObjC]    @ import module-name ;
1125 /// [Clang]   import module-name ;
1126 ///
1127 ///     header-name-tokens:
1128 ///           string-literal
1129 ///           < [any sequence of preprocessing-tokens other than >] >
1130 ///
1131 ///     module-name:
1132 ///           module-name-qualifier[opt] identifier
1133 ///
1134 ///     module-name-qualifier
1135 ///           module-name-qualifier[opt] identifier .
1136 ///
1137 /// We respond to a pp-import by importing macros from the named module.
1138 bool Preprocessor::LexAfterModuleImport(Token &Result) {
1139   // Figure out what kind of lexer we actually have.
1140   recomputeCurLexerKind();
1141 
1142   // Lex the next token. The header-name lexing rules are used at the start of
1143   // a pp-import.
1144   //
1145   // For now, we only support header-name imports in C++20 mode.
1146   // FIXME: Should we allow this in all language modes that support an import
1147   // declaration as an extension?
1148   if (ModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
1149     if (LexHeaderName(Result))
1150       return true;
1151   } else {
1152     Lex(Result);
1153   }
1154 
1155   // Allocate a holding buffer for a sequence of tokens and introduce it into
1156   // the token stream.
1157   auto EnterTokens = [this](ArrayRef<Token> Toks) {
1158     auto ToksCopy = std::make_unique<Token[]>(Toks.size());
1159     std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
1160     EnterTokenStream(std::move(ToksCopy), Toks.size(),
1161                      /*DisableMacroExpansion*/ true, /*IsReinject*/ false);
1162   };
1163 
1164   // Check for a header-name.
1165   SmallVector<Token, 32> Suffix;
1166   if (Result.is(tok::header_name)) {
1167     // Enter the header-name token into the token stream; a Lex action cannot
1168     // both return a token and cache tokens (doing so would corrupt the token
1169     // cache if the call to Lex comes from CachingLex / PeekAhead).
1170     Suffix.push_back(Result);
1171 
1172     // Consume the pp-import-suffix and expand any macros in it now. We'll add
1173     // it back into the token stream later.
1174     CollectPpImportSuffix(Suffix);
1175     if (Suffix.back().isNot(tok::semi)) {
1176       // This is not a pp-import after all.
1177       EnterTokens(Suffix);
1178       return false;
1179     }
1180 
1181     // C++2a [cpp.module]p1:
1182     //   The ';' preprocessing-token terminating a pp-import shall not have
1183     //   been produced by macro replacement.
1184     SourceLocation SemiLoc = Suffix.back().getLocation();
1185     if (SemiLoc.isMacroID())
1186       Diag(SemiLoc, diag::err_header_import_semi_in_macro);
1187 
1188     // Reconstitute the import token.
1189     Token ImportTok;
1190     ImportTok.startToken();
1191     ImportTok.setKind(tok::kw_import);
1192     ImportTok.setLocation(ModuleImportLoc);
1193     ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
1194     ImportTok.setLength(6);
1195 
1196     auto Action = HandleHeaderIncludeOrImport(
1197         /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
1198     switch (Action.Kind) {
1199     case ImportAction::None:
1200       break;
1201 
1202     case ImportAction::ModuleBegin:
1203       // Let the parser know we're textually entering the module.
1204       Suffix.emplace_back();
1205       Suffix.back().startToken();
1206       Suffix.back().setKind(tok::annot_module_begin);
1207       Suffix.back().setLocation(SemiLoc);
1208       Suffix.back().setAnnotationEndLoc(SemiLoc);
1209       Suffix.back().setAnnotationValue(Action.ModuleForHeader);
1210       LLVM_FALLTHROUGH;
1211 
1212     case ImportAction::ModuleImport:
1213     case ImportAction::SkippedModuleImport:
1214       // We chose to import (or textually enter) the file. Convert the
1215       // header-name token into a header unit annotation token.
1216       Suffix[0].setKind(tok::annot_header_unit);
1217       Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
1218       Suffix[0].setAnnotationValue(Action.ModuleForHeader);
1219       // FIXME: Call the moduleImport callback?
1220       break;
1221     case ImportAction::Failure:
1222       assert(TheModuleLoader.HadFatalFailure &&
1223              "This should be an early exit only to a fatal error");
1224       Result.setKind(tok::eof);
1225       CurLexer->cutOffLexing();
1226       EnterTokens(Suffix);
1227       return true;
1228     }
1229 
1230     EnterTokens(Suffix);
1231     return false;
1232   }
1233 
1234   // The token sequence
1235   //
1236   //   import identifier (. identifier)*
1237   //
1238   // indicates a module import directive. We already saw the 'import'
1239   // contextual keyword, so now we're looking for the identifiers.
1240   if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
1241     // We expected to see an identifier here, and we did; continue handling
1242     // identifiers.
1243     ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
1244                                               Result.getLocation()));
1245     ModuleImportExpectsIdentifier = false;
1246     CurLexerKind = CLK_LexAfterModuleImport;
1247     return true;
1248   }
1249 
1250   // If we're expecting a '.' or a ';', and we got a '.', then wait until we
1251   // see the next identifier. (We can also see a '[[' that begins an
1252   // attribute-specifier-seq here under the C++ Modules TS.)
1253   if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
1254     ModuleImportExpectsIdentifier = true;
1255     CurLexerKind = CLK_LexAfterModuleImport;
1256     return true;
1257   }
1258 
1259   // If we didn't recognize a module name at all, this is not a (valid) import.
1260   if (ModuleImportPath.empty() || Result.is(tok::eof))
1261     return true;
1262 
1263   // Consume the pp-import-suffix and expand any macros in it now, if we're not
1264   // at the semicolon already.
1265   SourceLocation SemiLoc = Result.getLocation();
1266   if (Result.isNot(tok::semi)) {
1267     Suffix.push_back(Result);
1268     CollectPpImportSuffix(Suffix);
1269     if (Suffix.back().isNot(tok::semi)) {
1270       // This is not an import after all.
1271       EnterTokens(Suffix);
1272       return false;
1273     }
1274     SemiLoc = Suffix.back().getLocation();
1275   }
1276 
1277   // Under the Modules TS, the dot is just part of the module name, and not
1278   // a real hierarchy separator. Flatten such module names now.
1279   //
1280   // FIXME: Is this the right level to be performing this transformation?
1281   std::string FlatModuleName;
1282   if (getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) {
1283     for (auto &Piece : ModuleImportPath) {
1284       if (!FlatModuleName.empty())
1285         FlatModuleName += ".";
1286       FlatModuleName += Piece.first->getName();
1287     }
1288     SourceLocation FirstPathLoc = ModuleImportPath[0].second;
1289     ModuleImportPath.clear();
1290     ModuleImportPath.push_back(
1291         std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
1292   }
1293 
1294   Module *Imported = nullptr;
1295   if (getLangOpts().Modules) {
1296     Imported = TheModuleLoader.loadModule(ModuleImportLoc,
1297                                           ModuleImportPath,
1298                                           Module::Hidden,
1299                                           /*IsInclusionDirective=*/false);
1300     if (Imported)
1301       makeModuleVisible(Imported, SemiLoc);
1302   }
1303   if (Callbacks)
1304     Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
1305 
1306   if (!Suffix.empty()) {
1307     EnterTokens(Suffix);
1308     return false;
1309   }
1310   return true;
1311 }
1312 
1313 void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
1314   CurSubmoduleState->VisibleModules.setVisible(
1315       M, Loc, [](Module *) {},
1316       [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
1317         // FIXME: Include the path in the diagnostic.
1318         // FIXME: Include the import location for the conflicting module.
1319         Diag(ModuleImportLoc, diag::warn_module_conflict)
1320             << Path[0]->getFullModuleName()
1321             << Conflict->getFullModuleName()
1322             << Message;
1323       });
1324 
1325   // Add this module to the imports list of the currently-built submodule.
1326   if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
1327     BuildingSubmoduleStack.back().M->Imports.insert(M);
1328 }
1329 
1330 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
1331                                           const char *DiagnosticTag,
1332                                           bool AllowMacroExpansion) {
1333   // We need at least one string literal.
1334   if (Result.isNot(tok::string_literal)) {
1335     Diag(Result, diag::err_expected_string_literal)
1336       << /*Source='in...'*/0 << DiagnosticTag;
1337     return false;
1338   }
1339 
1340   // Lex string literal tokens, optionally with macro expansion.
1341   SmallVector<Token, 4> StrToks;
1342   do {
1343     StrToks.push_back(Result);
1344 
1345     if (Result.hasUDSuffix())
1346       Diag(Result, diag::err_invalid_string_udl);
1347 
1348     if (AllowMacroExpansion)
1349       Lex(Result);
1350     else
1351       LexUnexpandedToken(Result);
1352   } while (Result.is(tok::string_literal));
1353 
1354   // Concatenate and parse the strings.
1355   StringLiteralParser Literal(StrToks, *this);
1356   assert(Literal.isOrdinary() && "Didn't allow wide strings in");
1357 
1358   if (Literal.hadError)
1359     return false;
1360 
1361   if (Literal.Pascal) {
1362     Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1363       << /*Source='in...'*/0 << DiagnosticTag;
1364     return false;
1365   }
1366 
1367   String = std::string(Literal.GetString());
1368   return true;
1369 }
1370 
1371 bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
1372   assert(Tok.is(tok::numeric_constant));
1373   SmallString<8> IntegerBuffer;
1374   bool NumberInvalid = false;
1375   StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1376   if (NumberInvalid)
1377     return false;
1378   NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
1379                                getLangOpts(), getTargetInfo(),
1380                                getDiagnostics());
1381   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1382     return false;
1383   llvm::APInt APVal(64, 0);
1384   if (Literal.GetIntegerValue(APVal))
1385     return false;
1386   Lex(Tok);
1387   Value = APVal.getLimitedValue();
1388   return true;
1389 }
1390 
1391 void Preprocessor::addCommentHandler(CommentHandler *Handler) {
1392   assert(Handler && "NULL comment handler");
1393   assert(!llvm::is_contained(CommentHandlers, Handler) &&
1394          "Comment handler already registered");
1395   CommentHandlers.push_back(Handler);
1396 }
1397 
1398 void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
1399   std::vector<CommentHandler *>::iterator Pos =
1400       llvm::find(CommentHandlers, Handler);
1401   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
1402   CommentHandlers.erase(Pos);
1403 }
1404 
1405 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
1406   bool AnyPendingTokens = false;
1407   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
1408        HEnd = CommentHandlers.end();
1409        H != HEnd; ++H) {
1410     if ((*H)->HandleComment(*this, Comment))
1411       AnyPendingTokens = true;
1412   }
1413   if (!AnyPendingTokens || getCommentRetentionState())
1414     return false;
1415   Lex(result);
1416   return true;
1417 }
1418 
1419 void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
1420   const MacroAnnotations &A =
1421       getMacroAnnotations(Identifier.getIdentifierInfo());
1422   assert(A.DeprecationInfo &&
1423          "Macro deprecation warning without recorded annotation!");
1424   const MacroAnnotationInfo &Info = *A.DeprecationInfo;
1425   if (Info.Message.empty())
1426     Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1427         << Identifier.getIdentifierInfo() << 0;
1428   else
1429     Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1430         << Identifier.getIdentifierInfo() << 1 << Info.Message;
1431   Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
1432 }
1433 
1434 void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
1435   const MacroAnnotations &A =
1436       getMacroAnnotations(Identifier.getIdentifierInfo());
1437   assert(A.RestrictExpansionInfo &&
1438          "Macro restricted expansion warning without recorded annotation!");
1439   const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
1440   if (Info.Message.empty())
1441     Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1442         << Identifier.getIdentifierInfo() << 0;
1443   else
1444     Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1445         << Identifier.getIdentifierInfo() << 1 << Info.Message;
1446   Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
1447 }
1448 
1449 void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
1450                                          bool IsUndef) const {
1451   const MacroAnnotations &A =
1452       getMacroAnnotations(Identifier.getIdentifierInfo());
1453   assert(A.FinalAnnotationLoc &&
1454          "Final macro warning without recorded annotation!");
1455 
1456   Diag(Identifier, diag::warn_pragma_final_macro)
1457       << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
1458   Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
1459 }
1460 
1461 ModuleLoader::~ModuleLoader() = default;
1462 
1463 CommentHandler::~CommentHandler() = default;
1464 
1465 EmptylineHandler::~EmptylineHandler() = default;
1466 
1467 CodeCompletionHandler::~CodeCompletionHandler() = default;
1468 
1469 void Preprocessor::createPreprocessingRecord() {
1470   if (Record)
1471     return;
1472 
1473   Record = new PreprocessingRecord(getSourceManager());
1474   addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
1475 }
1476