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