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