Preprocessor.cpp revision e434ec71fccfe078906403affd641f709702d598
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/SmallVector.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 173void Preprocessor::setPTHManager(PTHManager* pm) { 174 PTH.reset(pm); 175 FileMgr.addStatCache(PTH->createStatCache()); 176} 177 178void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 179 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" 180 << getSpelling(Tok) << "'"; 181 182 if (!DumpFlags) return; 183 184 llvm::errs() << "\t"; 185 if (Tok.isAtStartOfLine()) 186 llvm::errs() << " [StartOfLine]"; 187 if (Tok.hasLeadingSpace()) 188 llvm::errs() << " [LeadingSpace]"; 189 if (Tok.isExpandDisabled()) 190 llvm::errs() << " [ExpandDisabled]"; 191 if (Tok.needsCleaning()) { 192 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 193 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) 194 << "']"; 195 } 196 197 llvm::errs() << "\tLoc=<"; 198 DumpLocation(Tok.getLocation()); 199 llvm::errs() << ">"; 200} 201 202void Preprocessor::DumpLocation(SourceLocation Loc) const { 203 Loc.dump(SourceMgr); 204} 205 206void Preprocessor::DumpMacro(const MacroInfo &MI) const { 207 llvm::errs() << "MACRO: "; 208 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 209 DumpToken(MI.getReplacementToken(i)); 210 llvm::errs() << " "; 211 } 212 llvm::errs() << "\n"; 213} 214 215void Preprocessor::PrintStats() { 216 llvm::errs() << "\n*** Preprocessor Stats:\n"; 217 llvm::errs() << NumDirectives << " directives found:\n"; 218 llvm::errs() << " " << NumDefined << " #define.\n"; 219 llvm::errs() << " " << NumUndefined << " #undef.\n"; 220 llvm::errs() << " #include/#include_next/#import:\n"; 221 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n"; 222 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n"; 223 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 224 llvm::errs() << " " << NumElse << " #else/#elif.\n"; 225 llvm::errs() << " " << NumEndif << " #endif.\n"; 226 llvm::errs() << " " << NumPragma << " #pragma.\n"; 227 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 228 229 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 230 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 231 << NumFastMacroExpanded << " on the fast path.\n"; 232 llvm::errs() << (NumFastTokenPaste+NumTokenPaste) 233 << " token paste (##) operations performed, " 234 << NumFastTokenPaste << " on the fast path.\n"; 235} 236 237Preprocessor::macro_iterator 238Preprocessor::macro_begin(bool IncludeExternalMacros) const { 239 if (IncludeExternalMacros && ExternalSource && 240 !ReadMacrosFromExternalSource) { 241 ReadMacrosFromExternalSource = true; 242 ExternalSource->ReadDefinedMacros(); 243 } 244 245 return Macros.begin(); 246} 247 248size_t Preprocessor::getTotalMemory() const { 249 return BP.getTotalMemory() 250 + llvm::capacity_in_bytes(MacroExpandedTokens) 251 + Predefines.capacity() /* Predefines buffer. */ 252 + llvm::capacity_in_bytes(Macros) 253 + llvm::capacity_in_bytes(PragmaPushMacroInfo) 254 + llvm::capacity_in_bytes(PoisonReasons) 255 + llvm::capacity_in_bytes(CommentHandlers); 256} 257 258Preprocessor::macro_iterator 259Preprocessor::macro_end(bool IncludeExternalMacros) const { 260 if (IncludeExternalMacros && ExternalSource && 261 !ReadMacrosFromExternalSource) { 262 ReadMacrosFromExternalSource = true; 263 ExternalSource->ReadDefinedMacros(); 264 } 265 266 return Macros.end(); 267} 268 269void Preprocessor::recomputeCurLexerKind() { 270 if (CurLexer) 271 CurLexerKind = CLK_Lexer; 272 else if (CurPTHLexer) 273 CurLexerKind = CLK_PTHLexer; 274 else if (CurTokenLexer) 275 CurLexerKind = CLK_TokenLexer; 276 else 277 CurLexerKind = CLK_CachingLexer; 278} 279 280bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, 281 unsigned CompleteLine, 282 unsigned CompleteColumn) { 283 assert(File); 284 assert(CompleteLine && CompleteColumn && "Starts from 1:1"); 285 assert(!CodeCompletionFile && "Already set"); 286 287 using llvm::MemoryBuffer; 288 289 // Load the actual file's contents. 290 bool Invalid = false; 291 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid); 292 if (Invalid) 293 return true; 294 295 // Find the byte position of the truncation point. 296 const char *Position = Buffer->getBufferStart(); 297 for (unsigned Line = 1; Line < CompleteLine; ++Line) { 298 for (; *Position; ++Position) { 299 if (*Position != '\r' && *Position != '\n') 300 continue; 301 302 // Eat \r\n or \n\r as a single line. 303 if ((Position[1] == '\r' || Position[1] == '\n') && 304 Position[0] != Position[1]) 305 ++Position; 306 ++Position; 307 break; 308 } 309 } 310 311 Position += CompleteColumn - 1; 312 313 // Insert '\0' at the code-completion point. 314 if (Position < Buffer->getBufferEnd()) { 315 CodeCompletionFile = File; 316 CodeCompletionOffset = Position - Buffer->getBufferStart(); 317 318 MemoryBuffer *NewBuffer = 319 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1, 320 Buffer->getBufferIdentifier()); 321 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart()); 322 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf); 323 *NewPos = '\0'; 324 std::copy(Position, Buffer->getBufferEnd(), NewPos+1); 325 SourceMgr.overrideFileContents(File, NewBuffer); 326 } 327 328 return false; 329} 330 331void Preprocessor::CodeCompleteNaturalLanguage() { 332 if (CodeComplete) 333 CodeComplete->CodeCompleteNaturalLanguage(); 334 setCodeCompletionReached(); 335} 336 337/// getSpelling - This method is used to get the spelling of a token into a 338/// SmallVector. Note that the returned StringRef may not point to the 339/// supplied buffer if a copy can be avoided. 340StringRef Preprocessor::getSpelling(const Token &Tok, 341 SmallVectorImpl<char> &Buffer, 342 bool *Invalid) const { 343 // NOTE: this has to be checked *before* testing for an IdentifierInfo. 344 if (Tok.isNot(tok::raw_identifier)) { 345 // Try the fast path. 346 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) 347 return II->getName(); 348 } 349 350 // Resize the buffer if we need to copy into it. 351 if (Tok.needsCleaning()) 352 Buffer.resize(Tok.getLength()); 353 354 const char *Ptr = Buffer.data(); 355 unsigned Len = getSpelling(Tok, Ptr, Invalid); 356 return StringRef(Ptr, Len); 357} 358 359/// CreateString - Plop the specified string into a scratch buffer and return a 360/// location for it. If specified, the source location provides a source 361/// location for the token. 362void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok, 363 SourceLocation ExpansionLocStart, 364 SourceLocation ExpansionLocEnd) { 365 Tok.setLength(Len); 366 367 const char *DestPtr; 368 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr); 369 370 if (ExpansionLocStart.isValid()) 371 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart, 372 ExpansionLocEnd, Len); 373 Tok.setLocation(Loc); 374 375 // If this is a raw identifier or a literal token, set the pointer data. 376 if (Tok.is(tok::raw_identifier)) 377 Tok.setRawIdentifierData(DestPtr); 378 else if (Tok.isLiteral()) 379 Tok.setLiteralData(DestPtr); 380} 381 382Module *Preprocessor::getCurrentModule() { 383 if (getLangOptions().CurrentModule.empty()) 384 return 0; 385 386 return getHeaderSearchInfo().lookupModule(getLangOptions().CurrentModule); 387} 388 389//===----------------------------------------------------------------------===// 390// Preprocessor Initialization Methods 391//===----------------------------------------------------------------------===// 392 393 394/// EnterMainSourceFile - Enter the specified FileID as the main source file, 395/// which implicitly adds the builtin defines etc. 396void Preprocessor::EnterMainSourceFile() { 397 // We do not allow the preprocessor to reenter the main file. Doing so will 398 // cause FileID's to accumulate information from both runs (e.g. #line 399 // information) and predefined macros aren't guaranteed to be set properly. 400 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); 401 FileID MainFileID = SourceMgr.getMainFileID(); 402 403 // If MainFileID is loaded it means we loaded an AST file, no need to enter 404 // a main file. 405 if (!SourceMgr.isLoadedFileID(MainFileID)) { 406 // Enter the main file source buffer. 407 EnterSourceFile(MainFileID, 0, SourceLocation()); 408 409 // If we've been asked to skip bytes in the main file (e.g., as part of a 410 // precompiled preamble), do so now. 411 if (SkipMainFilePreamble.first > 0) 412 CurLexer->SkipBytes(SkipMainFilePreamble.first, 413 SkipMainFilePreamble.second); 414 415 // Tell the header info that the main file was entered. If the file is later 416 // #imported, it won't be re-entered. 417 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) 418 HeaderInfo.IncrementIncludeCount(FE); 419 } 420 421 // Preprocess Predefines to populate the initial preprocessor state. 422 llvm::MemoryBuffer *SB = 423 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>"); 424 assert(SB && "Cannot create predefined source buffer"); 425 FileID FID = SourceMgr.createFileIDForMemBuffer(SB); 426 assert(!FID.isInvalid() && "Could not create FileID for predefines?"); 427 428 // Start parsing the predefines. 429 EnterSourceFile(FID, 0, SourceLocation()); 430} 431 432void Preprocessor::EndSourceFile() { 433 // Notify the client that we reached the end of the source file. 434 if (Callbacks) 435 Callbacks->EndOfMainFile(); 436} 437 438//===----------------------------------------------------------------------===// 439// Lexer Event Handling. 440//===----------------------------------------------------------------------===// 441 442/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the 443/// identifier information for the token and install it into the token, 444/// updating the token kind accordingly. 445IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const { 446 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!"); 447 448 // Look up this token, see if it is a macro, or if it is a language keyword. 449 IdentifierInfo *II; 450 if (!Identifier.needsCleaning()) { 451 // No cleaning needed, just use the characters from the lexed buffer. 452 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(), 453 Identifier.getLength())); 454 } else { 455 // Cleaning needed, alloca a buffer, clean into it, then use the buffer. 456 llvm::SmallString<64> IdentifierBuffer; 457 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer); 458 II = getIdentifierInfo(CleanedStr); 459 } 460 461 // Update the token info (identifier info and appropriate token kind). 462 Identifier.setIdentifierInfo(II); 463 Identifier.setKind(II->getTokenID()); 464 465 return II; 466} 467 468void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { 469 PoisonReasons[II] = DiagID; 470} 471 472void Preprocessor::PoisonSEHIdentifiers(bool Poison) { 473 assert(Ident__exception_code && Ident__exception_info); 474 assert(Ident___exception_code && Ident___exception_info); 475 Ident__exception_code->setIsPoisoned(Poison); 476 Ident___exception_code->setIsPoisoned(Poison); 477 Ident_GetExceptionCode->setIsPoisoned(Poison); 478 Ident__exception_info->setIsPoisoned(Poison); 479 Ident___exception_info->setIsPoisoned(Poison); 480 Ident_GetExceptionInfo->setIsPoisoned(Poison); 481 Ident__abnormal_termination->setIsPoisoned(Poison); 482 Ident___abnormal_termination->setIsPoisoned(Poison); 483 Ident_AbnormalTermination->setIsPoisoned(Poison); 484} 485 486void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { 487 assert(Identifier.getIdentifierInfo() && 488 "Can't handle identifiers without identifier info!"); 489 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = 490 PoisonReasons.find(Identifier.getIdentifierInfo()); 491 if(it == PoisonReasons.end()) 492 Diag(Identifier, diag::err_pp_used_poisoned_id); 493 else 494 Diag(Identifier,it->second) << Identifier.getIdentifierInfo(); 495} 496 497/// HandleIdentifier - This callback is invoked when the lexer reads an 498/// identifier. This callback looks up the identifier in the map and/or 499/// potentially macro expands it or turns it into a named token (like 'for'). 500/// 501/// Note that callers of this method are guarded by checking the 502/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the 503/// IdentifierInfo methods that compute these properties will need to change to 504/// match. 505void Preprocessor::HandleIdentifier(Token &Identifier) { 506 assert(Identifier.getIdentifierInfo() && 507 "Can't handle identifiers without identifier info!"); 508 509 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 510 511 // If the information about this identifier is out of date, update it from 512 // the external source. 513 if (II.isOutOfDate()) { 514 ExternalSource->updateOutOfDateIdentifier(II); 515 Identifier.setKind(II.getTokenID()); 516 } 517 518 // If this identifier was poisoned, and if it was not produced from a macro 519 // expansion, emit an error. 520 if (II.isPoisoned() && CurPPLexer) { 521 HandlePoisonedIdentifier(Identifier); 522 } 523 524 // If this is a macro to be expanded, do it. 525 if (MacroInfo *MI = getMacroInfo(&II)) { 526 if (!DisableMacroExpansion) { 527 if (Identifier.isExpandDisabled()) { 528 Diag(Identifier, diag::pp_disabled_macro_expansion); 529 } else if (MI->isEnabled()) { 530 if (!HandleMacroExpandedIdentifier(Identifier, MI)) 531 return; 532 } else { 533 // C99 6.10.3.4p2 says that a disabled macro may never again be 534 // expanded, even if it's in a context where it could be expanded in the 535 // future. 536 Identifier.setFlag(Token::DisableExpand); 537 Diag(Identifier, diag::pp_disabled_macro_expansion); 538 } 539 } 540 } 541 542 // If this identifier is a keyword in C++11, produce a warning. Don't warn if 543 // we're not considering macro expansion, since this identifier might be the 544 // name of a macro. 545 // FIXME: This warning is disabled in cases where it shouldn't be, like 546 // "#define constexpr constexpr", "int constexpr;" 547 if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) { 548 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName(); 549 // Don't diagnose this keyword again in this translation unit. 550 II.setIsCXX11CompatKeyword(false); 551 } 552 553 // C++ 2.11p2: If this is an alternative representation of a C++ operator, 554 // then we act as if it is the actual operator and not the textual 555 // representation of it. 556 if (II.isCPlusPlusOperatorKeyword()) 557 Identifier.setIdentifierInfo(0); 558 559 // If this is an extension token, diagnose its use. 560 // We avoid diagnosing tokens that originate from macro definitions. 561 // FIXME: This warning is disabled in cases where it shouldn't be, 562 // like "#define TY typeof", "TY(1) x". 563 if (II.isExtensionToken() && !DisableMacroExpansion) 564 Diag(Identifier, diag::ext_token_used); 565 566 // If this is the 'import' contextual keyword, note that the next token 567 // indicates a module name. 568 // 569 // Note that we do not treat 'import' as a contextual keyword when we're 570 // in a caching lexer, because caching lexers only get used in contexts where 571 // import declarations are disallowed. 572 if (II.isImport() && !InMacroArgs && !DisableMacroExpansion && 573 getLangOptions().Modules && CurLexerKind != CLK_CachingLexer) { 574 ModuleImportLoc = Identifier.getLocation(); 575 ModuleImportPath.clear(); 576 ModuleImportExpectsIdentifier = true; 577 CurLexerKind = CLK_LexAfterModuleImport; 578 } 579} 580 581/// \brief Lex a token following the 'import' contextual keyword. 582/// 583void Preprocessor::LexAfterModuleImport(Token &Result) { 584 // Figure out what kind of lexer we actually have. 585 recomputeCurLexerKind(); 586 587 // Lex the next token. 588 Lex(Result); 589 590 // The token sequence 591 // 592 // import identifier (. identifier)* 593 // 594 // indicates a module import directive. We already saw the 'import' 595 // contextual keyword, so now we're looking for the identifiers. 596 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { 597 // We expected to see an identifier here, and we did; continue handling 598 // identifiers. 599 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(), 600 Result.getLocation())); 601 ModuleImportExpectsIdentifier = false; 602 CurLexerKind = CLK_LexAfterModuleImport; 603 return; 604 } 605 606 // If we're expecting a '.' or a ';', and we got a '.', then wait until we 607 // see the next identifier. 608 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) { 609 ModuleImportExpectsIdentifier = true; 610 CurLexerKind = CLK_LexAfterModuleImport; 611 return; 612 } 613 614 // If we have a non-empty module path, load the named module. 615 if (!ModuleImportPath.empty()) 616 (void)TheModuleLoader.loadModule(ModuleImportLoc, ModuleImportPath, 617 Module::MacrosVisible, 618 /*IsIncludeDirective=*/false); 619} 620 621void Preprocessor::AddCommentHandler(CommentHandler *Handler) { 622 assert(Handler && "NULL comment handler"); 623 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) == 624 CommentHandlers.end() && "Comment handler already registered"); 625 CommentHandlers.push_back(Handler); 626} 627 628void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) { 629 std::vector<CommentHandler *>::iterator Pos 630 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler); 631 assert(Pos != CommentHandlers.end() && "Comment handler not registered"); 632 CommentHandlers.erase(Pos); 633} 634 635bool Preprocessor::HandleComment(Token &result, SourceRange Comment) { 636 bool AnyPendingTokens = false; 637 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(), 638 HEnd = CommentHandlers.end(); 639 H != HEnd; ++H) { 640 if ((*H)->HandleComment(*this, Comment)) 641 AnyPendingTokens = true; 642 } 643 if (!AnyPendingTokens || getCommentRetentionState()) 644 return false; 645 Lex(result); 646 return true; 647} 648 649ModuleLoader::~ModuleLoader() { } 650 651CommentHandler::~CommentHandler() { } 652 653CodeCompletionHandler::~CodeCompletionHandler() { } 654 655void Preprocessor::createPreprocessingRecord( 656 bool IncludeNestedMacroExpansions) { 657 if (Record) 658 return; 659 660 Record = new PreprocessingRecord(getSourceManager(), 661 IncludeNestedMacroExpansions); 662 addPPCallbacks(Record); 663} 664