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