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