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"
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),
99 Identifiers(IILookup), PragmaHandlers(new
PragmaNamespace(StringRef())),
101 CurSubmoduleState(&NullSubmoduleState) {
102 OwnsHeaderSearch = OwnsHeaders;
105 KeepComments =
false;
106 KeepMacroComments =
false;
107 SuppressIncludeNotFoundError =
false;
110 DisableMacroExpansion =
false;
111 MacroExpansionInDirectivesOverride =
false;
114 InMacroArgPreExpansion =
false;
115 NumCachedTokenLexers = 0;
116 PragmasEnabled =
true;
117 ParsingIfOrElifDirective =
false;
118 PreprocessedOutput =
false;
121 ReadMacrosFromExternalSource =
false;
123 LastExportKeyword.startToken();
125 BuiltinInfo = std::make_unique<Builtin::Context>();
135 RegisterBuiltinPragmas();
138 RegisterBuiltinMacros();
140 if(LangOpts.Borland) {
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;
160 IncrementalProcessing = LangOpts.IncrementalExtensions;
164 SkippingUntilPragmaHdrStop =
true;
168 !this->PPOpts.ImplicitPCHInclude.empty())
169 SkippingUntilPCHThroughHeader =
true;
172 PreambleConditionalStack.startRecording();
174 MaxTokens = LangOpts.MaxTokens;
180 IncludeMacroStack.clear();
185 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers,
nullptr);
186 CurTokenLexer.reset();
189 for (
MacroArgs *ArgList = MacroArgCache; ArgList;)
190 ArgList = ArgList->deallocate();
193 if (OwnsHeaderSearch)
199 assert((!this->Target || this->Target == &Target) &&
200 "Invalid override of target information");
201 this->Target = &Target;
203 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
204 "Invalid override of aux target information.");
205 this->AuxTarget = AuxTarget;
208 BuiltinInfo->InitializeTarget(Target, AuxTarget);
209 HeaderInfo.setTarget(Target);
212 Identifiers.AddKeywords(LangOpts);
226 NumEnteredSourceFiles = 0;
229 PragmaHandlersBackup = std::move(PragmaHandlers);
230 PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
231 RegisterBuiltinPragmas();
234 PredefinesFileID =
FileID();
238 NumEnteredSourceFiles = 1;
240 PragmaHandlers = std::move(PragmaHandlersBackup);
244 std::string TokenStr;
245 llvm::raw_string_ostream OS(TokenStr);
252 if (!
Tok.isAnnotation()) {
261 llvm::errs() << llvm::formatv(
"{0,-48} ", OS.str());
263 if (!DumpFlags)
return;
265 auto Loc =
Tok.getLocation();
266 llvm::errs() <<
"Loc=<";
279 if (Loc.isFileID()) {
283 int LineWidth = llvm::utostr(PLoc.
getLine()).size();
288 const int ReservedSpace = 6;
290 int LeftSpace = ReservedSpace - LineWidth -
ColumnWidth;
291 int Padding = std::max<int>(0, LeftSpace);
293 llvm::errs().indent(Padding);
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()) <<
"']";
310 Loc.
print(llvm::errs(), SourceMgr);
314 llvm::errs() <<
"MACRO: ";
315 for (
unsigned i = 0, e = MI.
getNumTokens(); i != e; ++i) {
319 llvm::errs() <<
"\n";
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";
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";
343 llvm::errs() <<
"\nPreprocessor Memory: " <<
getTotalMemory() <<
"B total";
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();
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";
360llvm::iterator_range<Preprocessor::macro_iterator>
362 if (IncludeExternalMacros && ExternalSource &&
363 !ReadMacrosFromExternalSource) {
364 ReadMacrosFromExternalSource =
true;
365 ExternalSource->ReadDefinedMacros();
369 CurSubmoduleState->Macros.try_emplace(
Macro.II);
371 return CurSubmoduleState->Macros;
375 return BP.getTotalMemory()
376 + llvm::capacity_in_bytes(MacroExpandedTokens)
377 + Predefines.capacity()
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);
390 std::equal(Tokens.begin(), Tokens.end(), MI->
tokens_begin());
397 StringRef BestSpelling;
398 for (
const auto &M :
macros()) {
400 M.second.findDirectiveAtLoc(Loc, SourceMgr);
410 (Location.isValid() &&
411 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
412 BestLocation = Location;
413 BestSpelling = M.first->getName();
420 if (InCachingLexMode())
421 CurLexerCallback = CLK_CachingLexer;
423 CurLexerCallback = CurLexer->isDependencyDirectivesLexer()
424 ? CLK_DependencyDirectivesLexer
426 else if (CurTokenLexer)
427 CurLexerCallback = CLK_TokenLexer;
429 CurLexerCallback = CLK_Lexer;
433 unsigned CompleteLine,
434 unsigned CompleteColumn) {
435 assert(CompleteLine && CompleteColumn &&
"Starts from 1:1");
436 assert(!CodeCompletionFile &&
"Already set");
439 std::optional<llvm::MemoryBufferRef> Buffer =
440 SourceMgr.getMemoryBufferForFileOrNone(
File);
445 const char *Position = Buffer->getBufferStart();
447 for (; *Position; ++Position) {
448 if (*Position !=
'\r' && *Position !=
'\n')
452 if ((Position[1] ==
'\r' || Position[1] ==
'\n') &&
453 Position[0] != Position[1])
460 Position += CompleteColumn - 1;
464 if (SkipMainFilePreamble.first &&
465 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) ==
File) {
466 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
467 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
470 if (Position > Buffer->getBufferEnd())
471 Position = Buffer->getBufferEnd();
473 CodeCompletionFile =
File;
474 CodeCompletionOffset = Position - Buffer->getBufferStart();
476 auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
477 Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
478 char *NewBuf = NewBuffer->getBufferStart();
479 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
481 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
482 SourceMgr.overrideFileContents(
File, std::move(NewBuffer));
491 CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
497 CodeComplete->CodeCompleteNaturalLanguage();
507 if (
Tok.isNot(tok::raw_identifier) && !
Tok.hasUCN()) {
510 return II->getName();
514 if (
Tok.needsCleaning())
515 Buffer.resize(
Tok.getLength());
517 const char *Ptr = Buffer.data();
519 return StringRef(Ptr, Len);
528 Tok.setLength(Str.size());
531 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
533 if (ExpansionLocStart.
isValid())
534 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
535 ExpansionLocEnd, Str.size());
536 Tok.setLocation(Loc);
539 if (
Tok.is(tok::raw_identifier))
540 Tok.setRawIdentifierData(DestPtr);
541 else if (
Tok.isLiteral())
542 Tok.setLiteralData(DestPtr);
550 StringRef Buffer =
SM.getBufferData(LocInfo.first, &
Invalid);
557 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
569 if (!
getLangOpts().isCompilingModuleImplementation())
585 assert(NumEnteredSourceFiles == 0 &&
"Cannot reenter the main file!");
586 FileID MainFileID = SourceMgr.getMainFileID();
590 if (!SourceMgr.isLoadedFileID(MainFileID)) {
596 if (SkipMainFilePreamble.first > 0)
597 CurLexer->SetByteOffset(SkipMainFilePreamble.first,
598 SkipMainFilePreamble.second);
615 std::optional<StringRef> Input =
618 MainFileIsPreprocessedModuleFile =
620 auto Tracer = std::make_unique<NoTrivialPPDirectiveTracer>(*
this);
621 DirTracer = Tracer.get();
623 std::optional<Token> FirstPPTok = CurLexer->peekNextPPToken();
625 FirstPPTokenLoc = FirstPPTok->getLocation();
630 std::unique_ptr<llvm::MemoryBuffer> SB =
631 llvm::MemoryBuffer::getMemBufferCopy(Predefines,
"<built-in>");
632 assert(SB &&
"Cannot create predefined source buffer");
633 FileID FID = SourceMgr.createFileID(std::move(SB));
634 assert(FID.
isValid() &&
"Could not create FileID for predefines?");
635 setPredefinesFileID(FID);
640 if (!PPOpts.PCHThroughHeader.empty()) {
645 false,
nullptr,
nullptr,
646 nullptr,
nullptr,
nullptr,
651 << PPOpts.PCHThroughHeader;
654 setPCHThroughHeaderFileID(
664void Preprocessor::setPCHThroughHeaderFileID(
FileID FID) {
665 assert(PCHThroughHeaderFileID.
isInvalid() &&
666 "PCHThroughHeaderFileID already set!");
667 PCHThroughHeaderFileID = FID;
671 assert(PCHThroughHeaderFileID.isValid() &&
672 "Invalid PCH through header FileID");
673 return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
678 PCHThroughHeaderFileID.isValid();
683 PCHThroughHeaderFileID.isValid();
700 bool ReachedMainFileEOF =
false;
701 bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
702 bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
707 CurLexerCallback(*
this,
Tok);
708 if (
Tok.is(tok::eof) && !InPredefines) {
709 ReachedMainFileEOF =
true;
712 if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
714 if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
717 if (ReachedMainFileEOF) {
718 if (UsingPCHThroughHeader)
720 << PPOpts.PCHThroughHeader << 1;
721 else if (!PPOpts.PCHWithHdrStopCreate)
726void Preprocessor::replayPreambleConditionalStack() {
728 if (PreambleConditionalStack.isReplaying()) {
730 "CurPPLexer is null when calling replayPreambleConditionalStack.");
732 PreambleConditionalStack.doneReplaying();
733 if (PreambleConditionalStack.reachedEOFWhileSkipping())
734 SkipExcludedConditionalBlock(
735 PreambleConditionalStack.SkipInfo->HashTokenLoc,
736 PreambleConditionalStack.SkipInfo->IfTokenLoc,
737 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
738 PreambleConditionalStack.SkipInfo->FoundElse,
739 PreambleConditionalStack.SkipInfo->ElseLoc);
746 Callbacks->EndOfMainFile();
757 assert(!Identifier.
getRawIdentifier().empty() &&
"No raw identifier data!");
767 StringRef CleanedStr =
getSpelling(Identifier, IdentifierBuffer);
769 if (Identifier.
hasUCN()) {
792 PoisonReasons[II] = DiagID;
796 assert(Ident__exception_code && Ident__exception_info);
797 assert(Ident___exception_code && Ident___exception_info);
798 Ident__exception_code->setIsPoisoned(Poison);
799 Ident___exception_code->setIsPoisoned(Poison);
800 Ident_GetExceptionCode->setIsPoisoned(Poison);
801 Ident__exception_info->setIsPoisoned(Poison);
802 Ident___exception_info->setIsPoisoned(Poison);
803 Ident_GetExceptionInfo->setIsPoisoned(Poison);
804 Ident__abnormal_termination->setIsPoisoned(Poison);
805 Ident___abnormal_termination->setIsPoisoned(Poison);
806 Ident_AbnormalTermination->setIsPoisoned(Poison);
811 "Can't handle identifiers without identifier info!");
812 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
814 if(it == PoisonReasons.end())
815 Diag(Identifier, diag::err_pp_used_poisoned_id);
820void Preprocessor::updateOutOfDateIdentifier(
const IdentifierInfo &II)
const {
823 "getExternalSource() should not return nullptr");
837 "Can't handle identifiers without identifier info!");
847 bool CurrentIsPoisoned =
false;
848 const bool IsSpecialVariadicMacro =
849 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
850 if (IsSpecialVariadicMacro)
853 updateOutOfDateIdentifier(II);
856 if (IsSpecialVariadicMacro)
868 const auto *MI = MD.getMacroInfo();
869 assert(MI &&
"macro definition with no macro info?");
870 if (!DisableMacroExpansion) {
875 return HandleMacroExpandedIdentifier(Identifier, MD);
882 Diag(Identifier, diag::pp_disabled_macro_expansion);
902 Diag(Identifier, diag::warn_pp_identifier_is_cpp_keyword) << &II;
909 Diag(Identifier, diag::ext_token_used);
913 !CurLexer->isLexingRawMode() && !CurLexer->isPragmaLexer() &&
914 !CurLexer->ParsingPreprocessorDirective &&
929 while (!CurLexerCallback(*
this,
Result))
932 if (
Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
935 if (
Result.is(tok::code_completion) &&
Result.getIdentifierInfo()) {
941 Result.setIdentifierInfo(
nullptr);
949 if (
getLangOpts().CPlusPlusModules && LexLevel == 1 &&
951 switch (
Result.getKind()) {
952 case tok::l_paren:
case tok::l_square:
case tok::l_brace:
953 StdCXXImportSeqState.handleOpenBracket();
955 case tok::r_paren:
case tok::r_square:
956 StdCXXImportSeqState.handleCloseBracket();
959 StdCXXImportSeqState.handleCloseBrace();
961#define PRAGMA_ANNOTATION(X) case tok::annot_##X:
963#include "clang/Basic/TokenKinds.def"
964#undef PRAGMA_ANNOTATION
967 case tok::annot_module_include:
968 case tok::annot_repl_input_end:
970 TrackGMFState.handleSemi();
971 StdCXXImportSeqState.handleSemi();
972 ModuleDeclState.handleSemi();
974 case tok::header_name:
975 case tok::annot_header_unit:
976 StdCXXImportSeqState.handleHeaderName();
981 TrackGMFState.handleExport();
982 StdCXXImportSeqState.handleExport();
983 ModuleDeclState.handleExport();
986 ModuleDeclState.handleColon();
989 if (StdCXXImportSeqState.atTopLevel()) {
990 TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());
991 StdCXXImportSeqState.handleImport();
995 if (StdCXXImportSeqState.atTopLevel()) {
998 TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());
999 ModuleDeclState.handleModule();
1002 case tok::annot_module_name:
1003 ModuleDeclState.handleModuleName(
1005 if (ModuleDeclState.isModuleCandidate())
1009 TrackGMFState.handleMisc();
1010 StdCXXImportSeqState.handleMisc();
1011 ModuleDeclState.handleMisc();
1017 CheckPoints[CurLexer->getFileID()].push_back(CurLexer->BufferPtr);
1018 CheckPointCounter = 0;
1021 if (
Result.isNot(tok::kw_export))
1022 LastExportKeyword.startToken();
1029 if (LexLevel == 0 && !PendingDestroyLexers.empty())
1030 PendingDestroyLexers.clear();
1032 if ((LexLevel == 0 || PreprocessToken) &&
1045 if (
Tok.isOneOf(tok::unknown, tok::eof, tok::eod,
1046 tok::annot_repl_input_end))
1048 if (Tokens !=
nullptr)
1049 Tokens->push_back(
Tok);
1070 if (CurPPLexer->ParsingFilename)
1073 CurPPLexer->LexIncludeFilename(FilenameTok);
1081 if (FilenameTok.
is(tok::less) && AllowMacroExpansion) {
1088 FilenameBuffer.push_back(
'<');
1094 while (FilenameTok.
isNot(tok::greater)) {
1096 if (FilenameTok.
isOneOf(tok::eod, tok::eof)) {
1098 Diag(Start, diag::note_matching) << tok::less;
1105 if (FilenameTok.
is(tok::code_completion)) {
1114 FilenameBuffer.push_back(
' ');
1118 size_t PreAppendSize = FilenameBuffer.size();
1119 FilenameBuffer.resize(PreAppendSize + FilenameTok.
getLength());
1121 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1122 unsigned ActualLen =
getSpelling(FilenameTok, BufPtr);
1125 if (BufPtr != &FilenameBuffer[PreAppendSize])
1126 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1129 if (FilenameTok.
getLength() != ActualLen)
1130 FilenameBuffer.resize(PreAppendSize + ActualLen);
1134 FilenameTok.
setKind(tok::header_name);
1139 }
else if (FilenameTok.
is(tok::string_literal) && AllowMacroExpansion) {
1150 StringRef Str =
getSpelling(FilenameTok, FilenameBuffer);
1151 if (Str.size() >= 2 && Str.front() ==
'"' && Str.back() ==
'"')
1152 FilenameTok.
setKind(tok::header_name);
1158std::optional<Token> Preprocessor::peekNextPPToken()
const {
1160 std::optional<Token> Val;
1162 Val = CurLexer->peekNextPPToken();
1164 Val = CurTokenLexer->peekNextPPToken();
1171 return std::nullopt;
1172 for (
const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
1174 Val = Entry.TheLexer->peekNextPPToken();
1176 Val = Entry.TheTokenLexer->peekNextPPToken();
1182 if (Entry.ThePPLexer)
1183 return std::nullopt;
1201 for (
auto &Piece : Path) {
1202 assert(Piece.getIdentifierInfo() && Piece.getLoc().isValid());
1205 Name += Piece.getIdentifierInfo()->getName();
1211 assert(!Path.empty() &&
"expect at least one identifier in a module name");
1213 totalSizeToAlloc<IdentifierLoc>(Path.size()),
alignof(ModuleNameLoc));
1214 return new (Mem) ModuleNameLoc(Path);
1220 bool AllowMacroExpansion,
1222 auto ConsumeToken = [&]() {
1223 if (AllowMacroExpansion)
1227 Suffix.push_back(
Tok);
1231 if (
Tok.isNot(tok::identifier)) {
1232 if (
Tok.is(tok::code_completion)) {
1233 CurLexer->cutOffLexing();
1234 CodeComplete->CodeCompleteModuleImport(UseLoc, Path);
1238 Diag(
Tok, diag::err_pp_module_expected_ident) << Path.empty();
1247 !AllowMacroExpansion) {
1248 Diag(
Tok, diag::err_pp_module_name_is_macro)
1249 << IsPartition <<
Tok.getIdentifierInfo();
1250 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1251 <<
Tok.getIdentifierInfo();
1255 Path.emplace_back(
Tok.getLocation(),
Tok.getIdentifierInfo());
1258 if (
Tok.isNot(tok::period))
1269 bool AllowMacroExpansion,
1271 bool LeadingSpace =
Tok.hasLeadingSpace();
1272 unsigned NumToksInDirective = DirToks.size();
1275 if (
Tok.isNot(tok::eod))
1284 DirToks.resize(NumToksInDirective);
1286 DirToks.emplace_back();
1287 DirToks.back().setKind(tok::annot_module_name);
1288 DirToks.back().setAnnotationRange(NameLoc->
getRange());
1289 DirToks.back().setAnnotationValue(
static_cast<void *
>(NameLoc));
1291 DirToks.push_back(
Tok);
1324 if (
Result.is(tok::kw_export)) {
1325 LastExportKeyword =
Result;
1338 if (LastExportKeyword.is(tok::kw_export)) {
1341 if (!LastExportKeyword.isAtPhysicalStartOfLine())
1346 if (
Result.isAtPhysicalStartOfLine())
1348 }
else if (!
Result.isAtPhysicalStartOfLine())
1352 CurPPLexer->ParsingPreprocessorDirective,
true);
1356 CurPPLexer->ParsingFilename,
1357 Result.getIdentifierInfo()->isImportKeyword());
1359 std::optional<Token> NextTok = peekNextPPToken();
1363 if (NextTok->is(tok::raw_identifier))
1366 if (
Result.getIdentifierInfo()->isImportKeyword()) {
1367 if (NextTok->isOneOf(tok::identifier, tok::less, tok::colon,
1368 tok::header_name)) {
1369 Result.setKind(tok::kw_import);
1370 ModuleImportLoc =
Result.getLocation();
1375 if (
Result.getIdentifierInfo()->isModuleKeyword() &&
1376 NextTok->isOneOf(tok::identifier, tok::colon, tok::semi)) {
1377 Result.setKind(tok::kw_module);
1378 ModuleDeclLoc =
Result.getLocation();
1395 bool StopUntilEOD) {
1397 Toks.emplace_back();
1400 switch (Toks.back().getKind()) {
1419 auto ToksCopy = std::make_unique<Token[]>(Toks.size());
1420 std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
1421 EnterTokenStream(std::move(ToksCopy), Toks.size(),
1423 assert(CurTokenLexer &&
"Must have a TokenLexer");
1424 CurTokenLexer->setLexingCXXModuleDirective();
1428 bool IncludeExports) {
1429 CurSubmoduleState->VisibleModules.setVisible(
1430 M, Loc, IncludeExports, [](
Module *) {},
1434 Diag(ModuleImportLoc, diag::warn_module_conflict)
1435 << Path[0]->getFullModuleName()
1436 << Conflict->getFullModuleName()
1441 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
1442 BuildingSubmoduleStack.back().M->Imports.push_back(M);
1446 const char *DiagnosticTag,
1447 bool AllowMacroExpansion) {
1449 if (
Result.isNot(tok::string_literal)) {
1450 Diag(
Result, diag::err_expected_string_literal)
1451 << 0 << DiagnosticTag;
1458 StrToks.push_back(
Result);
1460 if (
Result.hasUDSuffix())
1463 if (AllowMacroExpansion)
1467 }
while (
Result.is(tok::string_literal));
1471 assert(Literal.isOrdinary() &&
"Didn't allow wide strings in");
1473 if (Literal.hadError)
1476 if (Literal.Pascal) {
1477 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1478 << 0 << DiagnosticTag;
1482 String = std::string(Literal.GetString());
1487 assert(
Tok.is(tok::numeric_constant));
1489 bool NumberInvalid =
false;
1490 StringRef Spelling =
getSpelling(
Tok, IntegerBuffer, &NumberInvalid);
1496 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1498 llvm::APInt APVal(64, 0);
1499 if (Literal.GetIntegerValue(APVal))
1502 Value = APVal.getLimitedValue();
1507 assert(Handler &&
"NULL comment handler");
1508 assert(!llvm::is_contained(CommentHandlers, Handler) &&
1509 "Comment handler already registered");
1510 CommentHandlers.push_back(Handler);
1514 std::vector<CommentHandler *>::iterator Pos =
1515 llvm::find(CommentHandlers, Handler);
1516 assert(Pos != CommentHandlers.end() &&
"Comment handler not registered");
1517 CommentHandlers.erase(Pos);
1521 bool AnyPendingTokens =
false;
1523 if (H->HandleComment(*
this, Comment))
1524 AnyPendingTokens =
true;
1532void Preprocessor::emitMacroDeprecationWarning(
const Token &Identifier)
const {
1533 const MacroAnnotations &A =
1535 assert(A.DeprecationInfo &&
1536 "Macro deprecation warning without recorded annotation!");
1537 const MacroAnnotationInfo &Info = *A.DeprecationInfo;
1538 if (Info.Message.empty())
1539 Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1542 Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1544 Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
1547void Preprocessor::emitRestrictExpansionWarning(
const Token &Identifier)
const {
1548 const MacroAnnotations &A =
1550 assert(A.RestrictExpansionInfo &&
1551 "Macro restricted expansion warning without recorded annotation!");
1552 const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
1553 if (Info.Message.empty())
1554 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1557 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1559 Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
1562void Preprocessor::emitRestrictInfNaNWarning(
const Token &Identifier,
1563 unsigned DiagSelection)
const {
1564 Diag(Identifier, diag::warn_fp_nan_inf_when_disabled) << DiagSelection << 1;
1567void Preprocessor::emitFinalMacroWarning(
const Token &Identifier,
1568 bool IsUndef)
const {
1569 const MacroAnnotations &A =
1571 assert(A.FinalAnnotationLoc &&
1572 "Final macro warning without recorded annotation!");
1574 Diag(Identifier, diag::warn_pragma_final_macro)
1576 Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
1583 auto TestInMap = [&SourceMgr](
const SafeBufferOptOutRegionsTy &Map,
1586 auto FirstRegionEndingAfterLoc = llvm::partition_point(
1588 &Loc](
const std::pair<SourceLocation, SourceLocation> &Region) {
1589 return SourceMgr.isBeforeInTranslationUnit(Region.second, Loc);
1592 if (FirstRegionEndingAfterLoc != Map.end()) {
1594 return SourceMgr.isBeforeInTranslationUnit(
1595 FirstRegionEndingAfterLoc->first, Loc);
1599 if (!Map.empty() && Map.back().first == Map.back().second)
1600 return SourceMgr.isBeforeInTranslationUnit(Map.back().first, Loc);
1622 if (SourceMgr.isLocalSourceLocation(Loc))
1623 return TestInMap(SafeBufferOptOutMap, Loc);
1626 LoadedSafeBufferOptOutMap.lookupLoadedOptOutMap(Loc, SourceMgr);
1638 InSafeBufferOptOutRegion =
true;
1639 CurrentSafeBufferOptOutStart = Loc;
1643 if (!SafeBufferOptOutMap.empty()) {
1644 [[maybe_unused]]
auto *PrevRegion = &SafeBufferOptOutMap.back();
1645 assert(PrevRegion->first != PrevRegion->second &&
1646 "Shall not begin a safe buffer opt-out region before closing the "
1652 SafeBufferOptOutMap.emplace_back(Loc, Loc);
1656 InSafeBufferOptOutRegion =
false;
1660 assert(!SafeBufferOptOutMap.empty() &&
1661 "Misordered safe buffer opt-out regions");
1662 auto *CurrRegion = &SafeBufferOptOutMap.back();
1663 assert(CurrRegion->first == CurrRegion->second &&
1664 "Set end location to a closed safe buffer opt-out region");
1665 CurrRegion->second = Loc;
1671 return InSafeBufferOptOutRegion;
1674 StartLoc = CurrentSafeBufferOptOutStart;
1675 return InSafeBufferOptOutRegion;
1680 assert(!InSafeBufferOptOutRegion &&
1681 "Attempt to serialize safe buffer opt-out regions before file being "
1682 "completely preprocessed");
1686 for (
const auto &[begin, end] : SafeBufferOptOutMap) {
1687 SrcSeq.push_back(begin);
1688 SrcSeq.push_back(end);
1700 if (SourceLocations.size() == 0)
1703 assert(SourceLocations.size() % 2 == 0 &&
1704 "ill-formed SourceLocation sequence");
1706 auto It = SourceLocations.begin();
1707 SafeBufferOptOutRegionsTy &Regions =
1708 LoadedSafeBufferOptOutMap.findAndConsLoadedOptOutMap(*It, SourceMgr);
1714 Regions.emplace_back(Begin, End);
1715 }
while (It != SourceLocations.end());
1737 return C == Record ||
C == DirTracer;
1742 for (
auto *P : Released)
1747 if (
auto It = CheckPoints.find(FID); It != CheckPoints.end()) {
1749 auto P = llvm::upper_bound(FileCheckPoints, Start);
1750 if (P == FileCheckPoints.begin())
1752 return *std::prev(P);
1758 return DirTracer && DirTracer->hasSeenNoTrivialPPDirective();
1762 return SeenNoTrivialPPDirective;
1765void NoTrivialPPDirectiveTracer::setSeenNoTrivialPPDirective() {
1766 if (InMainFile && !SeenNoTrivialPPDirective)
1767 SeenNoTrivialPPDirective =
true;
1773 InMainFile = (FID == PP.getSourceManager().getMainFileID());
1782 setSeenNoTrivialPPDirective();
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.
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.
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)
virtual ~CodeCompletionHandler()
Concrete class used by the front-end to report problems and issues.
virtual ~EmptylineHandler()
virtual ~ExternalPreprocessorSource()
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...
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...
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 ...
A description of the current definition of a macro.
MacroInfo * getMacroInfo() const
Get the MacroInfo that should be used for this definition.
MacroInfo * getMacroInfo()
SourceLocation getLocation() const
Encapsulates the data about a macro definition (e.g.
const_tokens_iterator tokens_begin() const
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
const Token & getReplacementToken(unsigned Tok) const
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
bool isObjectLike() const
Abstract interface for a module loader.
static std::string getFlatNameFromPath(ModuleIdPath Path)
Represents a macro directive exported by a module.
static ModuleNameLoc * Create(Preprocessor &PP, ModuleIdPath Path)
SourceRange getRange() const
Describes a module or submodule.
void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) override
Called by Preprocessor::HandleMacroExpandedIdentifier when a macro invocation is found.
bool hasSeenNoTrivialPPDirective() const
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.
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...
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...
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.
bool isPPInSafeBufferOptOutRegion()
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.
Token - This structure provides full information about a lexed token.
IdentifierInfo * getIdentifierInfo() const
bool hasUCN() const
Returns true if this token contains a universal character name.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
unsigned getLength() const
bool isExpandDisabled() const
Return true if this identifier token should never be expanded in the future, due to C99 6....
void setKind(tok::TokenKind K)
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)) {....
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
bool isOneOf(Ts... Ks) const
@ HasSeenNoTrivialPPDirective
bool isModuleContextualKeyword(bool AllowExport=true) const
Return true if we have a C++20 modules contextual keyword(export, importor module).
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
bool hasLeadingEmptyMacro() const
Return true if this token has an empty macro before it.
bool isNot(tok::TokenKind K) const
void startToken()
Reset all flags to cleared.
bool needsCleaning() const
Return true if this token has trigraphs or escaped newlines in it.
void setIdentifierInfo(IdentifierInfo *II)
void setFlagValue(TokenFlags Flag, bool Val)
Set a flag to either true or false.
StringRef getRawIdentifier() const
getRawIdentifier - For a raw identifier token (i.e., an identifier lexed in raw mode),...
void setFlag(TokenFlags Flag)
Set the specified flag.
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
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.
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.