21#include "llvm/ADT/StringSwitch.h"
22#include "llvm/Support/MemoryBufferRef.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/VirtualFileSystem.h"
37 return IncludeMacroStack.empty();
40 assert(IsFileLexer(IncludeMacroStack[0]) &&
41 "Top level include stack isn't our primary lexer?");
43 llvm::drop_begin(IncludeMacroStack),
44 [&](
const IncludeStackInfo &ISI) ->
bool {
return IsFileLexer(ISI); });
55 for (
const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
57 return ISI.ThePPLexer;
71 bool IsFirstIncludeOfFile) {
72 assert(!CurTokenLexer &&
"Cannot #include a file inside a macro!");
73 ++NumEnteredSourceFiles;
75 if (MaxIncludeStackDepth < IncludeMacroStack.size())
76 MaxIncludeStackDepth = IncludeMacroStack.size();
79 std::optional<llvm::MemoryBufferRef> InputFile =
83 Diag(Loc, diag::err_pp_error_opening_file)
84 << std::string(SourceMgr.getBufferName(FileStart)) <<
"";
89 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
90 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
92 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
96 std::make_unique<Lexer>(FID, *InputFile, *
this, IsFirstIncludeOfFile);
97 if (GetDependencyDirectives && FID != PredefinesFileID)
99 if (
auto MaybeDepDirectives = (*GetDependencyDirectives)(*
File))
100 TheLexer->DepDirectives = *MaybeDepDirectives;
102 EnterSourceFileWithLexer(std::move(TheLexer), CurDir);
108void Preprocessor::EnterSourceFileWithLexer(std::unique_ptr<Lexer> TheLexer,
113 if (CurPPLexer || CurTokenLexer)
114 PushIncludeMacroStack();
116 CurLexer = std::move(TheLexer);
117 CurPPLexer = CurLexer.get();
118 CurDirLookup = CurDir;
119 CurLexerSubmodule =
nullptr;
120 CurLexerCallback = CurLexer->isDependencyDirectivesLexer()
121 ? CLK_DependencyDirectivesLexer
125 if (Callbacks && !CurLexer->Is_PragmaLexer) {
127 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
137 Callbacks->LexedFileChanged(CurLexer->getFileID(),
147 std::unique_ptr<TokenLexer> TokLexer;
148 if (NumCachedTokenLexers == 0) {
149 TokLexer = std::make_unique<TokenLexer>(
Tok, ILEnd,
Macro, Args, *
this);
151 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
152 TokLexer->Init(
Tok, ILEnd,
Macro, Args);
155 PushIncludeMacroStack();
156 CurDirLookup =
nullptr;
157 CurTokenLexer = std::move(TokLexer);
158 CurLexerCallback = CLK_TokenLexer;
173void Preprocessor::EnterTokenStream(
const Token *Toks,
unsigned NumToks,
174 bool DisableMacroExpansion,
bool OwnsTokens,
176 if (InCachingLexMode()) {
178 assert(IsReinject &&
"new tokens in the middle of cached stream");
182 Toks, Toks + NumToks);
190 ExitCachingLexMode();
191 EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
193 EnterCachingLexMode();
198 std::unique_ptr<TokenLexer> TokLexer;
199 if (NumCachedTokenLexers == 0) {
200 TokLexer = std::make_unique<TokenLexer>(
201 Toks, NumToks, DisableMacroExpansion, OwnsTokens, IsReinject, *
this);
203 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
204 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
209 PushIncludeMacroStack();
210 CurDirLookup =
nullptr;
211 CurTokenLexer = std::move(TokLexer);
212 CurLexerCallback = CLK_TokenLexer;
221 StringRef FilePath =
File.getDir().getName();
222 StringRef Path = FilePath;
223 while (!Path.empty()) {
225 if (*CurDir == Dir) {
226 Result = FilePath.substr(Path.size());
227 llvm::sys::path::append(
Result,
228 llvm::sys::path::filename(
File.getName()));
233 Path = llvm::sys::path::parent_path(Path);
239void Preprocessor::PropagateLineStartLeadingSpaceInfo(
Token &
Result) {
241 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(
Result);
245 CurLexer->PropagateLineStartLeadingSpaceInfo(
Result);
258const char *Preprocessor::getCurLexerEndPos() {
259 const char *EndPos = CurLexer->BufferEnd;
260 if (EndPos != CurLexer->BufferStart &&
261 (EndPos[-1] ==
'\n' || EndPos[-1] ==
'\r')) {
265 if (EndPos != CurLexer->BufferStart &&
266 (EndPos[-1] ==
'\n' || EndPos[-1] ==
'\r') &&
267 EndPos[-1] != EndPos[0])
277 SubMods.push_back(&Mod);
282void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(
const Module &Mod) {
283 std::optional<Module::Header> UmbrellaHeader =
285 assert(UmbrellaHeader &&
"Module must use umbrella header");
286 const FileID &
File = SourceMgr.translateFile(UmbrellaHeader->Entry);
287 SourceLocation ExpectedHeadersLoc = SourceMgr.getLocForEndOfFile(
File);
288 if (
getDiagnostics().isIgnored(diag::warn_uncovered_module_header,
294 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
296 for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->
getName(), EC),
298 Entry != End && !EC; Entry.increment(EC)) {
299 using llvm::StringSwitch;
303 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
304 .Cases({
".h",
".H",
".hh",
".hpp"},
true)
308 if (
auto Header =
getFileManager().getOptionalFileRef(Entry->path()))
312 SmallString<128> RelativePath;
314 Diag(ExpectedHeadersLoc, diag::warn_uncovered_module_header)
325 assert(!CurTokenLexer &&
326 "Ending a file when currently in a macro!");
330 if (IncludeMacroStack.empty() &&
334 Diag(UnclosedSafeBufferOptOutLoc,
335 diag::err_pp_unclosed_pragma_unsafe_buffer_usage);
339 const bool LeavingSubmodule = CurLexer && CurLexerSubmodule;
340 if ((LeavingSubmodule || IncludeMacroStack.empty()) &&
341 !BuildingSubmoduleStack.empty() &&
342 BuildingSubmoduleStack.back().IsPragma) {
343 Diag(BuildingSubmoduleStack.back().ImportLoc,
344 diag::err_pp_module_begin_without_module_end);
348 const char *EndPos = getCurLexerEndPos();
349 CurLexer->BufferPtr = EndPos;
350 CurLexer->FormTokenWithChars(
Result, EndPos, tok::annot_module_end);
352 Result.setAnnotationValue(M);
359 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
362 HeaderInfo.SetFileControllingMacro(*FE, ControllingMacro);
364 MI->setUsedForHeaderGuard(
true);
366 CurPPLexer->MIOpt.GetDefinedMacro()) {
368 DefinedMacro != ControllingMacro &&
369 CurLexer->isFirstTimeLexingFile()) {
377 const StringRef ControllingMacroName = ControllingMacro->getName();
378 const StringRef DefinedMacroName = DefinedMacro->getName();
379 const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
380 DefinedMacroName.size()) / 2;
381 const unsigned ED = ControllingMacroName.edit_distance(
382 DefinedMacroName,
true, MaxHalfLength);
383 if (ED <= MaxHalfLength) {
385 Diag(CurPPLexer->MIOpt.GetMacroLocation(),
386 diag::warn_header_guard)
387 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
388 Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
389 diag::note_header_guard)
390 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
393 CurPPLexer->MIOpt.GetDefinedLocation(),
394 ControllingMacro->getName());
405 if (PragmaARCCFCodeAuditedInfo.getLoc().isValid() && !isEndOfMacro &&
406 !(CurLexer && CurLexer->Is_PragmaLexer)) {
407 Diag(PragmaARCCFCodeAuditedInfo.getLoc(),
408 diag::err_pp_eof_in_arc_cf_code_audited);
417 if (PragmaAssumeNonNullLoc.isValid() &&
418 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
423 PreambleRecordedPragmaAssumeNonNullLoc = PragmaAssumeNonNullLoc;
425 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
430 bool LeavingPCHThroughHeader =
false;
434 if (!IncludeMacroStack.empty()) {
438 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
439 CodeCompletionFileLoc) {
440 assert(CurLexer &&
"Got EOF but no current lexer set!");
442 CurLexer->FormTokenWithChars(
Result, CurLexer->BufferEnd, tok::eof);
443 PendingDestroyLexers.push_back(std::move(CurLexer));
445 CurPPLexer =
nullptr;
450 if (!isEndOfMacro && CurPPLexer &&
451 (SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid() ||
453 (PredefinesFileID.isValid() &&
454 CurPPLexer->getFileID() == PredefinesFileID))) {
458 SourceMgr.local_sloc_entry_size() -
459 CurPPLexer->getInitialNumSLocEntries() + 1;
460 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
463 bool ExitedFromPredefinesFile =
false;
465 if (!isEndOfMacro && CurPPLexer) {
466 ExitedFID = CurPPLexer->getFileID();
468 assert(PredefinesFileID.isValid() &&
469 "HandleEndOfFile is called before PredefinesFileId is set");
470 ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
473 if (LeavingSubmodule) {
478 const char *EndPos = getCurLexerEndPos();
480 CurLexer->BufferPtr = EndPos;
481 CurLexer->FormTokenWithChars(
Result, EndPos, tok::annot_module_end);
483 Result.setAnnotationValue(M);
486 bool FoundPCHThroughHeader =
false;
489 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
490 FoundPCHThroughHeader =
true;
496 PropagateLineStartLeadingSpaceInfo(
Result);
499 if (Callbacks && !isEndOfMacro && CurPPLexer) {
502 SourceMgr.getFileCharacteristic(Loc);
504 Callbacks->LexedFileChanged(CurPPLexer->getFileID(),
506 FileType, ExitedFID, Loc);
512 if (ExitedFromPredefinesFile) {
513 replayPreambleConditionalStack();
514 if (PreambleRecordedPragmaAssumeNonNullLoc.isValid())
515 PragmaAssumeNonNullLoc = PreambleRecordedPragmaAssumeNonNullLoc;
518 if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
523 LeavingPCHThroughHeader =
true;
526 return LeavingSubmodule;
530 assert(CurLexer &&
"Got EOF but no current lexer set!");
531 const char *EndPos = getCurLexerEndPos();
533 CurLexer->BufferPtr = EndPos;
535 CurLexer->FormTokenWithChars(
Result, EndPos, tok::eof);
544 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
545 Result.setLocation(
Result.getLocation().getLocWithOffset(-1));
550 Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
551 << PPOpts.PCHThroughHeader << 0;
559 if (LexLevel > 0 && CurLexer) {
560 PendingDestroyLexers.push_back(std::move(CurLexer));
567 CurPPLexer =
nullptr;
573 for (WarnUnusedMacroLocsTy::iterator
574 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
576 Diag(*I, diag::pp_macro_not_used);
586 for (
auto *M : AllMods)
587 diagnoseMissingHeaderInUmbrellaDir(*M);
596 assert(CurTokenLexer && !CurPPLexer &&
597 "Ending a macro when currently in a #include file!");
599 if (!MacroExpandingLexersStack.empty() &&
600 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
601 removeCachedMacroExpandedTokensOfLastLexer();
604 if (NumCachedTokenLexers == TokenLexerCacheSize)
605 CurTokenLexer.reset();
607 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
617 assert(!IncludeMacroStack.empty() &&
"Ran out of stack entries to load");
621 if (NumCachedTokenLexers == TokenLexerCacheSize)
622 CurTokenLexer.reset();
624 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
627 PopIncludeMacroStack();
634 assert(CurTokenLexer && !CurPPLexer &&
635 "Pasted comment can only be formed from macro");
640 bool LexerWasInPPMode =
false;
641 for (
const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
642 if (ISI.ThePPLexer ==
nullptr)
continue;
650 FoundLexer = ISI.ThePPLexer;
668 while (
Tok.isNot(tok::eod) &&
Tok.isNot(tok::eof))
672 if (
Tok.is(tok::eod)) {
673 assert(FoundLexer &&
"Can't get end of line without an active lexer");
679 if (LexerWasInPPMode)
return;
690 assert(!FoundLexer &&
"Lexer should return EOD before EOF in PP mode");
697 BuildingSubmoduleStack.push_back(
698 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
699 PendingModuleMacroNames.size()));
701 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
715 auto R = Submodules.try_emplace(M);
716 auto &State = R.first->second;
717 bool FirstTime = R.second;
725 auto &StartingMacros = NullSubmoduleState.Macros;
729 for (
auto &
Macro : StartingMacros) {
731 if (!
Macro.second.getLatest() &&
732 Macro.second.getOverriddenMacros().empty())
735 MacroState MS(
Macro.second.getLatest());
736 MS.setOverriddenMacros(*
this,
Macro.second.getOverriddenMacros());
737 State.Macros.insert(std::make_pair(
Macro.first, std::move(MS)));
742 BuildingSubmoduleStack.push_back(
743 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
744 PendingModuleMacroNames.size()));
747 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
750 CurSubmoduleState = &State;
758bool Preprocessor::needModuleMacros()
const {
760 if (BuildingSubmoduleStack.empty())
772 if (BuildingSubmoduleStack.empty() ||
773 BuildingSubmoduleStack.back().IsPragma != ForPragma) {
774 assert(ForPragma &&
"non-pragma module enter/leave mismatch");
778 auto &Info = BuildingSubmoduleStack.back();
780 Module *LeavingMod = Info.M;
783 if (!needModuleMacros() ||
789 BuildingSubmoduleStack.pop_back();
792 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
800 for (
unsigned I = Info.OuterPendingModuleMacroNames;
801 I != PendingModuleMacroNames.size(); ++I) {
802 auto *II = PendingModuleMacroNames[I];
803 if (!VisitedMacros.insert(II).second)
806 auto MacroIt = CurSubmoduleState->Macros.find(II);
807 if (MacroIt == CurSubmoduleState->Macros.end())
809 auto &
Macro = MacroIt->second;
813 auto *OldState = Info.OuterSubmoduleState;
815 OldState = &NullSubmoduleState;
816 if (OldState && OldState != CurSubmoduleState) {
819 auto &OldMacros = OldState->Macros;
820 auto OldMacroIt = OldMacros.find(II);
821 if (OldMacroIt == OldMacros.end())
824 OldMD = OldMacroIt->second.getLatest();
829 bool ExplicitlyPublic =
false;
831 assert(MD &&
"broken macro directive chain");
833 if (
auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
836 if (VisMD->isPublic())
837 ExplicitlyPublic =
true;
838 else if (!ExplicitlyPublic)
844 Def = DefMD->getInfo();
851 if (Def || !
Macro.getOverriddenMacros().empty())
858 Macro.setLatest(
nullptr);
859 Macro.setOverriddenMacros(*
this, {});
865 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
874 CurSubmoduleState = Info.OuterSubmoduleState;
876 BuildingSubmoduleStack.pop_back();
879 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
Defines the clang::FileManager interface and associated types.
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::FileType FileType
Defines the clang::MacroInfo and clang::MacroDirective classes.
static void collectAllSubModulesWithUmbrellaHeader(const Module &Mod, SmallVectorImpl< const Module * > &SubMods)
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
A directive for a defined macro or a macro imported from a module.
StringRef getName() const
Cached information about one directory (either on disk or in the virtual file system).
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
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.
OptionalDirectoryEntryRef getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
One of these records is kept for each identifier that is lexed.
A simple pair of identifier info and location.
bool isCompilingModule() const
Are we compiling a module?
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Encapsulates the data about a macro definition (e.g.
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
bool isHeaderInUnavailableModule(FileEntryRef Header) const
Determine whether the given header is part of a module marked 'unavailable'.
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Describes a module or submodule.
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
llvm::iterator_range< submodule_iterator > submodules()
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
OptionalDirectoryEntryRef getEffectiveUmbrellaDir() const
Get the effective umbrella directory for this module: either the one explicitly written in the module...
bool LexingRawMode
True if in raw mode.
bool ParsingPreprocessorDirective
True when parsing #XXX; turns '\n' into a tok::eod token.
virtual SourceLocation getSourceLocation()=0
Return the source location for the next observable location.
bool creatingPCHWithThroughHeader()
True if creating a PCH with a through header.
ModuleMacro * addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides, bool &IsNew)
Register an exported macro for a module and identifier.
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
bool isRecordingPreamble() const
bool isInPrimaryFile() const
Return true if we're in the top-level file, not in a #include.
void EnterSubmodule(Module *M, SourceLocation ImportLoc, bool ForPragma)
bool HandleEndOfTokenLexer(Token &Result)
Callback invoked when the current TokenLexer hits the end of its token stream.
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...
SourceManager & getSourceManager() const
bool isMacroDefined(StringRef Id)
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
bool isPPInSafeBufferOptOutRegion()
void makeModuleVisible(Module *M, SourceLocation Loc, bool IncludeExports=true)
FileManager & getFileManager() const
bool isPCHThroughHeader(const FileEntry *FE)
Returns true if the FileEntry is the PCH through header.
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
HeaderSearch & getHeaderSearchInfo() const
Module * LeaveSubmodule(bool ForPragma)
void recomputeCurLexerKind()
Recompute the current lexer kind based on the CurLexer/ CurTokenLexer pointers.
const LangOptions & getLangOpts() const
void RemoveTopOfLexerStack()
Pop the current lexer/macro exp off the top of the lexer stack.
bool HandleEndOfFile(Token &Result, bool isEndOfMacro=false)
Callback invoked when the lexer hits the end of the current file.
DiagnosticsEngine & getDiagnostics() const
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 HandleMicrosoftCommentPaste(Token &Tok)
When the macro expander pastes together a comment (/##/) in Microsoft mode, this method handles updat...
Encodes a location in the source.
std::optional< llvm::MemoryBufferRef > getBufferOrNone(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
Token - This structure provides full information about a lexed token.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Top level wrappers for InstallAPI frontend operations.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
detail::SearchDirIteratorImpl< true > ConstSearchDirIterator
@ Result
The result type of a method or function.
@ TU_Complete
The translation unit is a complete translation unit.
CustomizableOptional< DirectoryEntryRef > OptionalDirectoryEntryRef
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.