| 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/IdentifierTable.h" |
| 31 | #include "clang/Basic/LLVM.h" |
| 32 | #include "clang/Basic/LangOptions.h" |
| 33 | #include "clang/Basic/Module.h" |
| 34 | #include "clang/Basic/SourceLocation.h" |
| 35 | #include "clang/Basic/SourceManager.h" |
| 36 | #include "clang/Basic/TargetInfo.h" |
| 37 | #include "clang/Lex/CodeCompletionHandler.h" |
| 38 | #include "clang/Lex/DependencyDirectivesScanner.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/NoTrivialPPDirectiveTracer.h" |
| 48 | #include "clang/Lex/Pragma.h" |
| 49 | #include "clang/Lex/PreprocessingRecord.h" |
| 50 | #include "clang/Lex/PreprocessorLexer.h" |
| 51 | #include "clang/Lex/PreprocessorOptions.h" |
| 52 | #include "clang/Lex/ScratchBuffer.h" |
| 53 | #include "clang/Lex/Token.h" |
| 54 | #include "clang/Lex/TokenLexer.h" |
| 55 | #include "llvm/ADT/APInt.h" |
| 56 | #include "llvm/ADT/ArrayRef.h" |
| 57 | #include "llvm/ADT/DenseMap.h" |
| 58 | #include "llvm/ADT/STLExtras.h" |
| 59 | #include "llvm/ADT/ScopeExit.h" |
| 60 | #include "llvm/ADT/SmallVector.h" |
| 61 | #include "llvm/ADT/StringRef.h" |
| 62 | #include "llvm/Support/Capacity.h" |
| 63 | #include "llvm/Support/ErrorHandling.h" |
| 64 | #include "llvm/Support/FormatVariadic.h" |
| 65 | #include "llvm/Support/MemoryBuffer.h" |
| 66 | #include "llvm/Support/MemoryBufferRef.h" |
| 67 | #include "llvm/Support/SaveAndRestore.h" |
| 68 | #include "llvm/Support/raw_ostream.h" |
| 69 | #include <algorithm> |
| 70 | #include <cassert> |
| 71 | #include <memory> |
| 72 | #include <optional> |
| 73 | #include <string> |
| 74 | #include <utility> |
| 75 | #include <vector> |
| 76 | |
| 77 | using namespace clang; |
| 78 | |
| 79 | /// Minimum distance between two check points, in tokens. |
| 80 | static constexpr unsigned CheckPointStepSize = 1024; |
| 81 | |
| 82 | LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry) |
| 83 | |
| 84 | ExternalPreprocessorSource::~ExternalPreprocessorSource() = default; |
| 85 | |
| 86 | Preprocessor::(const PreprocessorOptions &PPOpts, |
| 87 | DiagnosticsEngine &diags, const LangOptions &opts, |
| 88 | SourceManager &SM, HeaderSearch &, |
| 89 | ModuleLoader &TheModuleLoader, |
| 90 | IdentifierInfoLookup *IILookup, bool , |
| 91 | TranslationUnitKind TUKind) |
| 92 | : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), |
| 93 | FileMgr(Headers.getFileMgr()), SourceMgr(SM), |
| 94 | ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers), |
| 95 | TheModuleLoader(TheModuleLoader), ExternalSource(nullptr), |
| 96 | // As the language options may have not been loaded yet (when |
| 97 | // deserializing an ASTUnit), adding keywords to the identifier table is |
| 98 | // deferred to Preprocessor::Initialize(). |
| 99 | Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())), |
| 100 | TUKind(TUKind), SkipMainFilePreamble(0, true), |
| 101 | CurSubmoduleState(&NullSubmoduleState) { |
| 102 | OwnsHeaderSearch = OwnsHeaders; |
| 103 | |
| 104 | // Default to discarding comments. |
| 105 | KeepComments = false; |
| 106 | KeepMacroComments = false; |
| 107 | SuppressIncludeNotFoundError = false; |
| 108 | |
| 109 | // Macro expansion is enabled. |
| 110 | DisableMacroExpansion = false; |
| 111 | MacroExpansionInDirectivesOverride = false; |
| 112 | InMacroArgs = false; |
| 113 | ArgMacro = nullptr; |
| 114 | InMacroArgPreExpansion = false; |
| 115 | NumCachedTokenLexers = 0; |
| 116 | PragmasEnabled = true; |
| 117 | ParsingIfOrElifDirective = false; |
| 118 | PreprocessedOutput = false; |
| 119 | |
| 120 | // We haven't read anything from the external source. |
| 121 | ReadMacrosFromExternalSource = false; |
| 122 | |
| 123 | LastExportKeyword.startToken(); |
| 124 | |
| 125 | BuiltinInfo = std::make_unique<Builtin::Context>(); |
| 126 | |
| 127 | // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of |
| 128 | // a macro. They get unpoisoned where it is allowed. |
| 129 | (Ident__VA_ARGS__ = getIdentifierInfo(Name: "__VA_ARGS__" ))->setIsPoisoned(); |
| 130 | SetPoisonReason(II: Ident__VA_ARGS__,DiagID: diag::ext_pp_bad_vaargs_use); |
| 131 | (Ident__VA_OPT__ = getIdentifierInfo(Name: "__VA_OPT__" ))->setIsPoisoned(); |
| 132 | SetPoisonReason(II: Ident__VA_OPT__,DiagID: diag::ext_pp_bad_vaopt_use); |
| 133 | |
| 134 | // Initialize the pragma handlers. |
| 135 | RegisterBuiltinPragmas(); |
| 136 | |
| 137 | // Initialize builtin macros like __LINE__ and friends. |
| 138 | RegisterBuiltinMacros(); |
| 139 | |
| 140 | if(LangOpts.Borland) { |
| 141 | Ident__exception_info = getIdentifierInfo(Name: "_exception_info" ); |
| 142 | Ident___exception_info = getIdentifierInfo(Name: "__exception_info" ); |
| 143 | Ident_GetExceptionInfo = getIdentifierInfo(Name: "GetExceptionInformation" ); |
| 144 | Ident__exception_code = getIdentifierInfo(Name: "_exception_code" ); |
| 145 | Ident___exception_code = getIdentifierInfo(Name: "__exception_code" ); |
| 146 | Ident_GetExceptionCode = getIdentifierInfo(Name: "GetExceptionCode" ); |
| 147 | Ident__abnormal_termination = getIdentifierInfo(Name: "_abnormal_termination" ); |
| 148 | Ident___abnormal_termination = getIdentifierInfo(Name: "__abnormal_termination" ); |
| 149 | Ident_AbnormalTermination = getIdentifierInfo(Name: "AbnormalTermination" ); |
| 150 | } else { |
| 151 | Ident__exception_info = Ident__exception_code = nullptr; |
| 152 | Ident__abnormal_termination = Ident___exception_info = nullptr; |
| 153 | Ident___exception_code = Ident___abnormal_termination = nullptr; |
| 154 | Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr; |
| 155 | Ident_AbnormalTermination = nullptr; |
| 156 | } |
| 157 | |
| 158 | // Default incremental processing to -fincremental-extensions, clients can |
| 159 | // override with `enableIncrementalProcessing` if desired. |
| 160 | IncrementalProcessing = LangOpts.IncrementalExtensions; |
| 161 | |
| 162 | // If using a PCH where a #pragma hdrstop is expected, start skipping tokens. |
| 163 | if (usingPCHWithPragmaHdrStop()) |
| 164 | SkippingUntilPragmaHdrStop = true; |
| 165 | |
| 166 | // If using a PCH with a through header, start skipping tokens. |
| 167 | if (!this->PPOpts.PCHThroughHeader.empty() && |
| 168 | !this->PPOpts.ImplicitPCHInclude.empty()) |
| 169 | SkippingUntilPCHThroughHeader = true; |
| 170 | |
| 171 | if (this->PPOpts.GeneratePreamble) |
| 172 | PreambleConditionalStack.startRecording(); |
| 173 | |
| 174 | MaxTokens = LangOpts.MaxTokens; |
| 175 | } |
| 176 | |
| 177 | Preprocessor::~Preprocessor() { |
| 178 | assert(!isBacktrackEnabled() && "EnableBacktrack/Backtrack imbalance!" ); |
| 179 | |
| 180 | IncludeMacroStack.clear(); |
| 181 | |
| 182 | // Free any cached macro expanders. |
| 183 | // This populates MacroArgCache, so all TokenLexers need to be destroyed |
| 184 | // before the code below that frees up the MacroArgCache list. |
| 185 | std::fill(first: TokenLexerCache, last: TokenLexerCache + NumCachedTokenLexers, value: nullptr); |
| 186 | CurTokenLexer.reset(); |
| 187 | |
| 188 | // Free any cached MacroArgs. |
| 189 | for (MacroArgs *ArgList = MacroArgCache; ArgList;) |
| 190 | ArgList = ArgList->deallocate(); |
| 191 | |
| 192 | // Delete the header search info, if we own it. |
| 193 | if (OwnsHeaderSearch) |
| 194 | delete &HeaderInfo; |
| 195 | } |
| 196 | |
| 197 | void Preprocessor::Initialize(const TargetInfo &Target, |
| 198 | const TargetInfo *AuxTarget) { |
| 199 | assert((!this->Target || this->Target == &Target) && |
| 200 | "Invalid override of target information" ); |
| 201 | this->Target = &Target; |
| 202 | |
| 203 | assert((!this->AuxTarget || this->AuxTarget == AuxTarget) && |
| 204 | "Invalid override of aux target information." ); |
| 205 | this->AuxTarget = AuxTarget; |
| 206 | |
| 207 | // Initialize information about built-ins. |
| 208 | BuiltinInfo->InitializeTarget(Target, AuxTarget); |
| 209 | HeaderInfo.setTarget(Target); |
| 210 | |
| 211 | // Populate the identifier table with info about keywords for the current language. |
| 212 | Identifiers.AddKeywords(LangOpts); |
| 213 | |
| 214 | // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo. |
| 215 | setTUFPEvalMethod(getTargetInfo().getFPEvalMethod()); |
| 216 | |
| 217 | if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine) |
| 218 | // Use setting from TargetInfo. |
| 219 | setCurrentFPEvalMethod(PragmaLoc: SourceLocation(), Val: Target.getFPEvalMethod()); |
| 220 | else |
| 221 | // Set initial value of __FLT_EVAL_METHOD__ from the command line. |
| 222 | setCurrentFPEvalMethod(PragmaLoc: SourceLocation(), Val: getLangOpts().getFPEvalMethod()); |
| 223 | } |
| 224 | |
| 225 | void Preprocessor::InitializeForModelFile() { |
| 226 | NumEnteredSourceFiles = 0; |
| 227 | |
| 228 | // Reset pragmas |
| 229 | PragmaHandlersBackup = std::move(PragmaHandlers); |
| 230 | PragmaHandlers = std::make_unique<PragmaNamespace>(args: StringRef()); |
| 231 | RegisterBuiltinPragmas(); |
| 232 | |
| 233 | // Reset PredefinesFileID |
| 234 | PredefinesFileID = FileID(); |
| 235 | } |
| 236 | |
| 237 | void Preprocessor::FinalizeForModelFile() { |
| 238 | NumEnteredSourceFiles = 1; |
| 239 | |
| 240 | PragmaHandlers = std::move(PragmaHandlersBackup); |
| 241 | } |
| 242 | |
| 243 | void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { |
| 244 | std::string TokenStr; |
| 245 | llvm::raw_string_ostream OS(TokenStr); |
| 246 | |
| 247 | // The alignment of 16 is chosen to comfortably fit most identifiers. |
| 248 | OS << llvm::formatv(Fmt: "{0,-16} " , Vals: tok::getTokenName(Kind: Tok.getKind())); |
| 249 | |
| 250 | // Annotation tokens are just markers that don't have a spelling -- they |
| 251 | // indicate where something expanded. |
| 252 | if (!Tok.isAnnotation()) { |
| 253 | OS << "'" ; |
| 254 | // Escape string to prevent token spelling from spanning multiple lines. |
| 255 | OS.write_escaped(Str: getSpelling(Tok)); |
| 256 | OS << "'" ; |
| 257 | } |
| 258 | |
| 259 | // The alignment of 48 (32 characters for the spelling + the 16 for |
| 260 | // the identifier name) fits most variable names, keywords and annotations. |
| 261 | llvm::errs() << llvm::formatv(Fmt: "{0,-48} " , Vals&: OS.str()); |
| 262 | |
| 263 | if (!DumpFlags) return; |
| 264 | |
| 265 | auto Loc = Tok.getLocation(); |
| 266 | llvm::errs() << "Loc=<" ; |
| 267 | DumpLocation(Loc); |
| 268 | llvm::errs() << ">" ; |
| 269 | |
| 270 | // If the token points directly to a file location (i.e. not a macro |
| 271 | // expansion), then add additional padding so that trailing markers |
| 272 | // align, provided the line/column numbers are reasonably sized. |
| 273 | // |
| 274 | // Otherwise, if it's a macro expansion, don't bother with alignment, |
| 275 | // as the line will include multiple locations and be very long. |
| 276 | // |
| 277 | // NOTE: To keep this stateless, it doesn't account for filename |
| 278 | // length, so when a header starts markers will be temporarily misaligned. |
| 279 | if (Loc.isFileID()) { |
| 280 | PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); |
| 281 | |
| 282 | if (!PLoc.isInvalid()) { |
| 283 | int LineWidth = llvm::utostr(X: PLoc.getLine()).size(); |
| 284 | int ColumnWidth = llvm::utostr(X: PLoc.getColumn()).size(); |
| 285 | |
| 286 | // Reserve space for lines up to 9999 and columns up to 99, |
| 287 | // which is 4 + 2 = 6 characters in total. |
| 288 | const int ReservedSpace = 6; |
| 289 | |
| 290 | int LeftSpace = ReservedSpace - LineWidth - ColumnWidth; |
| 291 | int Padding = std::max<int>(a: 0, b: LeftSpace); |
| 292 | |
| 293 | llvm::errs().indent(NumSpaces: Padding); |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | if (Tok.isAtStartOfLine()) |
| 298 | llvm::errs() << " [StartOfLine]" ; |
| 299 | if (Tok.hasLeadingSpace()) |
| 300 | llvm::errs() << " [LeadingSpace]" ; |
| 301 | if (Tok.isExpandDisabled()) |
| 302 | llvm::errs() << " [ExpandDisabled]" ; |
| 303 | if (Tok.needsCleaning()) { |
| 304 | const char *Start = SourceMgr.getCharacterData(SL: Tok.getLocation()); |
| 305 | llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) << "']" ; |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | void Preprocessor::DumpLocation(SourceLocation Loc) const { |
| 310 | Loc.print(OS&: llvm::errs(), SM: SourceMgr); |
| 311 | } |
| 312 | |
| 313 | void Preprocessor::DumpMacro(const MacroInfo &MI) const { |
| 314 | llvm::errs() << "MACRO: " ; |
| 315 | for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { |
| 316 | DumpToken(Tok: MI.getReplacementToken(Tok: i)); |
| 317 | llvm::errs() << " " ; |
| 318 | } |
| 319 | llvm::errs() << "\n" ; |
| 320 | } |
| 321 | |
| 322 | void Preprocessor::PrintStats() { |
| 323 | llvm::errs() << "\n*** Preprocessor Stats:\n" ; |
| 324 | llvm::errs() << NumDirectives << " directives found:\n" ; |
| 325 | llvm::errs() << " " << NumDefined << " #define.\n" ; |
| 326 | llvm::errs() << " " << NumUndefined << " #undef.\n" ; |
| 327 | llvm::errs() << " #include/#include_next/#import:\n" ; |
| 328 | llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n" ; |
| 329 | llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n" ; |
| 330 | llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n" ; |
| 331 | llvm::errs() << " " << NumElse << " #else/#elif/#elifdef/#elifndef.\n" ; |
| 332 | llvm::errs() << " " << NumEndif << " #endif.\n" ; |
| 333 | llvm::errs() << " " << NumPragma << " #pragma.\n" ; |
| 334 | llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n" ; |
| 335 | |
| 336 | llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" |
| 337 | << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " |
| 338 | << NumFastMacroExpanded << " on the fast path.\n" ; |
| 339 | llvm::errs() << (NumFastTokenPaste+NumTokenPaste) |
| 340 | << " token paste (##) operations performed, " |
| 341 | << NumFastTokenPaste << " on the fast path.\n" ; |
| 342 | |
| 343 | llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total" ; |
| 344 | |
| 345 | llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory(); |
| 346 | llvm::errs() << "\n Macro Expanded Tokens: " |
| 347 | << llvm::capacity_in_bytes(X: MacroExpandedTokens); |
| 348 | llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity(); |
| 349 | // FIXME: List information for all submodules. |
| 350 | llvm::errs() << "\n Macros: " |
| 351 | << llvm::capacity_in_bytes(X: CurSubmoduleState->Macros); |
| 352 | llvm::errs() << "\n #pragma push_macro Info: " |
| 353 | << llvm::capacity_in_bytes(X: PragmaPushMacroInfo); |
| 354 | llvm::errs() << "\n Poison Reasons: " |
| 355 | << llvm::capacity_in_bytes(X: PoisonReasons); |
| 356 | llvm::errs() << "\n Comment Handlers: " |
| 357 | << llvm::capacity_in_bytes(x: CommentHandlers) << "\n" ; |
| 358 | } |
| 359 | |
| 360 | Preprocessor::macro_iterator |
| 361 | Preprocessor::macro_begin(bool IncludeExternalMacros) const { |
| 362 | if (IncludeExternalMacros && ExternalSource && |
| 363 | !ReadMacrosFromExternalSource) { |
| 364 | ReadMacrosFromExternalSource = true; |
| 365 | ExternalSource->ReadDefinedMacros(); |
| 366 | } |
| 367 | |
| 368 | // Make sure we cover all macros in visible modules. |
| 369 | for (const ModuleMacro &Macro : ModuleMacros) |
| 370 | CurSubmoduleState->Macros.try_emplace(Key: Macro.II); |
| 371 | |
| 372 | return CurSubmoduleState->Macros.begin(); |
| 373 | } |
| 374 | |
| 375 | size_t Preprocessor::getTotalMemory() const { |
| 376 | return BP.getTotalMemory() |
| 377 | + llvm::capacity_in_bytes(X: MacroExpandedTokens) |
| 378 | + Predefines.capacity() /* Predefines buffer. */ |
| 379 | // FIXME: Include sizes from all submodules, and include MacroInfo sizes, |
| 380 | // and ModuleMacros. |
| 381 | + llvm::capacity_in_bytes(X: CurSubmoduleState->Macros) |
| 382 | + llvm::capacity_in_bytes(X: PragmaPushMacroInfo) |
| 383 | + llvm::capacity_in_bytes(X: PoisonReasons) |
| 384 | + llvm::capacity_in_bytes(x: CommentHandlers); |
| 385 | } |
| 386 | |
| 387 | Preprocessor::macro_iterator |
| 388 | Preprocessor::macro_end(bool IncludeExternalMacros) const { |
| 389 | if (IncludeExternalMacros && ExternalSource && |
| 390 | !ReadMacrosFromExternalSource) { |
| 391 | ReadMacrosFromExternalSource = true; |
| 392 | ExternalSource->ReadDefinedMacros(); |
| 393 | } |
| 394 | |
| 395 | return CurSubmoduleState->Macros.end(); |
| 396 | } |
| 397 | |
| 398 | /// Compares macro tokens with a specified token value sequence. |
| 399 | static bool MacroDefinitionEquals(const MacroInfo *MI, |
| 400 | ArrayRef<TokenValue> Tokens) { |
| 401 | return Tokens.size() == MI->getNumTokens() && |
| 402 | std::equal(first1: Tokens.begin(), last1: Tokens.end(), first2: MI->tokens_begin()); |
| 403 | } |
| 404 | |
| 405 | StringRef Preprocessor::getLastMacroWithSpelling( |
| 406 | SourceLocation Loc, |
| 407 | ArrayRef<TokenValue> Tokens) const { |
| 408 | SourceLocation BestLocation; |
| 409 | StringRef BestSpelling; |
| 410 | for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end(); |
| 411 | I != E; ++I) { |
| 412 | const MacroDirective::DefInfo |
| 413 | Def = I->second.findDirectiveAtLoc(Loc, SourceMgr); |
| 414 | if (!Def || !Def.getMacroInfo()) |
| 415 | continue; |
| 416 | if (!Def.getMacroInfo()->isObjectLike()) |
| 417 | continue; |
| 418 | if (!MacroDefinitionEquals(MI: Def.getMacroInfo(), Tokens)) |
| 419 | continue; |
| 420 | SourceLocation Location = Def.getLocation(); |
| 421 | // Choose the macro defined latest. |
| 422 | if (BestLocation.isInvalid() || |
| 423 | (Location.isValid() && |
| 424 | SourceMgr.isBeforeInTranslationUnit(LHS: BestLocation, RHS: Location))) { |
| 425 | BestLocation = Location; |
| 426 | BestSpelling = I->first->getName(); |
| 427 | } |
| 428 | } |
| 429 | return BestSpelling; |
| 430 | } |
| 431 | |
| 432 | void Preprocessor::recomputeCurLexerKind() { |
| 433 | if (CurLexer) |
| 434 | CurLexerCallback = CurLexer->isDependencyDirectivesLexer() |
| 435 | ? CLK_DependencyDirectivesLexer |
| 436 | : CLK_Lexer; |
| 437 | else if (CurTokenLexer) |
| 438 | CurLexerCallback = CLK_TokenLexer; |
| 439 | else |
| 440 | CurLexerCallback = CLK_CachingLexer; |
| 441 | } |
| 442 | |
| 443 | bool Preprocessor::SetCodeCompletionPoint(FileEntryRef File, |
| 444 | unsigned CompleteLine, |
| 445 | unsigned CompleteColumn) { |
| 446 | assert(CompleteLine && CompleteColumn && "Starts from 1:1" ); |
| 447 | assert(!CodeCompletionFile && "Already set" ); |
| 448 | |
| 449 | // Load the actual file's contents. |
| 450 | std::optional<llvm::MemoryBufferRef> Buffer = |
| 451 | SourceMgr.getMemoryBufferForFileOrNone(File); |
| 452 | if (!Buffer) |
| 453 | return true; |
| 454 | |
| 455 | // Find the byte position of the truncation point. |
| 456 | const char *Position = Buffer->getBufferStart(); |
| 457 | for (unsigned Line = 1; Line < CompleteLine; ++Line) { |
| 458 | for (; *Position; ++Position) { |
| 459 | if (*Position != '\r' && *Position != '\n') |
| 460 | continue; |
| 461 | |
| 462 | // Eat \r\n or \n\r as a single line. |
| 463 | if ((Position[1] == '\r' || Position[1] == '\n') && |
| 464 | Position[0] != Position[1]) |
| 465 | ++Position; |
| 466 | ++Position; |
| 467 | break; |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | Position += CompleteColumn - 1; |
| 472 | |
| 473 | // If pointing inside the preamble, adjust the position at the beginning of |
| 474 | // the file after the preamble. |
| 475 | if (SkipMainFilePreamble.first && |
| 476 | SourceMgr.getFileEntryForID(FID: SourceMgr.getMainFileID()) == File) { |
| 477 | if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first) |
| 478 | Position = Buffer->getBufferStart() + SkipMainFilePreamble.first; |
| 479 | } |
| 480 | |
| 481 | if (Position > Buffer->getBufferEnd()) |
| 482 | Position = Buffer->getBufferEnd(); |
| 483 | |
| 484 | CodeCompletionFile = File; |
| 485 | CodeCompletionOffset = Position - Buffer->getBufferStart(); |
| 486 | |
| 487 | auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer( |
| 488 | Size: Buffer->getBufferSize() + 1, BufferName: Buffer->getBufferIdentifier()); |
| 489 | char *NewBuf = NewBuffer->getBufferStart(); |
| 490 | char *NewPos = std::copy(first: Buffer->getBufferStart(), last: Position, result: NewBuf); |
| 491 | *NewPos = '\0'; |
| 492 | std::copy(first: Position, last: Buffer->getBufferEnd(), result: NewPos+1); |
| 493 | SourceMgr.overrideFileContents(SourceFile: File, Buffer: std::move(NewBuffer)); |
| 494 | |
| 495 | return false; |
| 496 | } |
| 497 | |
| 498 | void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir, |
| 499 | bool IsAngled) { |
| 500 | setCodeCompletionReached(); |
| 501 | if (CodeComplete) |
| 502 | CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled); |
| 503 | } |
| 504 | |
| 505 | void Preprocessor::CodeCompleteNaturalLanguage() { |
| 506 | setCodeCompletionReached(); |
| 507 | if (CodeComplete) |
| 508 | CodeComplete->CodeCompleteNaturalLanguage(); |
| 509 | } |
| 510 | |
| 511 | /// getSpelling - This method is used to get the spelling of a token into a |
| 512 | /// SmallVector. Note that the returned StringRef may not point to the |
| 513 | /// supplied buffer if a copy can be avoided. |
| 514 | StringRef Preprocessor::getSpelling(const Token &Tok, |
| 515 | SmallVectorImpl<char> &Buffer, |
| 516 | bool *Invalid) const { |
| 517 | // NOTE: this has to be checked *before* testing for an IdentifierInfo. |
| 518 | if (Tok.isNot(K: tok::raw_identifier) && !Tok.hasUCN()) { |
| 519 | // Try the fast path. |
| 520 | if (const IdentifierInfo *II = Tok.getIdentifierInfo()) |
| 521 | return II->getName(); |
| 522 | } |
| 523 | |
| 524 | // Resize the buffer if we need to copy into it. |
| 525 | if (Tok.needsCleaning()) |
| 526 | Buffer.resize(N: Tok.getLength()); |
| 527 | |
| 528 | const char *Ptr = Buffer.data(); |
| 529 | unsigned Len = getSpelling(Tok, Buffer&: Ptr, Invalid); |
| 530 | return StringRef(Ptr, Len); |
| 531 | } |
| 532 | |
| 533 | /// CreateString - Plop the specified string into a scratch buffer and return a |
| 534 | /// location for it. If specified, the source location provides a source |
| 535 | /// location for the token. |
| 536 | void Preprocessor::CreateString(StringRef Str, Token &Tok, |
| 537 | SourceLocation ExpansionLocStart, |
| 538 | SourceLocation ExpansionLocEnd) { |
| 539 | Tok.setLength(Str.size()); |
| 540 | |
| 541 | const char *DestPtr; |
| 542 | SourceLocation Loc = ScratchBuf->getToken(Buf: Str.data(), Len: Str.size(), DestPtr); |
| 543 | |
| 544 | if (ExpansionLocStart.isValid()) |
| 545 | Loc = SourceMgr.createExpansionLoc(SpellingLoc: Loc, ExpansionLocStart, |
| 546 | ExpansionLocEnd, Length: Str.size()); |
| 547 | Tok.setLocation(Loc); |
| 548 | |
| 549 | // If this is a raw identifier or a literal token, set the pointer data. |
| 550 | if (Tok.is(K: tok::raw_identifier)) |
| 551 | Tok.setRawIdentifierData(DestPtr); |
| 552 | else if (Tok.isLiteral()) |
| 553 | Tok.setLiteralData(DestPtr); |
| 554 | } |
| 555 | |
| 556 | SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) { |
| 557 | auto &SM = getSourceManager(); |
| 558 | SourceLocation SpellingLoc = SM.getSpellingLoc(Loc); |
| 559 | FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc: SpellingLoc); |
| 560 | bool Invalid = false; |
| 561 | StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid); |
| 562 | if (Invalid) |
| 563 | return SourceLocation(); |
| 564 | |
| 565 | // FIXME: We could consider re-using spelling for tokens we see repeatedly. |
| 566 | const char *DestPtr; |
| 567 | SourceLocation Spelling = |
| 568 | ScratchBuf->getToken(Buf: Buffer.data() + LocInfo.second, Len: Length, DestPtr); |
| 569 | return SM.createTokenSplitLoc(SpellingLoc: Spelling, TokenStart: Loc, TokenEnd: Loc.getLocWithOffset(Offset: Length)); |
| 570 | } |
| 571 | |
| 572 | Module *Preprocessor::getCurrentModule() { |
| 573 | if (!getLangOpts().isCompilingModule()) |
| 574 | return nullptr; |
| 575 | |
| 576 | return getHeaderSearchInfo().lookupModule(ModuleName: getLangOpts().CurrentModule); |
| 577 | } |
| 578 | |
| 579 | Module *Preprocessor::getCurrentModuleImplementation() { |
| 580 | if (!getLangOpts().isCompilingModuleImplementation()) |
| 581 | return nullptr; |
| 582 | |
| 583 | return getHeaderSearchInfo().lookupModule(ModuleName: getLangOpts().ModuleName); |
| 584 | } |
| 585 | |
| 586 | //===----------------------------------------------------------------------===// |
| 587 | // Preprocessor Initialization Methods |
| 588 | //===----------------------------------------------------------------------===// |
| 589 | |
| 590 | /// EnterMainSourceFile - Enter the specified FileID as the main source file, |
| 591 | /// which implicitly adds the builtin defines etc. |
| 592 | void Preprocessor::EnterMainSourceFile() { |
| 593 | // We do not allow the preprocessor to reenter the main file. Doing so will |
| 594 | // cause FileID's to accumulate information from both runs (e.g. #line |
| 595 | // information) and predefined macros aren't guaranteed to be set properly. |
| 596 | assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!" ); |
| 597 | FileID MainFileID = SourceMgr.getMainFileID(); |
| 598 | |
| 599 | // If MainFileID is loaded it means we loaded an AST file, no need to enter |
| 600 | // a main file. |
| 601 | if (!SourceMgr.isLoadedFileID(FID: MainFileID)) { |
| 602 | // Enter the main file source buffer. |
| 603 | EnterSourceFile(FID: MainFileID, Dir: nullptr, Loc: SourceLocation()); |
| 604 | |
| 605 | // If we've been asked to skip bytes in the main file (e.g., as part of a |
| 606 | // precompiled preamble), do so now. |
| 607 | if (SkipMainFilePreamble.first > 0) |
| 608 | CurLexer->SetByteOffset(Offset: SkipMainFilePreamble.first, |
| 609 | StartOfLine: SkipMainFilePreamble.second); |
| 610 | |
| 611 | // Tell the header info that the main file was entered. If the file is later |
| 612 | // #imported, it won't be re-entered. |
| 613 | if (OptionalFileEntryRef FE = SourceMgr.getFileEntryRefForID(FID: MainFileID)) |
| 614 | markIncluded(File: *FE); |
| 615 | |
| 616 | // Record the first PP token in the main file. This is used to generate |
| 617 | // better diagnostics for C++ modules. |
| 618 | // |
| 619 | // // This is a comment. |
| 620 | // #define FOO int // note: add 'module;' to the start of the file |
| 621 | // ^ FirstPPToken // to introduce a global module fragment. |
| 622 | // |
| 623 | // export module M; // error: module declaration must occur |
| 624 | // // at the start of the translation unit. |
| 625 | if (getLangOpts().CPlusPlusModules) { |
| 626 | std::optional<StringRef> Input = |
| 627 | getSourceManager().getBufferDataOrNone(FID: MainFileID); |
| 628 | if (!isPreprocessedModuleFile() && Input) |
| 629 | MainFileIsPreprocessedModuleFile = |
| 630 | clang::isPreprocessedModuleFile(Source: *Input); |
| 631 | auto Tracer = std::make_unique<NoTrivialPPDirectiveTracer>(args&: *this); |
| 632 | DirTracer = Tracer.get(); |
| 633 | addPPCallbacks(C: std::move(Tracer)); |
| 634 | std::optional<Token> FirstPPTok = CurLexer->peekNextPPToken(); |
| 635 | if (FirstPPTok) |
| 636 | FirstPPTokenLoc = FirstPPTok->getLocation(); |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | // Preprocess Predefines to populate the initial preprocessor state. |
| 641 | std::unique_ptr<llvm::MemoryBuffer> SB = |
| 642 | llvm::MemoryBuffer::getMemBufferCopy(InputData: Predefines, BufferName: "<built-in>" ); |
| 643 | assert(SB && "Cannot create predefined source buffer" ); |
| 644 | FileID FID = SourceMgr.createFileID(Buffer: std::move(SB)); |
| 645 | assert(FID.isValid() && "Could not create FileID for predefines?" ); |
| 646 | setPredefinesFileID(FID); |
| 647 | |
| 648 | // Start parsing the predefines. |
| 649 | EnterSourceFile(FID, Dir: nullptr, Loc: SourceLocation()); |
| 650 | |
| 651 | if (!PPOpts.PCHThroughHeader.empty()) { |
| 652 | // Lookup and save the FileID for the through header. If it isn't found |
| 653 | // in the search path, it's a fatal error. |
| 654 | OptionalFileEntryRef File = LookupFile( |
| 655 | FilenameLoc: SourceLocation(), Filename: PPOpts.PCHThroughHeader, |
| 656 | /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr, |
| 657 | /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr, |
| 658 | /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr, |
| 659 | /*IsFrameworkFound=*/nullptr); |
| 660 | if (!File) { |
| 661 | Diag(Loc: SourceLocation(), DiagID: diag::err_pp_through_header_not_found) |
| 662 | << PPOpts.PCHThroughHeader; |
| 663 | return; |
| 664 | } |
| 665 | setPCHThroughHeaderFileID( |
| 666 | SourceMgr.createFileID(SourceFile: *File, IncludePos: SourceLocation(), FileCharacter: SrcMgr::C_User)); |
| 667 | } |
| 668 | |
| 669 | // Skip tokens from the Predefines and if needed the main file. |
| 670 | if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) || |
| 671 | (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop)) |
| 672 | SkipTokensWhileUsingPCH(); |
| 673 | } |
| 674 | |
| 675 | void Preprocessor::(FileID FID) { |
| 676 | assert(PCHThroughHeaderFileID.isInvalid() && |
| 677 | "PCHThroughHeaderFileID already set!" ); |
| 678 | PCHThroughHeaderFileID = FID; |
| 679 | } |
| 680 | |
| 681 | bool Preprocessor::(const FileEntry *FE) { |
| 682 | assert(PCHThroughHeaderFileID.isValid() && |
| 683 | "Invalid PCH through header FileID" ); |
| 684 | return FE == SourceMgr.getFileEntryForID(FID: PCHThroughHeaderFileID); |
| 685 | } |
| 686 | |
| 687 | bool Preprocessor::() { |
| 688 | return TUKind == TU_Prefix && !PPOpts.PCHThroughHeader.empty() && |
| 689 | PCHThroughHeaderFileID.isValid(); |
| 690 | } |
| 691 | |
| 692 | bool Preprocessor::() { |
| 693 | return TUKind != TU_Prefix && !PPOpts.PCHThroughHeader.empty() && |
| 694 | PCHThroughHeaderFileID.isValid(); |
| 695 | } |
| 696 | |
| 697 | bool Preprocessor::creatingPCHWithPragmaHdrStop() { |
| 698 | return TUKind == TU_Prefix && PPOpts.PCHWithHdrStop; |
| 699 | } |
| 700 | |
| 701 | bool Preprocessor::usingPCHWithPragmaHdrStop() { |
| 702 | return TUKind != TU_Prefix && PPOpts.PCHWithHdrStop; |
| 703 | } |
| 704 | |
| 705 | /// Skip tokens until after the #include of the through header or |
| 706 | /// until after a #pragma hdrstop is seen. Tokens in the predefines file |
| 707 | /// and the main file may be skipped. If the end of the predefines file |
| 708 | /// is reached, skipping continues into the main file. If the end of the |
| 709 | /// main file is reached, it's a fatal error. |
| 710 | void Preprocessor::SkipTokensWhileUsingPCH() { |
| 711 | bool ReachedMainFileEOF = false; |
| 712 | bool = SkippingUntilPCHThroughHeader; |
| 713 | bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop; |
| 714 | Token Tok; |
| 715 | while (true) { |
| 716 | bool InPredefines = |
| 717 | (CurLexer && CurLexer->getFileID() == getPredefinesFileID()); |
| 718 | CurLexerCallback(*this, Tok); |
| 719 | if (Tok.is(K: tok::eof) && !InPredefines) { |
| 720 | ReachedMainFileEOF = true; |
| 721 | break; |
| 722 | } |
| 723 | if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader) |
| 724 | break; |
| 725 | if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop) |
| 726 | break; |
| 727 | } |
| 728 | if (ReachedMainFileEOF) { |
| 729 | if (UsingPCHThroughHeader) |
| 730 | Diag(Loc: SourceLocation(), DiagID: diag::err_pp_through_header_not_seen) |
| 731 | << PPOpts.PCHThroughHeader << 1; |
| 732 | else if (!PPOpts.PCHWithHdrStopCreate) |
| 733 | Diag(Loc: SourceLocation(), DiagID: diag::err_pp_pragma_hdrstop_not_seen); |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | void Preprocessor::replayPreambleConditionalStack() { |
| 738 | // Restore the conditional stack from the preamble, if there is one. |
| 739 | if (PreambleConditionalStack.isReplaying()) { |
| 740 | assert(CurPPLexer && |
| 741 | "CurPPLexer is null when calling replayPreambleConditionalStack." ); |
| 742 | CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack()); |
| 743 | PreambleConditionalStack.doneReplaying(); |
| 744 | if (PreambleConditionalStack.reachedEOFWhileSkipping()) |
| 745 | SkipExcludedConditionalBlock( |
| 746 | HashTokenLoc: PreambleConditionalStack.SkipInfo->HashTokenLoc, |
| 747 | IfTokenLoc: PreambleConditionalStack.SkipInfo->IfTokenLoc, |
| 748 | FoundNonSkipPortion: PreambleConditionalStack.SkipInfo->FoundNonSkipPortion, |
| 749 | FoundElse: PreambleConditionalStack.SkipInfo->FoundElse, |
| 750 | ElseLoc: PreambleConditionalStack.SkipInfo->ElseLoc); |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | void Preprocessor::EndSourceFile() { |
| 755 | // Notify the client that we reached the end of the source file. |
| 756 | if (Callbacks) |
| 757 | Callbacks->EndOfMainFile(); |
| 758 | } |
| 759 | |
| 760 | //===----------------------------------------------------------------------===// |
| 761 | // Lexer Event Handling. |
| 762 | //===----------------------------------------------------------------------===// |
| 763 | |
| 764 | /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the |
| 765 | /// identifier information for the token and install it into the token, |
| 766 | /// updating the token kind accordingly. |
| 767 | IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const { |
| 768 | assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!" ); |
| 769 | |
| 770 | // Look up this token, see if it is a macro, or if it is a language keyword. |
| 771 | IdentifierInfo *II; |
| 772 | if (!Identifier.needsCleaning() && !Identifier.hasUCN()) { |
| 773 | // No cleaning needed, just use the characters from the lexed buffer. |
| 774 | II = getIdentifierInfo(Name: Identifier.getRawIdentifier()); |
| 775 | } else { |
| 776 | // Cleaning needed, alloca a buffer, clean into it, then use the buffer. |
| 777 | SmallString<64> IdentifierBuffer; |
| 778 | StringRef CleanedStr = getSpelling(Tok: Identifier, Buffer&: IdentifierBuffer); |
| 779 | |
| 780 | if (Identifier.hasUCN()) { |
| 781 | SmallString<64> UCNIdentifierBuffer; |
| 782 | expandUCNs(Buf&: UCNIdentifierBuffer, Input: CleanedStr); |
| 783 | II = getIdentifierInfo(Name: UCNIdentifierBuffer); |
| 784 | } else { |
| 785 | II = getIdentifierInfo(Name: CleanedStr); |
| 786 | } |
| 787 | } |
| 788 | |
| 789 | // Update the token info (identifier info and appropriate token kind). |
| 790 | // FIXME: the raw_identifier may contain leading whitespace which is removed |
| 791 | // from the cleaned identifier token. The SourceLocation should be updated to |
| 792 | // refer to the non-whitespace character. For instance, the text "\\\nB" (a |
| 793 | // line continuation before 'B') is parsed as a single tok::raw_identifier and |
| 794 | // is cleaned to tok::identifier "B". After cleaning the token's length is |
| 795 | // still 3 and the SourceLocation refers to the location of the backslash. |
| 796 | Identifier.setIdentifierInfo(II); |
| 797 | Identifier.setKind(II->getTokenID()); |
| 798 | |
| 799 | return II; |
| 800 | } |
| 801 | |
| 802 | void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { |
| 803 | PoisonReasons[II] = DiagID; |
| 804 | } |
| 805 | |
| 806 | void Preprocessor::PoisonSEHIdentifiers(bool Poison) { |
| 807 | assert(Ident__exception_code && Ident__exception_info); |
| 808 | assert(Ident___exception_code && Ident___exception_info); |
| 809 | Ident__exception_code->setIsPoisoned(Poison); |
| 810 | Ident___exception_code->setIsPoisoned(Poison); |
| 811 | Ident_GetExceptionCode->setIsPoisoned(Poison); |
| 812 | Ident__exception_info->setIsPoisoned(Poison); |
| 813 | Ident___exception_info->setIsPoisoned(Poison); |
| 814 | Ident_GetExceptionInfo->setIsPoisoned(Poison); |
| 815 | Ident__abnormal_termination->setIsPoisoned(Poison); |
| 816 | Ident___abnormal_termination->setIsPoisoned(Poison); |
| 817 | Ident_AbnormalTermination->setIsPoisoned(Poison); |
| 818 | } |
| 819 | |
| 820 | void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { |
| 821 | assert(Identifier.getIdentifierInfo() && |
| 822 | "Can't handle identifiers without identifier info!" ); |
| 823 | llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = |
| 824 | PoisonReasons.find(Val: Identifier.getIdentifierInfo()); |
| 825 | if(it == PoisonReasons.end()) |
| 826 | Diag(Tok: Identifier, DiagID: diag::err_pp_used_poisoned_id); |
| 827 | else |
| 828 | Diag(Tok: Identifier,DiagID: it->second) << Identifier.getIdentifierInfo(); |
| 829 | } |
| 830 | |
| 831 | void Preprocessor::updateOutOfDateIdentifier(const IdentifierInfo &II) const { |
| 832 | assert(II.isOutOfDate() && "not out of date" ); |
| 833 | assert(getExternalSource() && |
| 834 | "getExternalSource() should not return nullptr" ); |
| 835 | getExternalSource()->updateOutOfDateIdentifier(II); |
| 836 | } |
| 837 | |
| 838 | /// HandleIdentifier - This callback is invoked when the lexer reads an |
| 839 | /// identifier. This callback looks up the identifier in the map and/or |
| 840 | /// potentially macro expands it or turns it into a named token (like 'for'). |
| 841 | /// |
| 842 | /// Note that callers of this method are guarded by checking the |
| 843 | /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the |
| 844 | /// IdentifierInfo methods that compute these properties will need to change to |
| 845 | /// match. |
| 846 | bool Preprocessor::HandleIdentifier(Token &Identifier) { |
| 847 | assert(Identifier.getIdentifierInfo() && |
| 848 | "Can't handle identifiers without identifier info!" ); |
| 849 | |
| 850 | IdentifierInfo &II = *Identifier.getIdentifierInfo(); |
| 851 | |
| 852 | // If the information about this identifier is out of date, update it from |
| 853 | // the external source. |
| 854 | // We have to treat __VA_ARGS__ in a special way, since it gets |
| 855 | // serialized with isPoisoned = true, but our preprocessor may have |
| 856 | // unpoisoned it if we're defining a C99 macro. |
| 857 | if (II.isOutOfDate()) { |
| 858 | bool CurrentIsPoisoned = false; |
| 859 | const bool IsSpecialVariadicMacro = |
| 860 | &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__; |
| 861 | if (IsSpecialVariadicMacro) |
| 862 | CurrentIsPoisoned = II.isPoisoned(); |
| 863 | |
| 864 | updateOutOfDateIdentifier(II); |
| 865 | Identifier.setKind(II.getTokenID()); |
| 866 | |
| 867 | if (IsSpecialVariadicMacro) |
| 868 | II.setIsPoisoned(CurrentIsPoisoned); |
| 869 | } |
| 870 | |
| 871 | // If this identifier was poisoned, and if it was not produced from a macro |
| 872 | // expansion, emit an error. |
| 873 | if (II.isPoisoned() && CurPPLexer) { |
| 874 | HandlePoisonedIdentifier(Identifier); |
| 875 | } |
| 876 | |
| 877 | // If this is a macro to be expanded, do it. |
| 878 | if (const MacroDefinition MD = getMacroDefinition(II: &II)) { |
| 879 | const auto *MI = MD.getMacroInfo(); |
| 880 | assert(MI && "macro definition with no macro info?" ); |
| 881 | if (!DisableMacroExpansion) { |
| 882 | if (!Identifier.isExpandDisabled() && MI->isEnabled()) { |
| 883 | // C99 6.10.3p10: If the preprocessing token immediately after the |
| 884 | // macro name isn't a '(', this macro should not be expanded. |
| 885 | if (!MI->isFunctionLike() || isNextPPTokenOneOf(Ks: tok::l_paren)) |
| 886 | return HandleMacroExpandedIdentifier(Identifier, MD); |
| 887 | } else { |
| 888 | // C99 6.10.3.4p2 says that a disabled macro may never again be |
| 889 | // expanded, even if it's in a context where it could be expanded in the |
| 890 | // future. |
| 891 | Identifier.setFlag(Token::DisableExpand); |
| 892 | if (MI->isObjectLike() || isNextPPTokenOneOf(Ks: tok::l_paren)) |
| 893 | Diag(Tok: Identifier, DiagID: diag::pp_disabled_macro_expansion); |
| 894 | } |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | // If this identifier is a keyword in a newer Standard or proposed Standard, |
| 899 | // produce a warning. Don't warn if we're not considering macro expansion, |
| 900 | // since this identifier might be the name of a macro. |
| 901 | // FIXME: This warning is disabled in cases where it shouldn't be, like |
| 902 | // "#define constexpr constexpr", "int constexpr;" |
| 903 | if (II.isFutureCompatKeyword() && !DisableMacroExpansion) { |
| 904 | Diag(Tok: Identifier, DiagID: getIdentifierTable().getFutureCompatDiagKind(II, LangOpts: getLangOpts())) |
| 905 | << II.getName(); |
| 906 | // Don't diagnose this keyword again in this translation unit. |
| 907 | II.setIsFutureCompatKeyword(false); |
| 908 | } |
| 909 | |
| 910 | // If this identifier would be a keyword in C++, diagnose as a compatibility |
| 911 | // issue. |
| 912 | if (II.IsKeywordInCPlusPlus() && !DisableMacroExpansion) |
| 913 | Diag(Tok: Identifier, DiagID: diag::warn_pp_identifier_is_cpp_keyword) << &II; |
| 914 | |
| 915 | // If this is an extension token, diagnose its use. |
| 916 | // We avoid diagnosing tokens that originate from macro definitions. |
| 917 | // FIXME: This warning is disabled in cases where it shouldn't be, |
| 918 | // like "#define TY typeof", "TY(1) x". |
| 919 | if (II.isExtensionToken() && !DisableMacroExpansion) |
| 920 | Diag(Tok: Identifier, DiagID: diag::ext_token_used); |
| 921 | |
| 922 | // Handle module contextual keywords. |
| 923 | if (getLangOpts().CPlusPlusModules && CurLexer && |
| 924 | !CurLexer->isLexingRawMode() && !CurLexer->isPragmaLexer() && |
| 925 | !CurLexer->ParsingPreprocessorDirective && |
| 926 | Identifier.isModuleContextualKeyword() && |
| 927 | HandleModuleContextualKeyword(Result&: Identifier)) { |
| 928 | HandleDirective(Result&: Identifier); |
| 929 | // With a fatal failure in the module loader, we abort parsing. |
| 930 | return hadModuleLoaderFatalFailure(); |
| 931 | } |
| 932 | |
| 933 | // If this is the 'import' contextual keyword following an '@', note |
| 934 | // that the next token indicates a module name. |
| 935 | // |
| 936 | // Note that we do not treat 'import' as a contextual |
| 937 | // keyword when we're in a caching lexer, because caching lexers only get |
| 938 | // used in contexts where import declarations are disallowed. |
| 939 | // |
| 940 | // Likewise if this is the standard C++ import keyword. |
| 941 | if (((LastTokenWasAt && II.isImportKeyword()) || |
| 942 | Identifier.is(K: tok::kw_import)) && |
| 943 | !InMacroArgs && |
| 944 | (!DisableMacroExpansion || MacroExpansionInDirectivesOverride) && |
| 945 | CurLexerCallback != CLK_CachingLexer) { |
| 946 | ModuleImportLoc = Identifier.getLocation(); |
| 947 | IsAtImport = true; |
| 948 | CurLexerCallback = CLK_LexAfterModuleImport; |
| 949 | } |
| 950 | return true; |
| 951 | } |
| 952 | |
| 953 | void Preprocessor::Lex(Token &Result) { |
| 954 | ++LexLevel; |
| 955 | |
| 956 | // We loop here until a lex function returns a token; this avoids recursion. |
| 957 | while (!CurLexerCallback(*this, Result)) |
| 958 | ; |
| 959 | |
| 960 | if (Result.is(K: tok::unknown) && TheModuleLoader.HadFatalFailure) |
| 961 | return; |
| 962 | |
| 963 | if (Result.is(K: tok::code_completion) && Result.getIdentifierInfo()) { |
| 964 | // Remember the identifier before code completion token. |
| 965 | setCodeCompletionIdentifierInfo(Result.getIdentifierInfo()); |
| 966 | setCodeCompletionTokenRange(Start: Result.getLocation(), End: Result.getEndLoc()); |
| 967 | // Set IdenfitierInfo to null to avoid confusing code that handles both |
| 968 | // identifiers and completion tokens. |
| 969 | Result.setIdentifierInfo(nullptr); |
| 970 | } |
| 971 | |
| 972 | // Update StdCXXImportSeqState to track our position within a C++20 import-seq |
| 973 | // if this token is being produced as a result of phase 4 of translation. |
| 974 | // Update TrackGMFState to decide if we are currently in a Global Module |
| 975 | // Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state |
| 976 | // depends on the prevailing StdCXXImportSeq state in two cases. |
| 977 | if (getLangOpts().CPlusPlusModules && LexLevel == 1 && |
| 978 | !Result.getFlag(Flag: Token::IsReinjected)) { |
| 979 | switch (Result.getKind()) { |
| 980 | case tok::l_paren: case tok::l_square: case tok::l_brace: |
| 981 | StdCXXImportSeqState.handleOpenBracket(); |
| 982 | break; |
| 983 | case tok::r_paren: case tok::r_square: |
| 984 | StdCXXImportSeqState.handleCloseBracket(); |
| 985 | break; |
| 986 | case tok::r_brace: |
| 987 | StdCXXImportSeqState.handleCloseBrace(); |
| 988 | break; |
| 989 | #define PRAGMA_ANNOTATION(X) case tok::annot_##X: |
| 990 | // For `#pragma ...` mimic ';'. |
| 991 | #include "clang/Basic/TokenKinds.def" |
| 992 | #undef PRAGMA_ANNOTATION |
| 993 | // This token is injected to represent the translation of '#include "a.h"' |
| 994 | // into "import a.h;". Mimic the notional ';'. |
| 995 | case tok::annot_module_include: |
| 996 | case tok::annot_repl_input_end: |
| 997 | case tok::semi: |
| 998 | TrackGMFState.handleSemi(); |
| 999 | StdCXXImportSeqState.handleSemi(); |
| 1000 | ModuleDeclState.handleSemi(); |
| 1001 | break; |
| 1002 | case tok::header_name: |
| 1003 | case tok::annot_header_unit: |
| 1004 | StdCXXImportSeqState.handleHeaderName(); |
| 1005 | break; |
| 1006 | case tok::kw_export: |
| 1007 | if (hasSeenNoTrivialPPDirective()) |
| 1008 | Result.setFlag(Token::HasSeenNoTrivialPPDirective); |
| 1009 | TrackGMFState.handleExport(); |
| 1010 | StdCXXImportSeqState.handleExport(); |
| 1011 | ModuleDeclState.handleExport(); |
| 1012 | break; |
| 1013 | case tok::colon: |
| 1014 | ModuleDeclState.handleColon(); |
| 1015 | break; |
| 1016 | case tok::kw_import: |
| 1017 | if (StdCXXImportSeqState.atTopLevel()) { |
| 1018 | TrackGMFState.handleImport(AfterTopLevelTokenSeq: StdCXXImportSeqState.afterTopLevelSeq()); |
| 1019 | StdCXXImportSeqState.handleImport(); |
| 1020 | } |
| 1021 | break; |
| 1022 | case tok::kw_module: |
| 1023 | if (StdCXXImportSeqState.atTopLevel()) { |
| 1024 | if (hasSeenNoTrivialPPDirective()) |
| 1025 | Result.setFlag(Token::HasSeenNoTrivialPPDirective); |
| 1026 | TrackGMFState.handleModule(AfterTopLevelTokenSeq: StdCXXImportSeqState.afterTopLevelSeq()); |
| 1027 | ModuleDeclState.handleModule(); |
| 1028 | } |
| 1029 | break; |
| 1030 | case tok::annot_module_name: |
| 1031 | ModuleDeclState.handleModuleName( |
| 1032 | NameLoc: static_cast<ModuleNameLoc *>(Result.getAnnotationValue())); |
| 1033 | if (ModuleDeclState.isModuleCandidate()) |
| 1034 | break; |
| 1035 | [[fallthrough]]; |
| 1036 | default: |
| 1037 | TrackGMFState.handleMisc(); |
| 1038 | StdCXXImportSeqState.handleMisc(); |
| 1039 | ModuleDeclState.handleMisc(); |
| 1040 | break; |
| 1041 | } |
| 1042 | } |
| 1043 | |
| 1044 | if (CurLexer && ++CheckPointCounter == CheckPointStepSize) { |
| 1045 | CheckPoints[CurLexer->getFileID()].push_back(Elt: CurLexer->BufferPtr); |
| 1046 | CheckPointCounter = 0; |
| 1047 | } |
| 1048 | |
| 1049 | LastTokenWasAt = Result.is(K: tok::at); |
| 1050 | if (Result.isNot(K: tok::kw_export)) |
| 1051 | LastExportKeyword.startToken(); |
| 1052 | |
| 1053 | --LexLevel; |
| 1054 | |
| 1055 | // Destroy any lexers that were deferred while we were in nested Lex calls. |
| 1056 | // This must happen after decrementing LexLevel but before any other |
| 1057 | // processing that might re-enter Lex. |
| 1058 | if (LexLevel == 0 && !PendingDestroyLexers.empty()) |
| 1059 | PendingDestroyLexers.clear(); |
| 1060 | |
| 1061 | if ((LexLevel == 0 || PreprocessToken) && |
| 1062 | !Result.getFlag(Flag: Token::IsReinjected)) { |
| 1063 | if (LexLevel == 0) |
| 1064 | ++TokenCount; |
| 1065 | if (OnToken) |
| 1066 | OnToken(Result); |
| 1067 | } |
| 1068 | } |
| 1069 | |
| 1070 | void Preprocessor::LexTokensUntilEOF(std::vector<Token> *Tokens) { |
| 1071 | while (1) { |
| 1072 | Token Tok; |
| 1073 | Lex(Result&: Tok); |
| 1074 | if (Tok.isOneOf(Ks: tok::unknown, Ks: tok::eof, Ks: tok::eod, |
| 1075 | Ks: tok::annot_repl_input_end)) |
| 1076 | break; |
| 1077 | if (Tokens != nullptr) |
| 1078 | Tokens->push_back(x: Tok); |
| 1079 | } |
| 1080 | } |
| 1081 | |
| 1082 | /// Lex a header-name token (including one formed from header-name-tokens if |
| 1083 | /// \p AllowMacroExpansion is \c true). |
| 1084 | /// |
| 1085 | /// \param FilenameTok Filled in with the next token. On success, this will |
| 1086 | /// be either a header_name token. On failure, it will be whatever other |
| 1087 | /// token was found instead. |
| 1088 | /// \param AllowMacroExpansion If \c true, allow the header name to be formed |
| 1089 | /// by macro expansion (concatenating tokens as necessary if the first |
| 1090 | /// token is a '<'). |
| 1091 | /// \return \c true if we reached EOD or EOF while looking for a > token in |
| 1092 | /// a concatenated header name and diagnosed it. \c false otherwise. |
| 1093 | bool Preprocessor::(Token &FilenameTok, bool AllowMacroExpansion) { |
| 1094 | // Lex using header-name tokenization rules if tokens are being lexed from |
| 1095 | // a file. Just grab a token normally if we're in a macro expansion. |
| 1096 | if (CurPPLexer) { |
| 1097 | // Avoid nested header-name lexing when macro expansion recurses |
| 1098 | // __has_include(__has_include)) |
| 1099 | if (CurPPLexer->ParsingFilename) |
| 1100 | LexUnexpandedToken(Result&: FilenameTok); |
| 1101 | else |
| 1102 | CurPPLexer->LexIncludeFilename(FilenameTok); |
| 1103 | } else { |
| 1104 | Lex(Result&: FilenameTok); |
| 1105 | } |
| 1106 | |
| 1107 | // This could be a <foo/bar.h> file coming from a macro expansion. In this |
| 1108 | // case, glue the tokens together into an angle_string_literal token. |
| 1109 | SmallString<128> FilenameBuffer; |
| 1110 | if (FilenameTok.is(K: tok::less) && AllowMacroExpansion) { |
| 1111 | bool StartOfLine = FilenameTok.isAtStartOfLine(); |
| 1112 | bool LeadingSpace = FilenameTok.hasLeadingSpace(); |
| 1113 | bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro(); |
| 1114 | |
| 1115 | SourceLocation Start = FilenameTok.getLocation(); |
| 1116 | SourceLocation End; |
| 1117 | FilenameBuffer.push_back(Elt: '<'); |
| 1118 | |
| 1119 | // Consume tokens until we find a '>'. |
| 1120 | // FIXME: A header-name could be formed starting or ending with an |
| 1121 | // alternative token. It's not clear whether that's ill-formed in all |
| 1122 | // cases. |
| 1123 | while (FilenameTok.isNot(K: tok::greater)) { |
| 1124 | Lex(Result&: FilenameTok); |
| 1125 | if (FilenameTok.isOneOf(Ks: tok::eod, Ks: tok::eof)) { |
| 1126 | Diag(Loc: FilenameTok.getLocation(), DiagID: diag::err_expected) << tok::greater; |
| 1127 | Diag(Loc: Start, DiagID: diag::note_matching) << tok::less; |
| 1128 | return true; |
| 1129 | } |
| 1130 | |
| 1131 | End = FilenameTok.getLocation(); |
| 1132 | |
| 1133 | // FIXME: Provide code completion for #includes. |
| 1134 | if (FilenameTok.is(K: tok::code_completion)) { |
| 1135 | setCodeCompletionReached(); |
| 1136 | Lex(Result&: FilenameTok); |
| 1137 | continue; |
| 1138 | } |
| 1139 | |
| 1140 | // Append the spelling of this token to the buffer. If there was a space |
| 1141 | // before it, add it now. |
| 1142 | if (FilenameTok.hasLeadingSpace()) |
| 1143 | FilenameBuffer.push_back(Elt: ' '); |
| 1144 | |
| 1145 | // Get the spelling of the token, directly into FilenameBuffer if |
| 1146 | // possible. |
| 1147 | size_t PreAppendSize = FilenameBuffer.size(); |
| 1148 | FilenameBuffer.resize(N: PreAppendSize + FilenameTok.getLength()); |
| 1149 | |
| 1150 | const char *BufPtr = &FilenameBuffer[PreAppendSize]; |
| 1151 | unsigned ActualLen = getSpelling(Tok: FilenameTok, Buffer&: BufPtr); |
| 1152 | |
| 1153 | // If the token was spelled somewhere else, copy it into FilenameBuffer. |
| 1154 | if (BufPtr != &FilenameBuffer[PreAppendSize]) |
| 1155 | memcpy(dest: &FilenameBuffer[PreAppendSize], src: BufPtr, n: ActualLen); |
| 1156 | |
| 1157 | // Resize FilenameBuffer to the correct size. |
| 1158 | if (FilenameTok.getLength() != ActualLen) |
| 1159 | FilenameBuffer.resize(N: PreAppendSize + ActualLen); |
| 1160 | } |
| 1161 | |
| 1162 | FilenameTok.startToken(); |
| 1163 | FilenameTok.setKind(tok::header_name); |
| 1164 | FilenameTok.setFlagValue(Flag: Token::StartOfLine, Val: StartOfLine); |
| 1165 | FilenameTok.setFlagValue(Flag: Token::LeadingSpace, Val: LeadingSpace); |
| 1166 | FilenameTok.setFlagValue(Flag: Token::LeadingEmptyMacro, Val: LeadingEmptyMacro); |
| 1167 | CreateString(Str: FilenameBuffer, Tok&: FilenameTok, ExpansionLocStart: Start, ExpansionLocEnd: End); |
| 1168 | } else if (FilenameTok.is(K: tok::string_literal) && AllowMacroExpansion) { |
| 1169 | // Convert a string-literal token of the form " h-char-sequence " |
| 1170 | // (produced by macro expansion) into a header-name token. |
| 1171 | // |
| 1172 | // The rules for header-names don't quite match the rules for |
| 1173 | // string-literals, but all the places where they differ result in |
| 1174 | // undefined behavior, so we can and do treat them the same. |
| 1175 | // |
| 1176 | // A string-literal with a prefix or suffix is not translated into a |
| 1177 | // header-name. This could theoretically be observable via the C++20 |
| 1178 | // context-sensitive header-name formation rules. |
| 1179 | StringRef Str = getSpelling(Tok: FilenameTok, Buffer&: FilenameBuffer); |
| 1180 | if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"') |
| 1181 | FilenameTok.setKind(tok::header_name); |
| 1182 | } |
| 1183 | |
| 1184 | return false; |
| 1185 | } |
| 1186 | |
| 1187 | std::optional<Token> Preprocessor::peekNextPPToken() const { |
| 1188 | // Do some quick tests for rejection cases. |
| 1189 | std::optional<Token> Val; |
| 1190 | if (CurLexer) |
| 1191 | Val = CurLexer->peekNextPPToken(); |
| 1192 | else |
| 1193 | Val = CurTokenLexer->peekNextPPToken(); |
| 1194 | |
| 1195 | if (!Val) { |
| 1196 | // We have run off the end. If it's a source file we don't |
| 1197 | // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the |
| 1198 | // macro stack. |
| 1199 | if (CurPPLexer) |
| 1200 | return std::nullopt; |
| 1201 | for (const IncludeStackInfo &Entry : llvm::reverse(C: IncludeMacroStack)) { |
| 1202 | if (Entry.TheLexer) |
| 1203 | Val = Entry.TheLexer->peekNextPPToken(); |
| 1204 | else |
| 1205 | Val = Entry.TheTokenLexer->peekNextPPToken(); |
| 1206 | |
| 1207 | if (Val) |
| 1208 | break; |
| 1209 | |
| 1210 | // Ran off the end of a source file? |
| 1211 | if (Entry.ThePPLexer) |
| 1212 | return std::nullopt; |
| 1213 | } |
| 1214 | } |
| 1215 | |
| 1216 | // Okay, we found the token and return. Otherwise we found the end of the |
| 1217 | // translation unit. |
| 1218 | return Val; |
| 1219 | } |
| 1220 | |
| 1221 | // We represent the primary and partition names as 'Paths' which are sections |
| 1222 | // of the hierarchical access path for a clang module. However for C++20 |
| 1223 | // the periods in a name are just another character, and we will need to |
| 1224 | // flatten them into a string. |
| 1225 | std::string ModuleLoader::getFlatNameFromPath(ModuleIdPath Path) { |
| 1226 | std::string Name; |
| 1227 | if (Path.empty()) |
| 1228 | return Name; |
| 1229 | |
| 1230 | for (auto &Piece : Path) { |
| 1231 | assert(Piece.getIdentifierInfo() && Piece.getLoc().isValid()); |
| 1232 | if (!Name.empty()) |
| 1233 | Name += "." ; |
| 1234 | Name += Piece.getIdentifierInfo()->getName(); |
| 1235 | } |
| 1236 | return Name; |
| 1237 | } |
| 1238 | |
| 1239 | ModuleNameLoc *ModuleNameLoc::Create(Preprocessor &PP, ModuleIdPath Path) { |
| 1240 | assert(!Path.empty() && "expect at least one identifier in a module name" ); |
| 1241 | void *Mem = PP.getPreprocessorAllocator().Allocate( |
| 1242 | Size: totalSizeToAlloc<IdentifierLoc>(Counts: Path.size()), Alignment: alignof(ModuleNameLoc)); |
| 1243 | return new (Mem) ModuleNameLoc(Path); |
| 1244 | } |
| 1245 | |
| 1246 | bool Preprocessor::LexModuleNameContinue(Token &Tok, SourceLocation UseLoc, |
| 1247 | SmallVectorImpl<Token> &Suffix, |
| 1248 | SmallVectorImpl<IdentifierLoc> &Path, |
| 1249 | bool AllowMacroExpansion, |
| 1250 | bool IsPartition) { |
| 1251 | auto ConsumeToken = [&]() { |
| 1252 | if (AllowMacroExpansion) |
| 1253 | Lex(Result&: Tok); |
| 1254 | else |
| 1255 | LexUnexpandedToken(Result&: Tok); |
| 1256 | Suffix.push_back(Elt: Tok); |
| 1257 | }; |
| 1258 | |
| 1259 | while (true) { |
| 1260 | if (Tok.isNot(K: tok::identifier)) { |
| 1261 | if (Tok.is(K: tok::code_completion)) { |
| 1262 | CurLexer->cutOffLexing(); |
| 1263 | CodeComplete->CodeCompleteModuleImport(ImportLoc: UseLoc, Path); |
| 1264 | return true; |
| 1265 | } |
| 1266 | |
| 1267 | Diag(Tok, DiagID: diag::err_pp_module_expected_ident) << Path.empty(); |
| 1268 | return true; |
| 1269 | } |
| 1270 | |
| 1271 | // [cpp.pre]/p2: |
| 1272 | // No identifier in the pp-module-name or pp-module-partition shall |
| 1273 | // currently be defined as an object-like macro. |
| 1274 | if (MacroInfo *MI = getMacroInfo(II: Tok.getIdentifierInfo()); |
| 1275 | MI && MI->isObjectLike() && getLangOpts().CPlusPlus20 && |
| 1276 | !AllowMacroExpansion) { |
| 1277 | Diag(Tok, DiagID: diag::err_pp_module_name_is_macro) |
| 1278 | << IsPartition << Tok.getIdentifierInfo(); |
| 1279 | Diag(Loc: MI->getDefinitionLoc(), DiagID: diag::note_macro_here) |
| 1280 | << Tok.getIdentifierInfo(); |
| 1281 | } |
| 1282 | |
| 1283 | // Record this part of the module path. |
| 1284 | Path.emplace_back(Args: Tok.getLocation(), Args: Tok.getIdentifierInfo()); |
| 1285 | ConsumeToken(); |
| 1286 | |
| 1287 | if (Tok.isNot(K: tok::period)) |
| 1288 | return false; |
| 1289 | |
| 1290 | ConsumeToken(); |
| 1291 | } |
| 1292 | } |
| 1293 | |
| 1294 | bool Preprocessor::HandleModuleName(StringRef DirType, SourceLocation UseLoc, |
| 1295 | Token &Tok, |
| 1296 | SmallVectorImpl<IdentifierLoc> &Path, |
| 1297 | SmallVectorImpl<Token> &DirToks, |
| 1298 | bool AllowMacroExpansion, |
| 1299 | bool IsPartition) { |
| 1300 | bool LeadingSpace = Tok.hasLeadingSpace(); |
| 1301 | unsigned NumToksInDirective = DirToks.size(); |
| 1302 | if (LexModuleNameContinue(Tok, UseLoc, Suffix&: DirToks, Path, AllowMacroExpansion, |
| 1303 | IsPartition)) { |
| 1304 | if (Tok.isNot(K: tok::eod)) |
| 1305 | CheckEndOfDirective(DirType, |
| 1306 | /*EnableMacros=*/false, ExtraToks: &DirToks); |
| 1307 | EnterModuleSuffixTokenStream(Toks: DirToks); |
| 1308 | return true; |
| 1309 | } |
| 1310 | |
| 1311 | // Clean the module-name tokens and replace these tokens with |
| 1312 | // annot_module_name. |
| 1313 | DirToks.resize(N: NumToksInDirective); |
| 1314 | ModuleNameLoc *NameLoc = ModuleNameLoc::Create(PP&: *this, Path); |
| 1315 | DirToks.emplace_back(); |
| 1316 | DirToks.back().setKind(tok::annot_module_name); |
| 1317 | DirToks.back().setAnnotationRange(NameLoc->getRange()); |
| 1318 | DirToks.back().setAnnotationValue(static_cast<void *>(NameLoc)); |
| 1319 | DirToks.back().setFlagValue(Flag: Token::LeadingSpace, Val: LeadingSpace); |
| 1320 | DirToks.push_back(Elt: Tok); |
| 1321 | return false; |
| 1322 | } |
| 1323 | |
| 1324 | /// [cpp.pre]/p2: |
| 1325 | /// A preprocessing directive consists of a sequence of preprocessing tokens |
| 1326 | /// that satisfies the following constraints: At the start of translation phase |
| 1327 | /// 4, the first preprocessing token in the sequence, referred to as a |
| 1328 | /// directive-introducing token, begins with the first character in the source |
| 1329 | /// file (optionally after whitespace containing no new-line characters) or |
| 1330 | /// follows whitespace containing at least one new-line character, and is: |
| 1331 | /// - a # preprocessing token, or |
| 1332 | /// - an import preprocessing token immediately followed on the same logical |
| 1333 | /// source line by a header-name, <, identifier, or : preprocessing token, or |
| 1334 | /// - a module preprocessing token immediately followed on the same logical |
| 1335 | /// source line by an identifier, :, or ; preprocessing token, or |
| 1336 | /// - an export preprocessing token immediately followed on the same logical |
| 1337 | /// source line by one of the two preceding forms. |
| 1338 | /// |
| 1339 | /// |
| 1340 | /// At the start of phase 4 an import or module token is treated as starting a |
| 1341 | /// directive and are converted to their respective keywords iff: |
| 1342 | /// - After skipping horizontal whitespace are |
| 1343 | /// - at the start of a logical line, or |
| 1344 | /// - preceded by an 'export' at the start of the logical line. |
| 1345 | /// - Are followed by an identifier pp token (before macro expansion), or |
| 1346 | /// - <, ", or : (but not ::) pp tokens for 'import', or |
| 1347 | /// - ; for 'module' |
| 1348 | /// Otherwise the token is treated as an identifier. |
| 1349 | bool Preprocessor::HandleModuleContextualKeyword(Token &Result) { |
| 1350 | if (!getLangOpts().CPlusPlusModules || !Result.isModuleContextualKeyword()) |
| 1351 | return false; |
| 1352 | |
| 1353 | if (Result.is(K: tok::kw_export)) { |
| 1354 | LastExportKeyword = Result; |
| 1355 | return false; |
| 1356 | } |
| 1357 | |
| 1358 | /// Trait 'module' and 'import' as a identifier when the main file is a |
| 1359 | /// preprocessed module file. We only allow '__preprocessed_module' and |
| 1360 | /// '__preprocessed_import' in this context. |
| 1361 | IdentifierInfo *II = Result.getIdentifierInfo(); |
| 1362 | if (isPreprocessedModuleFile() && |
| 1363 | (II->isStr(Str: tok::getKeywordSpelling(Kind: tok::kw_import)) || |
| 1364 | II->isStr(Str: tok::getKeywordSpelling(Kind: tok::kw_module)))) |
| 1365 | return false; |
| 1366 | |
| 1367 | if (LastExportKeyword.is(K: tok::kw_export)) { |
| 1368 | // The export keyword was not at the start of line, it's not a |
| 1369 | // directive-introducing token. |
| 1370 | if (!LastExportKeyword.isAtPhysicalStartOfLine()) |
| 1371 | return false; |
| 1372 | // [cpp.pre]/1.4 |
| 1373 | // export // not a preprocessing directive |
| 1374 | // import foo; // preprocessing directive (ill-formed at phase7) |
| 1375 | if (Result.isAtPhysicalStartOfLine()) |
| 1376 | return false; |
| 1377 | } else if (!Result.isAtPhysicalStartOfLine()) |
| 1378 | return false; |
| 1379 | |
| 1380 | llvm::SaveAndRestore<bool> SavedParsingPreprocessorDirective( |
| 1381 | CurPPLexer->ParsingPreprocessorDirective, true); |
| 1382 | |
| 1383 | // The next token may be an angled string literal after import keyword. |
| 1384 | llvm::SaveAndRestore<bool> SavedParsingFilemame( |
| 1385 | CurPPLexer->ParsingFilename, |
| 1386 | Result.getIdentifierInfo()->isImportKeyword()); |
| 1387 | |
| 1388 | std::optional<Token> NextTok = |
| 1389 | CurLexer ? CurLexer->peekNextPPToken() : CurTokenLexer->peekNextPPToken(); |
| 1390 | if (!NextTok) |
| 1391 | return false; |
| 1392 | |
| 1393 | if (NextTok->is(K: tok::raw_identifier)) |
| 1394 | LookUpIdentifierInfo(Identifier&: *NextTok); |
| 1395 | |
| 1396 | if (Result.getIdentifierInfo()->isImportKeyword()) { |
| 1397 | if (NextTok->isOneOf(Ks: tok::identifier, Ks: tok::less, Ks: tok::colon, |
| 1398 | Ks: tok::header_name)) { |
| 1399 | Result.setKind(tok::kw_import); |
| 1400 | ModuleImportLoc = Result.getLocation(); |
| 1401 | IsAtImport = false; |
| 1402 | return true; |
| 1403 | } |
| 1404 | } |
| 1405 | |
| 1406 | if (Result.getIdentifierInfo()->isModuleKeyword() && |
| 1407 | NextTok->isOneOf(Ks: tok::identifier, Ks: tok::colon, Ks: tok::semi)) { |
| 1408 | Result.setKind(tok::kw_module); |
| 1409 | ModuleDeclLoc = Result.getLocation(); |
| 1410 | return true; |
| 1411 | } |
| 1412 | |
| 1413 | // Ok, it's an identifier. |
| 1414 | return false; |
| 1415 | } |
| 1416 | |
| 1417 | bool Preprocessor::CollectPPImportSuffixAndEnterStream( |
| 1418 | SmallVectorImpl<Token> &Toks, bool StopUntilEOD) { |
| 1419 | CollectPPImportSuffix(Toks); |
| 1420 | EnterModuleSuffixTokenStream(Toks); |
| 1421 | return false; |
| 1422 | } |
| 1423 | |
| 1424 | /// Collect the tokens of a C++20 pp-import-suffix. |
| 1425 | void Preprocessor::CollectPPImportSuffix(SmallVectorImpl<Token> &Toks, |
| 1426 | bool StopUntilEOD) { |
| 1427 | while (true) { |
| 1428 | Toks.emplace_back(); |
| 1429 | Lex(Result&: Toks.back()); |
| 1430 | |
| 1431 | switch (Toks.back().getKind()) { |
| 1432 | case tok::semi: |
| 1433 | if (!StopUntilEOD) |
| 1434 | return; |
| 1435 | [[fallthrough]]; |
| 1436 | case tok::eod: |
| 1437 | case tok::eof: |
| 1438 | return; |
| 1439 | default: |
| 1440 | break; |
| 1441 | } |
| 1442 | } |
| 1443 | } |
| 1444 | |
| 1445 | // Allocate a holding buffer for a sequence of tokens and introduce it into |
| 1446 | // the token stream. |
| 1447 | void Preprocessor::EnterModuleSuffixTokenStream(ArrayRef<Token> Toks) { |
| 1448 | if (Toks.empty()) |
| 1449 | return; |
| 1450 | auto ToksCopy = std::make_unique<Token[]>(num: Toks.size()); |
| 1451 | std::copy(first: Toks.begin(), last: Toks.end(), result: ToksCopy.get()); |
| 1452 | EnterTokenStream(Toks: std::move(ToksCopy), NumToks: Toks.size(), |
| 1453 | /*DisableMacroExpansion*/ false, /*IsReinject*/ false); |
| 1454 | assert(CurTokenLexer && "Must have a TokenLexer" ); |
| 1455 | CurTokenLexer->setLexingCXXModuleDirective(); |
| 1456 | } |
| 1457 | |
| 1458 | /// Lex a token following the 'import' contextual keyword. |
| 1459 | /// |
| 1460 | /// pp-import: [C++20] |
| 1461 | /// import header-name pp-import-suffix[opt] ; |
| 1462 | /// import header-name-tokens pp-import-suffix[opt] ; |
| 1463 | /// [ObjC] @ import module-name ; |
| 1464 | /// [Clang] import module-name ; |
| 1465 | /// |
| 1466 | /// header-name-tokens: |
| 1467 | /// string-literal |
| 1468 | /// < [any sequence of preprocessing-tokens other than >] > |
| 1469 | /// |
| 1470 | /// module-name: |
| 1471 | /// module-name-qualifier[opt] identifier |
| 1472 | /// |
| 1473 | /// module-name-qualifier |
| 1474 | /// module-name-qualifier[opt] identifier . |
| 1475 | /// |
| 1476 | /// We respond to a pp-import by importing macros from the named module. |
| 1477 | bool Preprocessor::LexAfterModuleImport(Token &Result) { |
| 1478 | // Figure out what kind of lexer we actually have. |
| 1479 | recomputeCurLexerKind(); |
| 1480 | |
| 1481 | SmallVector<Token, 32> Suffix; |
| 1482 | SmallVector<IdentifierLoc, 3> Path; |
| 1483 | Lex(Result); |
| 1484 | if (LexModuleNameContinue(Tok&: Result, UseLoc: ModuleImportLoc, Suffix, Path, |
| 1485 | /*AllowMacroExpansion=*/true, |
| 1486 | /*IsPartition=*/false)) |
| 1487 | return CollectPPImportSuffixAndEnterStream(Toks&: Suffix); |
| 1488 | |
| 1489 | ModuleNameLoc *NameLoc = ModuleNameLoc::Create(PP&: *this, Path); |
| 1490 | Suffix.clear(); |
| 1491 | Suffix.emplace_back(); |
| 1492 | Suffix.back().setKind(tok::annot_module_name); |
| 1493 | Suffix.back().setAnnotationRange(NameLoc->getRange()); |
| 1494 | Suffix.back().setAnnotationValue(static_cast<void *>(NameLoc)); |
| 1495 | Suffix.push_back(Elt: Result); |
| 1496 | |
| 1497 | // Consume the pp-import-suffix and expand any macros in it now, if we're not |
| 1498 | // at the semicolon already. |
| 1499 | SourceLocation SemiLoc = Result.getLocation(); |
| 1500 | if (Suffix.back().isNot(K: tok::semi)) { |
| 1501 | if (Suffix.back().isNot(K: tok::eof)) |
| 1502 | CollectPPImportSuffix(Toks&: Suffix); |
| 1503 | if (Suffix.back().isNot(K: tok::semi)) { |
| 1504 | // This is not an import after all. |
| 1505 | EnterModuleSuffixTokenStream(Toks: Suffix); |
| 1506 | return false; |
| 1507 | } |
| 1508 | SemiLoc = Suffix.back().getLocation(); |
| 1509 | } |
| 1510 | |
| 1511 | Module *Imported = nullptr; |
| 1512 | if (getLangOpts().Modules) { |
| 1513 | Imported = TheModuleLoader.loadModule(ImportLoc: ModuleImportLoc, Path, Visibility: Module::Hidden, |
| 1514 | /*IsInclusionDirective=*/false); |
| 1515 | if (Imported) |
| 1516 | makeModuleVisible(M: Imported, Loc: SemiLoc); |
| 1517 | } |
| 1518 | |
| 1519 | if (Callbacks) |
| 1520 | Callbacks->moduleImport(ImportLoc: ModuleImportLoc, Path, Imported); |
| 1521 | |
| 1522 | if (!Suffix.empty()) { |
| 1523 | EnterModuleSuffixTokenStream(Toks: Suffix); |
| 1524 | return false; |
| 1525 | } |
| 1526 | return true; |
| 1527 | } |
| 1528 | |
| 1529 | void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc, |
| 1530 | bool IncludeExports) { |
| 1531 | CurSubmoduleState->VisibleModules.setVisible( |
| 1532 | M, Loc, IncludeExports, Vis: [](Module *) {}, |
| 1533 | Cb: [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) { |
| 1534 | // FIXME: Include the path in the diagnostic. |
| 1535 | // FIXME: Include the import location for the conflicting module. |
| 1536 | Diag(Loc: ModuleImportLoc, DiagID: diag::warn_module_conflict) |
| 1537 | << Path[0]->getFullModuleName() |
| 1538 | << Conflict->getFullModuleName() |
| 1539 | << Message; |
| 1540 | }); |
| 1541 | |
| 1542 | // Add this module to the imports list of the currently-built submodule. |
| 1543 | if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M) |
| 1544 | BuildingSubmoduleStack.back().M->Imports.insert(X: M); |
| 1545 | } |
| 1546 | |
| 1547 | bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String, |
| 1548 | const char *DiagnosticTag, |
| 1549 | bool AllowMacroExpansion) { |
| 1550 | // We need at least one string literal. |
| 1551 | if (Result.isNot(K: tok::string_literal)) { |
| 1552 | Diag(Tok: Result, DiagID: diag::err_expected_string_literal) |
| 1553 | << /*Source='in...'*/0 << DiagnosticTag; |
| 1554 | return false; |
| 1555 | } |
| 1556 | |
| 1557 | // Lex string literal tokens, optionally with macro expansion. |
| 1558 | SmallVector<Token, 4> StrToks; |
| 1559 | do { |
| 1560 | StrToks.push_back(Elt: Result); |
| 1561 | |
| 1562 | if (Result.hasUDSuffix()) |
| 1563 | Diag(Tok: Result, DiagID: diag::err_invalid_string_udl); |
| 1564 | |
| 1565 | if (AllowMacroExpansion) |
| 1566 | Lex(Result); |
| 1567 | else |
| 1568 | LexUnexpandedToken(Result); |
| 1569 | } while (Result.is(K: tok::string_literal)); |
| 1570 | |
| 1571 | // Concatenate and parse the strings. |
| 1572 | StringLiteralParser Literal(StrToks, *this); |
| 1573 | assert(Literal.isOrdinary() && "Didn't allow wide strings in" ); |
| 1574 | |
| 1575 | if (Literal.hadError) |
| 1576 | return false; |
| 1577 | |
| 1578 | if (Literal.Pascal) { |
| 1579 | Diag(Loc: StrToks[0].getLocation(), DiagID: diag::err_expected_string_literal) |
| 1580 | << /*Source='in...'*/0 << DiagnosticTag; |
| 1581 | return false; |
| 1582 | } |
| 1583 | |
| 1584 | String = std::string(Literal.GetString()); |
| 1585 | return true; |
| 1586 | } |
| 1587 | |
| 1588 | bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) { |
| 1589 | assert(Tok.is(tok::numeric_constant)); |
| 1590 | SmallString<8> IntegerBuffer; |
| 1591 | bool NumberInvalid = false; |
| 1592 | StringRef Spelling = getSpelling(Tok, Buffer&: IntegerBuffer, Invalid: &NumberInvalid); |
| 1593 | if (NumberInvalid) |
| 1594 | return false; |
| 1595 | NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(), |
| 1596 | getLangOpts(), getTargetInfo(), |
| 1597 | getDiagnostics()); |
| 1598 | if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix()) |
| 1599 | return false; |
| 1600 | llvm::APInt APVal(64, 0); |
| 1601 | if (Literal.GetIntegerValue(Val&: APVal)) |
| 1602 | return false; |
| 1603 | Lex(Result&: Tok); |
| 1604 | Value = APVal.getLimitedValue(); |
| 1605 | return true; |
| 1606 | } |
| 1607 | |
| 1608 | void Preprocessor::addCommentHandler(CommentHandler *Handler) { |
| 1609 | assert(Handler && "NULL comment handler" ); |
| 1610 | assert(!llvm::is_contained(CommentHandlers, Handler) && |
| 1611 | "Comment handler already registered" ); |
| 1612 | CommentHandlers.push_back(x: Handler); |
| 1613 | } |
| 1614 | |
| 1615 | void Preprocessor::removeCommentHandler(CommentHandler *Handler) { |
| 1616 | std::vector<CommentHandler *>::iterator Pos = |
| 1617 | llvm::find(Range&: CommentHandlers, Val: Handler); |
| 1618 | assert(Pos != CommentHandlers.end() && "Comment handler not registered" ); |
| 1619 | CommentHandlers.erase(position: Pos); |
| 1620 | } |
| 1621 | |
| 1622 | bool Preprocessor::HandleComment(Token &result, SourceRange ) { |
| 1623 | bool AnyPendingTokens = false; |
| 1624 | for (CommentHandler *H : CommentHandlers) { |
| 1625 | if (H->HandleComment(PP&: *this, Comment)) |
| 1626 | AnyPendingTokens = true; |
| 1627 | } |
| 1628 | if (!AnyPendingTokens || getCommentRetentionState()) |
| 1629 | return false; |
| 1630 | Lex(Result&: result); |
| 1631 | return true; |
| 1632 | } |
| 1633 | |
| 1634 | void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const { |
| 1635 | const MacroAnnotations &A = |
| 1636 | getMacroAnnotations(II: Identifier.getIdentifierInfo()); |
| 1637 | assert(A.DeprecationInfo && |
| 1638 | "Macro deprecation warning without recorded annotation!" ); |
| 1639 | const MacroAnnotationInfo &Info = *A.DeprecationInfo; |
| 1640 | if (Info.Message.empty()) |
| 1641 | Diag(Tok: Identifier, DiagID: diag::warn_pragma_deprecated_macro_use) |
| 1642 | << Identifier.getIdentifierInfo() << 0; |
| 1643 | else |
| 1644 | Diag(Tok: Identifier, DiagID: diag::warn_pragma_deprecated_macro_use) |
| 1645 | << Identifier.getIdentifierInfo() << 1 << Info.Message; |
| 1646 | Diag(Loc: Info.Location, DiagID: diag::note_pp_macro_annotation) << 0; |
| 1647 | } |
| 1648 | |
| 1649 | void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const { |
| 1650 | const MacroAnnotations &A = |
| 1651 | getMacroAnnotations(II: Identifier.getIdentifierInfo()); |
| 1652 | assert(A.RestrictExpansionInfo && |
| 1653 | "Macro restricted expansion warning without recorded annotation!" ); |
| 1654 | const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo; |
| 1655 | if (Info.Message.empty()) |
| 1656 | Diag(Tok: Identifier, DiagID: diag::warn_pragma_restrict_expansion_macro_use) |
| 1657 | << Identifier.getIdentifierInfo() << 0; |
| 1658 | else |
| 1659 | Diag(Tok: Identifier, DiagID: diag::warn_pragma_restrict_expansion_macro_use) |
| 1660 | << Identifier.getIdentifierInfo() << 1 << Info.Message; |
| 1661 | Diag(Loc: Info.Location, DiagID: diag::note_pp_macro_annotation) << 1; |
| 1662 | } |
| 1663 | |
| 1664 | void Preprocessor::emitRestrictInfNaNWarning(const Token &Identifier, |
| 1665 | unsigned DiagSelection) const { |
| 1666 | Diag(Tok: Identifier, DiagID: diag::warn_fp_nan_inf_when_disabled) << DiagSelection << 1; |
| 1667 | } |
| 1668 | |
| 1669 | void Preprocessor::emitFinalMacroWarning(const Token &Identifier, |
| 1670 | bool IsUndef) const { |
| 1671 | const MacroAnnotations &A = |
| 1672 | getMacroAnnotations(II: Identifier.getIdentifierInfo()); |
| 1673 | assert(A.FinalAnnotationLoc && |
| 1674 | "Final macro warning without recorded annotation!" ); |
| 1675 | |
| 1676 | Diag(Tok: Identifier, DiagID: diag::warn_pragma_final_macro) |
| 1677 | << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1); |
| 1678 | Diag(Loc: *A.FinalAnnotationLoc, DiagID: diag::note_pp_macro_annotation) << 2; |
| 1679 | } |
| 1680 | |
| 1681 | bool Preprocessor::isSafeBufferOptOut(const SourceManager &SourceMgr, |
| 1682 | const SourceLocation &Loc) const { |
| 1683 | // The lambda that tests if a `Loc` is in an opt-out region given one opt-out |
| 1684 | // region map: |
| 1685 | auto TestInMap = [&SourceMgr](const SafeBufferOptOutRegionsTy &Map, |
| 1686 | const SourceLocation &Loc) -> bool { |
| 1687 | // Try to find a region in `SafeBufferOptOutMap` where `Loc` is in: |
| 1688 | auto FirstRegionEndingAfterLoc = llvm::partition_point( |
| 1689 | Range: Map, P: [&SourceMgr, |
| 1690 | &Loc](const std::pair<SourceLocation, SourceLocation> &Region) { |
| 1691 | return SourceMgr.isBeforeInTranslationUnit(LHS: Region.second, RHS: Loc); |
| 1692 | }); |
| 1693 | |
| 1694 | if (FirstRegionEndingAfterLoc != Map.end()) { |
| 1695 | // To test if the start location of the found region precedes `Loc`: |
| 1696 | return SourceMgr.isBeforeInTranslationUnit( |
| 1697 | LHS: FirstRegionEndingAfterLoc->first, RHS: Loc); |
| 1698 | } |
| 1699 | // If we do not find a region whose end location passes `Loc`, we want to |
| 1700 | // check if the current region is still open: |
| 1701 | if (!Map.empty() && Map.back().first == Map.back().second) |
| 1702 | return SourceMgr.isBeforeInTranslationUnit(LHS: Map.back().first, RHS: Loc); |
| 1703 | return false; |
| 1704 | }; |
| 1705 | |
| 1706 | // What the following does: |
| 1707 | // |
| 1708 | // If `Loc` belongs to the local TU, we just look up `SafeBufferOptOutMap`. |
| 1709 | // Otherwise, `Loc` is from a loaded AST. We look up the |
| 1710 | // `LoadedSafeBufferOptOutMap` first to get the opt-out region map of the |
| 1711 | // loaded AST where `Loc` is at. Then we find if `Loc` is in an opt-out |
| 1712 | // region w.r.t. the region map. If the region map is absent, it means there |
| 1713 | // is no opt-out pragma in that loaded AST. |
| 1714 | // |
| 1715 | // Opt-out pragmas in the local TU or a loaded AST is not visible to another |
| 1716 | // one of them. That means if you put the pragmas around a `#include |
| 1717 | // "module.h"`, where module.h is a module, it is not actually suppressing |
| 1718 | // warnings in module.h. This is fine because warnings in module.h will be |
| 1719 | // reported when module.h is compiled in isolation and nothing in module.h |
| 1720 | // will be analyzed ever again. So you will not see warnings from the file |
| 1721 | // that imports module.h anyway. And you can't even do the same thing for PCHs |
| 1722 | // because they can only be included from the command line. |
| 1723 | |
| 1724 | if (SourceMgr.isLocalSourceLocation(Loc)) |
| 1725 | return TestInMap(SafeBufferOptOutMap, Loc); |
| 1726 | |
| 1727 | const SafeBufferOptOutRegionsTy *LoadedRegions = |
| 1728 | LoadedSafeBufferOptOutMap.lookupLoadedOptOutMap(Loc, SrcMgr: SourceMgr); |
| 1729 | |
| 1730 | if (LoadedRegions) |
| 1731 | return TestInMap(*LoadedRegions, Loc); |
| 1732 | return false; |
| 1733 | } |
| 1734 | |
| 1735 | bool Preprocessor::enterOrExitSafeBufferOptOutRegion( |
| 1736 | bool isEnter, const SourceLocation &Loc) { |
| 1737 | if (isEnter) { |
| 1738 | if (isPPInSafeBufferOptOutRegion()) |
| 1739 | return true; // invalid enter action |
| 1740 | InSafeBufferOptOutRegion = true; |
| 1741 | CurrentSafeBufferOptOutStart = Loc; |
| 1742 | |
| 1743 | // To set the start location of a new region: |
| 1744 | |
| 1745 | if (!SafeBufferOptOutMap.empty()) { |
| 1746 | [[maybe_unused]] auto *PrevRegion = &SafeBufferOptOutMap.back(); |
| 1747 | assert(PrevRegion->first != PrevRegion->second && |
| 1748 | "Shall not begin a safe buffer opt-out region before closing the " |
| 1749 | "previous one." ); |
| 1750 | } |
| 1751 | // If the start location equals to the end location, we call the region a |
| 1752 | // open region or a unclosed region (i.e., end location has not been set |
| 1753 | // yet). |
| 1754 | SafeBufferOptOutMap.emplace_back(Args: Loc, Args: Loc); |
| 1755 | } else { |
| 1756 | if (!isPPInSafeBufferOptOutRegion()) |
| 1757 | return true; // invalid enter action |
| 1758 | InSafeBufferOptOutRegion = false; |
| 1759 | |
| 1760 | // To set the end location of the current open region: |
| 1761 | |
| 1762 | assert(!SafeBufferOptOutMap.empty() && |
| 1763 | "Misordered safe buffer opt-out regions" ); |
| 1764 | auto *CurrRegion = &SafeBufferOptOutMap.back(); |
| 1765 | assert(CurrRegion->first == CurrRegion->second && |
| 1766 | "Set end location to a closed safe buffer opt-out region" ); |
| 1767 | CurrRegion->second = Loc; |
| 1768 | } |
| 1769 | return false; |
| 1770 | } |
| 1771 | |
| 1772 | bool Preprocessor::isPPInSafeBufferOptOutRegion() { |
| 1773 | return InSafeBufferOptOutRegion; |
| 1774 | } |
| 1775 | bool Preprocessor::isPPInSafeBufferOptOutRegion(SourceLocation &StartLoc) { |
| 1776 | StartLoc = CurrentSafeBufferOptOutStart; |
| 1777 | return InSafeBufferOptOutRegion; |
| 1778 | } |
| 1779 | |
| 1780 | SmallVector<SourceLocation, 64> |
| 1781 | Preprocessor::serializeSafeBufferOptOutMap() const { |
| 1782 | assert(!InSafeBufferOptOutRegion && |
| 1783 | "Attempt to serialize safe buffer opt-out regions before file being " |
| 1784 | "completely preprocessed" ); |
| 1785 | |
| 1786 | SmallVector<SourceLocation, 64> SrcSeq; |
| 1787 | |
| 1788 | for (const auto &[begin, end] : SafeBufferOptOutMap) { |
| 1789 | SrcSeq.push_back(Elt: begin); |
| 1790 | SrcSeq.push_back(Elt: end); |
| 1791 | } |
| 1792 | // Only `SafeBufferOptOutMap` gets serialized. No need to serialize |
| 1793 | // `LoadedSafeBufferOptOutMap` because if this TU loads a pch/module, every |
| 1794 | // pch/module in the pch-chain/module-DAG will be loaded one by one in order. |
| 1795 | // It means that for each loading pch/module m, it just needs to load m's own |
| 1796 | // `SafeBufferOptOutMap`. |
| 1797 | return SrcSeq; |
| 1798 | } |
| 1799 | |
| 1800 | bool Preprocessor::setDeserializedSafeBufferOptOutMap( |
| 1801 | const SmallVectorImpl<SourceLocation> &SourceLocations) { |
| 1802 | if (SourceLocations.size() == 0) |
| 1803 | return false; |
| 1804 | |
| 1805 | assert(SourceLocations.size() % 2 == 0 && |
| 1806 | "ill-formed SourceLocation sequence" ); |
| 1807 | |
| 1808 | auto It = SourceLocations.begin(); |
| 1809 | SafeBufferOptOutRegionsTy &Regions = |
| 1810 | LoadedSafeBufferOptOutMap.findAndConsLoadedOptOutMap(Loc: *It, SrcMgr&: SourceMgr); |
| 1811 | |
| 1812 | do { |
| 1813 | SourceLocation Begin = *It++; |
| 1814 | SourceLocation End = *It++; |
| 1815 | |
| 1816 | Regions.emplace_back(Args&: Begin, Args&: End); |
| 1817 | } while (It != SourceLocations.end()); |
| 1818 | return true; |
| 1819 | } |
| 1820 | |
| 1821 | ModuleLoader::~ModuleLoader() = default; |
| 1822 | |
| 1823 | CommentHandler::~CommentHandler() = default; |
| 1824 | |
| 1825 | EmptylineHandler::~EmptylineHandler() = default; |
| 1826 | |
| 1827 | CodeCompletionHandler::~CodeCompletionHandler() = default; |
| 1828 | |
| 1829 | void Preprocessor::createPreprocessingRecord() { |
| 1830 | if (Record) |
| 1831 | return; |
| 1832 | |
| 1833 | Record = new PreprocessingRecord(getSourceManager()); |
| 1834 | addPPCallbacks(C: std::unique_ptr<PPCallbacks>(Record)); |
| 1835 | } |
| 1836 | |
| 1837 | const char *Preprocessor::getCheckPoint(FileID FID, const char *Start) const { |
| 1838 | if (auto It = CheckPoints.find(Val: FID); It != CheckPoints.end()) { |
| 1839 | const SmallVector<const char *> &FileCheckPoints = It->second; |
| 1840 | const char *Last = nullptr; |
| 1841 | // FIXME: Do better than a linear search. |
| 1842 | for (const char *P : FileCheckPoints) { |
| 1843 | if (P > Start) |
| 1844 | break; |
| 1845 | Last = P; |
| 1846 | } |
| 1847 | return Last; |
| 1848 | } |
| 1849 | |
| 1850 | return nullptr; |
| 1851 | } |
| 1852 | |
| 1853 | bool Preprocessor::hasSeenNoTrivialPPDirective() const { |
| 1854 | return DirTracer && DirTracer->hasSeenNoTrivialPPDirective(); |
| 1855 | } |
| 1856 | |
| 1857 | bool NoTrivialPPDirectiveTracer::hasSeenNoTrivialPPDirective() const { |
| 1858 | return SeenNoTrivialPPDirective; |
| 1859 | } |
| 1860 | |
| 1861 | void NoTrivialPPDirectiveTracer::setSeenNoTrivialPPDirective() { |
| 1862 | if (InMainFile && !SeenNoTrivialPPDirective) |
| 1863 | SeenNoTrivialPPDirective = true; |
| 1864 | } |
| 1865 | |
| 1866 | void NoTrivialPPDirectiveTracer::LexedFileChanged( |
| 1867 | FileID FID, LexedFileChangeReason Reason, |
| 1868 | SrcMgr::CharacteristicKind FileType, FileID PrevFID, SourceLocation Loc) { |
| 1869 | InMainFile = (FID == PP.getSourceManager().getMainFileID()); |
| 1870 | } |
| 1871 | |
| 1872 | void NoTrivialPPDirectiveTracer::MacroExpands(const Token &MacroNameTok, |
| 1873 | const MacroDefinition &MD, |
| 1874 | SourceRange Range, |
| 1875 | const MacroArgs *Args) { |
| 1876 | // FIXME: Does only enable builtin macro expansion make sense? |
| 1877 | if (!MD.getMacroInfo()->isBuiltinMacro()) |
| 1878 | setSeenNoTrivialPPDirective(); |
| 1879 | } |
| 1880 | |