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