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 "MacroArgs.h"
     30 #include "clang/Basic/FileManager.h"
     31 #include "clang/Basic/SourceManager.h"
     32 #include "clang/Basic/TargetInfo.h"
     33 #include "clang/Lex/CodeCompletionHandler.h"
     34 #include "clang/Lex/ExternalPreprocessorSource.h"
     35 #include "clang/Lex/HeaderSearch.h"
     36 #include "clang/Lex/LexDiagnostic.h"
     37 #include "clang/Lex/LiteralSupport.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/SmallString.h"
     46 #include "llvm/ADT/STLExtras.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 PPMutationListener::~PPMutationListener() { }
     58 
     59 Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
     60                            DiagnosticsEngine &diags, LangOptions &opts,
     61                            const TargetInfo *target, SourceManager &SM,
     62                            HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
     63                            IdentifierInfoLookup *IILookup, bool OwnsHeaders,
     64                            bool DelayInitialization, bool IncrProcessing)
     65     : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(target),
     66       FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
     67       TheModuleLoader(TheModuleLoader), ExternalSource(0),
     68       Identifiers(opts, IILookup), IncrementalProcessing(IncrProcessing),
     69       CodeComplete(0), CodeCompletionFile(0), CodeCompletionOffset(0),
     70       CodeCompletionReached(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
     71       CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0), Listener(0),
     72       MacroArgCache(0), Record(0), MIChainHead(0), MICache(0) {
     73   OwnsHeaderSearch = OwnsHeaders;
     74 
     75   ScratchBuf = new ScratchBuffer(SourceMgr);
     76   CounterValue = 0; // __COUNTER__ starts at 0.
     77 
     78   // Clear stats.
     79   NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
     80   NumIf = NumElse = NumEndif = 0;
     81   NumEnteredSourceFiles = 0;
     82   NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
     83   NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
     84   MaxIncludeStackDepth = 0;
     85   NumSkipped = 0;
     86 
     87   // Default to discarding comments.
     88   KeepComments = false;
     89   KeepMacroComments = false;
     90   SuppressIncludeNotFoundError = false;
     91 
     92   // Macro expansion is enabled.
     93   DisableMacroExpansion = false;
     94   MacroExpansionInDirectivesOverride = false;
     95   InMacroArgs = false;
     96   InMacroArgPreExpansion = false;
     97   NumCachedTokenLexers = 0;
     98   PragmasEnabled = true;
     99   ParsingIfOrElifDirective = false;
    100   PreprocessedOutput = false;
    101 
    102   CachedLexPos = 0;
    103 
    104   // We haven't read anything from the external source.
    105   ReadMacrosFromExternalSource = false;
    106 
    107   // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
    108   // This gets unpoisoned where it is allowed.
    109   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
    110   SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
    111 
    112   // Initialize the pragma handlers.
    113   PragmaHandlers = new PragmaNamespace(StringRef());
    114   RegisterBuiltinPragmas();
    115 
    116   // Initialize builtin macros like __LINE__ and friends.
    117   RegisterBuiltinMacros();
    118 
    119   if(LangOpts.Borland) {
    120     Ident__exception_info        = getIdentifierInfo("_exception_info");
    121     Ident___exception_info       = getIdentifierInfo("__exception_info");
    122     Ident_GetExceptionInfo       = getIdentifierInfo("GetExceptionInformation");
    123     Ident__exception_code        = getIdentifierInfo("_exception_code");
    124     Ident___exception_code       = getIdentifierInfo("__exception_code");
    125     Ident_GetExceptionCode       = getIdentifierInfo("GetExceptionCode");
    126     Ident__abnormal_termination  = getIdentifierInfo("_abnormal_termination");
    127     Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
    128     Ident_AbnormalTermination    = getIdentifierInfo("AbnormalTermination");
    129   } else {
    130     Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
    131     Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
    132     Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
    133   }
    134 
    135   if (!DelayInitialization) {
    136     assert(Target && "Must provide target information for PP initialization");
    137     Initialize(*Target);
    138   }
    139 }
    140 
    141 Preprocessor::~Preprocessor() {
    142   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
    143 
    144   while (!IncludeMacroStack.empty()) {
    145     delete IncludeMacroStack.back().TheLexer;
    146     delete IncludeMacroStack.back().TheTokenLexer;
    147     IncludeMacroStack.pop_back();
    148   }
    149 
    150   // Free any macro definitions.
    151   for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
    152     I->MI.Destroy();
    153 
    154   // Free any cached macro expanders.
    155   for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
    156     delete TokenLexerCache[i];
    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->getInfo()->isObjectLike())
    310       continue;
    311     const MacroDirective *
    312       MD = I->second->findDirectiveAtLoc(Loc, SourceMgr);
    313     if (!MD)
    314       continue;
    315     if (!MacroDefinitionEquals(MD->getInfo(), Tokens))
    316       continue;
    317     SourceLocation Location = I->second->getInfo()->getDefinitionLoc();
    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 0;
    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, 0, 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.createFileIDForMemBuffer(SB);
    486   assert(!FID.isInvalid() && "Could not create FileID for predefines?");
    487   setPredefinesFileID(FID);
    488 
    489   // Start parsing the predefines.
    490   EnterSourceFile(FID, 0, 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 static void appendCodePoint(unsigned Codepoint,
    504                             llvm::SmallVectorImpl<char> &Str) {
    505   char ResultBuf[4];
    506   char *ResultPtr = ResultBuf;
    507   bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
    508   (void)Res;
    509   assert(Res && "Unexpected conversion failure");
    510   Str.append(ResultBuf, ResultPtr);
    511 }
    512 
    513 static void expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
    514   for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
    515     if (*I != '\\') {
    516       Buf.push_back(*I);
    517       continue;
    518     }
    519 
    520     ++I;
    521     assert(*I == 'u' || *I == 'U');
    522 
    523     unsigned NumHexDigits;
    524     if (*I == 'u')
    525       NumHexDigits = 4;
    526     else
    527       NumHexDigits = 8;
    528 
    529     assert(I + NumHexDigits <= E);
    530 
    531     uint32_t CodePoint = 0;
    532     for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
    533       unsigned Value = llvm::hexDigitValue(*I);
    534       assert(Value != -1U);
    535 
    536       CodePoint <<= 4;
    537       CodePoint += Value;
    538     }
    539 
    540     appendCodePoint(CodePoint, Buf);
    541     --I;
    542   }
    543 }
    544 
    545 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
    546 /// identifier information for the token and install it into the token,
    547 /// updating the token kind accordingly.
    548 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
    549   assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
    550 
    551   // Look up this token, see if it is a macro, or if it is a language keyword.
    552   IdentifierInfo *II;
    553   if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
    554     // No cleaning needed, just use the characters from the lexed buffer.
    555     II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
    556                                      Identifier.getLength()));
    557   } else {
    558     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
    559     SmallString<64> IdentifierBuffer;
    560     StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
    561 
    562     if (Identifier.hasUCN()) {
    563       SmallString<64> UCNIdentifierBuffer;
    564       expandUCNs(UCNIdentifierBuffer, CleanedStr);
    565       II = getIdentifierInfo(UCNIdentifierBuffer);
    566     } else {
    567       II = getIdentifierInfo(CleanedStr);
    568     }
    569   }
    570 
    571   // Update the token info (identifier info and appropriate token kind).
    572   Identifier.setIdentifierInfo(II);
    573   Identifier.setKind(II->getTokenID());
    574 
    575   return II;
    576 }
    577 
    578 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
    579   PoisonReasons[II] = DiagID;
    580 }
    581 
    582 void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
    583   assert(Ident__exception_code && Ident__exception_info);
    584   assert(Ident___exception_code && Ident___exception_info);
    585   Ident__exception_code->setIsPoisoned(Poison);
    586   Ident___exception_code->setIsPoisoned(Poison);
    587   Ident_GetExceptionCode->setIsPoisoned(Poison);
    588   Ident__exception_info->setIsPoisoned(Poison);
    589   Ident___exception_info->setIsPoisoned(Poison);
    590   Ident_GetExceptionInfo->setIsPoisoned(Poison);
    591   Ident__abnormal_termination->setIsPoisoned(Poison);
    592   Ident___abnormal_termination->setIsPoisoned(Poison);
    593   Ident_AbnormalTermination->setIsPoisoned(Poison);
    594 }
    595 
    596 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
    597   assert(Identifier.getIdentifierInfo() &&
    598          "Can't handle identifiers without identifier info!");
    599   llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
    600     PoisonReasons.find(Identifier.getIdentifierInfo());
    601   if(it == PoisonReasons.end())
    602     Diag(Identifier, diag::err_pp_used_poisoned_id);
    603   else
    604     Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
    605 }
    606 
    607 /// HandleIdentifier - This callback is invoked when the lexer reads an
    608 /// identifier.  This callback looks up the identifier in the map and/or
    609 /// potentially macro expands it or turns it into a named token (like 'for').
    610 ///
    611 /// Note that callers of this method are guarded by checking the
    612 /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
    613 /// IdentifierInfo methods that compute these properties will need to change to
    614 /// match.
    615 void Preprocessor::HandleIdentifier(Token &Identifier) {
    616   assert(Identifier.getIdentifierInfo() &&
    617          "Can't handle identifiers without identifier info!");
    618 
    619   IdentifierInfo &II = *Identifier.getIdentifierInfo();
    620 
    621   // If the information about this identifier is out of date, update it from
    622   // the external source.
    623   // We have to treat __VA_ARGS__ in a special way, since it gets
    624   // serialized with isPoisoned = true, but our preprocessor may have
    625   // unpoisoned it if we're defining a C99 macro.
    626   if (II.isOutOfDate()) {
    627     bool CurrentIsPoisoned = false;
    628     if (&II == Ident__VA_ARGS__)
    629       CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
    630 
    631     ExternalSource->updateOutOfDateIdentifier(II);
    632     Identifier.setKind(II.getTokenID());
    633 
    634     if (&II == Ident__VA_ARGS__)
    635       II.setIsPoisoned(CurrentIsPoisoned);
    636   }
    637 
    638   // If this identifier was poisoned, and if it was not produced from a macro
    639   // expansion, emit an error.
    640   if (II.isPoisoned() && CurPPLexer) {
    641     HandlePoisonedIdentifier(Identifier);
    642   }
    643 
    644   // If this is a macro to be expanded, do it.
    645   if (MacroDirective *MD = getMacroDirective(&II)) {
    646     MacroInfo *MI = MD->getInfo();
    647     if (!DisableMacroExpansion) {
    648       if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
    649         if (!HandleMacroExpandedIdentifier(Identifier, MD))
    650           return;
    651       } else {
    652         // C99 6.10.3.4p2 says that a disabled macro may never again be
    653         // expanded, even if it's in a context where it could be expanded in the
    654         // future.
    655         Identifier.setFlag(Token::DisableExpand);
    656         if (MI->isObjectLike() || isNextPPTokenLParen())
    657           Diag(Identifier, diag::pp_disabled_macro_expansion);
    658       }
    659     }
    660   }
    661 
    662   // If this identifier is a keyword in C++11, produce a warning. Don't warn if
    663   // we're not considering macro expansion, since this identifier might be the
    664   // name of a macro.
    665   // FIXME: This warning is disabled in cases where it shouldn't be, like
    666   //   "#define constexpr constexpr", "int constexpr;"
    667   if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) {
    668     Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
    669     // Don't diagnose this keyword again in this translation unit.
    670     II.setIsCXX11CompatKeyword(false);
    671   }
    672 
    673   // C++ 2.11p2: If this is an alternative representation of a C++ operator,
    674   // then we act as if it is the actual operator and not the textual
    675   // representation of it.
    676   if (II.isCPlusPlusOperatorKeyword())
    677     Identifier.setIdentifierInfo(0);
    678 
    679   // If this is an extension token, diagnose its use.
    680   // We avoid diagnosing tokens that originate from macro definitions.
    681   // FIXME: This warning is disabled in cases where it shouldn't be,
    682   // like "#define TY typeof", "TY(1) x".
    683   if (II.isExtensionToken() && !DisableMacroExpansion)
    684     Diag(Identifier, diag::ext_token_used);
    685 
    686   // If this is the 'import' contextual keyword, note
    687   // that the next token indicates a module name.
    688   //
    689   // Note that we do not treat 'import' as a contextual
    690   // keyword when we're in a caching lexer, because caching lexers only get
    691   // used in contexts where import declarations are disallowed.
    692   if (II.isModulesImport() && !InMacroArgs && !DisableMacroExpansion &&
    693       getLangOpts().Modules && CurLexerKind != CLK_CachingLexer) {
    694     ModuleImportLoc = Identifier.getLocation();
    695     ModuleImportPath.clear();
    696     ModuleImportExpectsIdentifier = true;
    697     CurLexerKind = CLK_LexAfterModuleImport;
    698   }
    699 }
    700 
    701 /// \brief Lex a token following the 'import' contextual keyword.
    702 ///
    703 void Preprocessor::LexAfterModuleImport(Token &Result) {
    704   // Figure out what kind of lexer we actually have.
    705   recomputeCurLexerKind();
    706 
    707   // Lex the next token.
    708   Lex(Result);
    709 
    710   // The token sequence
    711   //
    712   //   import identifier (. identifier)*
    713   //
    714   // indicates a module import directive. We already saw the 'import'
    715   // contextual keyword, so now we're looking for the identifiers.
    716   if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
    717     // We expected to see an identifier here, and we did; continue handling
    718     // identifiers.
    719     ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
    720                                               Result.getLocation()));
    721     ModuleImportExpectsIdentifier = false;
    722     CurLexerKind = CLK_LexAfterModuleImport;
    723     return;
    724   }
    725 
    726   // If we're expecting a '.' or a ';', and we got a '.', then wait until we
    727   // see the next identifier.
    728   if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
    729     ModuleImportExpectsIdentifier = true;
    730     CurLexerKind = CLK_LexAfterModuleImport;
    731     return;
    732   }
    733 
    734   // If we have a non-empty module path, load the named module.
    735   if (!ModuleImportPath.empty()) {
    736     Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
    737                                                   ModuleImportPath,
    738                                                   Module::MacrosVisible,
    739                                                   /*IsIncludeDirective=*/false);
    740     if (Callbacks)
    741       Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
    742   }
    743 }
    744 
    745 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
    746                                           const char *DiagnosticTag,
    747                                           bool AllowMacroExpansion) {
    748   // We need at least one string literal.
    749   if (Result.isNot(tok::string_literal)) {
    750     Diag(Result, diag::err_expected_string_literal)
    751       << /*Source='in...'*/0 << DiagnosticTag;
    752     return false;
    753   }
    754 
    755   // Lex string literal tokens, optionally with macro expansion.
    756   SmallVector<Token, 4> StrToks;
    757   do {
    758     StrToks.push_back(Result);
    759 
    760     if (Result.hasUDSuffix())
    761       Diag(Result, diag::err_invalid_string_udl);
    762 
    763     if (AllowMacroExpansion)
    764       Lex(Result);
    765     else
    766       LexUnexpandedToken(Result);
    767   } while (Result.is(tok::string_literal));
    768 
    769   // Concatenate and parse the strings.
    770   StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
    771   assert(Literal.isAscii() && "Didn't allow wide strings in");
    772 
    773   if (Literal.hadError)
    774     return false;
    775 
    776   if (Literal.Pascal) {
    777     Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
    778       << /*Source='in...'*/0 << DiagnosticTag;
    779     return false;
    780   }
    781 
    782   String = Literal.GetString();
    783   return true;
    784 }
    785 
    786 void Preprocessor::addCommentHandler(CommentHandler *Handler) {
    787   assert(Handler && "NULL comment handler");
    788   assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
    789          CommentHandlers.end() && "Comment handler already registered");
    790   CommentHandlers.push_back(Handler);
    791 }
    792 
    793 void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
    794   std::vector<CommentHandler *>::iterator Pos
    795   = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
    796   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
    797   CommentHandlers.erase(Pos);
    798 }
    799 
    800 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
    801   bool AnyPendingTokens = false;
    802   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
    803        HEnd = CommentHandlers.end();
    804        H != HEnd; ++H) {
    805     if ((*H)->HandleComment(*this, Comment))
    806       AnyPendingTokens = true;
    807   }
    808   if (!AnyPendingTokens || getCommentRetentionState())
    809     return false;
    810   Lex(result);
    811   return true;
    812 }
    813 
    814 ModuleLoader::~ModuleLoader() { }
    815 
    816 CommentHandler::~CommentHandler() { }
    817 
    818 CodeCompletionHandler::~CodeCompletionHandler() { }
    819 
    820 void Preprocessor::createPreprocessingRecord() {
    821   if (Record)
    822     return;
    823 
    824   Record = new PreprocessingRecord(getSourceManager());
    825   addPPCallbacks(Record);
    826 }
    827