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