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