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 // "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 // If using a PCH where a #pragma hdrstop is expected, start skipping tokens. 150 if (usingPCHWithPragmaHdrStop()) 151 SkippingUntilPragmaHdrStop = true; 152 153 // If using a PCH with a through header, start skipping tokens. 154 if (!this->PPOpts->PCHThroughHeader.empty() && 155 !this->PPOpts->ImplicitPCHInclude.empty()) 156 SkippingUntilPCHThroughHeader = true; 157 158 if (this->PPOpts->GeneratePreamble) 159 PreambleConditionalStack.startRecording(); 160 161 ExcludedConditionalDirectiveSkipMappings = 162 this->PPOpts->ExcludedConditionalDirectiveSkipMappings; 163 if (ExcludedConditionalDirectiveSkipMappings) 164 ExcludedConditionalDirectiveSkipMappings->clear(); 165 166 MaxTokens = LangOpts.MaxTokens; 167 } 168 169 Preprocessor::~Preprocessor() { 170 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); 171 172 IncludeMacroStack.clear(); 173 174 // Destroy any macro definitions. 175 while (MacroInfoChain *I = MIChainHead) { 176 MIChainHead = I->Next; 177 I->~MacroInfoChain(); 178 } 179 180 // Free any cached macro expanders. 181 // This populates MacroArgCache, so all TokenLexers need to be destroyed 182 // before the code below that frees up the MacroArgCache list. 183 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr); 184 CurTokenLexer.reset(); 185 186 // Free any cached MacroArgs. 187 for (MacroArgs *ArgList = MacroArgCache; ArgList;) 188 ArgList = ArgList->deallocate(); 189 190 // Delete the header search info, if we own it. 191 if (OwnsHeaderSearch) 192 delete &HeaderInfo; 193 } 194 195 void Preprocessor::Initialize(const TargetInfo &Target, 196 const TargetInfo *AuxTarget) { 197 assert((!this->Target || this->Target == &Target) && 198 "Invalid override of target information"); 199 this->Target = &Target; 200 201 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) && 202 "Invalid override of aux target information."); 203 this->AuxTarget = AuxTarget; 204 205 // Initialize information about built-ins. 206 BuiltinInfo->InitializeTarget(Target, AuxTarget); 207 HeaderInfo.setTarget(Target); 208 209 // Populate the identifier table with info about keywords for the current language. 210 Identifiers.AddKeywords(LangOpts); 211 } 212 213 void Preprocessor::InitializeForModelFile() { 214 NumEnteredSourceFiles = 0; 215 216 // Reset pragmas 217 PragmaHandlersBackup = std::move(PragmaHandlers); 218 PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef()); 219 RegisterBuiltinPragmas(); 220 221 // Reset PredefinesFileID 222 PredefinesFileID = FileID(); 223 } 224 225 void Preprocessor::FinalizeForModelFile() { 226 NumEnteredSourceFiles = 1; 227 228 PragmaHandlers = std::move(PragmaHandlersBackup); 229 } 230 231 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 232 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" 233 << getSpelling(Tok) << "'"; 234 235 if (!DumpFlags) return; 236 237 llvm::errs() << "\t"; 238 if (Tok.isAtStartOfLine()) 239 llvm::errs() << " [StartOfLine]"; 240 if (Tok.hasLeadingSpace()) 241 llvm::errs() << " [LeadingSpace]"; 242 if (Tok.isExpandDisabled()) 243 llvm::errs() << " [ExpandDisabled]"; 244 if (Tok.needsCleaning()) { 245 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 246 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) 247 << "']"; 248 } 249 250 llvm::errs() << "\tLoc=<"; 251 DumpLocation(Tok.getLocation()); 252 llvm::errs() << ">"; 253 } 254 255 void Preprocessor::DumpLocation(SourceLocation Loc) const { 256 Loc.print(llvm::errs(), SourceMgr); 257 } 258 259 void Preprocessor::DumpMacro(const MacroInfo &MI) const { 260 llvm::errs() << "MACRO: "; 261 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 262 DumpToken(MI.getReplacementToken(i)); 263 llvm::errs() << " "; 264 } 265 llvm::errs() << "\n"; 266 } 267 268 void Preprocessor::PrintStats() { 269 llvm::errs() << "\n*** Preprocessor Stats:\n"; 270 llvm::errs() << NumDirectives << " directives found:\n"; 271 llvm::errs() << " " << NumDefined << " #define.\n"; 272 llvm::errs() << " " << NumUndefined << " #undef.\n"; 273 llvm::errs() << " #include/#include_next/#import:\n"; 274 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n"; 275 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n"; 276 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 277 llvm::errs() << " " << NumElse << " #else/#elif/#elifdef/#elifndef.\n"; 278 llvm::errs() << " " << NumEndif << " #endif.\n"; 279 llvm::errs() << " " << NumPragma << " #pragma.\n"; 280 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 281 282 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 283 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 284 << NumFastMacroExpanded << " on the fast path.\n"; 285 llvm::errs() << (NumFastTokenPaste+NumTokenPaste) 286 << " token paste (##) operations performed, " 287 << NumFastTokenPaste << " on the fast path.\n"; 288 289 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total"; 290 291 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory(); 292 llvm::errs() << "\n Macro Expanded Tokens: " 293 << llvm::capacity_in_bytes(MacroExpandedTokens); 294 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity(); 295 // FIXME: List information for all submodules. 296 llvm::errs() << "\n Macros: " 297 << llvm::capacity_in_bytes(CurSubmoduleState->Macros); 298 llvm::errs() << "\n #pragma push_macro Info: " 299 << llvm::capacity_in_bytes(PragmaPushMacroInfo); 300 llvm::errs() << "\n Poison Reasons: " 301 << llvm::capacity_in_bytes(PoisonReasons); 302 llvm::errs() << "\n Comment Handlers: " 303 << llvm::capacity_in_bytes(CommentHandlers) << "\n"; 304 } 305 306 Preprocessor::macro_iterator 307 Preprocessor::macro_begin(bool IncludeExternalMacros) const { 308 if (IncludeExternalMacros && ExternalSource && 309 !ReadMacrosFromExternalSource) { 310 ReadMacrosFromExternalSource = true; 311 ExternalSource->ReadDefinedMacros(); 312 } 313 314 // Make sure we cover all macros in visible modules. 315 for (const ModuleMacro &Macro : ModuleMacros) 316 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState())); 317 318 return CurSubmoduleState->Macros.begin(); 319 } 320 321 size_t Preprocessor::getTotalMemory() const { 322 return BP.getTotalMemory() 323 + llvm::capacity_in_bytes(MacroExpandedTokens) 324 + Predefines.capacity() /* Predefines buffer. */ 325 // FIXME: Include sizes from all submodules, and include MacroInfo sizes, 326 // and ModuleMacros. 327 + llvm::capacity_in_bytes(CurSubmoduleState->Macros) 328 + llvm::capacity_in_bytes(PragmaPushMacroInfo) 329 + llvm::capacity_in_bytes(PoisonReasons) 330 + llvm::capacity_in_bytes(CommentHandlers); 331 } 332 333 Preprocessor::macro_iterator 334 Preprocessor::macro_end(bool IncludeExternalMacros) const { 335 if (IncludeExternalMacros && ExternalSource && 336 !ReadMacrosFromExternalSource) { 337 ReadMacrosFromExternalSource = true; 338 ExternalSource->ReadDefinedMacros(); 339 } 340 341 return CurSubmoduleState->Macros.end(); 342 } 343 344 /// Compares macro tokens with a specified token value sequence. 345 static bool MacroDefinitionEquals(const MacroInfo *MI, 346 ArrayRef<TokenValue> Tokens) { 347 return Tokens.size() == MI->getNumTokens() && 348 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin()); 349 } 350 351 StringRef Preprocessor::getLastMacroWithSpelling( 352 SourceLocation Loc, 353 ArrayRef<TokenValue> Tokens) const { 354 SourceLocation BestLocation; 355 StringRef BestSpelling; 356 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end(); 357 I != E; ++I) { 358 const MacroDirective::DefInfo 359 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr); 360 if (!Def || !Def.getMacroInfo()) 361 continue; 362 if (!Def.getMacroInfo()->isObjectLike()) 363 continue; 364 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens)) 365 continue; 366 SourceLocation Location = Def.getLocation(); 367 // Choose the macro defined latest. 368 if (BestLocation.isInvalid() || 369 (Location.isValid() && 370 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) { 371 BestLocation = Location; 372 BestSpelling = I->first->getName(); 373 } 374 } 375 return BestSpelling; 376 } 377 378 void Preprocessor::recomputeCurLexerKind() { 379 if (CurLexer) 380 CurLexerKind = CLK_Lexer; 381 else if (CurTokenLexer) 382 CurLexerKind = CLK_TokenLexer; 383 else 384 CurLexerKind = CLK_CachingLexer; 385 } 386 387 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, 388 unsigned CompleteLine, 389 unsigned CompleteColumn) { 390 assert(File); 391 assert(CompleteLine && CompleteColumn && "Starts from 1:1"); 392 assert(!CodeCompletionFile && "Already set"); 393 394 // Load the actual file's contents. 395 Optional<llvm::MemoryBufferRef> Buffer = 396 SourceMgr.getMemoryBufferForFileOrNone(File); 397 if (!Buffer) 398 return true; 399 400 // Find the byte position of the truncation point. 401 const char *Position = Buffer->getBufferStart(); 402 for (unsigned Line = 1; Line < CompleteLine; ++Line) { 403 for (; *Position; ++Position) { 404 if (*Position != '\r' && *Position != '\n') 405 continue; 406 407 // Eat \r\n or \n\r as a single line. 408 if ((Position[1] == '\r' || Position[1] == '\n') && 409 Position[0] != Position[1]) 410 ++Position; 411 ++Position; 412 break; 413 } 414 } 415 416 Position += CompleteColumn - 1; 417 418 // If pointing inside the preamble, adjust the position at the beginning of 419 // the file after the preamble. 420 if (SkipMainFilePreamble.first && 421 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) { 422 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first) 423 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first; 424 } 425 426 if (Position > Buffer->getBufferEnd()) 427 Position = Buffer->getBufferEnd(); 428 429 CodeCompletionFile = File; 430 CodeCompletionOffset = Position - Buffer->getBufferStart(); 431 432 auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer( 433 Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier()); 434 char *NewBuf = NewBuffer->getBufferStart(); 435 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf); 436 *NewPos = '\0'; 437 std::copy(Position, Buffer->getBufferEnd(), NewPos+1); 438 SourceMgr.overrideFileContents(File, std::move(NewBuffer)); 439 440 return false; 441 } 442 443 void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir, 444 bool IsAngled) { 445 setCodeCompletionReached(); 446 if (CodeComplete) 447 CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled); 448 } 449 450 void Preprocessor::CodeCompleteNaturalLanguage() { 451 setCodeCompletionReached(); 452 if (CodeComplete) 453 CodeComplete->CodeCompleteNaturalLanguage(); 454 } 455 456 /// getSpelling - This method is used to get the spelling of a token into a 457 /// SmallVector. Note that the returned StringRef may not point to the 458 /// supplied buffer if a copy can be avoided. 459 StringRef Preprocessor::getSpelling(const Token &Tok, 460 SmallVectorImpl<char> &Buffer, 461 bool *Invalid) const { 462 // NOTE: this has to be checked *before* testing for an IdentifierInfo. 463 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) { 464 // Try the fast path. 465 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) 466 return II->getName(); 467 } 468 469 // Resize the buffer if we need to copy into it. 470 if (Tok.needsCleaning()) 471 Buffer.resize(Tok.getLength()); 472 473 const char *Ptr = Buffer.data(); 474 unsigned Len = getSpelling(Tok, Ptr, Invalid); 475 return StringRef(Ptr, Len); 476 } 477 478 /// CreateString - Plop the specified string into a scratch buffer and return a 479 /// location for it. If specified, the source location provides a source 480 /// location for the token. 481 void Preprocessor::CreateString(StringRef Str, Token &Tok, 482 SourceLocation ExpansionLocStart, 483 SourceLocation ExpansionLocEnd) { 484 Tok.setLength(Str.size()); 485 486 const char *DestPtr; 487 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr); 488 489 if (ExpansionLocStart.isValid()) 490 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart, 491 ExpansionLocEnd, Str.size()); 492 Tok.setLocation(Loc); 493 494 // If this is a raw identifier or a literal token, set the pointer data. 495 if (Tok.is(tok::raw_identifier)) 496 Tok.setRawIdentifierData(DestPtr); 497 else if (Tok.isLiteral()) 498 Tok.setLiteralData(DestPtr); 499 } 500 501 SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) { 502 auto &SM = getSourceManager(); 503 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc); 504 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc); 505 bool Invalid = false; 506 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 507 if (Invalid) 508 return SourceLocation(); 509 510 // FIXME: We could consider re-using spelling for tokens we see repeatedly. 511 const char *DestPtr; 512 SourceLocation Spelling = 513 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr); 514 return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length)); 515 } 516 517 Module *Preprocessor::getCurrentModule() { 518 if (!getLangOpts().isCompilingModule()) 519 return nullptr; 520 521 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule, 522 SourceLocation()); 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 // FIXME: the raw_identifier may contain leading whitespace which is removed 721 // from the cleaned identifier token. The SourceLocation should be updated to 722 // refer to the non-whitespace character. For instance, the text "\\\nB" (a 723 // line continuation before 'B') is parsed as a single tok::raw_identifier and 724 // is cleaned to tok::identifier "B". After cleaning the token's length is 725 // still 3 and the SourceLocation refers to the location of the backslash. 726 Identifier.setIdentifierInfo(II); 727 Identifier.setKind(II->getTokenID()); 728 729 return II; 730 } 731 732 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { 733 PoisonReasons[II] = DiagID; 734 } 735 736 void Preprocessor::PoisonSEHIdentifiers(bool Poison) { 737 assert(Ident__exception_code && Ident__exception_info); 738 assert(Ident___exception_code && Ident___exception_info); 739 Ident__exception_code->setIsPoisoned(Poison); 740 Ident___exception_code->setIsPoisoned(Poison); 741 Ident_GetExceptionCode->setIsPoisoned(Poison); 742 Ident__exception_info->setIsPoisoned(Poison); 743 Ident___exception_info->setIsPoisoned(Poison); 744 Ident_GetExceptionInfo->setIsPoisoned(Poison); 745 Ident__abnormal_termination->setIsPoisoned(Poison); 746 Ident___abnormal_termination->setIsPoisoned(Poison); 747 Ident_AbnormalTermination->setIsPoisoned(Poison); 748 } 749 750 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { 751 assert(Identifier.getIdentifierInfo() && 752 "Can't handle identifiers without identifier info!"); 753 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = 754 PoisonReasons.find(Identifier.getIdentifierInfo()); 755 if(it == PoisonReasons.end()) 756 Diag(Identifier, diag::err_pp_used_poisoned_id); 757 else 758 Diag(Identifier,it->second) << Identifier.getIdentifierInfo(); 759 } 760 761 /// Returns a diagnostic message kind for reporting a future keyword as 762 /// appropriate for the identifier and specified language. 763 static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II, 764 const LangOptions &LangOpts) { 765 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed"); 766 767 if (LangOpts.CPlusPlus) 768 return llvm::StringSwitch<diag::kind>(II.getName()) 769 #define CXX11_KEYWORD(NAME, FLAGS) \ 770 .Case(#NAME, diag::warn_cxx11_keyword) 771 #define CXX20_KEYWORD(NAME, FLAGS) \ 772 .Case(#NAME, diag::warn_cxx20_keyword) 773 #include "clang/Basic/TokenKinds.def" 774 // char8_t is not modeled as a CXX20_KEYWORD because it's not 775 // unconditionally enabled in C++20 mode. (It can be disabled 776 // by -fno-char8_t.) 777 .Case("char8_t", diag::warn_cxx20_keyword) 778 ; 779 780 llvm_unreachable( 781 "Keyword not known to come from a newer Standard or proposed Standard"); 782 } 783 784 void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const { 785 assert(II.isOutOfDate() && "not out of date"); 786 getExternalSource()->updateOutOfDateIdentifier(II); 787 } 788 789 /// HandleIdentifier - This callback is invoked when the lexer reads an 790 /// identifier. This callback looks up the identifier in the map and/or 791 /// potentially macro expands it or turns it into a named token (like 'for'). 792 /// 793 /// Note that callers of this method are guarded by checking the 794 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the 795 /// IdentifierInfo methods that compute these properties will need to change to 796 /// match. 797 bool Preprocessor::HandleIdentifier(Token &Identifier) { 798 assert(Identifier.getIdentifierInfo() && 799 "Can't handle identifiers without identifier info!"); 800 801 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 802 803 // If the information about this identifier is out of date, update it from 804 // the external source. 805 // We have to treat __VA_ARGS__ in a special way, since it gets 806 // serialized with isPoisoned = true, but our preprocessor may have 807 // unpoisoned it if we're defining a C99 macro. 808 if (II.isOutOfDate()) { 809 bool CurrentIsPoisoned = false; 810 const bool IsSpecialVariadicMacro = 811 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__; 812 if (IsSpecialVariadicMacro) 813 CurrentIsPoisoned = II.isPoisoned(); 814 815 updateOutOfDateIdentifier(II); 816 Identifier.setKind(II.getTokenID()); 817 818 if (IsSpecialVariadicMacro) 819 II.setIsPoisoned(CurrentIsPoisoned); 820 } 821 822 // If this identifier was poisoned, and if it was not produced from a macro 823 // expansion, emit an error. 824 if (II.isPoisoned() && CurPPLexer) { 825 HandlePoisonedIdentifier(Identifier); 826 } 827 828 // If this is a macro to be expanded, do it. 829 if (MacroDefinition MD = getMacroDefinition(&II)) { 830 auto *MI = MD.getMacroInfo(); 831 assert(MI && "macro definition with no macro info?"); 832 if (!DisableMacroExpansion) { 833 if (!Identifier.isExpandDisabled() && MI->isEnabled()) { 834 // C99 6.10.3p10: If the preprocessing token immediately after the 835 // macro name isn't a '(', this macro should not be expanded. 836 if (!MI->isFunctionLike() || isNextPPTokenLParen()) 837 return HandleMacroExpandedIdentifier(Identifier, MD); 838 } else { 839 // C99 6.10.3.4p2 says that a disabled macro may never again be 840 // expanded, even if it's in a context where it could be expanded in the 841 // future. 842 Identifier.setFlag(Token::DisableExpand); 843 if (MI->isObjectLike() || isNextPPTokenLParen()) 844 Diag(Identifier, diag::pp_disabled_macro_expansion); 845 } 846 } 847 } 848 849 // If this identifier is a keyword in a newer Standard or proposed Standard, 850 // produce a warning. Don't warn if we're not considering macro expansion, 851 // since this identifier might be the name of a macro. 852 // FIXME: This warning is disabled in cases where it shouldn't be, like 853 // "#define constexpr constexpr", "int constexpr;" 854 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) { 855 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts())) 856 << II.getName(); 857 // Don't diagnose this keyword again in this translation unit. 858 II.setIsFutureCompatKeyword(false); 859 } 860 861 // If this is an extension token, diagnose its use. 862 // We avoid diagnosing tokens that originate from macro definitions. 863 // FIXME: This warning is disabled in cases where it shouldn't be, 864 // like "#define TY typeof", "TY(1) x". 865 if (II.isExtensionToken() && !DisableMacroExpansion) 866 Diag(Identifier, diag::ext_token_used); 867 868 // If this is the 'import' contextual keyword following an '@', note 869 // that the next token indicates a module name. 870 // 871 // Note that we do not treat 'import' as a contextual 872 // keyword when we're in a caching lexer, because caching lexers only get 873 // used in contexts where import declarations are disallowed. 874 // 875 // Likewise if this is the C++ Modules TS import keyword. 876 if (((LastTokenWasAt && II.isModulesImport()) || 877 Identifier.is(tok::kw_import)) && 878 !InMacroArgs && !DisableMacroExpansion && 879 (getLangOpts().Modules || getLangOpts().DebuggerSupport) && 880 CurLexerKind != CLK_CachingLexer) { 881 ModuleImportLoc = Identifier.getLocation(); 882 ModuleImportPath.clear(); 883 ModuleImportExpectsIdentifier = true; 884 CurLexerKind = CLK_LexAfterModuleImport; 885 } 886 return true; 887 } 888 889 void Preprocessor::Lex(Token &Result) { 890 ++LexLevel; 891 892 // We loop here until a lex function returns a token; this avoids recursion. 893 bool ReturnedToken; 894 do { 895 switch (CurLexerKind) { 896 case CLK_Lexer: 897 ReturnedToken = CurLexer->Lex(Result); 898 break; 899 case CLK_TokenLexer: 900 ReturnedToken = CurTokenLexer->Lex(Result); 901 break; 902 case CLK_CachingLexer: 903 CachingLex(Result); 904 ReturnedToken = true; 905 break; 906 case CLK_LexAfterModuleImport: 907 ReturnedToken = LexAfterModuleImport(Result); 908 break; 909 } 910 } while (!ReturnedToken); 911 912 if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure) 913 return; 914 915 if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) { 916 // Remember the identifier before code completion token. 917 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo()); 918 setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc()); 919 // Set IdenfitierInfo to null to avoid confusing code that handles both 920 // identifiers and completion tokens. 921 Result.setIdentifierInfo(nullptr); 922 } 923 924 // Update ImportSeqState to track our position within a C++20 import-seq 925 // if this token is being produced as a result of phase 4 of translation. 926 if (getLangOpts().CPlusPlusModules && LexLevel == 1 && 927 !Result.getFlag(Token::IsReinjected)) { 928 switch (Result.getKind()) { 929 case tok::l_paren: case tok::l_square: case tok::l_brace: 930 ImportSeqState.handleOpenBracket(); 931 break; 932 case tok::r_paren: case tok::r_square: 933 ImportSeqState.handleCloseBracket(); 934 break; 935 case tok::r_brace: 936 ImportSeqState.handleCloseBrace(); 937 break; 938 case tok::semi: 939 ImportSeqState.handleSemi(); 940 break; 941 case tok::header_name: 942 case tok::annot_header_unit: 943 ImportSeqState.handleHeaderName(); 944 break; 945 case tok::kw_export: 946 ImportSeqState.handleExport(); 947 break; 948 case tok::identifier: 949 if (Result.getIdentifierInfo()->isModulesImport()) { 950 ImportSeqState.handleImport(); 951 if (ImportSeqState.afterImportSeq()) { 952 ModuleImportLoc = Result.getLocation(); 953 ModuleImportPath.clear(); 954 ModuleImportExpectsIdentifier = true; 955 CurLexerKind = CLK_LexAfterModuleImport; 956 } 957 break; 958 } 959 LLVM_FALLTHROUGH; 960 default: 961 ImportSeqState.handleMisc(); 962 break; 963 } 964 } 965 966 LastTokenWasAt = Result.is(tok::at); 967 --LexLevel; 968 969 if ((LexLevel == 0 || PreprocessToken) && 970 !Result.getFlag(Token::IsReinjected)) { 971 if (LexLevel == 0) 972 ++TokenCount; 973 if (OnToken) 974 OnToken(Result); 975 } 976 } 977 978 /// Lex a header-name token (including one formed from header-name-tokens if 979 /// \p AllowConcatenation is \c true). 980 /// 981 /// \param FilenameTok Filled in with the next token. On success, this will 982 /// be either a header_name token. On failure, it will be whatever other 983 /// token was found instead. 984 /// \param AllowMacroExpansion If \c true, allow the header name to be formed 985 /// by macro expansion (concatenating tokens as necessary if the first 986 /// token is a '<'). 987 /// \return \c true if we reached EOD or EOF while looking for a > token in 988 /// a concatenated header name and diagnosed it. \c false otherwise. 989 bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) { 990 // Lex using header-name tokenization rules if tokens are being lexed from 991 // a file. Just grab a token normally if we're in a macro expansion. 992 if (CurPPLexer) 993 CurPPLexer->LexIncludeFilename(FilenameTok); 994 else 995 Lex(FilenameTok); 996 997 // This could be a <foo/bar.h> file coming from a macro expansion. In this 998 // case, glue the tokens together into an angle_string_literal token. 999 SmallString<128> FilenameBuffer; 1000 if (FilenameTok.is(tok::less) && AllowMacroExpansion) { 1001 bool StartOfLine = FilenameTok.isAtStartOfLine(); 1002 bool LeadingSpace = FilenameTok.hasLeadingSpace(); 1003 bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro(); 1004 1005 SourceLocation Start = FilenameTok.getLocation(); 1006 SourceLocation End; 1007 FilenameBuffer.push_back('<'); 1008 1009 // Consume tokens until we find a '>'. 1010 // FIXME: A header-name could be formed starting or ending with an 1011 // alternative token. It's not clear whether that's ill-formed in all 1012 // cases. 1013 while (FilenameTok.isNot(tok::greater)) { 1014 Lex(FilenameTok); 1015 if (FilenameTok.isOneOf(tok::eod, tok::eof)) { 1016 Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater; 1017 Diag(Start, diag::note_matching) << tok::less; 1018 return true; 1019 } 1020 1021 End = FilenameTok.getLocation(); 1022 1023 // FIXME: Provide code completion for #includes. 1024 if (FilenameTok.is(tok::code_completion)) { 1025 setCodeCompletionReached(); 1026 Lex(FilenameTok); 1027 continue; 1028 } 1029 1030 // Append the spelling of this token to the buffer. If there was a space 1031 // before it, add it now. 1032 if (FilenameTok.hasLeadingSpace()) 1033 FilenameBuffer.push_back(' '); 1034 1035 // Get the spelling of the token, directly into FilenameBuffer if 1036 // possible. 1037 size_t PreAppendSize = FilenameBuffer.size(); 1038 FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength()); 1039 1040 const char *BufPtr = &FilenameBuffer[PreAppendSize]; 1041 unsigned ActualLen = getSpelling(FilenameTok, BufPtr); 1042 1043 // If the token was spelled somewhere else, copy it into FilenameBuffer. 1044 if (BufPtr != &FilenameBuffer[PreAppendSize]) 1045 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); 1046 1047 // Resize FilenameBuffer to the correct size. 1048 if (FilenameTok.getLength() != ActualLen) 1049 FilenameBuffer.resize(PreAppendSize + ActualLen); 1050 } 1051 1052 FilenameTok.startToken(); 1053 FilenameTok.setKind(tok::header_name); 1054 FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine); 1055 FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace); 1056 FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro); 1057 CreateString(FilenameBuffer, FilenameTok, Start, End); 1058 } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) { 1059 // Convert a string-literal token of the form " h-char-sequence " 1060 // (produced by macro expansion) into a header-name token. 1061 // 1062 // The rules for header-names don't quite match the rules for 1063 // string-literals, but all the places where they differ result in 1064 // undefined behavior, so we can and do treat them the same. 1065 // 1066 // A string-literal with a prefix or suffix is not translated into a 1067 // header-name. This could theoretically be observable via the C++20 1068 // context-sensitive header-name formation rules. 1069 StringRef Str = getSpelling(FilenameTok, FilenameBuffer); 1070 if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"') 1071 FilenameTok.setKind(tok::header_name); 1072 } 1073 1074 return false; 1075 } 1076 1077 /// Collect the tokens of a C++20 pp-import-suffix. 1078 void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) { 1079 // FIXME: For error recovery, consider recognizing attribute syntax here 1080 // and terminating / diagnosing a missing semicolon if we find anything 1081 // else? (Can we leave that to the parser?) 1082 unsigned BracketDepth = 0; 1083 while (true) { 1084 Toks.emplace_back(); 1085 Lex(Toks.back()); 1086 1087 switch (Toks.back().getKind()) { 1088 case tok::l_paren: case tok::l_square: case tok::l_brace: 1089 ++BracketDepth; 1090 break; 1091 1092 case tok::r_paren: case tok::r_square: case tok::r_brace: 1093 if (BracketDepth == 0) 1094 return; 1095 --BracketDepth; 1096 break; 1097 1098 case tok::semi: 1099 if (BracketDepth == 0) 1100 return; 1101 break; 1102 1103 case tok::eof: 1104 return; 1105 1106 default: 1107 break; 1108 } 1109 } 1110 } 1111 1112 1113 /// Lex a token following the 'import' contextual keyword. 1114 /// 1115 /// pp-import: [C++20] 1116 /// import header-name pp-import-suffix[opt] ; 1117 /// import header-name-tokens pp-import-suffix[opt] ; 1118 /// [ObjC] @ import module-name ; 1119 /// [Clang] import module-name ; 1120 /// 1121 /// header-name-tokens: 1122 /// string-literal 1123 /// < [any sequence of preprocessing-tokens other than >] > 1124 /// 1125 /// module-name: 1126 /// module-name-qualifier[opt] identifier 1127 /// 1128 /// module-name-qualifier 1129 /// module-name-qualifier[opt] identifier . 1130 /// 1131 /// We respond to a pp-import by importing macros from the named module. 1132 bool Preprocessor::LexAfterModuleImport(Token &Result) { 1133 // Figure out what kind of lexer we actually have. 1134 recomputeCurLexerKind(); 1135 1136 // Lex the next token. The header-name lexing rules are used at the start of 1137 // a pp-import. 1138 // 1139 // For now, we only support header-name imports in C++20 mode. 1140 // FIXME: Should we allow this in all language modes that support an import 1141 // declaration as an extension? 1142 if (ModuleImportPath.empty() && getLangOpts().CPlusPlusModules) { 1143 if (LexHeaderName(Result)) 1144 return true; 1145 } else { 1146 Lex(Result); 1147 } 1148 1149 // Allocate a holding buffer for a sequence of tokens and introduce it into 1150 // the token stream. 1151 auto EnterTokens = [this](ArrayRef<Token> Toks) { 1152 auto ToksCopy = std::make_unique<Token[]>(Toks.size()); 1153 std::copy(Toks.begin(), Toks.end(), ToksCopy.get()); 1154 EnterTokenStream(std::move(ToksCopy), Toks.size(), 1155 /*DisableMacroExpansion*/ true, /*IsReinject*/ false); 1156 }; 1157 1158 // Check for a header-name. 1159 SmallVector<Token, 32> Suffix; 1160 if (Result.is(tok::header_name)) { 1161 // Enter the header-name token into the token stream; a Lex action cannot 1162 // both return a token and cache tokens (doing so would corrupt the token 1163 // cache if the call to Lex comes from CachingLex / PeekAhead). 1164 Suffix.push_back(Result); 1165 1166 // Consume the pp-import-suffix and expand any macros in it now. We'll add 1167 // it back into the token stream later. 1168 CollectPpImportSuffix(Suffix); 1169 if (Suffix.back().isNot(tok::semi)) { 1170 // This is not a pp-import after all. 1171 EnterTokens(Suffix); 1172 return false; 1173 } 1174 1175 // C++2a [cpp.module]p1: 1176 // The ';' preprocessing-token terminating a pp-import shall not have 1177 // been produced by macro replacement. 1178 SourceLocation SemiLoc = Suffix.back().getLocation(); 1179 if (SemiLoc.isMacroID()) 1180 Diag(SemiLoc, diag::err_header_import_semi_in_macro); 1181 1182 // Reconstitute the import token. 1183 Token ImportTok; 1184 ImportTok.startToken(); 1185 ImportTok.setKind(tok::kw_import); 1186 ImportTok.setLocation(ModuleImportLoc); 1187 ImportTok.setIdentifierInfo(getIdentifierInfo("import")); 1188 ImportTok.setLength(6); 1189 1190 auto Action = HandleHeaderIncludeOrImport( 1191 /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc); 1192 switch (Action.Kind) { 1193 case ImportAction::None: 1194 break; 1195 1196 case ImportAction::ModuleBegin: 1197 // Let the parser know we're textually entering the module. 1198 Suffix.emplace_back(); 1199 Suffix.back().startToken(); 1200 Suffix.back().setKind(tok::annot_module_begin); 1201 Suffix.back().setLocation(SemiLoc); 1202 Suffix.back().setAnnotationEndLoc(SemiLoc); 1203 Suffix.back().setAnnotationValue(Action.ModuleForHeader); 1204 LLVM_FALLTHROUGH; 1205 1206 case ImportAction::ModuleImport: 1207 case ImportAction::SkippedModuleImport: 1208 // We chose to import (or textually enter) the file. Convert the 1209 // header-name token into a header unit annotation token. 1210 Suffix[0].setKind(tok::annot_header_unit); 1211 Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation()); 1212 Suffix[0].setAnnotationValue(Action.ModuleForHeader); 1213 // FIXME: Call the moduleImport callback? 1214 break; 1215 case ImportAction::Failure: 1216 assert(TheModuleLoader.HadFatalFailure && 1217 "This should be an early exit only to a fatal error"); 1218 Result.setKind(tok::eof); 1219 CurLexer->cutOffLexing(); 1220 EnterTokens(Suffix); 1221 return true; 1222 } 1223 1224 EnterTokens(Suffix); 1225 return false; 1226 } 1227 1228 // The token sequence 1229 // 1230 // import identifier (. identifier)* 1231 // 1232 // indicates a module import directive. We already saw the 'import' 1233 // contextual keyword, so now we're looking for the identifiers. 1234 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { 1235 // We expected to see an identifier here, and we did; continue handling 1236 // identifiers. 1237 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(), 1238 Result.getLocation())); 1239 ModuleImportExpectsIdentifier = false; 1240 CurLexerKind = CLK_LexAfterModuleImport; 1241 return true; 1242 } 1243 1244 // If we're expecting a '.' or a ';', and we got a '.', then wait until we 1245 // see the next identifier. (We can also see a '[[' that begins an 1246 // attribute-specifier-seq here under the C++ Modules TS.) 1247 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) { 1248 ModuleImportExpectsIdentifier = true; 1249 CurLexerKind = CLK_LexAfterModuleImport; 1250 return true; 1251 } 1252 1253 // If we didn't recognize a module name at all, this is not a (valid) import. 1254 if (ModuleImportPath.empty() || Result.is(tok::eof)) 1255 return true; 1256 1257 // Consume the pp-import-suffix and expand any macros in it now, if we're not 1258 // at the semicolon already. 1259 SourceLocation SemiLoc = Result.getLocation(); 1260 if (Result.isNot(tok::semi)) { 1261 Suffix.push_back(Result); 1262 CollectPpImportSuffix(Suffix); 1263 if (Suffix.back().isNot(tok::semi)) { 1264 // This is not an import after all. 1265 EnterTokens(Suffix); 1266 return false; 1267 } 1268 SemiLoc = Suffix.back().getLocation(); 1269 } 1270 1271 // Under the Modules TS, the dot is just part of the module name, and not 1272 // a real hierarchy separator. Flatten such module names now. 1273 // 1274 // FIXME: Is this the right level to be performing this transformation? 1275 std::string FlatModuleName; 1276 if (getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) { 1277 for (auto &Piece : ModuleImportPath) { 1278 if (!FlatModuleName.empty()) 1279 FlatModuleName += "."; 1280 FlatModuleName += Piece.first->getName(); 1281 } 1282 SourceLocation FirstPathLoc = ModuleImportPath[0].second; 1283 ModuleImportPath.clear(); 1284 ModuleImportPath.push_back( 1285 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc)); 1286 } 1287 1288 Module *Imported = nullptr; 1289 if (getLangOpts().Modules) { 1290 Imported = TheModuleLoader.loadModule(ModuleImportLoc, 1291 ModuleImportPath, 1292 Module::Hidden, 1293 /*IsInclusionDirective=*/false); 1294 if (Imported) 1295 makeModuleVisible(Imported, SemiLoc); 1296 } 1297 if (Callbacks) 1298 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported); 1299 1300 if (!Suffix.empty()) { 1301 EnterTokens(Suffix); 1302 return false; 1303 } 1304 return true; 1305 } 1306 1307 void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) { 1308 CurSubmoduleState->VisibleModules.setVisible( 1309 M, Loc, [](Module *) {}, 1310 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) { 1311 // FIXME: Include the path in the diagnostic. 1312 // FIXME: Include the import location for the conflicting module. 1313 Diag(ModuleImportLoc, diag::warn_module_conflict) 1314 << Path[0]->getFullModuleName() 1315 << Conflict->getFullModuleName() 1316 << Message; 1317 }); 1318 1319 // Add this module to the imports list of the currently-built submodule. 1320 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M) 1321 BuildingSubmoduleStack.back().M->Imports.insert(M); 1322 } 1323 1324 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String, 1325 const char *DiagnosticTag, 1326 bool AllowMacroExpansion) { 1327 // We need at least one string literal. 1328 if (Result.isNot(tok::string_literal)) { 1329 Diag(Result, diag::err_expected_string_literal) 1330 << /*Source='in...'*/0 << DiagnosticTag; 1331 return false; 1332 } 1333 1334 // Lex string literal tokens, optionally with macro expansion. 1335 SmallVector<Token, 4> StrToks; 1336 do { 1337 StrToks.push_back(Result); 1338 1339 if (Result.hasUDSuffix()) 1340 Diag(Result, diag::err_invalid_string_udl); 1341 1342 if (AllowMacroExpansion) 1343 Lex(Result); 1344 else 1345 LexUnexpandedToken(Result); 1346 } while (Result.is(tok::string_literal)); 1347 1348 // Concatenate and parse the strings. 1349 StringLiteralParser Literal(StrToks, *this); 1350 assert(Literal.isAscii() && "Didn't allow wide strings in"); 1351 1352 if (Literal.hadError) 1353 return false; 1354 1355 if (Literal.Pascal) { 1356 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal) 1357 << /*Source='in...'*/0 << DiagnosticTag; 1358 return false; 1359 } 1360 1361 String = std::string(Literal.GetString()); 1362 return true; 1363 } 1364 1365 bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) { 1366 assert(Tok.is(tok::numeric_constant)); 1367 SmallString<8> IntegerBuffer; 1368 bool NumberInvalid = false; 1369 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid); 1370 if (NumberInvalid) 1371 return false; 1372 NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(), 1373 getLangOpts(), getTargetInfo(), 1374 getDiagnostics()); 1375 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix()) 1376 return false; 1377 llvm::APInt APVal(64, 0); 1378 if (Literal.GetIntegerValue(APVal)) 1379 return false; 1380 Lex(Tok); 1381 Value = APVal.getLimitedValue(); 1382 return true; 1383 } 1384 1385 void Preprocessor::addCommentHandler(CommentHandler *Handler) { 1386 assert(Handler && "NULL comment handler"); 1387 assert(llvm::find(CommentHandlers, Handler) == CommentHandlers.end() && 1388 "Comment handler already registered"); 1389 CommentHandlers.push_back(Handler); 1390 } 1391 1392 void Preprocessor::removeCommentHandler(CommentHandler *Handler) { 1393 std::vector<CommentHandler *>::iterator Pos = 1394 llvm::find(CommentHandlers, Handler); 1395 assert(Pos != CommentHandlers.end() && "Comment handler not registered"); 1396 CommentHandlers.erase(Pos); 1397 } 1398 1399 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) { 1400 bool AnyPendingTokens = false; 1401 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(), 1402 HEnd = CommentHandlers.end(); 1403 H != HEnd; ++H) { 1404 if ((*H)->HandleComment(*this, Comment)) 1405 AnyPendingTokens = true; 1406 } 1407 if (!AnyPendingTokens || getCommentRetentionState()) 1408 return false; 1409 Lex(result); 1410 return true; 1411 } 1412 1413 void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const { 1414 const MacroAnnotations &A = 1415 getMacroAnnotations(Identifier.getIdentifierInfo()); 1416 assert(A.DeprecationInfo && 1417 "Macro deprecation warning without recorded annotation!"); 1418 const MacroAnnotationInfo &Info = *A.DeprecationInfo; 1419 if (Info.Message.empty()) 1420 Diag(Identifier, diag::warn_pragma_deprecated_macro_use) 1421 << Identifier.getIdentifierInfo() << 0; 1422 else 1423 Diag(Identifier, diag::warn_pragma_deprecated_macro_use) 1424 << Identifier.getIdentifierInfo() << 1 << Info.Message; 1425 Diag(Info.Location, diag::note_pp_macro_annotation) << 0; 1426 } 1427 1428 void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const { 1429 const MacroAnnotations &A = 1430 getMacroAnnotations(Identifier.getIdentifierInfo()); 1431 assert(A.RestrictExpansionInfo && 1432 "Macro restricted expansion warning without recorded annotation!"); 1433 const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo; 1434 if (Info.Message.empty()) 1435 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use) 1436 << Identifier.getIdentifierInfo() << 0; 1437 else 1438 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use) 1439 << Identifier.getIdentifierInfo() << 1 << Info.Message; 1440 Diag(Info.Location, diag::note_pp_macro_annotation) << 1; 1441 } 1442 1443 void Preprocessor::emitFinalMacroWarning(const Token &Identifier, 1444 bool IsUndef) const { 1445 const MacroAnnotations &A = 1446 getMacroAnnotations(Identifier.getIdentifierInfo()); 1447 assert(A.FinalAnnotationLoc && 1448 "Final macro warning without recorded annotation!"); 1449 1450 Diag(Identifier, diag::warn_pragma_final_macro) 1451 << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1); 1452 Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2; 1453 } 1454 1455 ModuleLoader::~ModuleLoader() = default; 1456 1457 CommentHandler::~CommentHandler() = default; 1458 1459 EmptylineHandler::~EmptylineHandler() = default; 1460 1461 CodeCompletionHandler::~CodeCompletionHandler() = default; 1462 1463 void Preprocessor::createPreprocessingRecord() { 1464 if (Record) 1465 return; 1466 1467 Record = new PreprocessingRecord(getSourceManager()); 1468 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record)); 1469 } 1470