clang 24.0.0git
PPLexerChange.cpp
Go to the documentation of this file.
1//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements pieces of the Preprocessor interface that manage the
10// current lexer stack.
11//
12//===----------------------------------------------------------------------===//
13
18#include "clang/Lex/MacroInfo.h"
21#include "llvm/ADT/StringSwitch.h"
22#include "llvm/Support/MemoryBufferRef.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/VirtualFileSystem.h"
25#include <optional>
26
27using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// Miscellaneous Methods.
31//===----------------------------------------------------------------------===//
32
33/// isInPrimaryFile - Return true if we're in the top-level file, not in a
34/// \#include. This looks through macro expansions and active _Pragma lexers.
36 if (IsFileLexer())
37 return IncludeMacroStack.empty();
38
39 // If there are any stacked lexers, we're in a #include.
40 assert(IsFileLexer(IncludeMacroStack[0]) &&
41 "Top level include stack isn't our primary lexer?");
42 return llvm::none_of(
43 llvm::drop_begin(IncludeMacroStack),
44 [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });
45}
46
47/// getCurrentLexer - Return the current file lexer being lexed from. Note
48/// that this ignores any potentially active macro expansions and _Pragma
49/// expansions going on at the time.
51 if (IsFileLexer())
52 return CurPPLexer;
53
54 // Look for a stacked lexer.
55 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
56 if (IsFileLexer(ISI))
57 return ISI.ThePPLexer;
58 }
59 return nullptr;
60}
61
62
63//===----------------------------------------------------------------------===//
64// Methods for Entering and Callbacks for leaving various contexts
65//===----------------------------------------------------------------------===//
66
67/// EnterSourceFile - Add a source file to the top of the include stack and
68/// start lexing tokens from it instead of the current buffer.
71 bool IsFirstIncludeOfFile) {
72 assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
73 ++NumEnteredSourceFiles;
74
75 if (MaxIncludeStackDepth < IncludeMacroStack.size())
76 MaxIncludeStackDepth = IncludeMacroStack.size();
77
78 // Get the MemoryBuffer for this FID, if it fails, we fail.
79 std::optional<llvm::MemoryBufferRef> InputFile =
81 if (!InputFile) {
82 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
83 Diag(Loc, diag::err_pp_error_opening_file)
84 << std::string(SourceMgr.getBufferName(FileStart)) << "";
85 return true;
86 }
87
89 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
90 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
91 CodeCompletionLoc =
92 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
93 }
94
95 auto TheLexer =
96 std::make_unique<Lexer>(FID, *InputFile, *this, IsFirstIncludeOfFile);
97 if (GetDependencyDirectives && FID != PredefinesFileID)
98 if (OptionalFileEntryRef File = SourceMgr.getFileEntryRefForID(FID))
99 if (auto MaybeDepDirectives = (*GetDependencyDirectives)(*File))
100 TheLexer->DepDirectives = *MaybeDepDirectives;
101
102 EnterSourceFileWithLexer(std::move(TheLexer), CurDir);
103 return false;
104}
105
106/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
107/// and start lexing tokens from it instead of the current buffer.
108void Preprocessor::EnterSourceFileWithLexer(std::unique_ptr<Lexer> TheLexer,
109 ConstSearchDirIterator CurDir) {
110 PreprocessorLexer *PrevPPLexer = CurPPLexer;
111
112 // Add the current lexer to the include stack.
113 if (CurPPLexer || CurTokenLexer)
114 PushIncludeMacroStack();
115
116 CurLexer = std::move(TheLexer);
117 CurPPLexer = CurLexer.get();
118 CurDirLookup = CurDir;
119 CurLexerSubmodule = nullptr;
120 CurLexerCallback = CurLexer->isDependencyDirectivesLexer()
121 ? CLK_DependencyDirectivesLexer
122 : CLK_Lexer;
123
124 // Notify the client, if desired, that we are in a new source file.
125 if (Callbacks && !CurLexer->Is_PragmaLexer) {
127 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
128
129 FileID PrevFID;
130 SourceLocation EnterLoc;
131 if (PrevPPLexer) {
132 PrevFID = PrevPPLexer->getFileID();
133 EnterLoc = PrevPPLexer->getSourceLocation();
134 }
135 Callbacks->FileChanged(CurLexer->getFileLoc(), PPCallbacks::EnterFile,
136 FileType, PrevFID);
137 Callbacks->LexedFileChanged(CurLexer->getFileID(),
139 FileType, PrevFID, EnterLoc);
140 }
141}
142
143/// EnterMacro - Add a Macro to the top of the include stack and start lexing
144/// tokens from it instead of the current buffer.
146 MacroInfo *Macro, MacroArgs *Args) {
147 std::unique_ptr<TokenLexer> TokLexer;
148 if (NumCachedTokenLexers == 0) {
149 TokLexer = std::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
150 } else {
151 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
152 TokLexer->Init(Tok, ILEnd, Macro, Args);
153 }
154
155 PushIncludeMacroStack();
156 CurDirLookup = nullptr;
157 CurTokenLexer = std::move(TokLexer);
158 CurLexerCallback = CLK_TokenLexer;
159}
160
161/// EnterTokenStream - Add a "macro" context to the top of the include stack,
162/// which will cause the lexer to start returning the specified tokens.
163///
164/// If DisableMacroExpansion is true, tokens lexed from the token stream will
165/// not be subject to further macro expansion. Otherwise, these tokens will
166/// be re-macro-expanded when/if expansion is enabled.
167///
168/// If OwnsTokens is false, this method assumes that the specified stream of
169/// tokens has a permanent owner somewhere, so they do not need to be copied.
170/// If it is true, it assumes the array of tokens is allocated with new[] and
171/// must be freed.
172///
173void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
174 bool DisableMacroExpansion, bool OwnsTokens,
175 bool IsReinject) {
176 if (InCachingLexMode()) {
177 if (CachedLexPos < CachedTokens.size()) {
178 assert(IsReinject && "new tokens in the middle of cached stream");
179 // We're entering tokens into the middle of our cached token stream. We
180 // can't represent that, so just insert the tokens into the buffer.
181 CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
182 Toks, Toks + NumToks);
183 if (OwnsTokens)
184 delete [] Toks;
185 return;
186 }
187
188 // New tokens are at the end of the cached token sequnece; insert the
189 // token stream underneath the caching lexer.
190 ExitCachingLexMode();
191 EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
192 IsReinject);
193 EnterCachingLexMode();
194 return;
195 }
196
197 // Create a macro expander to expand from the specified token stream.
198 std::unique_ptr<TokenLexer> TokLexer;
199 if (NumCachedTokenLexers == 0) {
200 TokLexer = std::make_unique<TokenLexer>(
201 Toks, NumToks, DisableMacroExpansion, OwnsTokens, IsReinject, *this);
202 } else {
203 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
204 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
205 IsReinject);
206 }
207
208 // Save our current state.
209 PushIncludeMacroStack();
210 CurDirLookup = nullptr;
211 CurTokenLexer = std::move(TokLexer);
212 CurLexerCallback = CLK_TokenLexer;
213}
214
215/// Compute the relative path that names the given file relative to
216/// the given directory.
219 Result.clear();
220
221 StringRef FilePath = File.getDir().getName();
222 StringRef Path = FilePath;
223 while (!Path.empty()) {
224 if (auto CurDir = FM.getOptionalDirectoryRef(Path)) {
225 if (*CurDir == Dir) {
226 Result = FilePath.substr(Path.size());
227 llvm::sys::path::append(Result,
228 llvm::sys::path::filename(File.getName()));
229 return;
230 }
231 }
232
233 Path = llvm::sys::path::parent_path(Path);
234 }
235
236 Result = File.getName();
237}
238
239void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
240 if (CurTokenLexer) {
241 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
242 return;
243 }
244 if (CurLexer) {
245 CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
246 return;
247 }
248 // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
249 // but it might if they're empty?
250}
251
252/// Determine the location to use as the end of the buffer for a lexer.
253///
254/// If the file ends with a newline, form the EOF token on the newline itself,
255/// rather than "on the line following it", which doesn't exist. This makes
256/// diagnostics relating to the end of file include the last file that the user
257/// actually typed, which is goodness.
258const char *Preprocessor::getCurLexerEndPos() {
259 const char *EndPos = CurLexer->BufferEnd;
260 if (EndPos != CurLexer->BufferStart &&
261 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
262 --EndPos;
263
264 // Handle \n\r and \r\n:
265 if (EndPos != CurLexer->BufferStart &&
266 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
267 EndPos[-1] != EndPos[0])
268 --EndPos;
269 }
270
271 return EndPos;
272}
273
275 const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
277 SubMods.push_back(&Mod);
278 for (Module *M : Mod.submodules())
280}
281
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,
289 ExpectedHeadersLoc))
290 return;
291
292 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
294 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
295 std::error_code EC;
296 for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
297 End;
298 Entry != End && !EC; Entry.increment(EC)) {
299 using llvm::StringSwitch;
300
301 // Check whether this entry has an extension typically associated with
302 // headers.
303 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
304 .Cases({".h", ".H", ".hh", ".hpp"}, true)
305 .Default(false))
306 continue;
307
308 if (auto Header = getFileManager().getOptionalFileRef(Entry->path()))
309 if (!getSourceManager().hasFileInfo(*Header)) {
310 if (!ModMap.isHeaderInUnavailableModule(*Header)) {
311 // Find the relative path that would access this header.
312 SmallString<128> RelativePath;
313 computeRelativePath(FileMgr, *Dir, *Header, RelativePath);
314 Diag(ExpectedHeadersLoc, diag::warn_uncovered_module_header)
315 << Mod.getFullModuleName() << RelativePath;
316 }
317 }
318 }
319}
320
321/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
322/// the current file. This either returns the EOF token or pops a level off
323/// the include stack and keeps going.
324bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
325 assert(!CurTokenLexer &&
326 "Ending a file when currently in a macro!");
327
328 SourceLocation UnclosedSafeBufferOptOutLoc;
329
330 if (IncludeMacroStack.empty() &&
331 isPPInSafeBufferOptOutRegion(UnclosedSafeBufferOptOutLoc)) {
332 // To warn if a "-Wunsafe-buffer-usage" opt-out region is still open by the
333 // end of a file.
334 Diag(UnclosedSafeBufferOptOutLoc,
335 diag::err_pp_unclosed_pragma_unsafe_buffer_usage);
336 }
337 // If we have an unclosed module region from a pragma at the end of a
338 // module, complain and close it now.
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);
345 Module *M = LeaveSubmodule(/*ForPragma*/true);
346
347 Result.startToken();
348 const char *EndPos = getCurLexerEndPos();
349 CurLexer->BufferPtr = EndPos;
350 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
351 Result.setAnnotationEndLoc(Result.getLocation());
352 Result.setAnnotationValue(M);
353 return true;
354 }
355
356 // See if this file had a controlling macro.
357 if (CurPPLexer) { // Not ending a macro, ignore it.
358 if (const IdentifierInfo *ControllingMacro =
359 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
360 // Okay, this has a controlling macro, remember in HeaderFileInfo.
361 if (OptionalFileEntryRef FE = CurPPLexer->getFileEntry()) {
362 HeaderInfo.SetFileControllingMacro(*FE, ControllingMacro);
363 if (MacroInfo *MI = getMacroInfo(ControllingMacro))
364 MI->setUsedForHeaderGuard(true);
365 if (const IdentifierInfo *DefinedMacro =
366 CurPPLexer->MIOpt.GetDefinedMacro()) {
367 if (!isMacroDefined(ControllingMacro) &&
368 DefinedMacro != ControllingMacro &&
369 CurLexer->isFirstTimeLexingFile()) {
370
371 // If the edit distance between the two macros is more than 50%,
372 // DefinedMacro may not be header guard, or can be header guard of
373 // another header file. Therefore, it maybe defining something
374 // completely different. This can be observed in the wild when
375 // handling feature macros or header guards in different files.
376
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) {
384 // Emit a warning for a bad header guard.
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
391 << ControllingMacro
393 CurPPLexer->MIOpt.GetDefinedLocation(),
394 ControllingMacro->getName());
395 }
396 }
397 }
398 }
399 }
400 }
401
402 // Complain about reaching a true EOF within arc_cf_code_audited.
403 // We don't want to complain about reaching the end of a macro
404 // instantiation or a _Pragma.
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);
409
410 // Recover by leaving immediately.
411 PragmaARCCFCodeAuditedInfo = IdentifierLoc();
412 }
413
414 // Complain about reaching a true EOF within assume_nonnull.
415 // We don't want to complain about reaching the end of a macro
416 // instantiation or a _Pragma.
417 if (PragmaAssumeNonNullLoc.isValid() &&
418 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
419 // If we're at the end of generating a preamble, we should record the
420 // unterminated \#pragma clang assume_nonnull so we can restore it later
421 // when the preamble is loaded into the main file.
423 PreambleRecordedPragmaAssumeNonNullLoc = PragmaAssumeNonNullLoc;
424 else
425 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
426 // Recover by leaving immediately.
427 PragmaAssumeNonNullLoc = SourceLocation();
428 }
429
430 bool LeavingPCHThroughHeader = false;
431
432 // If this is a #include'd file, pop it off the include stack and continue
433 // lexing the #includer file.
434 if (!IncludeMacroStack.empty()) {
435
436 // If we lexed the code-completion file, act as if we reached EOF.
437 if (isCodeCompletionEnabled() && CurPPLexer &&
438 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
439 CodeCompletionFileLoc) {
440 assert(CurLexer && "Got EOF but no current lexer set!");
441 Result.startToken();
442 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
443 PendingDestroyLexers.push_back(std::move(CurLexer));
444
445 CurPPLexer = nullptr;
447 return true;
448 }
449
450 if (!isEndOfMacro && CurPPLexer &&
451 (SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid() ||
452 // Predefines file doesn't have a valid include location.
453 (PredefinesFileID.isValid() &&
454 CurPPLexer->getFileID() == PredefinesFileID))) {
455 // Notify SourceManager to record the number of FileIDs that were created
456 // during lexing of the #include'd file.
457 unsigned NumFIDs =
458 SourceMgr.local_sloc_entry_size() -
459 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
460 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
461 }
462
463 bool ExitedFromPredefinesFile = false;
464 FileID ExitedFID;
465 if (!isEndOfMacro && CurPPLexer) {
466 ExitedFID = CurPPLexer->getFileID();
467
468 assert(PredefinesFileID.isValid() &&
469 "HandleEndOfFile is called before PredefinesFileId is set");
470 ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
471 }
472
473 if (LeavingSubmodule) {
474 // We're done with this submodule.
475 Module *M = LeaveSubmodule(/*ForPragma*/false);
476
477 // Notify the parser that we've left the module.
478 const char *EndPos = getCurLexerEndPos();
479 Result.startToken();
480 CurLexer->BufferPtr = EndPos;
481 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
482 Result.setAnnotationEndLoc(Result.getLocation());
483 Result.setAnnotationValue(M);
484 }
485
486 bool FoundPCHThroughHeader = false;
487 if (CurPPLexer && creatingPCHWithThroughHeader() &&
489 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
490 FoundPCHThroughHeader = true;
491
492 // We're done with the #included file.
494
495 // Propagate info about start-of-line/leading white-space/etc.
496 PropagateLineStartLeadingSpaceInfo(Result);
497
498 // Notify the client, if desired, that we are in a new source file.
499 if (Callbacks && !isEndOfMacro && CurPPLexer) {
500 SourceLocation Loc = CurPPLexer->getSourceLocation();
502 SourceMgr.getFileCharacteristic(Loc);
503 Callbacks->FileChanged(Loc, PPCallbacks::ExitFile, FileType, ExitedFID);
504 Callbacks->LexedFileChanged(CurPPLexer->getFileID(),
506 FileType, ExitedFID, Loc);
507 }
508
509 // Restore conditional stack as well as the recorded
510 // \#pragma clang assume_nonnull from the preamble right after exiting
511 // from the predefines file.
512 if (ExitedFromPredefinesFile) {
513 replayPreambleConditionalStack();
514 if (PreambleRecordedPragmaAssumeNonNullLoc.isValid())
515 PragmaAssumeNonNullLoc = PreambleRecordedPragmaAssumeNonNullLoc;
516 }
517
518 if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
519 (isInPrimaryFile() ||
520 CurPPLexer->getFileID() == getPredefinesFileID())) {
521 // Leaving the through header. Continue directly to end of main file
522 // processing.
523 LeavingPCHThroughHeader = true;
524 } else {
525 // Client should lex another token unless we generated an EOM.
526 return LeavingSubmodule;
527 }
528 }
529 // If this is the end of the main file, form an EOF token.
530 assert(CurLexer && "Got EOF but no current lexer set!");
531 const char *EndPos = getCurLexerEndPos();
532 Result.startToken();
533 CurLexer->BufferPtr = EndPos;
534
535 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
536
538 // Inserting the code-completion point increases the source buffer by 1,
539 // but the main FileID was created before inserting the point.
540 // Compensate by reducing the EOF location by 1, otherwise the location
541 // will point to the next FileID.
542 // FIXME: This is hacky, the code-completion point should probably be
543 // inserted before the main FileID is created.
544 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
545 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
546 }
547
548 if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
549 // Reached the end of the compilation without finding the through header.
550 Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
551 << PPOpts.PCHThroughHeader << 0;
552 }
553
555 // We're done with lexing. If we're inside a nested Lex call (LexLevel > 0),
556 // defer destruction of the lexer until Lex returns to avoid use-after-free
557 // when HandleEndOfFile is called from within Lexer methods that still need
558 // to access their members after this function returns.
559 if (LexLevel > 0 && CurLexer) {
560 PendingDestroyLexers.push_back(std::move(CurLexer));
561 } else {
562 CurLexer.reset();
563 }
564 }
565
567 CurPPLexer = nullptr;
568
569 if (TUKind == TU_Complete) {
570 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
571 // collected all macro locations that we need to warn because they are not
572 // used.
573 for (WarnUnusedMacroLocsTy::iterator
574 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
575 I!=E; ++I)
576 Diag(*I, diag::pp_macro_not_used);
577 }
578
579 // If we are building a module that has an umbrella header, make sure that
580 // each of the headers within the directory, including all submodules, is
581 // covered by the umbrella header was actually included by the umbrella
582 // header.
583 if (Module *Mod = getCurrentModule()) {
586 for (auto *M : AllMods)
587 diagnoseMissingHeaderInUmbrellaDir(*M);
588 }
589
590 return true;
591}
592
593/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
594/// hits the end of its token stream.
596 assert(CurTokenLexer && !CurPPLexer &&
597 "Ending a macro when currently in a #include file!");
598
599 if (!MacroExpandingLexersStack.empty() &&
600 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
601 removeCachedMacroExpandedTokensOfLastLexer();
602
603 // Delete or cache the now-dead macro expander.
604 if (NumCachedTokenLexers == TokenLexerCacheSize)
605 CurTokenLexer.reset();
606 else
607 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
608
609 // Handle this like a #include file being popped off the stack.
610 return HandleEndOfFile(Result, true);
611}
612
613/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
614/// lexer stack. This should only be used in situations where the current
615/// state of the top-of-stack lexer is unknown.
617 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
618
619 if (CurTokenLexer) {
620 // Delete or cache the now-dead macro expander.
621 if (NumCachedTokenLexers == TokenLexerCacheSize)
622 CurTokenLexer.reset();
623 else
624 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
625 }
626
627 PopIncludeMacroStack();
628}
629
630/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
631/// comment (/##/) in microsoft mode, this method handles updating the current
632/// state, returning the token on the next source line.
634 assert(CurTokenLexer && !CurPPLexer &&
635 "Pasted comment can only be formed from macro");
636 // We handle this by scanning for the closest real lexer, switching it to
637 // raw mode and preprocessor mode. This will cause it to return \n as an
638 // explicit EOD token.
639 PreprocessorLexer *FoundLexer = nullptr;
640 bool LexerWasInPPMode = false;
641 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
642 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
643
644 // Once we find a real lexer, mark it as raw mode (disabling macro
645 // expansions) and preprocessor mode (return EOD). We know that the lexer
646 // was *not* in raw mode before, because the macro that the comment came
647 // from was expanded. However, it could have already been in preprocessor
648 // mode (#if COMMENT) in which case we have to return it to that mode and
649 // return EOD.
650 FoundLexer = ISI.ThePPLexer;
651 FoundLexer->LexingRawMode = true;
652 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
653 FoundLexer->ParsingPreprocessorDirective = true;
654 break;
655 }
656
657 // Okay, we either found and switched over the lexer, or we didn't find a
658 // lexer. In either case, finish off the macro the comment came from, getting
659 // the next token.
661
662 // Discarding comments as long as we don't have EOF or EOD. This 'comments
663 // out' the rest of the line, including any tokens that came from other macros
664 // that were active, as in:
665 // #define submacro a COMMENT b
666 // submacro c
667 // which should lex to 'a' only: 'b' and 'c' should be removed.
668 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
669 Lex(Tok);
670
671 // If we got an eod token, then we successfully found the end of the line.
672 if (Tok.is(tok::eod)) {
673 assert(FoundLexer && "Can't get end of line without an active lexer");
674 // Restore the lexer back to normal mode instead of raw mode.
675 FoundLexer->LexingRawMode = false;
676
677 // If the lexer was already in preprocessor mode, just return the EOD token
678 // to finish the preprocessor line.
679 if (LexerWasInPPMode) return;
680
681 // Otherwise, switch out of PP mode and return the next lexed token.
682 FoundLexer->ParsingPreprocessorDirective = false;
683 return Lex(Tok);
684 }
685
686 // If we got an EOF token, then we reached the end of the token stream but
687 // didn't find an explicit \n. This can only happen if there was no lexer
688 // active (an active lexer would return EOD at EOF if there was no \n in
689 // preprocessor directive mode), so just return EOF as our token.
690 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
691}
692
694 bool ForPragma) {
695 if (!getLangOpts().ModulesLocalVisibility) {
696 // Just track that we entered this submodule.
697 BuildingSubmoduleStack.push_back(
698 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
699 PendingModuleMacroNames.size()));
700 if (Callbacks)
701 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
702 return;
703 }
704
705 // Resolve as much of the module definition as we can now, before we enter
706 // one of its headers.
707 // FIXME: Can we enable Complain here?
708 // FIXME: Can we do this when local visibility is disabled?
710 ModMap.resolveExports(M, /*Complain=*/false);
711 ModMap.resolveUses(M, /*Complain=*/false);
712 ModMap.resolveConflicts(M, /*Complain=*/false);
713
714 // If this is the first time we've entered this module, set up its state.
715 auto R = Submodules.try_emplace(M);
716 auto &State = R.first->second;
717 bool FirstTime = R.second;
718 if (FirstTime) {
719 // Determine the set of starting macros for this submodule; take these
720 // from the "null" module (the predefines buffer).
721 //
722 // FIXME: If we have local visibility but not modules enabled, the
723 // NullSubmoduleState is polluted by #defines in the top-level source
724 // file.
725 auto &StartingMacros = NullSubmoduleState.Macros;
726
727 // Restore to the starting state.
728 // FIXME: Do this lazily, when each macro name is first referenced.
729 for (auto &Macro : StartingMacros) {
730 // Skip uninteresting macros.
731 if (!Macro.second.getLatest() &&
732 Macro.second.getOverriddenMacros().empty())
733 continue;
734
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)));
738 }
739 }
740
741 // Track that we entered this module.
742 BuildingSubmoduleStack.push_back(
743 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
744 PendingModuleMacroNames.size()));
745
746 if (Callbacks)
747 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
748
749 // Switch to this submodule as the current submodule.
750 CurSubmoduleState = &State;
751
752 // This module is visible to itself, but exports should not be made visible
753 // until they are imported.
754 if (FirstTime)
755 makeModuleVisible(M, ImportLoc, /*IncludeExports=*/false);
756}
757
758bool Preprocessor::needModuleMacros() const {
759 // If we're not within a submodule, we never need to create ModuleMacros.
760 if (BuildingSubmoduleStack.empty())
761 return false;
762 // If we are tracking module macro visibility even for textually-included
763 // headers, we need ModuleMacros.
764 if (getLangOpts().ModulesLocalVisibility)
765 return true;
766 // Otherwise, we only need module macros if we're actually compiling a module
767 // interface.
769}
770
772 if (BuildingSubmoduleStack.empty() ||
773 BuildingSubmoduleStack.back().IsPragma != ForPragma) {
774 assert(ForPragma && "non-pragma module enter/leave mismatch");
775 return nullptr;
776 }
777
778 auto &Info = BuildingSubmoduleStack.back();
779
780 Module *LeavingMod = Info.M;
781 SourceLocation ImportLoc = Info.ImportLoc;
782
783 if (!needModuleMacros() ||
784 (!getLangOpts().ModulesLocalVisibility &&
785 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
786 // If we don't need module macros, or this is not a module for which we
787 // are tracking macro visibility, don't build any, and preserve the list
788 // of pending names for the surrounding submodule.
789 BuildingSubmoduleStack.pop_back();
790
791 if (Callbacks)
792 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
793
794 makeModuleVisible(LeavingMod, ImportLoc);
795 return LeavingMod;
796 }
797
798 // Create ModuleMacros for any macros defined in this submodule.
800 for (unsigned I = Info.OuterPendingModuleMacroNames;
801 I != PendingModuleMacroNames.size(); ++I) {
802 auto *II = PendingModuleMacroNames[I];
803 if (!VisitedMacros.insert(II).second)
804 continue;
805
806 auto MacroIt = CurSubmoduleState->Macros.find(II);
807 if (MacroIt == CurSubmoduleState->Macros.end())
808 continue;
809 auto &Macro = MacroIt->second;
810
811 // Find the starting point for the MacroDirective chain in this submodule.
812 MacroDirective *OldMD = nullptr;
813 auto *OldState = Info.OuterSubmoduleState;
814 if (getLangOpts().ModulesLocalVisibility)
815 OldState = &NullSubmoduleState;
816 if (OldState && OldState != CurSubmoduleState) {
817 // FIXME: It'd be better to start at the state from when we most recently
818 // entered this submodule, but it doesn't really matter.
819 auto &OldMacros = OldState->Macros;
820 auto OldMacroIt = OldMacros.find(II);
821 if (OldMacroIt == OldMacros.end())
822 OldMD = nullptr;
823 else
824 OldMD = OldMacroIt->second.getLatest();
825 }
826
827 // This module may have exported a new macro. If so, create a ModuleMacro
828 // representing that fact.
829 bool ExplicitlyPublic = false;
830 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
831 assert(MD && "broken macro directive chain");
832
833 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
834 // The latest visibility directive for a name in a submodule affects
835 // all the directives that come before it.
836 if (VisMD->isPublic())
837 ExplicitlyPublic = true;
838 else if (!ExplicitlyPublic)
839 // Private with no following public directive: not exported.
840 break;
841 } else {
842 MacroInfo *Def = nullptr;
843 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
844 Def = DefMD->getInfo();
845
846 // FIXME: Issue a warning if multiple headers for the same submodule
847 // define a macro, rather than silently ignoring all but the first.
848 bool IsNew;
849 // Don't bother creating a module macro if it would represent a #undef
850 // that doesn't override anything.
851 if (Def || !Macro.getOverriddenMacros().empty())
852 addModuleMacro(LeavingMod, II, Def, Macro.getOverriddenMacros(),
853 IsNew);
854
855 if (!getLangOpts().ModulesLocalVisibility) {
856 // This macro is exposed to the rest of this compilation as a
857 // ModuleMacro; we don't need to track its MacroDirective any more.
858 Macro.setLatest(nullptr);
859 Macro.setOverriddenMacros(*this, {});
860 }
861 break;
862 }
863 }
864 }
865 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
866
867 // FIXME: Before we leave this submodule, we should parse all the other
868 // headers within it. Otherwise, we're left with an inconsistent state
869 // where we've made the module visible but don't yet have its complete
870 // contents.
871
872 // Put back the outer module's state, if we're tracking it.
873 if (getLangOpts().ModulesLocalVisibility)
874 CurSubmoduleState = Info.OuterSubmoduleState;
875
876 BuildingSubmoduleStack.pop_back();
877
878 if (Callbacks)
879 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
880
881 // A nested #include makes the included submodule visible.
882 makeModuleVisible(LeavingMod, ImportLoc);
883 return LeavingMod;
884}
Defines the clang::FileManager interface and associated types.
Token Tok
The Token.
static StringRef computeRelativePath(StringRef FileName, StringRef DirPath)
Compute relative path from DirPath to FileName by stripping the DirPath prefix.
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::FileType FileType
Definition MachO.h:46
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.
Definition MacroInfo.h:433
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...
Definition FileEntry.h:57
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.
Definition FileManager.h:57
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.
Definition Diagnostic.h:140
ModuleMap & getModuleMap()
Retrieve the module map.
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,...
Definition MacroInfo.h:314
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition MacroInfo.h:355
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:40
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.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:953
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:1079
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:988
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:242
OptionalDirectoryEntryRef getEffectiveUmbrellaDir() const
Get the effective umbrella directory for this module: either the one explicitly written in the module...
Definition Module.cpp:266
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)
friend class MacroArgs
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.
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.
Definition Token.h:36
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
Definition FileEntry.h:196
detail::SearchDirIteratorImpl< true > ConstSearchDirIterator
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ 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.
Definition DeclSpec.h:218