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