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