1 //===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Preprocessor interface. 10 // 11 //===----------------------------------------------------------------------===// 12 // 13 // Options to support: 14 // -H - Print the name of each header file used. 15 // -d[DNI] - Dump various things. 16 // -fworking-directory - #line's with preprocessor's working dir. 17 // -fpreprocessed 18 // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD 19 // -W* 20 // -w 21 // 22 // Messages to emit: 23 // "Multiple include guards may be useful for:\n" 24 // 25 //===----------------------------------------------------------------------===// 26 27 #include "clang/Lex/Preprocessor.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/FileManager.h" 30 #include "clang/Basic/FileSystemStatCache.h" 31 #include "clang/Basic/IdentifierTable.h" 32 #include "clang/Basic/LLVM.h" 33 #include "clang/Basic/LangOptions.h" 34 #include "clang/Basic/Module.h" 35 #include "clang/Basic/SourceLocation.h" 36 #include "clang/Basic/SourceManager.h" 37 #include "clang/Basic/TargetInfo.h" 38 #include "clang/Lex/CodeCompletionHandler.h" 39 #include "clang/Lex/ExternalPreprocessorSource.h" 40 #include "clang/Lex/HeaderSearch.h" 41 #include "clang/Lex/LexDiagnostic.h" 42 #include "clang/Lex/Lexer.h" 43 #include "clang/Lex/LiteralSupport.h" 44 #include "clang/Lex/MacroArgs.h" 45 #include "clang/Lex/MacroInfo.h" 46 #include "clang/Lex/ModuleLoader.h" 47 #include "clang/Lex/Pragma.h" 48 #include "clang/Lex/PreprocessingRecord.h" 49 #include "clang/Lex/PreprocessorLexer.h" 50 #include "clang/Lex/PreprocessorOptions.h" 51 #include "clang/Lex/ScratchBuffer.h" 52 #include "clang/Lex/Token.h" 53 #include "clang/Lex/TokenLexer.h" 54 #include "llvm/ADT/APInt.h" 55 #include "llvm/ADT/ArrayRef.h" 56 #include "llvm/ADT/DenseMap.h" 57 #include "llvm/ADT/STLExtras.h" 58 #include "llvm/ADT/SmallString.h" 59 #include "llvm/ADT/SmallVector.h" 60 #include "llvm/ADT/StringRef.h" 61 #include "llvm/ADT/StringSwitch.h" 62 #include "llvm/Support/Capacity.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/MemoryBuffer.h" 65 #include "llvm/Support/raw_ostream.h" 66 #include <algorithm> 67 #include <cassert> 68 #include <memory> 69 #include <string> 70 #include <utility> 71 #include <vector> 72 73 using namespace clang; 74 75 LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry) 76 77 ExternalPreprocessorSource::~ExternalPreprocessorSource() = default; 78 79 Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts, 80 DiagnosticsEngine &diags, LangOptions &opts, 81 SourceManager &SM, HeaderSearch &Headers, 82 ModuleLoader &TheModuleLoader, 83 IdentifierInfoLookup *IILookup, bool OwnsHeaders, 84 TranslationUnitKind TUKind) 85 : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts), 86 FileMgr(Headers.getFileMgr()), SourceMgr(SM), 87 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers), 88 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr), 89 // As the language options may have not been loaded yet (when 90 // deserializing an ASTUnit), adding keywords to the identifier table is 91 // deferred to Preprocessor::Initialize(). 92 Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())), 93 TUKind(TUKind), SkipMainFilePreamble(0, true), 94 CurSubmoduleState(&NullSubmoduleState) { 95 OwnsHeaderSearch = OwnsHeaders; 96 97 // Default to discarding comments. 98 KeepComments = false; 99 KeepMacroComments = false; 100 SuppressIncludeNotFoundError = false; 101 102 // Macro expansion is enabled. 103 DisableMacroExpansion = false; 104 MacroExpansionInDirectivesOverride = false; 105 InMacroArgs = false; 106 ArgMacro = nullptr; 107 InMacroArgPreExpansion = false; 108 NumCachedTokenLexers = 0; 109 PragmasEnabled = true; 110 ParsingIfOrElifDirective = false; 111 PreprocessedOutput = false; 112 113 // We haven't read anything from the external source. 114 ReadMacrosFromExternalSource = false; 115 116 BuiltinInfo = std::make_unique<Builtin::Context>(); 117 118 // Initialize the pragma handlers. 119 RegisterBuiltinPragmas(); 120 121 // Initialize builtin macros like __LINE__ and friends. 122 RegisterBuiltinMacros(); 123 124 // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of 125 // a macro. They get unpoisoned where it is allowed. Note that we model 126 // __VA_OPT__ as a builtin macro to allow #ifdef and friends to detect it. 127 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); 128 SetPoisonReason(Ident__VA_ARGS__, diag::ext_pp_bad_vaargs_use); 129 Ident__VA_OPT__->setIsPoisoned(); 130 SetPoisonReason(Ident__VA_OPT__, diag::ext_pp_bad_vaopt_use); 131 132 if(LangOpts.Borland) { 133 Ident__exception_info = getIdentifierInfo("_exception_info"); 134 Ident___exception_info = getIdentifierInfo("__exception_info"); 135 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation"); 136 Ident__exception_code = getIdentifierInfo("_exception_code"); 137 Ident___exception_code = getIdentifierInfo("__exception_code"); 138 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode"); 139 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination"); 140 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination"); 141 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination"); 142 } else { 143 Ident__exception_info = Ident__exception_code = nullptr; 144 Ident__abnormal_termination = Ident___exception_info = nullptr; 145 Ident___exception_code = Ident___abnormal_termination = nullptr; 146 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr; 147 Ident_AbnormalTermination = nullptr; 148 } 149 150 // If using a PCH where a #pragma hdrstop is expected, start skipping tokens. 151 if (usingPCHWithPragmaHdrStop()) 152 SkippingUntilPragmaHdrStop = true; 153 154 // If using a PCH with a through header, start skipping tokens. 155 if (!this->PPOpts->PCHThroughHeader.empty() && 156 !this->PPOpts->ImplicitPCHInclude.empty()) 157 SkippingUntilPCHThroughHeader = true; 158 159 if (this->PPOpts->GeneratePreamble) 160 PreambleConditionalStack.startRecording(); 161 162 ExcludedConditionalDirectiveSkipMappings = 163 this->PPOpts->ExcludedConditionalDirectiveSkipMappings; 164 if (ExcludedConditionalDirectiveSkipMappings) 165 ExcludedConditionalDirectiveSkipMappings->clear(); 166 167 MaxTokens = LangOpts.MaxTokens; 168 } 169 170 Preprocessor::~Preprocessor() { 171 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); 172 173 IncludeMacroStack.clear(); 174 175 // Destroy any macro definitions. 176 while (MacroInfoChain *I = MIChainHead) { 177 MIChainHead = I->Next; 178 I->~MacroInfoChain(); 179 } 180 181 // Free any cached macro expanders. 182 // This populates MacroArgCache, so all TokenLexers need to be destroyed 183 // before the code below that frees up the MacroArgCache list. 184 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr); 185 CurTokenLexer.reset(); 186 187 // Free any cached MacroArgs. 188 for (MacroArgs *ArgList = MacroArgCache; ArgList;) 189 ArgList = ArgList->deallocate(); 190 191 // Delete the header search info, if we own it. 192 if (OwnsHeaderSearch) 193 delete &HeaderInfo; 194 } 195 196 void Preprocessor::Initialize(const TargetInfo &Target, 197 const TargetInfo *AuxTarget) { 198 assert((!this->Target || this->Target == &Target) && 199 "Invalid override of target information"); 200 this->Target = &Target; 201 202 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) && 203 "Invalid override of aux target information."); 204 this->AuxTarget = AuxTarget; 205 206 // Initialize information about built-ins. 207 BuiltinInfo->InitializeTarget(Target, AuxTarget); 208 HeaderInfo.setTarget(Target); 209 210 // Populate the identifier table with info about keywords for the current language. 211 Identifiers.AddKeywords(LangOpts); 212 } 213 214 void Preprocessor::InitializeForModelFile() { 215 NumEnteredSourceFiles = 0; 216 217 // Reset pragmas 218 PragmaHandlersBackup = std::move(PragmaHandlers); 219 PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef()); 220 RegisterBuiltinPragmas(); 221 222 // Reset PredefinesFileID 223 PredefinesFileID = FileID(); 224 } 225 226 void Preprocessor::FinalizeForModelFile() { 227 NumEnteredSourceFiles = 1; 228 229 PragmaHandlers = std::move(PragmaHandlersBackup); 230 } 231 232 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 233 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" 234 << getSpelling(Tok) << "'"; 235 236 if (!DumpFlags) return; 237 238 llvm::errs() << "\t"; 239 if (Tok.isAtStartOfLine()) 240 llvm::errs() << " [StartOfLine]"; 241 if (Tok.hasLeadingSpace()) 242 llvm::errs() << " [LeadingSpace]"; 243 if (Tok.isExpandDisabled()) 244 llvm::errs() << " [ExpandDisabled]"; 245 if (Tok.needsCleaning()) { 246 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 247 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) 248 << "']"; 249 } 250 251 llvm::errs() << "\tLoc=<"; 252 DumpLocation(Tok.getLocation()); 253 llvm::errs() << ">"; 254 } 255 256 void Preprocessor::DumpLocation(SourceLocation Loc) const { 257 Loc.print(llvm::errs(), SourceMgr); 258 } 259 260 void Preprocessor::DumpMacro(const MacroInfo &MI) const { 261 llvm::errs() << "MACRO: "; 262 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 263 DumpToken(MI.getReplacementToken(i)); 264 llvm::errs() << " "; 265 } 266 llvm::errs() << "\n"; 267 } 268 269 void Preprocessor::PrintStats() { 270 llvm::errs() << "\n*** Preprocessor Stats:\n"; 271 llvm::errs() << NumDirectives << " directives found:\n"; 272 llvm::errs() << " " << NumDefined << " #define.\n"; 273 llvm::errs() << " " << NumUndefined << " #undef.\n"; 274 llvm::errs() << " #include/#include_next/#import:\n"; 275 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n"; 276 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n"; 277 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 278 llvm::errs() << " " << NumElse << " #else/#elif.\n"; 279 llvm::errs() << " " << NumEndif << " #endif.\n"; 280 llvm::errs() << " " << NumPragma << " #pragma.\n"; 281 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 282 283 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 284 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 285 << NumFastMacroExpanded << " on the fast path.\n"; 286 llvm::errs() << (NumFastTokenPaste+NumTokenPaste) 287 << " token paste (##) operations performed, " 288 << NumFastTokenPaste << " on the fast path.\n"; 289 290 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total"; 291 292 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory(); 293 llvm::errs() << "\n Macro Expanded Tokens: " 294 << llvm::capacity_in_bytes(MacroExpandedTokens); 295 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity(); 296 // FIXME: List information for all submodules. 297 llvm::errs() << "\n Macros: " 298 << llvm::capacity_in_bytes(CurSubmoduleState->Macros); 299 llvm::errs() << "\n #pragma push_macro Info: " 300 << llvm::capacity_in_bytes(PragmaPushMacroInfo); 301 llvm::errs() << "\n Poison Reasons: " 302 << llvm::capacity_in_bytes(PoisonReasons); 303 llvm::errs() << "\n Comment Handlers: " 304 << llvm::capacity_in_bytes(CommentHandlers) << "\n"; 305 } 306 307 Preprocessor::macro_iterator 308 Preprocessor::macro_begin(bool IncludeExternalMacros) const { 309 if (IncludeExternalMacros && ExternalSource && 310 !ReadMacrosFromExternalSource) { 311 ReadMacrosFromExternalSource = true; 312 ExternalSource->ReadDefinedMacros(); 313 } 314 315 // Make sure we cover all macros in visible modules. 316 for (const ModuleMacro &Macro : ModuleMacros) 317 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState())); 318 319 return CurSubmoduleState->Macros.begin(); 320 } 321 322 size_t Preprocessor::getTotalMemory() const { 323 return BP.getTotalMemory() 324 + llvm::capacity_in_bytes(MacroExpandedTokens) 325 + Predefines.capacity() /* Predefines buffer. */ 326 // FIXME: Include sizes from all submodules, and include MacroInfo sizes, 327 // and ModuleMacros. 328 + llvm::capacity_in_bytes(CurSubmoduleState->Macros) 329 + llvm::capacity_in_bytes(PragmaPushMacroInfo) 330 + llvm::capacity_in_bytes(PoisonReasons) 331 + llvm::capacity_in_bytes(CommentHandlers); 332 } 333 334 Preprocessor::macro_iterator 335 Preprocessor::macro_end(bool IncludeExternalMacros) const { 336 if (IncludeExternalMacros && ExternalSource && 337 !ReadMacrosFromExternalSource) { 338 ReadMacrosFromExternalSource = true; 339 ExternalSource->ReadDefinedMacros(); 340 } 341 342 return CurSubmoduleState->Macros.end(); 343 } 344 345 /// Compares macro tokens with a specified token value sequence. 346 static bool MacroDefinitionEquals(const MacroInfo *MI, 347 ArrayRef<TokenValue> Tokens) { 348 return Tokens.size() == MI->getNumTokens() && 349 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin()); 350 } 351 352 StringRef Preprocessor::getLastMacroWithSpelling( 353 SourceLocation Loc, 354 ArrayRef<TokenValue> Tokens) const { 355 SourceLocation BestLocation; 356 StringRef BestSpelling; 357 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end(); 358 I != E; ++I) { 359 const MacroDirective::DefInfo 360 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr); 361 if (!Def || !Def.getMacroInfo()) 362 continue; 363 if (!Def.getMacroInfo()->isObjectLike()) 364 continue; 365 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens)) 366 continue; 367 SourceLocation Location = Def.getLocation(); 368 // Choose the macro defined latest. 369 if (BestLocation.isInvalid() || 370 (Location.isValid() && 371 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) { 372 BestLocation = Location; 373 BestSpelling = I->first->getName(); 374 } 375 } 376 return BestSpelling; 377 } 378 379 void Preprocessor::recomputeCurLexerKind() { 380 if (CurLexer) 381 CurLexerKind = CLK_Lexer; 382 else if (CurTokenLexer) 383 CurLexerKind = CLK_TokenLexer; 384 else 385 CurLexerKind = CLK_CachingLexer; 386 } 387 388 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, 389 unsigned CompleteLine, 390 unsigned CompleteColumn) { 391 assert(File); 392 assert(CompleteLine && CompleteColumn && "Starts from 1:1"); 393 assert(!CodeCompletionFile && "Already set"); 394 395 // Load the actual file's contents. 396 Optional<llvm::MemoryBufferRef> Buffer = 397 SourceMgr.getMemoryBufferForFileOrNone(File); 398 if (!Buffer) 399 return true; 400 401 // Find the byte position of the truncation point. 402 const char *Position = Buffer->getBufferStart(); 403 for (unsigned Line = 1; Line < CompleteLine; ++Line) { 404 for (; *Position; ++Position) { 405 if (*Position != '\r' && *Position != '\n') 406 continue; 407 408 // Eat \r\n or \n\r as a single line. 409 if ((Position[1] == '\r' || Position[1] == '\n') && 410 Position[0] != Position[1]) 411 ++Position; 412 ++Position; 413 break; 414 } 415 } 416 417 Position += CompleteColumn - 1; 418 419 // If pointing inside the preamble, adjust the position at the beginning of 420 // the file after the preamble. 421 if (SkipMainFilePreamble.first && 422 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) { 423 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first) 424 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first; 425 } 426 427 if (Position > Buffer->getBufferEnd()) 428 Position = Buffer->getBufferEnd(); 429 430 CodeCompletionFile = File; 431 CodeCompletionOffset = Position - Buffer->getBufferStart(); 432 433 auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer( 434 Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier()); 435 char *NewBuf = NewBuffer->getBufferStart(); 436 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf); 437 *NewPos = '\0'; 438 std::copy(Position, Buffer->getBufferEnd(), NewPos+1); 439 SourceMgr.overrideFileContents(File, std::move(NewBuffer)); 440 441 return false; 442 } 443 444 void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir, 445 bool IsAngled) { 446 if (CodeComplete) 447 CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled); 448 setCodeCompletionReached(); 449 } 450 451 void Preprocessor::CodeCompleteNaturalLanguage() { 452 if (CodeComplete) 453 CodeComplete->CodeCompleteNaturalLanguage(); 454 setCodeCompletionReached(); 455 } 456 457 /// getSpelling - This method is used to get the spelling of a token into a 458 /// SmallVector. Note that the returned StringRef may not point to the 459 /// supplied buffer if a copy can be avoided. 460 StringRef Preprocessor::getSpelling(const Token &Tok, 461 SmallVectorImpl<char> &Buffer, 462 bool *Invalid) const { 463 // NOTE: this has to be checked *before* testing for an IdentifierInfo. 464 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) { 465 // Try the fast path. 466 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) 467 return II->getName(); 468 } 469 470 // Resize the buffer if we need to copy into it. 471 if (Tok.needsCleaning()) 472 Buffer.resize(Tok.getLength()); 473 474 const char *Ptr = Buffer.data(); 475 unsigned Len = getSpelling(Tok, Ptr, Invalid); 476 return StringRef(Ptr, Len); 477 } 478 479 /// CreateString - Plop the specified string into a scratch buffer and return a 480 /// location for it. If specified, the source location provides a source 481 /// location for the token. 482 void Preprocessor::CreateString(StringRef Str, Token &Tok, 483 SourceLocation ExpansionLocStart, 484 SourceLocation ExpansionLocEnd) { 485 Tok.setLength(Str.size()); 486 487 const char *DestPtr; 488 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr); 489 490 if (ExpansionLocStart.isValid()) 491 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart, 492 ExpansionLocEnd, Str.size()); 493 Tok.setLocation(Loc); 494 495 // If this is a raw identifier or a literal token, set the pointer data. 496 if (Tok.is(tok::raw_identifier)) 497 Tok.setRawIdentifierData(DestPtr); 498 else if (Tok.isLiteral()) 499 Tok.setLiteralData(DestPtr); 500 } 501 502 SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) { 503 auto &SM = getSourceManager(); 504 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc); 505 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc); 506 bool Invalid = false; 507 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 508 if (Invalid) 509 return SourceLocation(); 510 511 // FIXME: We could consider re-using spelling for tokens we see repeatedly. 512 const char *DestPtr; 513 SourceLocation Spelling = 514 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr); 515 return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length)); 516 } 517 518 Module *Preprocessor::getCurrentModule() { 519 if (!getLangOpts().isCompilingModule()) 520 return nullptr; 521 522 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule); 523 } 524 525 //===----------------------------------------------------------------------===// 526 // Preprocessor Initialization Methods 527 //===----------------------------------------------------------------------===// 528 529 /// EnterMainSourceFile - Enter the specified FileID as the main source file, 530 /// which implicitly adds the builtin defines etc. 531 void Preprocessor::EnterMainSourceFile() { 532 // We do not allow the preprocessor to reenter the main file. Doing so will 533 // cause FileID's to accumulate information from both runs (e.g. #line 534 // information) and predefined macros aren't guaranteed to be set properly. 535 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); 536 FileID MainFileID = SourceMgr.getMainFileID(); 537 538 // If MainFileID is loaded it means we loaded an AST file, no need to enter 539 // a main file. 540 if (!SourceMgr.isLoadedFileID(MainFileID)) { 541 // Enter the main file source buffer. 542 EnterSourceFile(MainFileID, nullptr, SourceLocation()); 543 544 // If we've been asked to skip bytes in the main file (e.g., as part of a 545 // precompiled preamble), do so now. 546 if (SkipMainFilePreamble.first > 0) 547 CurLexer->SetByteOffset(SkipMainFilePreamble.first, 548 SkipMainFilePreamble.second); 549 550 // Tell the header info that the main file was entered. If the file is later 551 // #imported, it won't be re-entered. 552 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) 553 HeaderInfo.IncrementIncludeCount(FE); 554 } 555 556 // Preprocess Predefines to populate the initial preprocessor state. 557 std::unique_ptr<llvm::MemoryBuffer> SB = 558 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>"); 559 assert(SB && "Cannot create predefined source buffer"); 560 FileID FID = SourceMgr.createFileID(std::move(SB)); 561 assert(FID.isValid() && "Could not create FileID for predefines?"); 562 setPredefinesFileID(FID); 563 564 // Start parsing the predefines. 565 EnterSourceFile(FID, nullptr, SourceLocation()); 566 567 if (!PPOpts->PCHThroughHeader.empty()) { 568 // Lookup and save the FileID for the through header. If it isn't found 569 // in the search path, it's a fatal error. 570 const DirectoryLookup *CurDir; 571 Optional<FileEntryRef> File = LookupFile( 572 SourceLocation(), PPOpts->PCHThroughHeader, 573 /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr, CurDir, 574 /*SearchPath=*/nullptr, /*RelativePath=*/nullptr, 575 /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr, 576 /*IsFrameworkFound=*/nullptr); 577 if (!File) { 578 Diag(SourceLocation(), diag::err_pp_through_header_not_found) 579 << PPOpts->PCHThroughHeader; 580 return; 581 } 582 setPCHThroughHeaderFileID( 583 SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User)); 584 } 585 586 // Skip tokens from the Predefines and if needed the main file. 587 if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) || 588 (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop)) 589 SkipTokensWhileUsingPCH(); 590 } 591 592 void Preprocessor::setPCHThroughHeaderFileID(FileID FID) { 593 assert(PCHThroughHeaderFileID.isInvalid() && 594 "PCHThroughHeaderFileID already set!"); 595 PCHThroughHeaderFileID = FID; 596 } 597 598 bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) { 599 assert(PCHThroughHeaderFileID.isValid() && 600 "Invalid PCH through header FileID"); 601 return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID); 602 } 603 604 bool Preprocessor::creatingPCHWithThroughHeader() { 605 return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() && 606 PCHThroughHeaderFileID.isValid(); 607 } 608 609 bool Preprocessor::usingPCHWithThroughHeader() { 610 return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() && 611 PCHThroughHeaderFileID.isValid(); 612 } 613 614 bool Preprocessor::creatingPCHWithPragmaHdrStop() { 615 return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop; 616 } 617 618 bool Preprocessor::usingPCHWithPragmaHdrStop() { 619 return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop; 620 } 621 622 /// Skip tokens until after the #include of the through header or 623 /// until after a #pragma hdrstop is seen. Tokens in the predefines file 624 /// and the main file may be skipped. If the end of the predefines file 625 /// is reached, skipping continues into the main file. If the end of the 626 /// main file is reached, it's a fatal error. 627 void Preprocessor::SkipTokensWhileUsingPCH() { 628 bool ReachedMainFileEOF = false; 629 bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader; 630 bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop; 631 Token Tok; 632 while (true) { 633 bool InPredefines = 634 (CurLexer && CurLexer->getFileID() == getPredefinesFileID()); 635 switch (CurLexerKind) { 636 case CLK_Lexer: 637 CurLexer->Lex(Tok); 638 break; 639 case CLK_TokenLexer: 640 CurTokenLexer->Lex(Tok); 641 break; 642 case CLK_CachingLexer: 643 CachingLex(Tok); 644 break; 645 case CLK_LexAfterModuleImport: 646 LexAfterModuleImport(Tok); 647 break; 648 } 649 if (Tok.is(tok::eof) && !InPredefines) { 650 ReachedMainFileEOF = true; 651 break; 652 } 653 if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader) 654 break; 655 if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop) 656 break; 657 } 658 if (ReachedMainFileEOF) { 659 if (UsingPCHThroughHeader) 660 Diag(SourceLocation(), diag::err_pp_through_header_not_seen) 661 << PPOpts->PCHThroughHeader << 1; 662 else if (!PPOpts->PCHWithHdrStopCreate) 663 Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen); 664 } 665 } 666 667 void Preprocessor::replayPreambleConditionalStack() { 668 // Restore the conditional stack from the preamble, if there is one. 669 if (PreambleConditionalStack.isReplaying()) { 670 assert(CurPPLexer && 671 "CurPPLexer is null when calling replayPreambleConditionalStack."); 672 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack()); 673 PreambleConditionalStack.doneReplaying(); 674 if (PreambleConditionalStack.reachedEOFWhileSkipping()) 675 SkipExcludedConditionalBlock( 676 PreambleConditionalStack.SkipInfo->HashTokenLoc, 677 PreambleConditionalStack.SkipInfo->IfTokenLoc, 678 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion, 679 PreambleConditionalStack.SkipInfo->FoundElse, 680 PreambleConditionalStack.SkipInfo->ElseLoc); 681 } 682 } 683 684 void Preprocessor::EndSourceFile() { 685 // Notify the client that we reached the end of the source file. 686 if (Callbacks) 687 Callbacks->EndOfMainFile(); 688 } 689 690 //===----------------------------------------------------------------------===// 691 // Lexer Event Handling. 692 //===----------------------------------------------------------------------===// 693 694 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the 695 /// identifier information for the token and install it into the token, 696 /// updating the token kind accordingly. 697 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const { 698 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!"); 699 700 // Look up this token, see if it is a macro, or if it is a language keyword. 701 IdentifierInfo *II; 702 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) { 703 // No cleaning needed, just use the characters from the lexed buffer. 704 II = getIdentifierInfo(Identifier.getRawIdentifier()); 705 } else { 706 // Cleaning needed, alloca a buffer, clean into it, then use the buffer. 707 SmallString<64> IdentifierBuffer; 708 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer); 709 710 if (Identifier.hasUCN()) { 711 SmallString<64> UCNIdentifierBuffer; 712 expandUCNs(UCNIdentifierBuffer, CleanedStr); 713 II = getIdentifierInfo(UCNIdentifierBuffer); 714 } else { 715 II = getIdentifierInfo(CleanedStr); 716 } 717 } 718 719 // Update the token info (identifier info and appropriate token kind). 720 Identifier.setIdentifierInfo(II); 721 if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() && 722 getSourceManager().isInSystemHeader(Identifier.getLocation())) 723 Identifier.setKind(tok::identifier); 724 else 725 Identifier.setKind(II->getTokenID()); 726 727 return II; 728 } 729 730 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { 731 PoisonReasons[II] = DiagID; 732 } 733 734 void Preprocessor::PoisonSEHIdentifiers(bool Poison) { 735 assert(Ident__exception_code && Ident__exception_info); 736 assert(Ident___exception_code && Ident___exception_info); 737 Ident__exception_code->setIsPoisoned(Poison); 738 Ident___exception_code->setIsPoisoned(Poison); 739 Ident_GetExceptionCode->setIsPoisoned(Poison); 740 Ident__exception_info->setIsPoisoned(Poison); 741 Ident___exception_info->setIsPoisoned(Poison); 742 Ident_GetExceptionInfo->setIsPoisoned(Poison); 743 Ident__abnormal_termination->setIsPoisoned(Poison); 744 Ident___abnormal_termination->setIsPoisoned(Poison); 745 Ident_AbnormalTermination->setIsPoisoned(Poison); 746 } 747 748 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { 749 assert(Identifier.getIdentifierInfo() && 750 "Can't handle identifiers without identifier info!"); 751 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = 752 PoisonReasons.find(Identifier.getIdentifierInfo()); 753 if(it == PoisonReasons.end()) 754 Diag(Identifier, diag::err_pp_used_poisoned_id); 755 else 756 Diag(Identifier,it->second) << Identifier.getIdentifierInfo(); 757 } 758 759 /// Returns a diagnostic message kind for reporting a future keyword as 760 /// appropriate for the identifier and specified language. 761 static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II, 762 const LangOptions &LangOpts) { 763 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed"); 764 765 if (LangOpts.CPlusPlus) 766 return llvm::StringSwitch<diag::kind>(II.getName()) 767 #define CXX11_KEYWORD(NAME, FLAGS) \ 768 .Case(#NAME, diag::warn_cxx11_keyword) 769 #define CXX20_KEYWORD(NAME, FLAGS) \ 770 .Case(#NAME, diag::warn_cxx20_keyword) 771 #include "clang/Basic/TokenKinds.def" 772 // char8_t is not modeled as a CXX20_KEYWORD because it's not 773 // unconditionally enabled in C++20 mode. (It can be disabled 774 // by -fno-char8_t.) 775 .Case("char8_t", diag::warn_cxx20_keyword) 776 ; 777 778 llvm_unreachable( 779 "Keyword not known to come from a newer Standard or proposed Standard"); 780 } 781 782 void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const { 783 assert(II.isOutOfDate() && "not out of date"); 784 getExternalSource()->updateOutOfDateIdentifier(II); 785 } 786 787 /// HandleIdentifier - This callback is invoked when the lexer reads an 788 /// identifier. This callback looks up the identifier in the map and/or 789 /// potentially macro expands it or turns it into a named token (like 'for'). 790 /// 791 /// Note that callers of this method are guarded by checking the 792 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the 793 /// IdentifierInfo methods that compute these properties will need to change to 794 /// match. 795 bool Preprocessor::HandleIdentifier(Token &Identifier) { 796 assert(Identifier.getIdentifierInfo() && 797 "Can't handle identifiers without identifier info!"); 798 799 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 800 801 // If the information about this identifier is out of date, update it from 802 // the external source. 803 // We have to treat __VA_ARGS__ in a special way, since it gets 804 // serialized with isPoisoned = true, but our preprocessor may have 805 // unpoisoned it if we're defining a C99 macro. 806 if (II.isOutOfDate()) { 807 bool CurrentIsPoisoned = false; 808 const bool IsSpecialVariadicMacro = 809 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__; 810 if (IsSpecialVariadicMacro) 811 CurrentIsPoisoned = II.isPoisoned(); 812 813 updateOutOfDateIdentifier(II); 814 Identifier.setKind(II.getTokenID()); 815 816 if (IsSpecialVariadicMacro) 817 II.setIsPoisoned(CurrentIsPoisoned); 818 } 819 820 // If this identifier was poisoned, and if it was not produced from a macro 821 // expansion, emit an error. 822 if (II.isPoisoned() && CurPPLexer) { 823 HandlePoisonedIdentifier(Identifier); 824 } 825 826 // If this is a macro to be expanded, do it. 827 if (MacroDefinition MD = getMacroDefinition(&II)) { 828 auto *MI = MD.getMacroInfo(); 829 assert(MI && "macro definition with no macro info?"); 830 if (!DisableMacroExpansion) { 831 if (!Identifier.isExpandDisabled() && MI->isEnabled()) { 832 // C99 6.10.3p10: If the preprocessing token immediately after the 833 // macro name isn't a '(', this macro should not be expanded. 834 if (!MI->isFunctionLike() || isNextPPTokenLParen()) 835 return HandleMacroExpandedIdentifier(Identifier, MD); 836 } else { 837 // C99 6.10.3.4p2 says that a disabled macro may never again be 838 // expanded, even if it's in a context where it could be expanded in the 839 // future. 840 Identifier.setFlag(Token::DisableExpand); 841 if (MI->isObjectLike() || isNextPPTokenLParen()) 842 Diag(Identifier, diag::pp_disabled_macro_expansion); 843 } 844 } 845 } 846 847 // If this identifier is a keyword in a newer Standard or proposed Standard, 848 // produce a warning. Don't warn if we're not considering macro expansion, 849 // since this identifier might be the name of a macro. 850 // FIXME: This warning is disabled in cases where it shouldn't be, like 851 // "#define constexpr constexpr", "int constexpr;" 852 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) { 853 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts())) 854 << II.getName(); 855 // Don't diagnose this keyword again in this translation unit. 856 II.setIsFutureCompatKeyword(false); 857 } 858 859 // If this is an extension token, diagnose its use. 860 // We avoid diagnosing tokens that originate from macro definitions. 861 // FIXME: This warning is disabled in cases where it shouldn't be, 862 // like "#define TY typeof", "TY(1) x". 863 if (II.isExtensionToken() && !DisableMacroExpansion) 864 Diag(Identifier, diag::ext_token_used); 865 866 // If this is the 'import' contextual keyword following an '@', note 867 // that the next token indicates a module name. 868 // 869 // Note that we do not treat 'import' as a contextual 870 // keyword when we're in a caching lexer, because caching lexers only get 871 // used in contexts where import declarations are disallowed. 872 // 873 // Likewise if this is the C++ Modules TS import keyword. 874 if (((LastTokenWasAt && II.isModulesImport()) || 875 Identifier.is(tok::kw_import)) && 876 !InMacroArgs && !DisableMacroExpansion && 877 (getLangOpts().Modules || getLangOpts().DebuggerSupport) && 878 CurLexerKind != CLK_CachingLexer) { 879 ModuleImportLoc = Identifier.getLocation(); 880 ModuleImportPath.clear(); 881 ModuleImportExpectsIdentifier = true; 882 CurLexerKind = CLK_LexAfterModuleImport; 883 } 884 return true; 885 } 886 887 void Preprocessor::Lex(Token &Result) { 888 ++LexLevel; 889 890 // We loop here until a lex function returns a token; this avoids recursion. 891 bool ReturnedToken; 892 do { 893 switch (CurLexerKind) { 894 case CLK_Lexer: 895 ReturnedToken = CurLexer->Lex(Result); 896 break; 897 case CLK_TokenLexer: 898 ReturnedToken = CurTokenLexer->Lex(Result); 899 break; 900 case CLK_CachingLexer: 901 CachingLex(Result); 902 ReturnedToken = true; 903 break; 904 case CLK_LexAfterModuleImport: 905 ReturnedToken = LexAfterModuleImport(Result); 906 break; 907 } 908 } while (!ReturnedToken); 909 910 if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure) 911 return; 912 913 if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) { 914 // Remember the identifier before code completion token. 915 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo()); 916 setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc()); 917 // Set IdenfitierInfo to null to avoid confusing code that handles both 918 // identifiers and completion tokens. 919 Result.setIdentifierInfo(nullptr); 920 } 921 922 // Update ImportSeqState to track our position within a C++20 import-seq 923 // if this token is being produced as a result of phase 4 of translation. 924 if (getLangOpts().CPlusPlusModules && LexLevel == 1 && 925 !Result.getFlag(Token::IsReinjected)) { 926 switch (Result.getKind()) { 927 case tok::l_paren: case tok::l_square: case tok::l_brace: 928 ImportSeqState.handleOpenBracket(); 929 break; 930 case tok::r_paren: case tok::r_square: 931 ImportSeqState.handleCloseBracket(); 932 break; 933 case tok::r_brace: 934 ImportSeqState.handleCloseBrace(); 935 break; 936 case tok::semi: 937 ImportSeqState.handleSemi(); 938 break; 939 case tok::header_name: 940 case tok::annot_header_unit: 941 ImportSeqState.handleHeaderName(); 942 break; 943 case tok::kw_export: 944 ImportSeqState.handleExport(); 945 break; 946 case tok::identifier: 947 if (Result.getIdentifierInfo()->isModulesImport()) { 948 ImportSeqState.handleImport(); 949 if (ImportSeqState.afterImportSeq()) { 950 ModuleImportLoc = Result.getLocation(); 951 ModuleImportPath.clear(); 952 ModuleImportExpectsIdentifier = true; 953 CurLexerKind = CLK_LexAfterModuleImport; 954 } 955 break; 956 } 957 LLVM_FALLTHROUGH; 958 default: 959 ImportSeqState.handleMisc(); 960 break; 961 } 962 } 963 964 LastTokenWasAt = Result.is(tok::at); 965 --LexLevel; 966 967 if ((LexLevel == 0 || PreprocessToken) && 968 !Result.getFlag(Token::IsReinjected)) { 969 if (LexLevel == 0) 970 ++TokenCount; 971 if (OnToken) 972 OnToken(Result); 973 } 974 } 975 976 /// Lex a header-name token (including one formed from header-name-tokens if 977 /// \p AllowConcatenation is \c true). 978 /// 979 /// \param FilenameTok Filled in with the next token. On success, this will 980 /// be either a header_name token. On failure, it will be whatever other 981 /// token was found instead. 982 /// \param AllowMacroExpansion If \c true, allow the header name to be formed 983 /// by macro expansion (concatenating tokens as necessary if the first 984 /// token is a '<'). 985 /// \return \c true if we reached EOD or EOF while looking for a > token in 986 /// a concatenated header name and diagnosed it. \c false otherwise. 987 bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) { 988 // Lex using header-name tokenization rules if tokens are being lexed from 989 // a file. Just grab a token normally if we're in a macro expansion. 990 if (CurPPLexer) 991 CurPPLexer->LexIncludeFilename(FilenameTok); 992 else 993 Lex(FilenameTok); 994 995 // This could be a <foo/bar.h> file coming from a macro expansion. In this 996 // case, glue the tokens together into an angle_string_literal token. 997 SmallString<128> FilenameBuffer; 998 if (FilenameTok.is(tok::less) && AllowMacroExpansion) { 999 bool StartOfLine = FilenameTok.isAtStartOfLine(); 1000 bool LeadingSpace = FilenameTok.hasLeadingSpace(); 1001 bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro(); 1002 1003 SourceLocation Start = FilenameTok.getLocation(); 1004 SourceLocation End; 1005 FilenameBuffer.push_back('<'); 1006 1007 // Consume tokens until we find a '>'. 1008 // FIXME: A header-name could be formed starting or ending with an 1009 // alternative token. It's not clear whether that's ill-formed in all 1010 // cases. 1011 while (FilenameTok.isNot(tok::greater)) { 1012 Lex(FilenameTok); 1013 if (FilenameTok.isOneOf(tok::eod, tok::eof)) { 1014 Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater; 1015 Diag(Start, diag::note_matching) << tok::less; 1016 return true; 1017 } 1018 1019 End = FilenameTok.getLocation(); 1020 1021 // FIXME: Provide code completion for #includes. 1022 if (FilenameTok.is(tok::code_completion)) { 1023 setCodeCompletionReached(); 1024 Lex(FilenameTok); 1025 continue; 1026 } 1027 1028 // Append the spelling of this token to the buffer. If there was a space 1029 // before it, add it now. 1030 if (FilenameTok.hasLeadingSpace()) 1031 FilenameBuffer.push_back(' '); 1032 1033 // Get the spelling of the token, directly into FilenameBuffer if 1034 // possible. 1035 size_t PreAppendSize = FilenameBuffer.size(); 1036 FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength()); 1037 1038 const char *BufPtr = &FilenameBuffer[PreAppendSize]; 1039 unsigned ActualLen = getSpelling(FilenameTok, BufPtr); 1040 1041 // If the token was spelled somewhere else, copy it into FilenameBuffer. 1042 if (BufPtr != &FilenameBuffer[PreAppendSize]) 1043 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); 1044 1045 // Resize FilenameBuffer to the correct size. 1046 if (FilenameTok.getLength() != ActualLen) 1047 FilenameBuffer.resize(PreAppendSize + ActualLen); 1048 } 1049 1050 FilenameTok.startToken(); 1051 FilenameTok.setKind(tok::header_name); 1052 FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine); 1053 FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace); 1054 FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro); 1055 CreateString(FilenameBuffer, FilenameTok, Start, End); 1056 } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) { 1057 // Convert a string-literal token of the form " h-char-sequence " 1058 // (produced by macro expansion) into a header-name token. 1059 // 1060 // The rules for header-names don't quite match the rules for 1061 // string-literals, but all the places where they differ result in 1062 // undefined behavior, so we can and do treat them the same. 1063 // 1064 // A string-literal with a prefix or suffix is not translated into a 1065 // header-name. This could theoretically be observable via the C++20 1066 // context-sensitive header-name formation rules. 1067 StringRef Str = getSpelling(FilenameTok, FilenameBuffer); 1068 if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"') 1069 FilenameTok.setKind(tok::header_name); 1070 } 1071 1072 return false; 1073 } 1074 1075 /// Collect the tokens of a C++20 pp-import-suffix. 1076 void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) { 1077 // FIXME: For error recovery, consider recognizing attribute syntax here 1078 // and terminating / diagnosing a missing semicolon if we find anything 1079 // else? (Can we leave that to the parser?) 1080 unsigned BracketDepth = 0; 1081 while (true) { 1082 Toks.emplace_back(); 1083 Lex(Toks.back()); 1084 1085 switch (Toks.back().getKind()) { 1086 case tok::l_paren: case tok::l_square: case tok::l_brace: 1087 ++BracketDepth; 1088 break; 1089 1090 case tok::r_paren: case tok::r_square: case tok::r_brace: 1091 if (BracketDepth == 0) 1092 return; 1093 --BracketDepth; 1094 break; 1095 1096 case tok::semi: 1097 if (BracketDepth == 0) 1098 return; 1099 break; 1100 1101 case tok::eof: 1102 return; 1103 1104 default: 1105 break; 1106 } 1107 } 1108 } 1109 1110 1111 /// Lex a token following the 'import' contextual keyword. 1112 /// 1113 /// pp-import: [C++20] 1114 /// import header-name pp-import-suffix[opt] ; 1115 /// import header-name-tokens pp-import-suffix[opt] ; 1116 /// [ObjC] @ import module-name ; 1117 /// [Clang] import module-name ; 1118 /// 1119 /// header-name-tokens: 1120 /// string-literal 1121 /// < [any sequence of preprocessing-tokens other than >] > 1122 /// 1123 /// module-name: 1124 /// module-name-qualifier[opt] identifier 1125 /// 1126 /// module-name-qualifier 1127 /// module-name-qualifier[opt] identifier . 1128 /// 1129 /// We respond to a pp-import by importing macros from the named module. 1130 bool Preprocessor::LexAfterModuleImport(Token &Result) { 1131 // Figure out what kind of lexer we actually have. 1132 recomputeCurLexerKind(); 1133 1134 // Lex the next token. The header-name lexing rules are used at the start of 1135 // a pp-import. 1136 // 1137 // For now, we only support header-name imports in C++20 mode. 1138 // FIXME: Should we allow this in all language modes that support an import 1139 // declaration as an extension? 1140 if (ModuleImportPath.empty() && getLangOpts().CPlusPlusModules) { 1141 if (LexHeaderName(Result)) 1142 return true; 1143 } else { 1144 Lex(Result); 1145 } 1146 1147 // Allocate a holding buffer for a sequence of tokens and introduce it into 1148 // the token stream. 1149 auto EnterTokens = [this](ArrayRef<Token> Toks) { 1150 auto ToksCopy = std::make_unique<Token[]>(Toks.size()); 1151 std::copy(Toks.begin(), Toks.end(), ToksCopy.get()); 1152 EnterTokenStream(std::move(ToksCopy), Toks.size(), 1153 /*DisableMacroExpansion*/ true, /*IsReinject*/ false); 1154 }; 1155 1156 // Check for a header-name. 1157 SmallVector<Token, 32> Suffix; 1158 if (Result.is(tok::header_name)) { 1159 // Enter the header-name token into the token stream; a Lex action cannot 1160 // both return a token and cache tokens (doing so would corrupt the token 1161 // cache if the call to Lex comes from CachingLex / PeekAhead). 1162 Suffix.push_back(Result); 1163 1164 // Consume the pp-import-suffix and expand any macros in it now. We'll add 1165 // it back into the token stream later. 1166 CollectPpImportSuffix(Suffix); 1167 if (Suffix.back().isNot(tok::semi)) { 1168 // This is not a pp-import after all. 1169 EnterTokens(Suffix); 1170 return false; 1171 } 1172 1173 // C++2a [cpp.module]p1: 1174 // The ';' preprocessing-token terminating a pp-import shall not have 1175 // been produced by macro replacement. 1176 SourceLocation SemiLoc = Suffix.back().getLocation(); 1177 if (SemiLoc.isMacroID()) 1178 Diag(SemiLoc, diag::err_header_import_semi_in_macro); 1179 1180 // Reconstitute the import token. 1181 Token ImportTok; 1182 ImportTok.startToken(); 1183 ImportTok.setKind(tok::kw_import); 1184 ImportTok.setLocation(ModuleImportLoc); 1185 ImportTok.setIdentifierInfo(getIdentifierInfo("import")); 1186 ImportTok.setLength(6); 1187 1188 auto Action = HandleHeaderIncludeOrImport( 1189 /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc); 1190 switch (Action.Kind) { 1191 case ImportAction::None: 1192 break; 1193 1194 case ImportAction::ModuleBegin: 1195 // Let the parser know we're textually entering the module. 1196 Suffix.emplace_back(); 1197 Suffix.back().startToken(); 1198 Suffix.back().setKind(tok::annot_module_begin); 1199 Suffix.back().setLocation(SemiLoc); 1200 Suffix.back().setAnnotationEndLoc(SemiLoc); 1201 Suffix.back().setAnnotationValue(Action.ModuleForHeader); 1202 LLVM_FALLTHROUGH; 1203 1204 case ImportAction::ModuleImport: 1205 case ImportAction::SkippedModuleImport: 1206 // We chose to import (or textually enter) the file. Convert the 1207 // header-name token into a header unit annotation token. 1208 Suffix[0].setKind(tok::annot_header_unit); 1209 Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation()); 1210 Suffix[0].setAnnotationValue(Action.ModuleForHeader); 1211 // FIXME: Call the moduleImport callback? 1212 break; 1213 case ImportAction::Failure: 1214 assert(TheModuleLoader.HadFatalFailure && 1215 "This should be an early exit only to a fatal error"); 1216 Result.setKind(tok::eof); 1217 CurLexer->cutOffLexing(); 1218 EnterTokens(Suffix); 1219 return true; 1220 } 1221 1222 EnterTokens(Suffix); 1223 return false; 1224 } 1225 1226 // The token sequence 1227 // 1228 // import identifier (. identifier)* 1229 // 1230 // indicates a module import directive. We already saw the 'import' 1231 // contextual keyword, so now we're looking for the identifiers. 1232 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { 1233 // We expected to see an identifier here, and we did; continue handling 1234 // identifiers. 1235 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(), 1236 Result.getLocation())); 1237 ModuleImportExpectsIdentifier = false; 1238 CurLexerKind = CLK_LexAfterModuleImport; 1239 return true; 1240 } 1241 1242 // If we're expecting a '.' or a ';', and we got a '.', then wait until we 1243 // see the next identifier. (We can also see a '[[' that begins an 1244 // attribute-specifier-seq here under the C++ Modules TS.) 1245 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) { 1246 ModuleImportExpectsIdentifier = true; 1247 CurLexerKind = CLK_LexAfterModuleImport; 1248 return true; 1249 } 1250 1251 // If we didn't recognize a module name at all, this is not a (valid) import. 1252 if (ModuleImportPath.empty() || Result.is(tok::eof)) 1253 return true; 1254 1255 // Consume the pp-import-suffix and expand any macros in it now, if we're not 1256 // at the semicolon already. 1257 SourceLocation SemiLoc = Result.getLocation(); 1258 if (Result.isNot(tok::semi)) { 1259 Suffix.push_back(Result); 1260 CollectPpImportSuffix(Suffix); 1261 if (Suffix.back().isNot(tok::semi)) { 1262 // This is not an import after all. 1263 EnterTokens(Suffix); 1264 return false; 1265 } 1266 SemiLoc = Suffix.back().getLocation(); 1267 } 1268 1269 // Under the Modules TS, the dot is just part of the module name, and not 1270 // a real hierarchy separator. Flatten such module names now. 1271 // 1272 // FIXME: Is this the right level to be performing this transformation? 1273 std::string FlatModuleName; 1274 if (getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) { 1275 for (auto &Piece : ModuleImportPath) { 1276 if (!FlatModuleName.empty()) 1277 FlatModuleName += "."; 1278 FlatModuleName += Piece.first->getName(); 1279 } 1280 SourceLocation FirstPathLoc = ModuleImportPath[0].second; 1281 ModuleImportPath.clear(); 1282 ModuleImportPath.push_back( 1283 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc)); 1284 } 1285 1286 Module *Imported = nullptr; 1287 if (getLangOpts().Modules) { 1288 Imported = TheModuleLoader.loadModule(ModuleImportLoc, 1289 ModuleImportPath, 1290 Module::Hidden, 1291 /*IsInclusionDirective=*/false); 1292 if (Imported) 1293 makeModuleVisible(Imported, SemiLoc); 1294 } 1295 if (Callbacks) 1296 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported); 1297 1298 if (!Suffix.empty()) { 1299 EnterTokens(Suffix); 1300 return false; 1301 } 1302 return true; 1303 } 1304 1305 void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) { 1306 CurSubmoduleState->VisibleModules.setVisible( 1307 M, Loc, [](Module *) {}, 1308 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) { 1309 // FIXME: Include the path in the diagnostic. 1310 // FIXME: Include the import location for the conflicting module. 1311 Diag(ModuleImportLoc, diag::warn_module_conflict) 1312 << Path[0]->getFullModuleName() 1313 << Conflict->getFullModuleName() 1314 << Message; 1315 }); 1316 1317 // Add this module to the imports list of the currently-built submodule. 1318 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M) 1319 BuildingSubmoduleStack.back().M->Imports.insert(M); 1320 } 1321 1322 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String, 1323 const char *DiagnosticTag, 1324 bool AllowMacroExpansion) { 1325 // We need at least one string literal. 1326 if (Result.isNot(tok::string_literal)) { 1327 Diag(Result, diag::err_expected_string_literal) 1328 << /*Source='in...'*/0 << DiagnosticTag; 1329 return false; 1330 } 1331 1332 // Lex string literal tokens, optionally with macro expansion. 1333 SmallVector<Token, 4> StrToks; 1334 do { 1335 StrToks.push_back(Result); 1336 1337 if (Result.hasUDSuffix()) 1338 Diag(Result, diag::err_invalid_string_udl); 1339 1340 if (AllowMacroExpansion) 1341 Lex(Result); 1342 else 1343 LexUnexpandedToken(Result); 1344 } while (Result.is(tok::string_literal)); 1345 1346 // Concatenate and parse the strings. 1347 StringLiteralParser Literal(StrToks, *this); 1348 assert(Literal.isAscii() && "Didn't allow wide strings in"); 1349 1350 if (Literal.hadError) 1351 return false; 1352 1353 if (Literal.Pascal) { 1354 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal) 1355 << /*Source='in...'*/0 << DiagnosticTag; 1356 return false; 1357 } 1358 1359 String = std::string(Literal.GetString()); 1360 return true; 1361 } 1362 1363 bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) { 1364 assert(Tok.is(tok::numeric_constant)); 1365 SmallString<8> IntegerBuffer; 1366 bool NumberInvalid = false; 1367 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid); 1368 if (NumberInvalid) 1369 return false; 1370 NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(), 1371 getLangOpts(), getTargetInfo(), 1372 getDiagnostics()); 1373 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix()) 1374 return false; 1375 llvm::APInt APVal(64, 0); 1376 if (Literal.GetIntegerValue(APVal)) 1377 return false; 1378 Lex(Tok); 1379 Value = APVal.getLimitedValue(); 1380 return true; 1381 } 1382 1383 void Preprocessor::addCommentHandler(CommentHandler *Handler) { 1384 assert(Handler && "NULL comment handler"); 1385 assert(llvm::find(CommentHandlers, Handler) == CommentHandlers.end() && 1386 "Comment handler already registered"); 1387 CommentHandlers.push_back(Handler); 1388 } 1389 1390 void Preprocessor::removeCommentHandler(CommentHandler *Handler) { 1391 std::vector<CommentHandler *>::iterator Pos = 1392 llvm::find(CommentHandlers, Handler); 1393 assert(Pos != CommentHandlers.end() && "Comment handler not registered"); 1394 CommentHandlers.erase(Pos); 1395 } 1396 1397 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) { 1398 bool AnyPendingTokens = false; 1399 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(), 1400 HEnd = CommentHandlers.end(); 1401 H != HEnd; ++H) { 1402 if ((*H)->HandleComment(*this, Comment)) 1403 AnyPendingTokens = true; 1404 } 1405 if (!AnyPendingTokens || getCommentRetentionState()) 1406 return false; 1407 Lex(result); 1408 return true; 1409 } 1410 1411 ModuleLoader::~ModuleLoader() = default; 1412 1413 CommentHandler::~CommentHandler() = default; 1414 1415 EmptylineHandler::~EmptylineHandler() = default; 1416 1417 CodeCompletionHandler::~CodeCompletionHandler() = default; 1418 1419 void Preprocessor::createPreprocessingRecord() { 1420 if (Record) 1421 return; 1422 1423 Record = new PreprocessingRecord(getSourceManager()); 1424 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record)); 1425 } 1426