14#ifndef LLVM_CLANG_LEX_PREPROCESSOR_H
15#define LLVM_CLANG_LEX_PREPROCESSOR_H
36#include "llvm/ADT/APSInt.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/FoldingSet.h"
40#include "llvm/ADT/FunctionExtras.h"
41#include "llvm/ADT/PointerUnion.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/SmallPtrSet.h"
44#include "llvm/ADT/SmallVector.h"
45#include "llvm/ADT/StringRef.h"
46#include "llvm/ADT/TinyPtrVector.h"
47#include "llvm/ADT/iterator_range.h"
48#include "llvm/Support/Allocator.h"
49#include "llvm/Support/Casting.h"
50#include "llvm/Support/Registry.h"
63template<
unsigned InternalLen>
class SmallString;
69class CodeCompletionHandler;
72class EmptylineHandler;
73class ExternalPreprocessorSource;
80class PreprocessingRecord;
81class PreprocessorLexer;
82class PreprocessorOptions;
85class NoTrivialPPDirectiveTracer;
99 assert(Kind != tok::raw_identifier &&
"Raw identifiers are not supported.");
100 assert(Kind != tok::identifier &&
101 "Identifiers should be created by TokenValue(IdentifierInfo *)");
109 return Tok.
getKind() == Kind &&
149 llvm::unique_function<void(
const clang::Token &)> OnToken;
163 std::unique_ptr<ScratchBuffer> ScratchBuf;
172 llvm::BumpPtrAllocator BP;
229 unsigned CounterValue = 0;
233 MaxAllowedIncludeStackDepth = 200
237 bool KeepComments : 1;
238 bool KeepMacroComments : 1;
239 bool SuppressIncludeNotFoundError : 1;
242 bool InMacroArgs : 1;
245 bool OwnsHeaderSearch : 1;
248 bool DisableMacroExpansion : 1;
252 bool MacroExpansionInDirectivesOverride : 1;
254 class ResetMacroExpansionHelper;
257 mutable bool ReadMacrosFromExternalSource : 1;
260 bool PragmasEnabled : 1;
263 bool PreprocessedOutput : 1;
266 bool ParsingIfOrElifDirective;
269 bool InMacroArgPreExpansion;
287 std::unique_ptr<Builtin::Context> BuiltinInfo;
291 std::unique_ptr<PragmaNamespace> PragmaHandlers;
295 std::unique_ptr<PragmaNamespace> PragmaHandlersBackup;
299 std::vector<CommentHandler *> CommentHandlers;
305 bool IncrementalProcessing =
false;
323 const FileEntry *CodeCompletionFile =
nullptr;
326 unsigned CodeCompletionOffset = 0;
345 llvm::DenseMap<FileID, SmallVector<const char *>> CheckPoints;
346 unsigned CheckPointCounter = 0;
349 bool IsAtImport =
false;
352 bool LastTokenWasAt =
false;
363 class StdCXXImportSeq {
368 AfterTopLevelTokenSeq = -1,
373 StdCXXImportSeq(State S) : S(S) {}
376 void handleOpenBracket() {
377 S =
static_cast<State
>(std::max<int>(S, 0) + 1);
380 void handleCloseBracket() {
381 S =
static_cast<State
>(std::max<int>(S, 1) - 1);
384 void handleCloseBrace() {
385 handleCloseBracket();
386 if (S == AtTopLevel && !AfterHeaderName)
387 S = AfterTopLevelTokenSeq;
392 S = AfterTopLevelTokenSeq;
393 AfterHeaderName =
false;
398 void handleExport() {
399 if (S == AfterTopLevelTokenSeq)
405 void handleImport() {
406 if (S == AfterTopLevelTokenSeq || S == AfterExport)
414 void handleHeaderName() {
415 if (S == AfterImportSeq)
416 AfterHeaderName =
true;
426 bool atTopLevel() {
return S <= 0; }
427 bool afterImportSeq() {
return S == AfterImportSeq; }
428 bool afterTopLevelSeq() {
return S == AfterTopLevelTokenSeq; }
435 bool AfterHeaderName =
false;
439 StdCXXImportSeq StdCXXImportSeqState = StdCXXImportSeq::AfterTopLevelTokenSeq;
444 enum GMFState :
int {
447 BeforeGMFIntroducer = -1,
448 GMFAbsentOrEnded = -2,
451 TrackGMF(GMFState S) : S(S) {}
462 void handleExport() {
464 S = GMFAbsentOrEnded;
468 void handleImport(
bool AfterTopLevelTokenSeq) {
470 if (AfterTopLevelTokenSeq && S == BeforeGMFIntroducer)
471 S = GMFAbsentOrEnded;
475 void handleModule(
bool AfterTopLevelTokenSeq) {
479 if (AfterTopLevelTokenSeq && S == BeforeGMFIntroducer)
482 S = GMFAbsentOrEnded;
489 S = GMFAbsentOrEnded;
492 bool inGMF() {
return S == GMFActive; }
500 TrackGMF TrackGMFState = TrackGMF::BeforeGMFIntroducer;
536 class ModuleDeclSeq {
537 enum ModuleDeclState :
int {
541 ImplementationCandidate,
542 NamedModuleInterface,
543 NamedModuleImplementation,
547 ModuleDeclSeq() =
default;
549 void handleExport() {
550 if (State == NotAModuleDecl)
552 else if (!isNamedModule())
556 void handleModule() {
557 if (State == FoundExport)
558 State = InterfaceCandidate;
559 else if (State == NotAModuleDecl)
560 State = ImplementationCandidate;
561 else if (!isNamedModule())
565 void handleIdentifier(IdentifierInfo *
Identifier) {
568 else if (!isNamedModule())
573 if (isModuleCandidate())
575 else if (!isNamedModule())
579 void handlePeriod() {
580 if (isModuleCandidate())
582 else if (!isNamedModule())
587 if (!Name.empty() && isModuleCandidate()) {
588 if (State == InterfaceCandidate)
589 State = NamedModuleInterface;
590 else if (State == ImplementationCandidate)
591 State = NamedModuleImplementation;
593 llvm_unreachable(
"Unimaged ModuleDeclState.");
594 }
else if (!isNamedModule())
599 if (!isNamedModule())
603 bool isModuleCandidate()
const {
604 return State == InterfaceCandidate || State == ImplementationCandidate;
607 bool isNamedModule()
const {
608 return State == NamedModuleInterface ||
609 State == NamedModuleImplementation;
612 bool isNamedInterface()
const {
return State == NamedModuleInterface; }
614 bool isImplementationUnit()
const {
615 return State == NamedModuleImplementation && !
getName().contains(
':');
618 bool isNotAModuleDecl()
const {
return State == NotAModuleDecl; }
621 assert(isNamedModule() &&
"Can't get name from a non named module");
625 StringRef getPrimaryName()
const {
626 assert(isNamedModule() &&
"Can't get name from a non named module");
627 return getName().split(
':').first;
632 State = NotAModuleDecl;
636 ModuleDeclState State = NotAModuleDecl;
640 ModuleDeclSeq ModuleDeclState;
644 bool ModuleImportExpectsIdentifier =
false;
648 IdentifierLoc PragmaARCCFCodeAuditedInfo;
652 SourceLocation PragmaAssumeNonNullLoc;
660 SourceLocation PreambleRecordedPragmaAssumeNonNullLoc;
663 bool CodeCompletionReached =
false;
667 IdentifierInfo *CodeCompletionII =
nullptr;
670 SourceRange CodeCompletionTokenRange;
682 std::pair<int, bool> SkipMainFilePreamble;
686 bool HasReachedMaxIncludeDepth =
false;
694 unsigned LexLevel = 0;
697 unsigned TokenCount = 0;
700 bool PreprocessToken =
false;
704 unsigned MaxTokens = 0;
705 SourceLocation MaxTokensOverrideLoc;
729 class PreambleConditionalStackStore {
737 PreambleConditionalStackStore() =
default;
739 void startRecording() { ConditionalStackState = Recording; }
740 void startReplaying() { ConditionalStackState = Replaying; }
741 bool isRecording()
const {
return ConditionalStackState == Recording; }
742 bool isReplaying()
const {
return ConditionalStackState == Replaying; }
744 ArrayRef<PPConditionalInfo> getStack()
const {
745 return ConditionalStack;
748 void doneReplaying() {
749 ConditionalStack.clear();
750 ConditionalStackState = Off;
753 void setStack(ArrayRef<PPConditionalInfo>
s) {
754 if (!isRecording() && !isReplaying())
756 ConditionalStack.clear();
757 ConditionalStack.append(
s.begin(),
s.end());
760 bool hasRecordedPreamble()
const {
return !ConditionalStack.empty(); }
762 bool reachedEOFWhileSkipping()
const {
return SkipInfo.has_value(); }
764 void clearSkipInfo() { SkipInfo.reset(); }
766 std::optional<PreambleSkipInfo> SkipInfo;
769 SmallVector<PPConditionalInfo, 4> ConditionalStack;
770 State ConditionalStackState = Off;
771 } PreambleConditionalStack;
777 std::unique_ptr<Lexer> CurLexer;
783 PreprocessorLexer *CurPPLexer =
nullptr;
795 std::unique_ptr<TokenLexer> CurTokenLexer;
799 LexerCallback CurLexerCallback = &CLK_Lexer;
803 Module *CurLexerSubmodule =
nullptr;
808 struct IncludeStackInfo {
809 LexerCallback CurLexerCallback;
811 std::unique_ptr<Lexer> TheLexer;
812 PreprocessorLexer *ThePPLexer;
813 std::unique_ptr<TokenLexer> TheTokenLexer;
818 IncludeStackInfo(LexerCallback CurLexerCallback, Module *TheSubmodule,
819 std::unique_ptr<Lexer> &&TheLexer,
820 PreprocessorLexer *ThePPLexer,
821 std::unique_ptr<TokenLexer> &&TheTokenLexer,
823 : CurLexerCallback(
std::move(CurLexerCallback)),
824 TheSubmodule(
std::move(TheSubmodule)), TheLexer(
std::move(TheLexer)),
825 ThePPLexer(
std::move(ThePPLexer)),
826 TheTokenLexer(
std::move(TheTokenLexer)),
827 TheDirLookup(
std::move(TheDirLookup)) {}
829 std::vector<IncludeStackInfo> IncludeMacroStack;
833 std::unique_ptr<PPCallbacks> Callbacks;
835 struct MacroExpandsInfo {
840 MacroExpandsInfo(Token Tok, MacroDefinition MD, SourceRange Range)
843 SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks;
846 struct ModuleMacroInfo {
851 llvm::TinyPtrVector<ModuleMacro *> ActiveModuleMacros;
855 unsigned ActiveModuleMacrosGeneration = 0;
858 bool IsAmbiguous =
false;
861 llvm::TinyPtrVector<ModuleMacro *> OverriddenMacros;
863 ModuleMacroInfo(MacroDirective *MD) : MD(MD) {}
868 mutable llvm::PointerUnion<MacroDirective *, ModuleMacroInfo *> State;
870 ModuleMacroInfo *getModuleInfo(Preprocessor &PP,
871 const IdentifierInfo *II)
const {
872 if (II->isOutOfDate())
873 PP.updateOutOfDateIdentifier(*II);
876 if (!II->hasMacroDefinition() ||
877 (!PP.getLangOpts().Modules &&
878 !PP.getLangOpts().ModulesLocalVisibility) ||
879 !PP.CurSubmoduleState->VisibleModules.getGeneration())
882 auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State);
884 Info =
new (PP.getPreprocessorAllocator())
885 ModuleMacroInfo(cast<MacroDirective *>(State));
889 if (PP.CurSubmoduleState->VisibleModules.getGeneration() !=
890 Info->ActiveModuleMacrosGeneration)
891 PP.updateModuleMacroInfo(II, *Info);
896 MacroState() : MacroState(nullptr) {}
897 MacroState(MacroDirective *MD) : State(MD) {}
899 MacroState(MacroState &&O) noexcept : State(O.State) {
900 O.State = (MacroDirective *)
nullptr;
903 MacroState &operator=(MacroState &&O)
noexcept {
905 O.State = (MacroDirective *)
nullptr;
911 if (
auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State))
912 Info->~ModuleMacroInfo();
915 MacroDirective *getLatest()
const {
916 if (
auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State))
918 return cast<MacroDirective *>(State);
921 void setLatest(MacroDirective *MD) {
922 if (
auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State))
928 bool isAmbiguous(Preprocessor &PP,
const IdentifierInfo *II)
const {
929 auto *Info = getModuleInfo(PP, II);
930 return Info ? Info->IsAmbiguous :
false;
933 ArrayRef<ModuleMacro *>
934 getActiveModuleMacros(Preprocessor &PP,
const IdentifierInfo *II)
const {
935 if (
auto *Info = getModuleInfo(PP, II))
936 return Info->ActiveModuleMacros;
940 MacroDirective::DefInfo findDirectiveAtLoc(SourceLocation
Loc,
941 SourceManager &SourceMgr)
const {
943 if (
auto *Latest = getLatest())
944 return Latest->findDirectiveAtLoc(
Loc, SourceMgr);
948 void overrideActiveModuleMacros(Preprocessor &PP, IdentifierInfo *II) {
949 if (
auto *Info = getModuleInfo(PP, II)) {
950 Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
951 Info->ActiveModuleMacros.begin(),
952 Info->ActiveModuleMacros.end());
953 Info->ActiveModuleMacros.clear();
954 Info->IsAmbiguous =
false;
958 ArrayRef<ModuleMacro*> getOverriddenMacros()
const {
959 if (
auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State))
960 return Info->OverriddenMacros;
964 void setOverriddenMacros(Preprocessor &PP,
965 ArrayRef<ModuleMacro *> Overrides) {
966 auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State);
968 if (Overrides.empty())
970 Info =
new (PP.getPreprocessorAllocator())
971 ModuleMacroInfo(cast<MacroDirective *>(State));
974 Info->OverriddenMacros.clear();
975 Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
976 Overrides.begin(), Overrides.end());
977 Info->ActiveModuleMacrosGeneration = 0;
986 using MacroMap = llvm::DenseMap<const IdentifierInfo *, MacroState>;
988 struct SubmoduleState;
991 struct BuildingSubmoduleInfo {
996 SourceLocation ImportLoc;
1002 SubmoduleState *OuterSubmoduleState;
1005 unsigned OuterPendingModuleMacroNames;
1007 BuildingSubmoduleInfo(Module *M, SourceLocation ImportLoc,
bool IsPragma,
1008 SubmoduleState *OuterSubmoduleState,
1009 unsigned OuterPendingModuleMacroNames)
1010 : M(M), ImportLoc(ImportLoc), IsPragma(IsPragma),
1011 OuterSubmoduleState(OuterSubmoduleState),
1012 OuterPendingModuleMacroNames(OuterPendingModuleMacroNames) {}
1014 SmallVector<BuildingSubmoduleInfo, 8> BuildingSubmoduleStack;
1017 struct SubmoduleState {
1022 VisibleModuleSet VisibleModules;
1027 std::map<Module *, SubmoduleState> Submodules;
1030 SubmoduleState NullSubmoduleState;
1034 SubmoduleState *CurSubmoduleState;
1044 llvm::FoldingSet<ModuleMacro> ModuleMacros;
1051 llvm::DenseMap<const IdentifierInfo *, llvm::TinyPtrVector<ModuleMacro *>>
1062 using WarnUnusedMacroLocsTy = llvm::SmallDenseSet<SourceLocation, 32>;
1063 WarnUnusedMacroLocsTy WarnUnusedMacroLocs;
1069 using MsgLocationPair = std::pair<std::string, SourceLocation>;
1071 struct MacroAnnotationInfo {
1072 SourceLocation Location;
1073 std::string Message;
1076 struct MacroAnnotations {
1077 std::optional<MacroAnnotationInfo> DeprecationInfo;
1078 std::optional<MacroAnnotationInfo> RestrictExpansionInfo;
1079 std::optional<SourceLocation> FinalAnnotationLoc;
1083 llvm::DenseMap<const IdentifierInfo *, MacroAnnotations> AnnotationInfos;
1091 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>
1092 PragmaPushMacroInfo;
1095 unsigned NumDirectives = 0;
1096 unsigned NumDefined = 0;
1097 unsigned NumUndefined = 0;
1098 unsigned NumPragma = 0;
1100 unsigned NumElse = 0;
1101 unsigned NumEndif = 0;
1102 unsigned NumEnteredSourceFiles = 0;
1103 unsigned MaxIncludeStackDepth = 0;
1104 unsigned NumMacroExpanded = 0;
1105 unsigned NumFnMacroExpanded = 0;
1106 unsigned NumBuiltinMacroExpanded = 0;
1107 unsigned NumFastMacroExpanded = 0;
1108 unsigned NumTokenPaste = 0;
1109 unsigned NumFastTokenPaste = 0;
1110 unsigned NumSkipped = 0;
1114 std::string Predefines;
1117 FileID PredefinesFileID;
1120 FileID PCHThroughHeaderFileID;
1123 bool SkippingUntilPragmaHdrStop =
false;
1126 bool SkippingUntilPCHThroughHeader =
false;
1130 enum { TokenLexerCacheSize = 8 };
1131 unsigned NumCachedTokenLexers;
1132 std::unique_ptr<TokenLexer> TokenLexerCache[TokenLexerCacheSize];
1140 SmallVector<Token, 16> MacroExpandedTokens;
1141 std::vector<std::pair<TokenLexer *, size_t>> MacroExpandingLexersStack;
1148 PreprocessingRecord *
Record =
nullptr;
1151 using CachedTokensTy = SmallVector<Token, 1>;
1155 CachedTokensTy CachedTokens;
1162 CachedTokensTy::size_type CachedLexPos = 0;
1169 std::vector<CachedTokensTy::size_type> BacktrackPositions;
1173 std::vector<std::pair<CachedTokensTy, CachedTokensTy::size_type>>
1174 UnannotatedBacktrackTokens;
1180 bool SkippingExcludedConditionalBlock =
false;
1186 llvm::DenseMap<const char *, unsigned> RecordedSkippedRanges;
1188 void updateOutOfDateIdentifier(
const IdentifierInfo &II)
const;
1191 Preprocessor(
const PreprocessorOptions &PPOpts, DiagnosticsEngine &diags,
1192 const LangOptions &LangOpts, SourceManager &
SM,
1193 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
1194 IdentifierInfoLookup *IILookup =
nullptr,
1195 bool OwnsHeaderSearch =
false,
1207 const TargetInfo *AuxTarget =
nullptr);
1257 return NumDirectives;
1262 return ParsingIfOrElifDirective;
1267 this->KeepComments = KeepComments | KeepMacroComments;
1268 this->KeepMacroComments = KeepMacroComments;
1277 SuppressIncludeNotFoundError = Suppress;
1281 return SuppressIncludeNotFoundError;
1287 PreprocessedOutput = IsPreprocessedOutput;
1296 return CurPPLexer == L;
1326 C = std::make_unique<PPChainedCallbacks>(std::move(
C),
1327 std::move(Callbacks));
1328 Callbacks = std::move(
C);
1340 MaxTokensOverrideLoc =
Loc;
1349 OnToken = std::move(F);
1353 GetDependencyDirectives = &Get;
1372 auto I = Submodules.find(M);
1373 if (I == Submodules.end())
1375 auto J = I->second.Macros.find(II);
1376 if (J == I->second.Macros.end())
1378 auto *MD = J->second.getLatest();
1379 return MD && MD->isDefined();
1386 MacroState &S = CurSubmoduleState->Macros[II];
1387 auto *MD = S.getLatest();
1388 while (isa_and_nonnull<VisibilityMacroDirective>(MD))
1389 MD = MD->getPrevious();
1391 S.getActiveModuleMacros(*
this, II),
1392 S.isAmbiguous(*
this, II));
1400 MacroState &S = CurSubmoduleState->Macros[II];
1402 if (
auto *MD = S.getLatest())
1406 S.getActiveModuleMacros(*
this, II),
1407 S.isAmbiguous(*
this, II));
1417 if (!MD || MD->getDefinition().isUndefined())
1431 return MD.getMacroInfo();
1468 updateOutOfDateIdentifier(*II);
1469 auto I = LeafModuleMacros.find(II);
1470 if (I != LeafModuleMacros.end())
1477 return BuildingSubmoduleStack;
1489 llvm::iterator_range<macro_iterator>
1490 macros(
bool IncludeExternalMacros =
true)
const {
1493 return llvm::make_range(begin, end);
1501 if (!BuildingSubmoduleStack.empty()) {
1502 if (M != BuildingSubmoduleStack.back().M)
1503 BuildingSubmoduleStack.back().M->AffectingClangModules.insert(M);
1505 AffectingClangModules.insert(M);
1512 return AffectingClangModules;
1519 return IncludedFiles.insert(
File).second;
1525 return IncludedFiles.count(
File);
1551 return &Identifiers.
get(Name);
1591 CodeComplete = &Handler;
1596 return CodeComplete;
1601 CodeComplete =
nullptr;
1614 CodeCompletionII = Filter;
1621 CodeCompletionTokenRange = {Start, End};
1624 return CodeCompletionTokenRange;
1629 if (CodeCompletionII)
1630 return CodeCompletionII->getName();
1704 void EnterTokenStream(
const Token *Toks,
unsigned NumToks,
1705 bool DisableMacroExpansion,
bool OwnsTokens,
1710 bool DisableMacroExpansion,
bool IsReinject) {
1711 EnterTokenStream(Toks.release(), NumToks, DisableMacroExpansion,
true,
1717 EnterTokenStream(Toks.data(), Toks.size(), DisableMacroExpansion,
false,
1745 std::pair<CachedTokensTy::size_type, bool> LastBacktrackPos();
1747 CachedTokensTy PopUnannotatedBacktrackTokens();
1764 return !UnannotatedBacktrackTokens.empty();
1782 assert(FirstPPTokenLoc.
isValid() &&
1783 "Did not see the first pp-token in the main file");
1784 return FirstPPTokenLoc;
1791 bool IncludeExports =
true);
1794 return CurSubmoduleState->VisibleModules.getImportLoc(M);
1801 const char *DiagnosticTag,
bool AllowMacroExpansion) {
1802 if (AllowMacroExpansion)
1807 AllowMacroExpansion);
1813 const char *DiagnosticTag,
1814 bool AllowMacroExpansion);
1824 while (
Result.getKind() == tok::comment);
1830 bool OldVal = DisableMacroExpansion;
1831 DisableMacroExpansion =
true;
1836 DisableMacroExpansion = OldVal;
1844 while (
Result.getKind() == tok::comment);
1854 DisableMacroExpansion =
true;
1855 MacroExpansionInDirectivesOverride =
true;
1859 DisableMacroExpansion = MacroExpansionInDirectivesOverride =
false;
1870 assert(LexLevel == 0 &&
"cannot use lookahead while lexing");
1874 return PeekAhead(N+1);
1884 "Should only be called when tokens are cached for backtracking");
1885 assert(
signed(CachedLexPos) -
signed(N) >=
1886 signed(LastBacktrackPos().first) &&
1887 "Should revert tokens up to the last backtrack position, not more");
1888 assert(
signed(CachedLexPos) -
signed(N) >= 0 &&
1889 "Corrupted backtrack positions ?");
1903 auto TokCopy = std::make_unique<Token[]>(1);
1905 EnterTokenStream(std::move(TokCopy), 1,
true, IsReinject);
1907 EnterCachingLexMode();
1908 assert(IsReinject &&
"new tokens in the middle of cached stream");
1922 assert(Tok.
isAnnotation() &&
"Expected annotation token");
1924 AnnotatePreviousCachedTokens(Tok);
1930 assert(CachedLexPos != 0);
1954 assert(Tok.
isAnnotation() &&
"Expected annotation token");
1961 void *AnnotationVal);
1966 return CurLexerCallback != CLK_Lexer;
1986 IncrementalProcessing = value;
2020 return CodeCompletionFileLoc;
2030 CodeCompletionReached =
true;
2040 return PragmaARCCFCodeAuditedInfo;
2055 return PragmaAssumeNonNullLoc;
2061 PragmaAssumeNonNullLoc =
Loc;
2070 return PreambleRecordedPragmaAssumeNonNullLoc;
2076 PreambleRecordedPragmaAssumeNonNullLoc =
Loc;
2090 SkipMainFilePreamble.first = Bytes;
2091 SkipMainFilePreamble.second = StartOfLine;
2114 bool *invalid =
nullptr)
const {
2143 bool *
Invalid =
nullptr)
const {
2153 bool *
Invalid =
nullptr)
const;
2158 bool IgnoreWhiteSpace =
false) {
2166 bool *
Invalid =
nullptr)
const {
2167 assert((Tok.
is(tok::numeric_constant) || Tok.
is(tok::binary_data)) &&
2168 Tok.
getLength() == 1 &&
"Called on unsupported token");
2169 assert(!Tok.
needsCleaning() &&
"Token can't need cleaning with length 1");
2173 return (Tok.
getKind() == tok::binary_data) ? *
D : *
D -
'0';
2175 assert(Tok.
is(tok::numeric_constant) &&
"binary data with no data");
2256 unsigned Char)
const {
2266 ++NumFastTokenPaste;
2290 llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons;
2304 if(II->isPoisoned()) {
2313 static_assert(
sizeof...(Ts) > 0,
2314 "requires at least one tok::TokenKind specified");
2316 std::optional<Token> Val;
2318 Val = CurLexer->peekNextPPToken();
2320 Val = CurTokenLexer->peekNextPPToken();
2328 for (
const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
2330 Val = Entry.TheLexer->peekNextPPToken();
2332 Val = Entry.TheTokenLexer->peekNextPPToken();
2338 if (Entry.ThePPLexer)
2345 return Val->isOneOf(Ks...);
2353 *Ident___exception_code,
2354 *Ident_GetExceptionCode;
2357 *Ident___exception_info,
2358 *Ident_GetExceptionInfo;
2361 *Ident___abnormal_termination,
2362 *Ident_AbnormalTermination;
2364 const char *getCurLexerEndPos();
2365 void diagnoseMissingHeaderInUmbrellaDir(
const Module &Mod);
2407 bool EnableMacros =
false);
2429 "FPEvalMethod should be set either from command line or from the "
2431 return CurrentFPEvalMethod;
2435 return TUFPEvalMethod;
2439 return LastFPEvalPragmaLocation;
2445 "FPEvalMethod should never be set to FEM_UnsetOnCommandLine");
2448 LastFPEvalPragmaLocation = PragmaLoc;
2449 CurrentFPEvalMethod = Val;
2450 TUFPEvalMethod = Val;
2455 "TUPEvalMethod should never be set to FEM_UnsetOnCommandLine");
2456 TUFPEvalMethod = Val;
2473 return ModuleDeclState.isNamedInterface();
2484 return ModuleDeclState.isImplementationUnit();
2491 return !NamedModuleImportPath.empty() &&
getLangOpts().CPlusPlusModules &&
2519 bool *IsFrameworkFound,
bool SkipCache =
false,
2520 bool OpenFile =
true,
bool CacheFailures =
true);
2532 const FileEntry *LookupFromFile =
nullptr);
2542 bool *ShadowFlag =
nullptr);
2550 void PushIncludeMacroStack() {
2551 assert(CurLexerCallback != CLK_CachingLexer &&
2552 "cannot push a caching lexer");
2553 IncludeMacroStack.emplace_back(CurLexerCallback, CurLexerSubmodule,
2554 std::move(CurLexer), CurPPLexer,
2555 std::move(CurTokenLexer), CurDirLookup);
2556 CurPPLexer =
nullptr;
2559 void PopIncludeMacroStack() {
2560 CurLexer = std::move(IncludeMacroStack.back().TheLexer);
2561 CurPPLexer = IncludeMacroStack.back().ThePPLexer;
2562 CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer);
2563 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
2564 CurLexerSubmodule = IncludeMacroStack.back().TheSubmodule;
2565 CurLexerCallback = IncludeMacroStack.back().CurLexerCallback;
2566 IncludeMacroStack.pop_back();
2569 void PropagateLineStartLeadingSpaceInfo(Token &
Result);
2573 bool needModuleMacros()
const;
2577 void updateModuleMacroInfo(
const IdentifierInfo *II, ModuleMacroInfo &Info);
2579 DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI,
2580 SourceLocation
Loc);
2581 UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc);
2582 VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation
Loc,
2596 bool *ShadowFlag =
nullptr);
2607 MacroInfo *ReadOptionalMacroParameterListAndBody(
2608 const Token &MacroNameTok,
bool ImmediatelyAfterHeaderGuard);
2614 bool ReadMacroParameterList(MacroInfo *MI, Token& LastTok);
2621 void SuggestTypoedDirective(
const Token &Tok, StringRef
Directive)
const;
2631 void SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
2632 SourceLocation IfTokenLoc,
2633 bool FoundNonSkipPortion,
bool FoundElse,
2634 SourceLocation ElseLoc = SourceLocation());
2638 struct DirectiveEvalResult {
2640 std::optional<llvm::APSInt>
Value;
2646 bool IncludedUndefinedIds;
2649 SourceRange ExprRange;
2656 DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
2657 bool CheckForEoD =
true);
2665 DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
2667 bool &EvaluatedDefined,
2668 bool CheckForEoD =
true);
2674 EmbedResult EvaluateHasEmbed(Token &Tok, IdentifierInfo *II);
2679 bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II);
2684 bool EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II);
2687 std::pair<ConstSearchDirIterator, const FileEntry *>
2688 getIncludeNextStart(
const Token &IncludeNextTok)
const;
2692 void RegisterBuiltinPragmas();
2696 IdentifierInfo *RegisterBuiltinMacro(
const char *Name) {
2702 MI->setIsBuiltinMacro();
2708 void RegisterBuiltinMacros();
2713 bool HandleMacroExpandedIdentifier(Token &
Identifier,
const MacroDefinition &MD);
2720 Token *cacheMacroExpandedTokens(TokenLexer *tokLexer,
2721 ArrayRef<Token> tokens);
2723 void removeCachedMacroExpandedTokensOfLastLexer();
2727 MacroArgs *ReadMacroCallArgumentList(Token &MacroName, MacroInfo *MI,
2728 SourceLocation &MacroEnd);
2732 void ExpandBuiltinMacro(Token &Tok);
2737 void Handle_Pragma(Token &Tok);
2741 void HandleMicrosoft__pragma(Token &Tok);
2748 void setPredefinesFileID(FileID FID) {
2749 assert(PredefinesFileID.isInvalid() &&
"PredefinesFileID already set!");
2750 PredefinesFileID = FID;
2754 void setPCHThroughHeaderFileID(FileID FID);
2758 static bool IsFileLexer(
const Lexer* L,
const PreprocessorLexer*
P) {
2759 return L ? !L->isPragmaLexer() :
P !=
nullptr;
2762 static bool IsFileLexer(
const IncludeStackInfo& I) {
2763 return IsFileLexer(I.TheLexer.get(), I.ThePPLexer);
2766 bool IsFileLexer()
const {
2767 return IsFileLexer(CurLexer.get(), CurPPLexer);
2772 std::optional<CXXStandardLibraryVersionInfo> CXXStandardLibraryVersion;
2781 void CachingLex(Token &
Result);
2783 bool InCachingLexMode()
const {
2786 return !CurPPLexer && !CurTokenLexer && !IncludeMacroStack.empty();
2789 void EnterCachingLexMode();
2790 void EnterCachingLexModeUnchecked();
2792 void ExitCachingLexMode() {
2793 if (InCachingLexMode())
2797 const Token &PeekAhead(
unsigned N);
2798 void AnnotatePreviousCachedTokens(
const Token &Tok);
2804 void HandleLineDirective();
2805 void HandleDigitDirective(Token &Tok);
2806 void HandleUserDiagnosticDirective(Token &Tok,
bool isWarning);
2807 void HandleIdentSCCSDirective(Token &Tok);
2808 void HandleMacroPublicDirective(Token &Tok);
2809 void HandleMacroPrivateDirective();
2813 struct ImportAction {
2819 SkippedModuleImport,
2822 Module *ModuleForHeader =
nullptr;
2824 ImportAction(ActionKind AK, Module *Mod =
nullptr)
2825 :
Kind(AK), ModuleForHeader(Mod) {
2826 assert((AK == None || Mod || AK == Failure) &&
2827 "no module for module action");
2833 SourceLocation FilenameLoc, CharSourceRange FilenameRange,
2834 const Token &FilenameTok,
bool &IsFrameworkFound,
bool IsImportDecl,
2836 const FileEntry *LookupFromFile, StringRef &LookupFilename,
2837 SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
2838 ModuleMap::KnownHeader &SuggestedModule,
bool isAngled);
2840 void HandleEmbedDirective(SourceLocation HashLoc, Token &Tok,
2841 const FileEntry *LookupFromFile =
nullptr);
2842 void HandleEmbedDirectiveImpl(SourceLocation HashLoc,
2843 const LexEmbedParametersResult &Params,
2844 StringRef BinaryContents, StringRef
FileName);
2847 void HandleIncludeDirective(SourceLocation HashLoc, Token &Tok,
2849 const FileEntry *LookupFromFile =
nullptr);
2851 HandleHeaderIncludeOrImport(SourceLocation HashLoc, Token &IncludeTok,
2852 Token &FilenameTok, SourceLocation EndLoc,
2854 const FileEntry *LookupFromFile =
nullptr);
2855 void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok);
2856 void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok);
2857 void HandleImportDirective(SourceLocation HashLoc, Token &Tok);
2858 void HandleMicrosoftImportDirective(Token &Tok);
2865 const TargetInfo &TargetInfo,
2866 const Module &M, DiagnosticsEngine &Diags);
2889 SourceLocation MLoc);
2892 return PreambleConditionalStack.isRecording();
2896 return PreambleConditionalStack.hasRecordedPreamble();
2900 return PreambleConditionalStack.getStack();
2904 PreambleConditionalStack.setStack(
s);
2909 PreambleConditionalStack.startReplaying();
2910 PreambleConditionalStack.setStack(
s);
2911 PreambleConditionalStack.SkipInfo = SkipInfo;
2915 return PreambleConditionalStack.SkipInfo;
2921 void replayPreambleConditionalStack();
2924 void HandleDefineDirective(
Token &Tok,
bool ImmediatelyAfterHeaderGuard);
2925 void HandleUndefDirective();
2929 bool isIfndef,
bool ReadAnyTokensBeforeDirective);
2930 void HandleIfDirective(
Token &IfToken,
const Token &HashToken,
2931 bool ReadAnyTokensBeforeDirective);
2932 void HandleEndifDirective(
Token &EndifToken);
2934 void HandleElifFamilyDirective(
Token &ElifToken,
const Token &HashToken,
2963 AnnotationInfos[II].DeprecationInfo =
2964 MacroAnnotationInfo{AnnotationLoc, std::move(Msg)};
2969 AnnotationInfos[II].RestrictExpansionInfo =
2970 MacroAnnotationInfo{AnnotationLoc, std::move(Msg)};
2974 AnnotationInfos[II].FinalAnnotationLoc = AnnotationLoc;
2978 return AnnotationInfos.find(II)->second;
2982 bool IsIfnDef =
false)
const {
2988 !SourceMgr.isInMainFile(
Identifier.getLocation()))
3011 void emitFinalMacroWarning(
const Token &
Identifier,
bool IsUndef)
const;
3013 unsigned DiagSelection)
const;
3018 bool InSafeBufferOptOutRegion =
false;
3025 using SafeBufferOptOutRegionsTy =
3030 SafeBufferOptOutRegionsTy SafeBufferOptOutMap;
3049 const SafeBufferOptOutRegionsTy *
3057 return &
Iter->getSecond();
3059 } LoadedSafeBufferOptOutMap;
3077 const SourceLocation &
Loc);
3100 const SmallVectorImpl<SourceLocation> &SrcLocSeqs);
3109 static bool CLK_Lexer(Preprocessor &
P, Token &
Result) {
3110 return P.CurLexer->Lex(
Result);
3112 static bool CLK_TokenLexer(Preprocessor &
P, Token &
Result) {
3113 return P.CurTokenLexer->Lex(
Result);
3115 static bool CLK_CachingLexer(Preprocessor &
P, Token &
Result) {
3119 static bool CLK_DependencyDirectivesLexer(Preprocessor &
P, Token &
Result) {
3120 return P.CurLexer->LexDependencyDirectiveToken(
Result);
3122 static bool CLK_LexAfterModuleImport(Preprocessor &
P, Token &
Result) {
3123 return P.LexAfterModuleImport(
Result);
3161extern template class CLANG_TEMPLATE_ABI Registry<clang::PragmaHandler>;
Defines the Diagnostic-related interfaces.
enum clang::sema::@1840::IndirectLocalPathEntry::EntryKind Kind
Defines the Diagnostic IDs-related interfaces.
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.
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
Defines the PPCallbacks interface.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the clang::TokenKind enum and support functions.
__device__ __2f16 float __ockl_bool s
Reads an AST files chain containing the contents of a translation unit.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Callback handler that receives notifications when performing code completion within the preprocessor.
A directive for a defined macro or a macro imported from a module.
Functor that returns the dependency directives for a given file.
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void setSuppressAllDiagnostics(bool Val)
Suppress all diagnostics, to silence the front end when we know that we don't want any more diagnosti...
A reference to a DirectoryEntry that includes the name of the directory as it was accessed by the Fil...
Abstract base class that describes a handler that will receive source ranges for empty lines encounte...
virtual void HandleEmptyline(SourceRange Range)=0
virtual ~EmptylineHandler()
Abstract interface for external sources of preprocessor information.
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Cached information about one file (either on disk or in the virtual file system).
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
One of these records is kept for each identifier that is lexed.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
bool hasMacroDefinition() const
Return true if this identifier is #defined to some other value.
bool isDeprecatedMacro() const
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
StringRef getName() const
Return the actual identifier string.
bool isRestrictExpansion() const
A simple pair of identifier info and location.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
FPEvalMethodKind
Possible float expression evaluation method choices.
@ 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...
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
static bool isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin=nullptr)
Returns true if the given MacroID location points at the first token of the macro expansion.
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
static bool isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd=nullptr)
Returns true if the given MacroID location points at the last token of the macro expansion.
static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid=nullptr)
getSpelling - This method is used to get the spelling of a token into a preallocated buffer,...
static bool getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, const LangOptions &LangOpts, bool IgnoreWhiteSpace=false)
Relex the token at the specified location.
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
A description of the current definition of a macro.
const DefMacroDirective * getDirective() const
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Encapsulates the data about a macro definition (e.g.
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Abstract interface for a module loader.
Represents a macro directive exported by a module.
Describes a module or submodule.
bool isModuleMapModule() const
Consider the following code:
This interface provides a way to observe the actions of the preprocessor as it does its thing.
PragmaHandler - Instances of this interface defined to handle the various pragmas that the language f...
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
SourceLocation getLastFPEvalPragmaLocation() const
bool isMacroDefined(const IdentifierInfo *II)
MacroDirective * getLocalMacroDirective(const IdentifierInfo *II) const
Given an identifier, return its latest non-imported MacroDirective if it is #define'd and not #undef'...
bool markIncluded(FileEntryRef File)
Mark the file as included.
void HandlePragmaPushMacro(Token &Tok)
Handle #pragma push_macro.
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...
void HandlePragmaPoison()
HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
void setCodeCompletionHandler(CodeCompletionHandler &Handler)
Set the code completion handler to the given object.
void dumpMacroInfo(const IdentifierInfo *II)
void HandlePragmaSystemHeader(Token &SysHeaderTok)
HandlePragmaSystemHeader - Implement #pragma GCC system_header.
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 MaybeHandlePoisonedIdentifier(Token &Identifier)
ModuleMacro * addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides, bool &IsNew)
Register an exported macro for a module and identifier.
void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, MacroDirective *MD)
Set a MacroDirective that was loaded from a PCH file.
MacroDefinition getMacroDefinitionAtLoc(const IdentifierInfo *II, SourceLocation Loc)
void markClangModuleAsAffecting(Module *M)
Mark the given clang module as affecting the current clang module or translation unit.
void setPragmaARCCFCodeAuditedInfo(IdentifierInfo *Ident, SourceLocation Loc)
Set the location of the currently-active #pragma clang arc_cf_code_audited begin.
void HandlePragmaModuleBuild(Token &Tok)
void InitializeForModelFile()
Initialize the preprocessor to parse a model file.
OptionalFileEntryRef LookupEmbedFile(StringRef Filename, bool isAngled, bool OpenFile, const FileEntry *LookupFromFile=nullptr)
Given a "Filename" or <Filename> reference, look up the indicated embed resource.
SourceLocation getCodeCompletionLoc() const
Returns the location of the code-completion point.
ArrayRef< ModuleMacro * > getLeafModuleMacros(const IdentifierInfo *II) const
Get the list of leaf (non-overridden) module macros for a name.
void CollectPpImportSuffix(SmallVectorImpl< Token > &Toks)
Collect the tokens of a C++20 pp-import-suffix.
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
void IgnorePragmas()
Install empty handlers for all pragmas (making them ignored).
DefMacroDirective * appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI)
PPCallbacks * getPPCallbacks() const
bool isInNamedInterfaceUnit() const
If we are proprocessing a named interface unit.
ArrayRef< PPConditionalInfo > getPreambleConditionalStack() const
void setPreambleRecordedPragmaAssumeNonNullLoc(SourceLocation Loc)
Record the location of the unterminated #pragma clang assume_nonnull begin in the preamble.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
ArrayRef< BuildingSubmoduleInfo > getBuildingSubmodules() const
Get the list of submodules that we're currently building.
SourceLocation getCodeCompletionFileLoc() const
Returns the start location of the file of code-completion point.
DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const
SourceRange getCodeCompletionTokenRange() const
SourceLocation getModuleImportLoc(Module *M) const
void overrideMaxTokens(unsigned Value, SourceLocation Loc)
void setCodeCompletionTokenRange(const SourceLocation Start, const SourceLocation End)
Set the code completion token range for detecting replacement range later on.
bool isRecordingPreamble() const
void HandleSkippedDirectiveWhileUsingPCH(Token &Result, SourceLocation HashLoc)
Process directives while skipping until the through header or #pragma hdrstop is found.
void setRecordedPreambleConditionalStack(ArrayRef< PPConditionalInfo > s)
void enableIncrementalProcessing(bool value=true)
Enables the incremental processing.
bool LexAfterModuleImport(Token &Result)
Lex a token following the 'import' contextual keyword.
void TypoCorrectToken(const Token &Tok)
Update the current token to represent the provided identifier, in order to cache an action performed ...
bool GetSuppressIncludeNotFoundError()
bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M)
Determine whether II is defined as a macro within the module M, if that is a module that we've alread...
void setPragmaAssumeNonNullLoc(SourceLocation Loc)
Set the location of the currently-active #pragma clang assume_nonnull begin.
bool isInPrimaryFile() const
Return true if we're in the top-level file, not in a #include.
macro_iterator macro_begin(bool IncludeExternalMacros=true) const
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 ...
void markMacroAsUsed(MacroInfo *MI)
A macro is used, update information about macros that need unused warnings.
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
void EnterSubmodule(Module *M, SourceLocation ImportLoc, bool ForPragma)
bool isSafeBufferOptOut(const SourceManager &SourceMgr, const SourceLocation &Loc) const
void addMacroDeprecationMsg(const IdentifierInfo *II, std::string Msg, SourceLocation AnnotationLoc)
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.
void addRestrictExpansionMsg(const IdentifierInfo *II, std::string Msg, SourceLocation AnnotationLoc)
IdentifierInfo * LookUpIdentifierInfo(Token &Identifier) const
Given a tok::raw_identifier token, look up the identifier information for the token and install it in...
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
void setPreprocessedOutput(bool IsPreprocessedOutput)
Sets whether the preprocessor is responsible for producing output or if it is producing tokens to be ...
void addFinalLoc(const IdentifierInfo *II, SourceLocation AnnotationLoc)
bool IsPreviousCachedToken(const Token &Tok) const
Whether Tok is the most recent token (CachedLexPos - 1) in CachedTokens.
bool SawDateOrTime() const
Returns true if the preprocessor has seen a use of DATE or TIME in the file so far.
const TargetInfo * getAuxTargetInfo() const
void CommitBacktrackedTokens()
Disable the last EnableBacktrackAtThisPos call.
void DumpMacro(const MacroInfo &MI) const
bool HandleEndOfTokenLexer(Token &Result)
Callback invoked when the current TokenLexer hits the end of its token stream.
void setDiagnostics(DiagnosticsEngine &D)
IncludedFilesSet & getIncludedFiles()
Get the set of included files.
friend void TokenLexer::ExpandFunctionArguments()
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 AnnotateCachedTokens(const Token &Tok)
We notify the Preprocessor that if it is caching tokens (because backtrack is enabled) it should repl...
bool isPreprocessedOutput() const
Returns true if the preprocessor is responsible for generating output, false if it is producing token...
StringRef getNamedModuleName() const
Get the named module name we're preprocessing.
unsigned getCounterValue() const
bool mightHavePendingAnnotationTokens()
Determine whether it's possible for a future call to Lex to produce an annotation token created by a ...
bool isInImportingCXXNamedModules() const
If we're importing a standard C++20 Named Modules.
void Lex(Token &Result)
Lex the next token for this preprocessor.
void EnterTokenStream(ArrayRef< Token > Toks, bool DisableMacroExpansion, bool IsReinject)
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...
bool isParsingIfOrElifDirective() const
True if we are currently preprocessing a if or #elif directive.
unsigned getNumDirectives() const
Retrieve the number of Directives that have been processed by the Preprocessor.
bool isInImplementationUnit() const
If we are implementing an implementation module unit.
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with this preprocessor.
void LexNonComment(Token &Result)
Lex a token.
void removeCommentHandler(CommentHandler *Handler)
Remove the specified comment handler.
PreprocessorLexer * getCurrentLexer() const
Return the current lexer being lexed from.
SourceRange DiscardUntilEndOfDirective()
Read and discard all tokens remaining on the current line until the tok::eod token is found.
bool LexOnOffSwitch(tok::OnOffSwitch &Result)
Lex an on-off-switch (C99 6.10.6p2) and verify that it is followed by EOD.
StringRef getCodeCompletionFilter()
Get the code completion token for filtering purposes.
void setMainFileDir(DirectoryEntryRef Dir)
Set the directory in which the main file should be considered to have been found, if it is not a real...
const IdentifierTable & getIdentifierTable() const
void HandlePragmaDependency(Token &DependencyTok)
HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
SourceLocation CheckEndOfDirective(const char *DirType, bool EnableMacros=false)
Ensure that the next token is a tok::eod token.
void HandlePoisonedIdentifier(Token &Identifier)
Display reason for poisoned identifier.
void Backtrack()
Make Preprocessor re-lex the tokens that were lexed since EnableBacktrackAtThisPos() was previously c...
bool isCurrentLexer(const PreprocessorLexer *L) const
Return true if we are lexing directly from the specified lexer.
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 IncrementPasteCounter(bool isFast)
Increment the counters for the number of token paste operations performed.
IdentifierLoc getPragmaARCCFCodeAuditedInfo() const
The location of the currently-active #pragma clang arc_cf_code_audited begin.
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc.
void setReplayablePreambleConditionalStack(ArrayRef< PPConditionalInfo > s, std::optional< PreambleSkipInfo > SkipInfo)
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
const MacroAnnotations & getMacroAnnotations(const IdentifierInfo *II) const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
uint8_t getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the value of constant as an unsign...
macro_iterator macro_end(bool IncludeExternalMacros=true) const
SourceManager & getSourceManager() const
bool isBacktrackEnabled() const
True if EnableBacktrackAtThisPos() was called and caching of tokens is on.
MacroDefinition getMacroDefinition(const IdentifierInfo *II)
bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag=nullptr)
std::optional< PreambleSkipInfo > getPreambleSkipInfo() const
void setPreprocessToken(bool Preprocess)
void SetPoisonReason(IdentifierInfo *II, unsigned DiagID)
Specifies the reason for poisoning an identifier.
void HandlePragmaOnce(Token &OnceTok)
HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
EmptylineHandler * getEmptylineHandler() const
bool getCommentRetentionState() const
bool isMacroDefined(StringRef Id)
static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, const Module &M, DiagnosticsEngine &Diags)
Check that the given module is available, producing a diagnostic if not.
Module * getCurrentModuleImplementation()
Retrieves the module whose implementation we're current compiling, if any.
void SetMacroExpansionOnlyInDirectives()
Disables macro expansion everywhere except for preprocessor directives.
bool hasRecordedPreamble() const
SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Char) const
Given a location that specifies the start of a token, return a new location that specifies a characte...
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
bool isNextPPTokenOneOf(Ts... Ks)
Check whether the next pp-token is one of the specificed token kind.
MacroMap::const_iterator macro_iterator
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 ...
bool isUnannotatedBacktrackEnabled() const
True if EnableBacktrackAtThisPos() was called and caching of unannotated tokens is on.
void EnterTokenStream(std::unique_ptr< Token[]> Toks, unsigned NumToks, bool DisableMacroExpansion, bool IsReinject)
void RevertCachedTokens(unsigned N)
When backtracking is enabled and tokens are cached, this allows to revert a specific number of tokens...
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
std::optional< std::uint64_t > getStdLibCxxVersion()
void RemovePragmaHandler(PragmaHandler *Handler)
bool isPPInSafeBufferOptOutRegion()
unsigned getTokenCount() const
Get the number of tokens processed so far.
unsigned getMaxTokens() const
Get the max number of tokens before issuing a -Wmax-tokens warning.
SourceLocation getMaxTokensOverrideLoc() const
void makeModuleVisible(Module *M, SourceLocation Loc, bool IncludeExports=true)
bool hadModuleLoaderFatalFailure() const
static void processPathToFileName(SmallVectorImpl< char > &FileName, const PresumedLoc &PLoc, const LangOptions &LangOpts, const TargetInfo &TI)
void setCurrentFPEvalMethod(SourceLocation PragmaLoc, LangOptions::FPEvalMethodKind Val)
const TargetInfo & getTargetInfo() const
FileManager & getFileManager() const
bool LexHeaderName(Token &Result, bool AllowMacroExpansion=true)
Lex a token, forming a header-name token if possible.
std::string getSpelling(const Token &Tok, bool *Invalid=nullptr) const
Return the 'spelling' of the Tok token.
bool isPCHThroughHeader(const FileEntry *FE)
Returns true if the FileEntry is the PCH through header.
void DumpLocation(SourceLocation Loc) const
Module * getCurrentLexerSubmodule() const
Return the submodule owning the file being lexed.
bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value)
Parses a simple integer literal to get its numeric value.
MacroInfo * AllocateMacroInfo(SourceLocation L)
Allocate a new MacroInfo object with the provided SourceLocation.
void setDependencyDirectivesGetter(DependencyDirectivesGetter &Get)
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool creatingPCHWithPragmaHdrStop()
True if creating a PCH with a #pragma hdrstop.
bool alreadyIncluded(FileEntryRef File) const
Return true if this header has already been included.
llvm::iterator_range< macro_iterator > macros(bool IncludeExternalMacros=true) const
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.
void LexUnexpandedNonComment(Token &Result)
Like LexNonComment, but this disables macro expansion of identifier tokens.
void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler)
Add the specified pragma handler to this preprocessor.
llvm::BumpPtrAllocator & getPreprocessorAllocator()
ModuleMacro * getModuleMacro(Module *Mod, const IdentifierInfo *II)
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)
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
bool GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer)
Turn the specified lexer token into a fully checked and spelled filename, e.g.
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
HeaderSearch & getHeaderSearchInfo() const
void emitMacroExpansionWarnings(const Token &Identifier, bool IsIfnDef=false) const
bool setDeserializedSafeBufferOptOutMap(const SmallVectorImpl< SourceLocation > &SrcLocSeqs)
void HandlePragmaPopMacro(Token &Tok)
Handle #pragma pop_macro.
void ReplaceLastTokenWithAnnotation(const Token &Tok)
Replace the last token with an annotation token.
ExternalPreprocessorSource * getExternalSource() const
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
Module * LeaveSubmodule(bool ForPragma)
const std::string & getPredefines() const
Get the predefines for this processor.
void HandleDirective(Token &Result)
Callback invoked when the lexer sees a # token at the start of a line.
SmallVector< SourceLocation, 64 > serializeSafeBufferOptOutMap() const
CodeCompletionHandler * getCodeCompletionHandler() const
Retrieve the current code-completion handler.
void recomputeCurLexerKind()
Recompute the current lexer kind based on the CurLexer/ CurTokenLexer pointers.
void EnterAnnotationToken(SourceRange Range, tok::TokenKind Kind, void *AnnotationVal)
Enter an annotation token into the token stream.
void setTokenWatcher(llvm::unique_function< void(const clang::Token &)> F)
Register a function that would be called on each token in the final expanded token stream.
MacroInfo * getMacroInfo(const IdentifierInfo *II)
void setPredefines(std::string P)
Set the predefines for this Preprocessor.
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()
Builtin::Context & getBuiltinInfo()
void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine)
Instruct the preprocessor to skip part of the main source file.
const PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
void ReplacePreviousCachedToken(ArrayRef< Token > NewToks)
Replace token in CachedLexPos - 1 in CachedTokens by the tokens in NewToks.
LangOptions::FPEvalMethodKind getTUFPEvalMethod() const
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.
void SetSuppressIncludeNotFoundError(bool Suppress)
static void processPathForFileMacro(SmallVectorImpl< char > &Path, const LangOptions &LangOpts, const TargetInfo &TI)
llvm::DenseMap< FileID, SafeBufferOptOutRegionsTy > LoadedRegions
bool isInNamedModule() const
If we are preprocessing a named module.
void EnableBacktrackAtThisPos(bool Unannotated=false)
From the point that this method is called, and until CommitBacktrackedTokens() or Backtrack() is call...
void RemoveTopOfLexerStack()
Pop the current lexer/macro exp off the top of the lexer stack.
void PoisonSEHIdentifiers(bool Poison=true)
bool isAtStartOfMacroExpansion(SourceLocation loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the first token of the macro expansion.
size_t getTotalMemory() const
void setExternalSource(ExternalPreprocessorSource *Source)
void clearCodeCompletionHandler()
Clear out the code completion handler.
void AddPragmaHandler(PragmaHandler *Handler)
OptionalFileEntryRef getHeaderToIncludeForDiagnostics(SourceLocation IncLoc, SourceLocation MLoc)
We want to produce a diagnostic at location IncLoc concerning an unreachable effect at location MLoc ...
void setCounterValue(unsigned V)
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
IdentifierInfo * ParsePragmaPushOrPopMacro(Token &Tok)
ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
void LexTokensUntilEOF(std::vector< Token > *Tokens=nullptr)
Lex all tokens for this preprocessor until (and excluding) end of file.
bool getRawToken(SourceLocation Loc, Token &Result, bool IgnoreWhiteSpace=false)
Relex the token at the specified location.
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.
bool HandleEndOfFile(Token &Result, bool isEndOfMacro=false)
Callback invoked when the lexer hits the end of the current file.
void setPragmasEnabled(bool Enabled)
DefMacroDirective * appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI, SourceLocation Loc)
void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments)
Control whether the preprocessor retains comments in output.
bool isAtEndOfMacroExpansion(SourceLocation loc, SourceLocation *MacroEnd=nullptr) const
Returns true if the given MacroID location points at the last token of the macro expansion.
SourceLocation getMainFileFirstPPTokenLoc() const
Get the start location of the first pp-token in main file.
void HandlePragmaMark(Token &MarkTok)
bool getPragmasEnabled() const
void HandlePragmaHdrstop(Token &Tok)
void SetEnableMacroExpansion()
PreprocessingRecord * getPreprocessingRecord() const
Retrieve the preprocessing record, or NULL if there is no preprocessing record.
void setEmptylineHandler(EmptylineHandler *Handler)
Set empty line handler.
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLastCachedTokenLocation() const
Get the location of the last cached token, suitable for setting the end location of an annotation tok...
bool hasSeenNoTrivialPPDirective() const
Whether we've seen pp-directives which may have changed the preprocessing state.
llvm::DenseSet< const FileEntry * > IncludedFilesSet
unsigned getSpelling(const Token &Tok, const char *&Buffer, bool *Invalid=nullptr) const
Get the spelling of a token into a preallocated buffer, instead of as an std::string.
SelectorTable & getSelectorTable()
void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler)
Remove the specific pragma handler from this preprocessor.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
const llvm::SmallSetVector< Module *, 2 > & getAffectingClangModules() const
Get the set of top-level clang modules that affected preprocessing, but were not imported.
std::optional< LexEmbedParametersResult > LexEmbedParameters(Token &Current, bool ForHasEmbed)
Lex the parameters for an #embed directive, returns nullopt on error.
const IncludedFilesSet & getIncludedFiles() const
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
void HandlePragmaIncludeAlias(Token &Tok)
Module * getModuleForLocation(SourceLocation Loc, bool AllowTextual)
Find the module that owns the source or header file that Loc points to.
void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter)
Set the code completion token for filtering purposes.
SourceLocation getPreambleRecordedPragmaAssumeNonNullLoc() const
Get the location of the recorded unterminated #pragma clang assume_nonnull begin in the preamble,...
void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args)
Add a Macro to the top of the include stack and start lexing tokens from it instead of the current bu...
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 LexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Lex a string literal, which may be the concatenation of multiple string literals and may even come fr...
void HandleMicrosoftCommentPaste(Token &Tok)
When the macro expander pastes together a comment (/##/) in Microsoft mode, this method handles updat...
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)
void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD)
Add a directive to the macro directive history for this identifier.
Represents an unpacked "presumed" location which can be presented to the user.
This table allows us to fully hide how we implement multi-keyword caching.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
FileID getUniqueLoadedASTFileID(SourceLocation Loc) const
A trivial tuple used to represent a source range.
Exposes information about the current target.
Stores token information for comparing actual tokens with predefined values.
TokenValue(IdentifierInfo *II)
TokenValue(tok::TokenKind Kind)
bool operator==(const Token &Tok) const
Token - This structure provides full information about a lexed token.
IdentifierInfo * getIdentifierInfo() const
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
unsigned getLength() const
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)) {....
tok::TokenKind getKind() const
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
bool needsCleaning() const
Return true if this token has trigraphs or escaped newlines in it.
const char * getLiteralData() const
getLiteralData - For a literal token (numeric constant, string, etc), this returns a pointer to the s...
A class for tracking whether we're inside a VA_OPT during a traversal of the tokens of a variadic mac...
An RAII class that tracks when the Preprocessor starts and stops lexing the definition of a (ISO C/C+...
Directive - Abstract class representing a parsed verify directive.
constexpr XRayInstrMask None
StringRef getName(const HeaderType T)
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
OnOffSwitch
Defines the possible values of an on-off-switch (C99 6.10.6p2).
bool isLiteral(TokenKind K)
Return true if this is a "literal" kind, like a numeric constant, string, etc.
PPKeywordKind
Provides a namespace for preprocessor keywords which start with a '#' at the beginning of the line.
bool isAnnotation(TokenKind K)
Return true if this is any of tok::annot_* kinds.
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< DirectoryEntryRef > OptionalDirectoryEntryRef
detail::SearchDirIteratorImpl< true > ConstSearchDirIterator
MacroUse
Context in which macro name is used.
llvm::Registry< PragmaHandler > PragmaHandlerRegistry
Registry of pragma handlers added by plugins.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ Result
The result type of a method or function.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Complete
The translation unit is a complete translation unit.
Diagnostic wrappers for TextAPI types for error reporting.
Helper class to shuttle information about #embed directives from the preprocessor to the parser throu...
Describes how and where the pragma was introduced.
SourceLocation IfTokenLoc
SourceLocation HashTokenLoc
PreambleSkipInfo(SourceLocation HashTokenLoc, SourceLocation IfTokenLoc, bool FoundNonSkipPortion, bool FoundElse, SourceLocation ElseLoc)