clang 23.0.0git
Preprocessor.cpp
Go to the documentation of this file.
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
31#include "clang/Basic/LLVM.h"
33#include "clang/Basic/Module.h"
42#include "clang/Lex/Lexer.h"
44#include "clang/Lex/MacroArgs.h"
45#include "clang/Lex/MacroInfo.h"
48#include "clang/Lex/Pragma.h"
53#include "clang/Lex/Token.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
77using namespace clang;
78
79/// Minimum distance between two check points, in tokens.
80static constexpr unsigned CheckPointStepSize = 1024;
81
82LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
83
85
87 DiagnosticsEngine &diags, const LangOptions &opts,
88 SourceManager &SM, HeaderSearch &Headers,
89 ModuleLoader &TheModuleLoader,
90 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
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("__VA_ARGS__"))->setIsPoisoned();
130 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
131 (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
132 SetPoisonReason(Ident__VA_OPT__,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("_exception_info");
142 Ident___exception_info = getIdentifierInfo("__exception_info");
143 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
144 Ident__exception_code = getIdentifierInfo("_exception_code");
145 Ident___exception_code = getIdentifierInfo("__exception_code");
146 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
147 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
148 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
149 Ident_AbnormalTermination = getIdentifierInfo("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.
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
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(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, 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
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(SourceLocation(), Target.getFPEvalMethod());
220 else
221 // Set initial value of __FLT_EVAL_METHOD__ from the command line.
222 setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
223}
224
226 NumEnteredSourceFiles = 0;
227
228 // Reset pragmas
229 PragmaHandlersBackup = std::move(PragmaHandlers);
230 PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
231 RegisterBuiltinPragmas();
232
233 // Reset PredefinesFileID
234 PredefinesFileID = FileID();
235}
236
238 NumEnteredSourceFiles = 1;
239
240 PragmaHandlers = std::move(PragmaHandlersBackup);
241}
242
243void 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("{0,-16} ", tok::getTokenName(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(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("{0,-48} ", 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(PLoc.getLine()).size();
284 int ColumnWidth = llvm::utostr(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>(0, LeftSpace);
292
293 llvm::errs().indent(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(Tok.getLocation());
305 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) << "']";
306 }
307}
308
310 Loc.print(llvm::errs(), SourceMgr);
311}
312
313void Preprocessor::DumpMacro(const MacroInfo &MI) const {
314 llvm::errs() << "MACRO: ";
315 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
317 llvm::errs() << " ";
318 }
319 llvm::errs() << "\n";
320}
321
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(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(CurSubmoduleState->Macros);
352 llvm::errs() << "\n #pragma push_macro Info: "
353 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
354 llvm::errs() << "\n Poison Reasons: "
355 << llvm::capacity_in_bytes(PoisonReasons);
356 llvm::errs() << "\n Comment Handlers: "
357 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
358}
359
360llvm::iterator_range<Preprocessor::macro_iterator>
361Preprocessor::macros(bool IncludeExternalMacros) const {
362 if (IncludeExternalMacros && ExternalSource &&
363 !ReadMacrosFromExternalSource) {
364 ReadMacrosFromExternalSource = true;
365 ExternalSource->ReadDefinedMacros();
366 }
367 // Make sure we cover all macros in visible modules.
368 for (const ModuleMacro &Macro : ModuleMacros)
369 CurSubmoduleState->Macros.try_emplace(Macro.II);
370
371 return CurSubmoduleState->Macros;
372}
373
375 return BP.getTotalMemory()
376 + llvm::capacity_in_bytes(MacroExpandedTokens)
377 + Predefines.capacity() /* Predefines buffer. */
378 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
379 // and ModuleMacros.
380 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
381 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
382 + llvm::capacity_in_bytes(PoisonReasons)
383 + llvm::capacity_in_bytes(CommentHandlers);
384}
385
386/// Compares macro tokens with a specified token value sequence.
387static bool MacroDefinitionEquals(const MacroInfo *MI,
388 ArrayRef<TokenValue> Tokens) {
389 return Tokens.size() == MI->getNumTokens() &&
390 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
391}
392
394 SourceLocation Loc,
395 ArrayRef<TokenValue> Tokens) const {
396 SourceLocation BestLocation;
397 StringRef BestSpelling;
398 for (const auto &M : macros()) {
399 const MacroDirective::DefInfo Def =
400 M.second.findDirectiveAtLoc(Loc, SourceMgr);
401 if (!Def || !Def.getMacroInfo())
402 continue;
403 if (!Def.getMacroInfo()->isObjectLike())
404 continue;
405 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
406 continue;
407 SourceLocation Location = Def.getLocation();
408 // Choose the macro defined latest.
409 if (BestLocation.isInvalid() ||
410 (Location.isValid() &&
411 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
412 BestLocation = Location;
413 BestSpelling = M.first->getName();
414 }
415 }
416 return BestSpelling;
417}
418
420 if (CurLexer)
421 CurLexerCallback = CurLexer->isDependencyDirectivesLexer()
422 ? CLK_DependencyDirectivesLexer
423 : CLK_Lexer;
424 else if (CurTokenLexer)
425 CurLexerCallback = CLK_TokenLexer;
426 else
427 CurLexerCallback = CLK_CachingLexer;
428}
429
431 unsigned CompleteLine,
432 unsigned CompleteColumn) {
433 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
434 assert(!CodeCompletionFile && "Already set");
435
436 // Load the actual file's contents.
437 std::optional<llvm::MemoryBufferRef> Buffer =
438 SourceMgr.getMemoryBufferForFileOrNone(File);
439 if (!Buffer)
440 return true;
441
442 // Find the byte position of the truncation point.
443 const char *Position = Buffer->getBufferStart();
444 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
445 for (; *Position; ++Position) {
446 if (*Position != '\r' && *Position != '\n')
447 continue;
448
449 // Eat \r\n or \n\r as a single line.
450 if ((Position[1] == '\r' || Position[1] == '\n') &&
451 Position[0] != Position[1])
452 ++Position;
453 ++Position;
454 break;
455 }
456 }
457
458 Position += CompleteColumn - 1;
459
460 // If pointing inside the preamble, adjust the position at the beginning of
461 // the file after the preamble.
462 if (SkipMainFilePreamble.first &&
463 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
464 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
465 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
466 }
467
468 if (Position > Buffer->getBufferEnd())
469 Position = Buffer->getBufferEnd();
470
471 CodeCompletionFile = File;
472 CodeCompletionOffset = Position - Buffer->getBufferStart();
473
474 auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
475 Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
476 char *NewBuf = NewBuffer->getBufferStart();
477 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
478 *NewPos = '\0';
479 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
480 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
481
482 return false;
483}
484
486 bool IsAngled) {
488 if (CodeComplete)
489 CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
490}
491
494 if (CodeComplete)
495 CodeComplete->CodeCompleteNaturalLanguage();
496}
497
498/// getSpelling - This method is used to get the spelling of a token into a
499/// SmallVector. Note that the returned StringRef may not point to the
500/// supplied buffer if a copy can be avoided.
502 SmallVectorImpl<char> &Buffer,
503 bool *Invalid) const {
504 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
505 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
506 // Try the fast path.
507 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
508 return II->getName();
509 }
510
511 // Resize the buffer if we need to copy into it.
512 if (Tok.needsCleaning())
513 Buffer.resize(Tok.getLength());
514
515 const char *Ptr = Buffer.data();
516 unsigned Len = getSpelling(Tok, Ptr, Invalid);
517 return StringRef(Ptr, Len);
518}
519
520/// CreateString - Plop the specified string into a scratch buffer and return a
521/// location for it. If specified, the source location provides a source
522/// location for the token.
524 SourceLocation ExpansionLocStart,
525 SourceLocation ExpansionLocEnd) {
526 Tok.setLength(Str.size());
527
528 const char *DestPtr;
529 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
530
531 if (ExpansionLocStart.isValid())
532 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
533 ExpansionLocEnd, Str.size());
534 Tok.setLocation(Loc);
535
536 // If this is a raw identifier or a literal token, set the pointer data.
537 if (Tok.is(tok::raw_identifier))
538 Tok.setRawIdentifierData(DestPtr);
539 else if (Tok.isLiteral())
540 Tok.setLiteralData(DestPtr);
541}
542
544 auto &SM = getSourceManager();
545 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
546 FileIDAndOffset LocInfo = SM.getDecomposedLoc(SpellingLoc);
547 bool Invalid = false;
548 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
549 if (Invalid)
550 return SourceLocation();
551
552 // FIXME: We could consider re-using spelling for tokens we see repeatedly.
553 const char *DestPtr;
554 SourceLocation Spelling =
555 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
556 return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
557}
558
560 if (!getLangOpts().isCompilingModule())
561 return nullptr;
562
563 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
564}
565
567 if (!getLangOpts().isCompilingModuleImplementation())
568 return nullptr;
569
570 return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);
571}
572
573//===----------------------------------------------------------------------===//
574// Preprocessor Initialization Methods
575//===----------------------------------------------------------------------===//
576
577/// EnterMainSourceFile - Enter the specified FileID as the main source file,
578/// which implicitly adds the builtin defines etc.
580 // We do not allow the preprocessor to reenter the main file. Doing so will
581 // cause FileID's to accumulate information from both runs (e.g. #line
582 // information) and predefined macros aren't guaranteed to be set properly.
583 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
584 FileID MainFileID = SourceMgr.getMainFileID();
585
586 // If MainFileID is loaded it means we loaded an AST file, no need to enter
587 // a main file.
588 if (!SourceMgr.isLoadedFileID(MainFileID)) {
589 // Enter the main file source buffer.
590 EnterSourceFile(MainFileID, nullptr, SourceLocation());
591
592 // If we've been asked to skip bytes in the main file (e.g., as part of a
593 // precompiled preamble), do so now.
594 if (SkipMainFilePreamble.first > 0)
595 CurLexer->SetByteOffset(SkipMainFilePreamble.first,
596 SkipMainFilePreamble.second);
597
598 // Tell the header info that the main file was entered. If the file is later
599 // #imported, it won't be re-entered.
600 if (OptionalFileEntryRef FE = SourceMgr.getFileEntryRefForID(MainFileID))
601 markIncluded(*FE);
602
603 // Record the first PP token in the main file. This is used to generate
604 // better diagnostics for C++ modules.
605 //
606 // // This is a comment.
607 // #define FOO int // note: add 'module;' to the start of the file
608 // ^ FirstPPToken // to introduce a global module fragment.
609 //
610 // export module M; // error: module declaration must occur
611 // // at the start of the translation unit.
612 if (getLangOpts().CPlusPlusModules) {
613 std::optional<StringRef> Input =
615 if (!isPreprocessedModuleFile() && Input)
616 MainFileIsPreprocessedModuleFile =
618 auto Tracer = std::make_unique<NoTrivialPPDirectiveTracer>(*this);
619 DirTracer = Tracer.get();
620 addPPCallbacks(std::move(Tracer));
621 std::optional<Token> FirstPPTok = CurLexer->peekNextPPToken();
622 if (FirstPPTok)
623 FirstPPTokenLoc = FirstPPTok->getLocation();
624 }
625 }
626
627 // Preprocess Predefines to populate the initial preprocessor state.
628 std::unique_ptr<llvm::MemoryBuffer> SB =
629 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
630 assert(SB && "Cannot create predefined source buffer");
631 FileID FID = SourceMgr.createFileID(std::move(SB));
632 assert(FID.isValid() && "Could not create FileID for predefines?");
633 setPredefinesFileID(FID);
634
635 // Start parsing the predefines.
636 EnterSourceFile(FID, nullptr, SourceLocation());
637
638 if (!PPOpts.PCHThroughHeader.empty()) {
639 // Lookup and save the FileID for the through header. If it isn't found
640 // in the search path, it's a fatal error.
642 SourceLocation(), PPOpts.PCHThroughHeader,
643 /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
644 /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
645 /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
646 /*IsFrameworkFound=*/nullptr);
647 if (!File) {
648 Diag(SourceLocation(), diag::err_pp_through_header_not_found)
649 << PPOpts.PCHThroughHeader;
650 return;
651 }
652 setPCHThroughHeaderFileID(
653 SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
654 }
655
656 // Skip tokens from the Predefines and if needed the main file.
657 if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
658 (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
660}
661
662void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
663 assert(PCHThroughHeaderFileID.isInvalid() &&
664 "PCHThroughHeaderFileID already set!");
665 PCHThroughHeaderFileID = FID;
666}
667
669 assert(PCHThroughHeaderFileID.isValid() &&
670 "Invalid PCH through header FileID");
671 return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
672}
673
675 return TUKind == TU_Prefix && !PPOpts.PCHThroughHeader.empty() &&
676 PCHThroughHeaderFileID.isValid();
677}
678
680 return TUKind != TU_Prefix && !PPOpts.PCHThroughHeader.empty() &&
681 PCHThroughHeaderFileID.isValid();
682}
683
685 return TUKind == TU_Prefix && PPOpts.PCHWithHdrStop;
686}
687
689 return TUKind != TU_Prefix && PPOpts.PCHWithHdrStop;
690}
691
692/// Skip tokens until after the #include of the through header or
693/// until after a #pragma hdrstop is seen. Tokens in the predefines file
694/// and the main file may be skipped. If the end of the predefines file
695/// is reached, skipping continues into the main file. If the end of the
696/// main file is reached, it's a fatal error.
698 bool ReachedMainFileEOF = false;
699 bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
700 bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
701 Token Tok;
702 while (true) {
703 bool InPredefines =
704 (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
705 CurLexerCallback(*this, Tok);
706 if (Tok.is(tok::eof) && !InPredefines) {
707 ReachedMainFileEOF = true;
708 break;
709 }
710 if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
711 break;
712 if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
713 break;
714 }
715 if (ReachedMainFileEOF) {
716 if (UsingPCHThroughHeader)
717 Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
718 << PPOpts.PCHThroughHeader << 1;
719 else if (!PPOpts.PCHWithHdrStopCreate)
720 Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
721 }
722}
723
724void Preprocessor::replayPreambleConditionalStack() {
725 // Restore the conditional stack from the preamble, if there is one.
726 if (PreambleConditionalStack.isReplaying()) {
727 assert(CurPPLexer &&
728 "CurPPLexer is null when calling replayPreambleConditionalStack.");
729 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
730 PreambleConditionalStack.doneReplaying();
731 if (PreambleConditionalStack.reachedEOFWhileSkipping())
732 SkipExcludedConditionalBlock(
733 PreambleConditionalStack.SkipInfo->HashTokenLoc,
734 PreambleConditionalStack.SkipInfo->IfTokenLoc,
735 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
736 PreambleConditionalStack.SkipInfo->FoundElse,
737 PreambleConditionalStack.SkipInfo->ElseLoc);
738 }
739}
740
742 // Notify the client that we reached the end of the source file.
743 if (Callbacks)
744 Callbacks->EndOfMainFile();
745}
746
747//===----------------------------------------------------------------------===//
748// Lexer Event Handling.
749//===----------------------------------------------------------------------===//
750
751/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
752/// identifier information for the token and install it into the token,
753/// updating the token kind accordingly.
755 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
756
757 // Look up this token, see if it is a macro, or if it is a language keyword.
758 IdentifierInfo *II;
759 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
760 // No cleaning needed, just use the characters from the lexed buffer.
761 II = getIdentifierInfo(Identifier.getRawIdentifier());
762 } else {
763 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
764 SmallString<64> IdentifierBuffer;
765 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
766
767 if (Identifier.hasUCN()) {
768 SmallString<64> UCNIdentifierBuffer;
769 expandUCNs(UCNIdentifierBuffer, CleanedStr);
770 II = getIdentifierInfo(UCNIdentifierBuffer);
771 } else {
772 II = getIdentifierInfo(CleanedStr);
773 }
774 }
775
776 // Update the token info (identifier info and appropriate token kind).
777 // FIXME: the raw_identifier may contain leading whitespace which is removed
778 // from the cleaned identifier token. The SourceLocation should be updated to
779 // refer to the non-whitespace character. For instance, the text "\\\nB" (a
780 // line continuation before 'B') is parsed as a single tok::raw_identifier and
781 // is cleaned to tok::identifier "B". After cleaning the token's length is
782 // still 3 and the SourceLocation refers to the location of the backslash.
783 Identifier.setIdentifierInfo(II);
784 Identifier.setKind(II->getTokenID());
785
786 return II;
787}
788
790 PoisonReasons[II] = DiagID;
791}
792
794 assert(Ident__exception_code && Ident__exception_info);
795 assert(Ident___exception_code && Ident___exception_info);
796 Ident__exception_code->setIsPoisoned(Poison);
797 Ident___exception_code->setIsPoisoned(Poison);
798 Ident_GetExceptionCode->setIsPoisoned(Poison);
799 Ident__exception_info->setIsPoisoned(Poison);
800 Ident___exception_info->setIsPoisoned(Poison);
801 Ident_GetExceptionInfo->setIsPoisoned(Poison);
802 Ident__abnormal_termination->setIsPoisoned(Poison);
803 Ident___abnormal_termination->setIsPoisoned(Poison);
804 Ident_AbnormalTermination->setIsPoisoned(Poison);
805}
806
808 assert(Identifier.getIdentifierInfo() &&
809 "Can't handle identifiers without identifier info!");
810 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
811 PoisonReasons.find(Identifier.getIdentifierInfo());
812 if(it == PoisonReasons.end())
813 Diag(Identifier, diag::err_pp_used_poisoned_id);
814 else
815 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
816}
817
818void Preprocessor::updateOutOfDateIdentifier(const IdentifierInfo &II) const {
819 assert(II.isOutOfDate() && "not out of date");
820 assert(getExternalSource() &&
821 "getExternalSource() should not return nullptr");
823}
824
825/// HandleIdentifier - This callback is invoked when the lexer reads an
826/// identifier. This callback looks up the identifier in the map and/or
827/// potentially macro expands it or turns it into a named token (like 'for').
828///
829/// Note that callers of this method are guarded by checking the
830/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
831/// IdentifierInfo methods that compute these properties will need to change to
832/// match.
834 assert(Identifier.getIdentifierInfo() &&
835 "Can't handle identifiers without identifier info!");
836
837 IdentifierInfo &II = *Identifier.getIdentifierInfo();
838
839 // If the information about this identifier is out of date, update it from
840 // the external source.
841 // We have to treat __VA_ARGS__ in a special way, since it gets
842 // serialized with isPoisoned = true, but our preprocessor may have
843 // unpoisoned it if we're defining a C99 macro.
844 if (II.isOutOfDate()) {
845 bool CurrentIsPoisoned = false;
846 const bool IsSpecialVariadicMacro =
847 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
848 if (IsSpecialVariadicMacro)
849 CurrentIsPoisoned = II.isPoisoned();
850
851 updateOutOfDateIdentifier(II);
852 Identifier.setKind(II.getTokenID());
853
854 if (IsSpecialVariadicMacro)
855 II.setIsPoisoned(CurrentIsPoisoned);
856 }
857
858 // If this identifier was poisoned, and if it was not produced from a macro
859 // expansion, emit an error.
860 if (II.isPoisoned() && CurPPLexer) {
861 HandlePoisonedIdentifier(Identifier);
862 }
863
864 // If this is a macro to be expanded, do it.
865 if (const MacroDefinition MD = getMacroDefinition(&II)) {
866 const auto *MI = MD.getMacroInfo();
867 assert(MI && "macro definition with no macro info?");
868 if (!DisableMacroExpansion) {
869 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
870 // C99 6.10.3p10: If the preprocessing token immediately after the
871 // macro name isn't a '(', this macro should not be expanded.
872 if (!MI->isFunctionLike() || isNextPPTokenOneOf(tok::l_paren))
873 return HandleMacroExpandedIdentifier(Identifier, MD);
874 } else {
875 // C99 6.10.3.4p2 says that a disabled macro may never again be
876 // expanded, even if it's in a context where it could be expanded in the
877 // future.
878 Identifier.setFlag(Token::DisableExpand);
879 if (MI->isObjectLike() || isNextPPTokenOneOf(tok::l_paren))
880 Diag(Identifier, diag::pp_disabled_macro_expansion);
881 }
882 }
883 }
884
885 // If this identifier is a keyword in a newer Standard or proposed Standard,
886 // produce a warning. Don't warn if we're not considering macro expansion,
887 // since this identifier might be the name of a macro.
888 // FIXME: This warning is disabled in cases where it shouldn't be, like
889 // "#define constexpr constexpr", "int constexpr;"
890 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
891 Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))
892 << II.getName();
893 // Don't diagnose this keyword again in this translation unit.
894 II.setIsFutureCompatKeyword(false);
895 }
896
897 // If this identifier would be a keyword in C++, diagnose as a compatibility
898 // issue.
899 if (II.IsKeywordInCPlusPlus() && !DisableMacroExpansion)
900 Diag(Identifier, diag::warn_pp_identifier_is_cpp_keyword) << &II;
901
902 // If this is an extension token, diagnose its use.
903 // We avoid diagnosing tokens that originate from macro definitions.
904 // FIXME: This warning is disabled in cases where it shouldn't be,
905 // like "#define TY typeof", "TY(1) x".
906 if (II.isExtensionToken() && !DisableMacroExpansion)
907 Diag(Identifier, diag::ext_token_used);
908
909 // Handle module contextual keywords.
910 if (getLangOpts().CPlusPlusModules && CurLexer &&
911 !CurLexer->isLexingRawMode() && !CurLexer->isPragmaLexer() &&
912 !CurLexer->ParsingPreprocessorDirective &&
913 Identifier.isModuleContextualKeyword() &&
914 HandleModuleContextualKeyword(Identifier)) {
915 HandleDirective(Identifier);
916 // With a fatal failure in the module loader, we abort parsing.
918 }
919
920 return true;
921}
922
924 ++LexLevel;
925
926 // We loop here until a lex function returns a token; this avoids recursion.
927 while (!CurLexerCallback(*this, Result))
928 ;
929
930 if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
931 return;
932
933 if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
934 // Remember the identifier before code completion token.
935 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
936 setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
937 // Set IdenfitierInfo to null to avoid confusing code that handles both
938 // identifiers and completion tokens.
939 Result.setIdentifierInfo(nullptr);
940 }
941
942 // Update StdCXXImportSeqState to track our position within a C++20 import-seq
943 // if this token is being produced as a result of phase 4 of translation.
944 // Update TrackGMFState to decide if we are currently in a Global Module
945 // Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state
946 // depends on the prevailing StdCXXImportSeq state in two cases.
947 if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
948 !Result.getFlag(Token::IsReinjected)) {
949 switch (Result.getKind()) {
950 case tok::l_paren: case tok::l_square: case tok::l_brace:
951 StdCXXImportSeqState.handleOpenBracket();
952 break;
953 case tok::r_paren: case tok::r_square:
954 StdCXXImportSeqState.handleCloseBracket();
955 break;
956 case tok::r_brace:
957 StdCXXImportSeqState.handleCloseBrace();
958 break;
959#define PRAGMA_ANNOTATION(X) case tok::annot_##X:
960// For `#pragma ...` mimic ';'.
961#include "clang/Basic/TokenKinds.def"
962#undef PRAGMA_ANNOTATION
963 // This token is injected to represent the translation of '#include "a.h"'
964 // into "import a.h;". Mimic the notional ';'.
965 case tok::annot_module_include:
966 case tok::annot_repl_input_end:
967 case tok::semi:
968 TrackGMFState.handleSemi();
969 StdCXXImportSeqState.handleSemi();
970 ModuleDeclState.handleSemi();
971 break;
972 case tok::header_name:
973 case tok::annot_header_unit:
974 StdCXXImportSeqState.handleHeaderName();
975 break;
976 case tok::kw_export:
979 TrackGMFState.handleExport();
980 StdCXXImportSeqState.handleExport();
981 ModuleDeclState.handleExport();
982 break;
983 case tok::colon:
984 ModuleDeclState.handleColon();
985 break;
986 case tok::kw_import:
987 if (StdCXXImportSeqState.atTopLevel()) {
988 TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());
989 StdCXXImportSeqState.handleImport();
990 }
991 break;
992 case tok::kw_module:
993 if (StdCXXImportSeqState.atTopLevel()) {
996 TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());
997 ModuleDeclState.handleModule();
998 }
999 break;
1000 case tok::annot_module_name:
1001 ModuleDeclState.handleModuleName(
1002 static_cast<ModuleNameLoc *>(Result.getAnnotationValue()));
1003 if (ModuleDeclState.isModuleCandidate())
1004 break;
1005 [[fallthrough]];
1006 default:
1007 TrackGMFState.handleMisc();
1008 StdCXXImportSeqState.handleMisc();
1009 ModuleDeclState.handleMisc();
1010 break;
1011 }
1012 }
1013
1014 if (CurLexer && ++CheckPointCounter == CheckPointStepSize) {
1015 CheckPoints[CurLexer->getFileID()].push_back(CurLexer->BufferPtr);
1016 CheckPointCounter = 0;
1017 }
1018
1019 if (Result.isNot(tok::kw_export))
1020 LastExportKeyword.startToken();
1021
1022 --LexLevel;
1023
1024 // Destroy any lexers that were deferred while we were in nested Lex calls.
1025 // This must happen after decrementing LexLevel but before any other
1026 // processing that might re-enter Lex.
1027 if (LexLevel == 0 && !PendingDestroyLexers.empty())
1028 PendingDestroyLexers.clear();
1029
1030 if ((LexLevel == 0 || PreprocessToken) &&
1031 !Result.getFlag(Token::IsReinjected)) {
1032 if (LexLevel == 0)
1033 ++TokenCount;
1034 if (OnToken)
1035 OnToken(Result);
1036 }
1037}
1038
1039void Preprocessor::LexTokensUntilEOF(std::vector<Token> *Tokens) {
1040 while (1) {
1041 Token Tok;
1042 Lex(Tok);
1043 if (Tok.isOneOf(tok::unknown, tok::eof, tok::eod,
1044 tok::annot_repl_input_end))
1045 break;
1046 if (Tokens != nullptr)
1047 Tokens->push_back(Tok);
1048 }
1049}
1050
1051/// Lex a header-name token (including one formed from header-name-tokens if
1052/// \p AllowMacroExpansion is \c true).
1053///
1054/// \param FilenameTok Filled in with the next token. On success, this will
1055/// be either a header_name token. On failure, it will be whatever other
1056/// token was found instead.
1057/// \param AllowMacroExpansion If \c true, allow the header name to be formed
1058/// by macro expansion (concatenating tokens as necessary if the first
1059/// token is a '<').
1060/// \return \c true if we reached EOD or EOF while looking for a > token in
1061/// a concatenated header name and diagnosed it. \c false otherwise.
1062bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
1063 // Lex using header-name tokenization rules if tokens are being lexed from
1064 // a file. Just grab a token normally if we're in a macro expansion.
1065 if (CurPPLexer) {
1066 // Avoid nested header-name lexing when macro expansion recurses
1067 // __has_include(__has_include))
1068 if (CurPPLexer->ParsingFilename)
1069 LexUnexpandedToken(FilenameTok);
1070 else
1071 CurPPLexer->LexIncludeFilename(FilenameTok);
1072 } else {
1073 Lex(FilenameTok);
1074 }
1075
1076 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1077 // case, glue the tokens together into an angle_string_literal token.
1078 SmallString<128> FilenameBuffer;
1079 if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
1080 bool StartOfLine = FilenameTok.isAtStartOfLine();
1081 bool LeadingSpace = FilenameTok.hasLeadingSpace();
1082 bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
1083
1084 SourceLocation Start = FilenameTok.getLocation();
1085 SourceLocation End;
1086 FilenameBuffer.push_back('<');
1087
1088 // Consume tokens until we find a '>'.
1089 // FIXME: A header-name could be formed starting or ending with an
1090 // alternative token. It's not clear whether that's ill-formed in all
1091 // cases.
1092 while (FilenameTok.isNot(tok::greater)) {
1093 Lex(FilenameTok);
1094 if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
1095 Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
1096 Diag(Start, diag::note_matching) << tok::less;
1097 return true;
1098 }
1099
1100 End = FilenameTok.getLocation();
1101
1102 // FIXME: Provide code completion for #includes.
1103 if (FilenameTok.is(tok::code_completion)) {
1105 Lex(FilenameTok);
1106 continue;
1107 }
1108
1109 // Append the spelling of this token to the buffer. If there was a space
1110 // before it, add it now.
1111 if (FilenameTok.hasLeadingSpace())
1112 FilenameBuffer.push_back(' ');
1113
1114 // Get the spelling of the token, directly into FilenameBuffer if
1115 // possible.
1116 size_t PreAppendSize = FilenameBuffer.size();
1117 FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
1118
1119 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1120 unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
1121
1122 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1123 if (BufPtr != &FilenameBuffer[PreAppendSize])
1124 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1125
1126 // Resize FilenameBuffer to the correct size.
1127 if (FilenameTok.getLength() != ActualLen)
1128 FilenameBuffer.resize(PreAppendSize + ActualLen);
1129 }
1130
1131 FilenameTok.startToken();
1132 FilenameTok.setKind(tok::header_name);
1133 FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
1134 FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
1135 FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
1136 CreateString(FilenameBuffer, FilenameTok, Start, End);
1137 } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
1138 // Convert a string-literal token of the form " h-char-sequence "
1139 // (produced by macro expansion) into a header-name token.
1140 //
1141 // The rules for header-names don't quite match the rules for
1142 // string-literals, but all the places where they differ result in
1143 // undefined behavior, so we can and do treat them the same.
1144 //
1145 // A string-literal with a prefix or suffix is not translated into a
1146 // header-name. This could theoretically be observable via the C++20
1147 // context-sensitive header-name formation rules.
1148 StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
1149 if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
1150 FilenameTok.setKind(tok::header_name);
1151 }
1152
1153 return false;
1154}
1155
1156std::optional<Token> Preprocessor::peekNextPPToken() const {
1157 // Do some quick tests for rejection cases.
1158 std::optional<Token> Val;
1159 if (CurLexer)
1160 Val = CurLexer->peekNextPPToken();
1161 else
1162 Val = CurTokenLexer->peekNextPPToken();
1163
1164 if (!Val) {
1165 // We have run off the end. If it's a source file we don't
1166 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
1167 // macro stack.
1168 if (CurPPLexer)
1169 return std::nullopt;
1170 for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
1171 if (Entry.TheLexer)
1172 Val = Entry.TheLexer->peekNextPPToken();
1173 else
1174 Val = Entry.TheTokenLexer->peekNextPPToken();
1175
1176 if (Val)
1177 break;
1178
1179 // Ran off the end of a source file?
1180 if (Entry.ThePPLexer)
1181 return std::nullopt;
1182 }
1183 }
1184
1185 // Okay, we found the token and return. Otherwise we found the end of the
1186 // translation unit.
1187 return Val;
1188}
1189
1190// We represent the primary and partition names as 'Paths' which are sections
1191// of the hierarchical access path for a clang module. However for C++20
1192// the periods in a name are just another character, and we will need to
1193// flatten them into a string.
1195 std::string Name;
1196 if (Path.empty())
1197 return Name;
1198
1199 for (auto &Piece : Path) {
1200 assert(Piece.getIdentifierInfo() && Piece.getLoc().isValid());
1201 if (!Name.empty())
1202 Name += ".";
1203 Name += Piece.getIdentifierInfo()->getName();
1204 }
1205 return Name;
1206}
1207
1209 assert(!Path.empty() && "expect at least one identifier in a module name");
1210 void *Mem = PP.getPreprocessorAllocator().Allocate(
1211 totalSizeToAlloc<IdentifierLoc>(Path.size()), alignof(ModuleNameLoc));
1212 return new (Mem) ModuleNameLoc(Path);
1213}
1214
1216 SmallVectorImpl<Token> &Suffix,
1218 bool AllowMacroExpansion,
1219 bool IsPartition) {
1220 auto ConsumeToken = [&]() {
1221 if (AllowMacroExpansion)
1222 Lex(Tok);
1223 else
1225 Suffix.push_back(Tok);
1226 };
1227
1228 while (true) {
1229 if (Tok.isNot(tok::identifier)) {
1230 if (Tok.is(tok::code_completion)) {
1231 CurLexer->cutOffLexing();
1232 CodeComplete->CodeCompleteModuleImport(UseLoc, Path);
1233 return true;
1234 }
1235
1236 Diag(Tok, diag::err_pp_module_expected_ident) << Path.empty();
1237 return true;
1238 }
1239
1240 // [cpp.pre]/p2:
1241 // No identifier in the pp-module-name or pp-module-partition shall
1242 // currently be defined as an object-like macro.
1243 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo());
1244 MI && MI->isObjectLike() && getLangOpts().CPlusPlus20 &&
1245 !AllowMacroExpansion) {
1246 Diag(Tok, diag::err_pp_module_name_is_macro)
1247 << IsPartition << Tok.getIdentifierInfo();
1248 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1249 << Tok.getIdentifierInfo();
1250 }
1251
1252 // Record this part of the module path.
1253 Path.emplace_back(Tok.getLocation(), Tok.getIdentifierInfo());
1254 ConsumeToken();
1255
1256 if (Tok.isNot(tok::period))
1257 return false;
1258
1259 ConsumeToken();
1260 }
1261}
1262
1263bool Preprocessor::HandleModuleName(StringRef DirType, SourceLocation UseLoc,
1264 Token &Tok,
1266 SmallVectorImpl<Token> &DirToks,
1267 bool AllowMacroExpansion,
1268 bool IsPartition) {
1269 bool LeadingSpace = Tok.hasLeadingSpace();
1270 unsigned NumToksInDirective = DirToks.size();
1271 if (LexModuleNameContinue(Tok, UseLoc, DirToks, Path, AllowMacroExpansion,
1272 IsPartition)) {
1273 if (Tok.isNot(tok::eod))
1274 CheckEndOfDirective(DirType,
1275 /*EnableMacros=*/false, &DirToks);
1277 return true;
1278 }
1279
1280 // Clean the module-name tokens and replace these tokens with
1281 // annot_module_name.
1282 DirToks.resize(NumToksInDirective);
1283 ModuleNameLoc *NameLoc = ModuleNameLoc::Create(*this, Path);
1284 DirToks.emplace_back();
1285 DirToks.back().setKind(tok::annot_module_name);
1286 DirToks.back().setAnnotationRange(NameLoc->getRange());
1287 DirToks.back().setAnnotationValue(static_cast<void *>(NameLoc));
1288 DirToks.back().setFlagValue(Token::LeadingSpace, LeadingSpace);
1289 DirToks.push_back(Tok);
1290 return false;
1291}
1292
1293/// [cpp.pre]/p2:
1294/// A preprocessing directive consists of a sequence of preprocessing tokens
1295/// that satisfies the following constraints: At the start of translation phase
1296/// 4, the first preprocessing token in the sequence, referred to as a
1297/// directive-introducing token, begins with the first character in the source
1298/// file (optionally after whitespace containing no new-line characters) or
1299/// follows whitespace containing at least one new-line character, and is:
1300/// - a # preprocessing token, or
1301/// - an import preprocessing token immediately followed on the same logical
1302/// source line by a header-name, <, identifier, or : preprocessing token, or
1303/// - a module preprocessing token immediately followed on the same logical
1304/// source line by an identifier, :, or ; preprocessing token, or
1305/// - an export preprocessing token immediately followed on the same logical
1306/// source line by one of the two preceding forms.
1307///
1308///
1309/// At the start of phase 4 an import or module token is treated as starting a
1310/// directive and are converted to their respective keywords iff:
1311/// - After skipping horizontal whitespace are
1312/// - at the start of a logical line, or
1313/// - preceded by an 'export' at the start of the logical line.
1314/// - Are followed by an identifier pp token (before macro expansion), or
1315/// - <, ", or : (but not ::) pp tokens for 'import', or
1316/// - ; for 'module'
1317/// Otherwise the token is treated as an identifier.
1319 if (!getLangOpts().CPlusPlusModules || !Result.isModuleContextualKeyword())
1320 return false;
1321
1322 if (Result.is(tok::kw_export)) {
1323 LastExportKeyword = Result;
1324 return false;
1325 }
1326
1327 /// Trait 'module' and 'import' as a identifier when the main file is a
1328 /// preprocessed module file. We only allow '__preprocessed_module' and
1329 /// '__preprocessed_import' in this context.
1330 IdentifierInfo *II = Result.getIdentifierInfo();
1332 (II->isStr(tok::getKeywordSpelling(tok::kw_import)) ||
1333 II->isStr(tok::getKeywordSpelling(tok::kw_module))))
1334 return false;
1335
1336 if (LastExportKeyword.is(tok::kw_export)) {
1337 // The export keyword was not at the start of line, it's not a
1338 // directive-introducing token.
1339 if (!LastExportKeyword.isAtPhysicalStartOfLine())
1340 return false;
1341 // [cpp.pre]/1.4
1342 // export // not a preprocessing directive
1343 // import foo; // preprocessing directive (ill-formed at phase7)
1344 if (Result.isAtPhysicalStartOfLine())
1345 return false;
1346 } else if (!Result.isAtPhysicalStartOfLine())
1347 return false;
1348
1349 llvm::SaveAndRestore<bool> SavedParsingPreprocessorDirective(
1350 CurPPLexer->ParsingPreprocessorDirective, true);
1351
1352 // The next token may be an angled string literal after import keyword.
1353 llvm::SaveAndRestore<bool> SavedParsingFilemame(
1354 CurPPLexer->ParsingFilename,
1355 Result.getIdentifierInfo()->isImportKeyword());
1356
1357 std::optional<Token> NextTok = peekNextPPToken();
1358 if (!NextTok)
1359 return false;
1360
1361 if (NextTok->is(tok::raw_identifier))
1362 LookUpIdentifierInfo(*NextTok);
1363
1364 if (Result.getIdentifierInfo()->isImportKeyword()) {
1365 if (NextTok->isOneOf(tok::identifier, tok::less, tok::colon,
1366 tok::header_name)) {
1367 Result.setKind(tok::kw_import);
1368 ModuleImportLoc = Result.getLocation();
1369 return true;
1370 }
1371 }
1372
1373 if (Result.getIdentifierInfo()->isModuleKeyword() &&
1374 NextTok->isOneOf(tok::identifier, tok::colon, tok::semi)) {
1375 Result.setKind(tok::kw_module);
1376 ModuleDeclLoc = Result.getLocation();
1377 return true;
1378 }
1379
1380 // Ok, it's an identifier.
1381 return false;
1382}
1383
1385 SmallVectorImpl<Token> &Toks, bool StopUntilEOD) {
1388 return false;
1389}
1390
1391/// Collect the tokens of a C++20 pp-import-suffix.
1393 bool StopUntilEOD) {
1394 while (true) {
1395 Toks.emplace_back();
1396 Lex(Toks.back());
1397
1398 switch (Toks.back().getKind()) {
1399 case tok::semi:
1400 if (!StopUntilEOD)
1401 return;
1402 [[fallthrough]];
1403 case tok::eod:
1404 case tok::eof:
1405 return;
1406 default:
1407 break;
1408 }
1409 }
1410}
1411
1412// Allocate a holding buffer for a sequence of tokens and introduce it into
1413// the token stream.
1415 if (Toks.empty())
1416 return;
1417 auto ToksCopy = std::make_unique<Token[]>(Toks.size());
1418 std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
1419 EnterTokenStream(std::move(ToksCopy), Toks.size(),
1420 /*DisableMacroExpansion*/ false, /*IsReinject*/ false);
1421 assert(CurTokenLexer && "Must have a TokenLexer");
1422 CurTokenLexer->setLexingCXXModuleDirective();
1423}
1424
1426 bool IncludeExports) {
1427 CurSubmoduleState->VisibleModules.setVisible(
1428 M, Loc, IncludeExports, [](Module *) {},
1429 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
1430 // FIXME: Include the path in the diagnostic.
1431 // FIXME: Include the import location for the conflicting module.
1432 Diag(ModuleImportLoc, diag::warn_module_conflict)
1433 << Path[0]->getFullModuleName()
1434 << Conflict->getFullModuleName()
1435 << Message;
1436 });
1437
1438 // Add this module to the imports list of the currently-built submodule.
1439 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
1440 BuildingSubmoduleStack.back().M->Imports.push_back(M);
1441}
1442
1444 const char *DiagnosticTag,
1445 bool AllowMacroExpansion) {
1446 // We need at least one string literal.
1447 if (Result.isNot(tok::string_literal)) {
1448 Diag(Result, diag::err_expected_string_literal)
1449 << /*Source='in...'*/0 << DiagnosticTag;
1450 return false;
1451 }
1452
1453 // Lex string literal tokens, optionally with macro expansion.
1454 SmallVector<Token, 4> StrToks;
1455 do {
1456 StrToks.push_back(Result);
1457
1458 if (Result.hasUDSuffix())
1459 Diag(Result, diag::err_invalid_string_udl);
1460
1461 if (AllowMacroExpansion)
1462 Lex(Result);
1463 else
1465 } while (Result.is(tok::string_literal));
1466
1467 // Concatenate and parse the strings.
1468 StringLiteralParser Literal(StrToks, *this);
1469 assert(Literal.isOrdinary() && "Didn't allow wide strings in");
1470
1471 if (Literal.hadError)
1472 return false;
1473
1474 if (Literal.Pascal) {
1475 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1476 << /*Source='in...'*/0 << DiagnosticTag;
1477 return false;
1478 }
1479
1480 String = std::string(Literal.GetString());
1481 return true;
1482}
1483
1485 assert(Tok.is(tok::numeric_constant));
1486 SmallString<8> IntegerBuffer;
1487 bool NumberInvalid = false;
1488 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1489 if (NumberInvalid)
1490 return false;
1491 NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
1493 getDiagnostics());
1494 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1495 return false;
1496 llvm::APInt APVal(64, 0);
1497 if (Literal.GetIntegerValue(APVal))
1498 return false;
1499 Lex(Tok);
1500 Value = APVal.getLimitedValue();
1501 return true;
1502}
1503
1505 assert(Handler && "NULL comment handler");
1506 assert(!llvm::is_contained(CommentHandlers, Handler) &&
1507 "Comment handler already registered");
1508 CommentHandlers.push_back(Handler);
1509}
1510
1512 std::vector<CommentHandler *>::iterator Pos =
1513 llvm::find(CommentHandlers, Handler);
1514 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
1515 CommentHandlers.erase(Pos);
1516}
1517
1519 bool AnyPendingTokens = false;
1520 for (CommentHandler *H : CommentHandlers) {
1521 if (H->HandleComment(*this, Comment))
1522 AnyPendingTokens = true;
1523 }
1524 if (!AnyPendingTokens || getCommentRetentionState())
1525 return false;
1526 Lex(result);
1527 return true;
1528}
1529
1530void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
1531 const MacroAnnotations &A =
1533 assert(A.DeprecationInfo &&
1534 "Macro deprecation warning without recorded annotation!");
1535 const MacroAnnotationInfo &Info = *A.DeprecationInfo;
1536 if (Info.Message.empty())
1537 Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1538 << Identifier.getIdentifierInfo() << 0;
1539 else
1540 Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1541 << Identifier.getIdentifierInfo() << 1 << Info.Message;
1542 Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
1543}
1544
1545void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
1546 const MacroAnnotations &A =
1548 assert(A.RestrictExpansionInfo &&
1549 "Macro restricted expansion warning without recorded annotation!");
1550 const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
1551 if (Info.Message.empty())
1552 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1553 << Identifier.getIdentifierInfo() << 0;
1554 else
1555 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1556 << Identifier.getIdentifierInfo() << 1 << Info.Message;
1557 Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
1558}
1559
1560void Preprocessor::emitRestrictInfNaNWarning(const Token &Identifier,
1561 unsigned DiagSelection) const {
1562 Diag(Identifier, diag::warn_fp_nan_inf_when_disabled) << DiagSelection << 1;
1563}
1564
1565void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
1566 bool IsUndef) const {
1567 const MacroAnnotations &A =
1569 assert(A.FinalAnnotationLoc &&
1570 "Final macro warning without recorded annotation!");
1571
1572 Diag(Identifier, diag::warn_pragma_final_macro)
1573 << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
1574 Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
1575}
1576
1578 const SourceLocation &Loc) const {
1579 // The lambda that tests if a `Loc` is in an opt-out region given one opt-out
1580 // region map:
1581 auto TestInMap = [&SourceMgr](const SafeBufferOptOutRegionsTy &Map,
1582 const SourceLocation &Loc) -> bool {
1583 // Try to find a region in `SafeBufferOptOutMap` where `Loc` is in:
1584 auto FirstRegionEndingAfterLoc = llvm::partition_point(
1585 Map, [&SourceMgr,
1586 &Loc](const std::pair<SourceLocation, SourceLocation> &Region) {
1587 return SourceMgr.isBeforeInTranslationUnit(Region.second, Loc);
1588 });
1589
1590 if (FirstRegionEndingAfterLoc != Map.end()) {
1591 // To test if the start location of the found region precedes `Loc`:
1592 return SourceMgr.isBeforeInTranslationUnit(
1593 FirstRegionEndingAfterLoc->first, Loc);
1594 }
1595 // If we do not find a region whose end location passes `Loc`, we want to
1596 // check if the current region is still open:
1597 if (!Map.empty() && Map.back().first == Map.back().second)
1598 return SourceMgr.isBeforeInTranslationUnit(Map.back().first, Loc);
1599 return false;
1600 };
1601
1602 // What the following does:
1603 //
1604 // If `Loc` belongs to the local TU, we just look up `SafeBufferOptOutMap`.
1605 // Otherwise, `Loc` is from a loaded AST. We look up the
1606 // `LoadedSafeBufferOptOutMap` first to get the opt-out region map of the
1607 // loaded AST where `Loc` is at. Then we find if `Loc` is in an opt-out
1608 // region w.r.t. the region map. If the region map is absent, it means there
1609 // is no opt-out pragma in that loaded AST.
1610 //
1611 // Opt-out pragmas in the local TU or a loaded AST is not visible to another
1612 // one of them. That means if you put the pragmas around a `#include
1613 // "module.h"`, where module.h is a module, it is not actually suppressing
1614 // warnings in module.h. This is fine because warnings in module.h will be
1615 // reported when module.h is compiled in isolation and nothing in module.h
1616 // will be analyzed ever again. So you will not see warnings from the file
1617 // that imports module.h anyway. And you can't even do the same thing for PCHs
1618 // because they can only be included from the command line.
1619
1620 if (SourceMgr.isLocalSourceLocation(Loc))
1621 return TestInMap(SafeBufferOptOutMap, Loc);
1622
1623 const SafeBufferOptOutRegionsTy *LoadedRegions =
1624 LoadedSafeBufferOptOutMap.lookupLoadedOptOutMap(Loc, SourceMgr);
1625
1626 if (LoadedRegions)
1627 return TestInMap(*LoadedRegions, Loc);
1628 return false;
1629}
1630
1632 bool isEnter, const SourceLocation &Loc) {
1633 if (isEnter) {
1635 return true; // invalid enter action
1636 InSafeBufferOptOutRegion = true;
1637 CurrentSafeBufferOptOutStart = Loc;
1638
1639 // To set the start location of a new region:
1640
1641 if (!SafeBufferOptOutMap.empty()) {
1642 [[maybe_unused]] auto *PrevRegion = &SafeBufferOptOutMap.back();
1643 assert(PrevRegion->first != PrevRegion->second &&
1644 "Shall not begin a safe buffer opt-out region before closing the "
1645 "previous one.");
1646 }
1647 // If the start location equals to the end location, we call the region a
1648 // open region or a unclosed region (i.e., end location has not been set
1649 // yet).
1650 SafeBufferOptOutMap.emplace_back(Loc, Loc);
1651 } else {
1653 return true; // invalid enter action
1654 InSafeBufferOptOutRegion = false;
1655
1656 // To set the end location of the current open region:
1657
1658 assert(!SafeBufferOptOutMap.empty() &&
1659 "Misordered safe buffer opt-out regions");
1660 auto *CurrRegion = &SafeBufferOptOutMap.back();
1661 assert(CurrRegion->first == CurrRegion->second &&
1662 "Set end location to a closed safe buffer opt-out region");
1663 CurrRegion->second = Loc;
1664 }
1665 return false;
1666}
1667
1669 return InSafeBufferOptOutRegion;
1670}
1672 StartLoc = CurrentSafeBufferOptOutStart;
1673 return InSafeBufferOptOutRegion;
1674}
1675
1678 assert(!InSafeBufferOptOutRegion &&
1679 "Attempt to serialize safe buffer opt-out regions before file being "
1680 "completely preprocessed");
1681
1683
1684 for (const auto &[begin, end] : SafeBufferOptOutMap) {
1685 SrcSeq.push_back(begin);
1686 SrcSeq.push_back(end);
1687 }
1688 // Only `SafeBufferOptOutMap` gets serialized. No need to serialize
1689 // `LoadedSafeBufferOptOutMap` because if this TU loads a pch/module, every
1690 // pch/module in the pch-chain/module-DAG will be loaded one by one in order.
1691 // It means that for each loading pch/module m, it just needs to load m's own
1692 // `SafeBufferOptOutMap`.
1693 return SrcSeq;
1694}
1695
1697 const SmallVectorImpl<SourceLocation> &SourceLocations) {
1698 if (SourceLocations.size() == 0)
1699 return false;
1700
1701 assert(SourceLocations.size() % 2 == 0 &&
1702 "ill-formed SourceLocation sequence");
1703
1704 auto It = SourceLocations.begin();
1705 SafeBufferOptOutRegionsTy &Regions =
1706 LoadedSafeBufferOptOutMap.findAndConsLoadedOptOutMap(*It, SourceMgr);
1707
1708 do {
1709 SourceLocation Begin = *It++;
1710 SourceLocation End = *It++;
1711
1712 Regions.emplace_back(Begin, End);
1713 } while (It != SourceLocations.end());
1714 return true;
1715}
1716
1717ModuleLoader::~ModuleLoader() = default;
1718
1720
1722
1724
1726 if (Record)
1727 return;
1728
1729 Record = new PreprocessingRecord(getSourceManager());
1730 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
1731}
1732
1734 auto IsPreserved = [&](PPCallbacks *C) {
1735 return C == Record || C == DirTracer;
1736 };
1738 PPCallbacks::releaseIfPreserved(Callbacks, IsPreserved, Released);
1739 Callbacks.reset();
1740 for (auto *P : Released)
1741 addPPCallbacks(std::unique_ptr<PPCallbacks>(P));
1742}
1743
1744const char *Preprocessor::getCheckPoint(FileID FID, const char *Start) const {
1745 if (auto It = CheckPoints.find(FID); It != CheckPoints.end()) {
1746 const SmallVector<const char *> &FileCheckPoints = It->second;
1747 const char *Last = nullptr;
1748 // FIXME: Do better than a linear search.
1749 for (const char *P : FileCheckPoints) {
1750 if (P > Start)
1751 break;
1752 Last = P;
1753 }
1754 return Last;
1755 }
1756
1757 return nullptr;
1758}
1759
1761 return DirTracer && DirTracer->hasSeenNoTrivialPPDirective();
1762}
1763
1765 return SeenNoTrivialPPDirective;
1766}
1767
1768void NoTrivialPPDirectiveTracer::setSeenNoTrivialPPDirective() {
1769 if (InMainFile && !SeenNoTrivialPPDirective)
1770 SeenNoTrivialPPDirective = true;
1771}
1772
1774 FileID FID, LexedFileChangeReason Reason,
1775 SrcMgr::CharacteristicKind FileType, FileID PrevFID, SourceLocation Loc) {
1776 InMainFile = (FID == PP.getSourceManager().getMainFileID());
1777}
1778
1780 const MacroDefinition &MD,
1781 SourceRange Range,
1782 const MacroArgs *Args) {
1783 // FIXME: Does only enable builtin macro expansion make sense?
1784 if (!MD.getMacroInfo()->isBuiltinMacro())
1785 setSeenNoTrivialPPDirective();
1786}
Defines enum values for all the target-independent builtin functions.
This is the interface for scanning header and source files to get the minimum necessary preprocessor ...
Defines the clang::FileManager interface and associated types.
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
Token Tok
The Token.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
#define SM(sm)
Defines the PreprocessorLexer interface.
static bool MacroDefinitionEquals(const MacroInfo *MI, ArrayRef< TokenValue > Tokens)
Compares macro tokens with a specified token value sequence.
static constexpr unsigned CheckPointStepSize
Minimum distance between two check points, in tokens.
Defines the clang::Preprocessor interface.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Abstract base class that describes a handler that will receive source ranges for each of the comments...
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
virtual void updateOutOfDateIdentifier(const IdentifierInfo &II)=0
Update an out-of-date identifier.
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:302
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
Provides lookups to, and iteration over, IdentiferInfo objects.
One of these records is kept for each identifier that is lexed.
bool IsKeywordInCPlusPlus() const
Return true if this identifier would be a keyword in C++ mode.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
bool isPoisoned() const
Return true if this token has been poisoned.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setIsFutureCompatKeyword(bool Val)
StringRef getName() const
Return the actual identifier string.
bool isFutureCompatKeyword() const
is/setIsFutureCompatKeyword - Initialize information about whether or not this language token is a ke...
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition MacroArgs.h:30
A description of the current definition of a macro.
Definition MacroInfo.h:595
MacroInfo * getMacroInfo() const
Get the MacroInfo that should be used for this definition.
Definition MacroInfo.h:611
SourceLocation getLocation() const
Definition MacroInfo.h:488
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
const_tokens_iterator tokens_begin() const
Definition MacroInfo.h:244
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition MacroInfo.h:235
const Token & getReplacementToken(unsigned Tok) const
Definition MacroInfo.h:237
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition MacroInfo.h:217
bool isObjectLike() const
Definition MacroInfo.h:202
Abstract interface for a module loader.
virtual ~ModuleLoader()
static std::string getFlatNameFromPath(ModuleIdPath Path)
Represents a macro directive exported by a module.
Definition MacroInfo.h:514
static ModuleNameLoc * Create(Preprocessor &PP, ModuleIdPath Path)
SourceRange getRange() const
Describes a module or submodule.
Definition Module.h:340
void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) override
Called by Preprocessor::HandleMacroExpandedIdentifier when a macro invocation is found.
void LexedFileChanged(FileID FID, LexedFileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID, SourceLocation Loc) override
Callback invoked whenever the Lexer moves to a different file for lexing.
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
static void releaseIfPreserved(std::unique_ptr< PPCallbacks > &CB, llvm::function_ref< bool(PPCallbacks *)> Pred, SmallVectorImpl< PPCallbacks * > &Released)
Walk the subtree rooted at CB (recursing into descendants first), then check CB itself.
PragmaNamespace - This PragmaHandler subdivides the namespace of pragmas, allowing hierarchical pragm...
Definition Pragma.h:96
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
void setConditionalLevels(ArrayRef< PPConditionalInfo > CL)
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::string PCHThroughHeader
If non-empty, the filename used in an include directive in the primary source file (or command-line p...
bool GeneratePreamble
True indicates that a preamble is being generated.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
bool markIncluded(FileEntryRef File)
Mark the file as included.
void FinalizeForModelFile()
Cleanup after model file parsing.
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
bool creatingPCHWithThroughHeader()
True if creating a PCH with a through header.
void DumpToken(const Token &Tok, bool DumpFlags=false) const
Print the token to stderr, used for debugging.
void EnterModuleSuffixTokenStream(ArrayRef< Token > Toks)
void InitializeForModelFile()
Initialize the preprocessor to parse a model file.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
void setCodeCompletionTokenRange(const SourceLocation Start, const SourceLocation End)
Set the code completion token range for detecting replacement range later on.
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
bool isSafeBufferOptOut(const SourceManager &SourceMgr, const SourceLocation &Loc) const
const char * getCheckPoint(FileID FID, const char *Start) const
Returns a pointer into the given file's buffer that's guaranteed to be between tokens.
IdentifierInfo * LookUpIdentifierInfo(Token &Identifier) const
Given a tok::raw_identifier token, look up the identifier information for the token and install it in...
friend class MacroArgs
void DumpMacro(const MacroInfo &MI) const
llvm::iterator_range< macro_iterator > macros(bool IncludeExternalMacros=true) const
void setCodeCompletionReached()
Note that we hit the code-completion point.
bool SetCodeCompletionPoint(FileEntryRef File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
void Lex(Token &Result)
Lex the next token for this preprocessor.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
bool EnterSourceFile(FileID FID, ConstSearchDirIterator Dir, SourceLocation Loc, bool IsFirstIncludeOfFile=true)
Add a source file to the top of the include stack and start lexing tokens from it instead of the curr...
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
void removeCommentHandler(CommentHandler *Handler)
Remove the specified comment handler.
void HandlePoisonedIdentifier(Token &Identifier)
Display reason for poisoned identifier.
bool HandleIdentifier(Token &Identifier)
Callback invoked when the lexer reads an identifier and has filled in the tokens IdentifierInfo membe...
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
bool enterOrExitSafeBufferOptOutRegion(bool isEnter, const SourceLocation &Loc)
Alter the state of whether this PP currently is in a "-Wunsafe-buffer-usage" opt-out region.
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc.
const MacroAnnotations & getMacroAnnotations(const IdentifierInfo *II) const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
bool isBacktrackEnabled() const
True if EnableBacktrackAtThisPos() was called and caching of tokens is on.
MacroDefinition getMacroDefinition(const IdentifierInfo *II)
bool isPreprocessedModuleFile() const
Whether the main file is preprocessed module file.
void SetPoisonReason(IdentifierInfo *II, unsigned DiagID)
Specifies the reason for poisoning an identifier.
SourceLocation CheckEndOfDirective(StringRef DirType, bool EnableMacros=false, SmallVectorImpl< Token > *ExtraToks=nullptr)
Ensure that the next token is a tok::eod token.
bool getCommentRetentionState() const
Module * getCurrentModuleImplementation()
Retrieves the module whose implementation we're current compiling, if any.
void createPreprocessingRecord()
Create a new preprocessing record, which will keep track of all macro expansions, macro definitions,...
SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length)
Split the first Length characters out of the token starting at TokLoc and return a location pointing ...
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
void makeModuleVisible(Module *M, SourceLocation Loc, bool IncludeExports=true)
bool hadModuleLoaderFatalFailure() const
void setCurrentFPEvalMethod(SourceLocation PragmaLoc, LangOptions::FPEvalMethodKind Val)
bool HandleModuleContextualKeyword(Token &Result)
Callback invoked when the lexer sees one of export, import or module token at the start of a line.
const TargetInfo & getTargetInfo() const
bool LexHeaderName(Token &Result, bool AllowMacroExpansion=true)
Lex a token, forming a header-name token if possible.
bool isPCHThroughHeader(const FileEntry *FE)
Returns true if the FileEntry is the PCH through header.
void DumpLocation(SourceLocation Loc) const
bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value)
Parses a simple integer literal to get its numeric value.
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
bool creatingPCHWithPragmaHdrStop()
True if creating a PCH with a pragma hdrstop.
void Initialize(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize the preprocessor using information about the target.
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
llvm::BumpPtrAllocator & getPreprocessorAllocator()
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool HandleComment(Token &result, SourceRange Comment)
HeaderSearch & getHeaderSearchInfo() const
bool setDeserializedSafeBufferOptOutMap(const SmallVectorImpl< SourceLocation > &SrcLocSeqs)
ExternalPreprocessorSource * getExternalSource() const
void HandleDirective(Token &Result)
Callback invoked when the lexer sees a # token at the start of a line.
SmallVector< SourceLocation, 64 > serializeSafeBufferOptOutMap() const
void recomputeCurLexerKind()
Recompute the current lexer kind based on the CurLexer/ CurTokenLexer pointers.
OptionalFileEntryRef LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, ConstSearchDirIterator FromDir, const FileEntry *FromFile, ConstSearchDirIterator *CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool OpenFile=true, bool CacheFailures=true)
Given a "foo" or <foo> reference, look up the indicated file.
IdentifierTable & getIdentifierTable()
bool LexModuleNameContinue(Token &Tok, SourceLocation UseLoc, SmallVectorImpl< Token > &Suffix, SmallVectorImpl< IdentifierLoc > &Path, bool AllowMacroExpansion, bool IsPartition)
const LangOptions & getLangOpts() const
void setTUFPEvalMethod(LangOptions::FPEvalMethodKind Val)
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled)
Hook used by the lexer to invoke the "included file" code completion point.
llvm::DenseMap< FileID, SafeBufferOptOutRegionsTy > LoadedRegions
void PoisonSEHIdentifiers(bool Poison=true)
size_t getTotalMemory() const
void LexTokensUntilEOF(std::vector< Token > *Tokens=nullptr)
Lex all tokens for this preprocessor until (and excluding) end of file.
bool isNextPPTokenOneOf(Ts... Ks) const
isNextPPTokenOneOf - Check whether the next pp-token is one of the specificed token kind.
bool usingPCHWithPragmaHdrStop()
True if using a PCH with a pragma hdrstop.
void CodeCompleteNaturalLanguage()
Hook used by the lexer to invoke the "natural language" code completion point.
void EndSourceFile()
Inform the preprocessor callbacks that processing is complete.
void CollectPPImportSuffix(SmallVectorImpl< Token > &Toks, bool StopUntilEOD=false)
Collect the tokens of a C++20 pp-import-suffix.
DiagnosticsEngine & getDiagnostics() const
bool hasSeenNoTrivialPPDirective() const
Whether we've seen pp-directives which may have changed the preprocessing state.
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter)
Set the code completion token for filtering purposes.
bool HandleModuleName(StringRef DirType, SourceLocation UseLoc, Token &Tok, SmallVectorImpl< IdentifierLoc > &Path, SmallVectorImpl< Token > &DirToks, bool AllowMacroExpansion, bool IsPartition)
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
void SkipTokensWhileUsingPCH()
Skip tokens until after the include of the through header or until after a pragma hdrstop.
bool usingPCHWithThroughHeader()
True if using a PCH with a through header.
bool CollectPPImportSuffixAndEnterStream(SmallVectorImpl< Token > &Toks, bool StopUntilEOD=false)
Preprocessor(const PreprocessorOptions &PPOpts, DiagnosticsEngine &diags, const LangOptions &LangOpts, SourceManager &SM, HeaderSearch &Headers, ModuleLoader &TheModuleLoader, IdentifierInfoLookup *IILookup=nullptr, bool OwnsHeaderSearch=false, TranslationUnitKind TUKind=TU_Complete)
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
unsigned getLine() const
Return the presumed line number of this location.
bool isInvalid() const
Return true if this object is invalid or uninitialized.
ScratchBuffer - This class exposes a simple interface for the dynamic construction of tokens.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
void print(raw_ostream &OS, const SourceManager &SM) const
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
std::optional< StringRef > getBufferDataOrNone(FileID FID) const
Return a StringRef to the source buffer data for the specified FileID, returning std::nullopt if inva...
A trivial tuple used to represent a source range.
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
Exposes information about the current target.
Definition TargetInfo.h:227
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:197
bool hasUCN() const
Returns true if this token contains a universal character name.
Definition Token.h:324
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
unsigned getLength() const
Definition Token.h:145
bool isExpandDisabled() const
Return true if this identifier token should never be expanded in the future, due to C99 6....
Definition Token.h:298
void setKind(tok::TokenKind K)
Definition Token.h:100
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition Token.h:286
bool isOneOf(Ts... Ks) const
Definition Token.h:105
@ DisableExpand
Definition Token.h:79
@ HasSeenNoTrivialPPDirective
Definition Token.h:92
@ IsReinjected
Definition Token.h:89
@ LeadingEmptyMacro
Definition Token.h:81
@ LeadingSpace
Definition Token.h:77
@ StartOfLine
Definition Token.h:75
bool isModuleContextualKeyword(bool AllowExport=true) const
Return true if we have a C++20 modules contextual keyword(export, importor module).
Definition Lexer.cpp:76
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition Token.h:294
bool hasLeadingEmptyMacro() const
Return true if this token has an empty macro before it.
Definition Token.h:317
bool isNot(tok::TokenKind K) const
Definition Token.h:111
void startToken()
Reset all flags to cleared.
Definition Token.h:187
bool needsCleaning() const
Return true if this token has trigraphs or escaped newlines in it.
Definition Token.h:313
void setIdentifierInfo(IdentifierInfo *II)
Definition Token.h:206
void setFlagValue(TokenFlags Flag, bool Val)
Set a flag to either true or false.
Definition Token.h:277
StringRef getRawIdentifier() const
getRawIdentifier - For a raw identifier token (i.e., an identifier lexed in raw mode),...
Definition Token.h:223
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition Token.h:254
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
const char * getTokenName(TokenKind Kind) LLVM_READNONE
Determines the name of a token as used within the front end.
const char * getKeywordSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple keyword and contextual keyword tokens like 'int' and 'dynamic_cast'...
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
@ CPlusPlus20
llvm::Registry< PragmaHandler > PragmaHandlerRegistry
Registry of pragma handlers added by plugins.
void expandUCNs(SmallVectorImpl< char > &Buf, StringRef Input)
Copy characters from Input to Buf, expanding any UCNs.
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
std::pair< FileID, unsigned > FileIDAndOffset
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isPreprocessedModuleFile(StringRef Source)
Scan an input source buffer, and check whether the input source is a preprocessed output.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
#define true
Definition stdbool.h:25