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 if (getLangOpts().IncrementalExtensions) {
536 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_repl_input_end);
537 Result.setAnnotationEndLoc(Result.getLocation());
538 Result.setAnnotationValue(nullptr);
539 } else {
540 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
541 }
542
544 // Inserting the code-completion point increases the source buffer by 1,
545 // but the main FileID was created before inserting the point.
546 // Compensate by reducing the EOF location by 1, otherwise the location
547 // will point to the next FileID.
548 // FIXME: This is hacky, the code-completion point should probably be
549 // inserted before the main FileID is created.
550 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
551 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
552 }
553
554 if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
555 // Reached the end of the compilation without finding the through header.
556 Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
557 << PPOpts.PCHThroughHeader << 0;
558 }
559
561 // We're done with lexing. If we're inside a nested Lex call (LexLevel > 0),
562 // defer destruction of the lexer until Lex returns to avoid use-after-free
563 // when HandleEndOfFile is called from within Lexer methods that still need
564 // to access their members after this function returns.
565 if (LexLevel > 0 && CurLexer) {
566 PendingDestroyLexers.push_back(std::move(CurLexer));
567 } else {
568 CurLexer.reset();
569 }
570 }
571
573 CurPPLexer = nullptr;
574
575 if (TUKind == TU_Complete) {
576 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
577 // collected all macro locations that we need to warn because they are not
578 // used.
579 for (WarnUnusedMacroLocsTy::iterator
580 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
581 I!=E; ++I)
582 Diag(*I, diag::pp_macro_not_used);
583 }
584
585 // If we are building a module that has an umbrella header, make sure that
586 // each of the headers within the directory, including all submodules, is
587 // covered by the umbrella header was actually included by the umbrella
588 // header.
589 if (Module *Mod = getCurrentModule()) {
592 for (auto *M : AllMods)
593 diagnoseMissingHeaderInUmbrellaDir(*M);
594 }
595
596 return true;
597}
598
599/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
600/// hits the end of its token stream.
602 assert(CurTokenLexer && !CurPPLexer &&
603 "Ending a macro when currently in a #include file!");
604
605 if (!MacroExpandingLexersStack.empty() &&
606 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
607 removeCachedMacroExpandedTokensOfLastLexer();
608
609 // Delete or cache the now-dead macro expander.
610 if (NumCachedTokenLexers == TokenLexerCacheSize)
611 CurTokenLexer.reset();
612 else
613 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
614
615 // Handle this like a #include file being popped off the stack.
616 return HandleEndOfFile(Result, true);
617}
618
619/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
620/// lexer stack. This should only be used in situations where the current
621/// state of the top-of-stack lexer is unknown.
623 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
624
625 if (CurTokenLexer) {
626 // Delete or cache the now-dead macro expander.
627 if (NumCachedTokenLexers == TokenLexerCacheSize)
628 CurTokenLexer.reset();
629 else
630 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
631 }
632
633 PopIncludeMacroStack();
634}
635
636/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
637/// comment (/##/) in microsoft mode, this method handles updating the current
638/// state, returning the token on the next source line.
640 assert(CurTokenLexer && !CurPPLexer &&
641 "Pasted comment can only be formed from macro");
642 // We handle this by scanning for the closest real lexer, switching it to
643 // raw mode and preprocessor mode. This will cause it to return \n as an
644 // explicit EOD token.
645 PreprocessorLexer *FoundLexer = nullptr;
646 bool LexerWasInPPMode = false;
647 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
648 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
649
650 // Once we find a real lexer, mark it as raw mode (disabling macro
651 // expansions) and preprocessor mode (return EOD). We know that the lexer
652 // was *not* in raw mode before, because the macro that the comment came
653 // from was expanded. However, it could have already been in preprocessor
654 // mode (#if COMMENT) in which case we have to return it to that mode and
655 // return EOD.
656 FoundLexer = ISI.ThePPLexer;
657 FoundLexer->LexingRawMode = true;
658 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
659 FoundLexer->ParsingPreprocessorDirective = true;
660 break;
661 }
662
663 // Okay, we either found and switched over the lexer, or we didn't find a
664 // lexer. In either case, finish off the macro the comment came from, getting
665 // the next token.
667
668 // Discarding comments as long as we don't have EOF or EOD. This 'comments
669 // out' the rest of the line, including any tokens that came from other macros
670 // that were active, as in:
671 // #define submacro a COMMENT b
672 // submacro c
673 // which should lex to 'a' only: 'b' and 'c' should be removed.
674 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
675 Lex(Tok);
676
677 // If we got an eod token, then we successfully found the end of the line.
678 if (Tok.is(tok::eod)) {
679 assert(FoundLexer && "Can't get end of line without an active lexer");
680 // Restore the lexer back to normal mode instead of raw mode.
681 FoundLexer->LexingRawMode = false;
682
683 // If the lexer was already in preprocessor mode, just return the EOD token
684 // to finish the preprocessor line.
685 if (LexerWasInPPMode) return;
686
687 // Otherwise, switch out of PP mode and return the next lexed token.
688 FoundLexer->ParsingPreprocessorDirective = false;
689 return Lex(Tok);
690 }
691
692 // If we got an EOF token, then we reached the end of the token stream but
693 // didn't find an explicit \n. This can only happen if there was no lexer
694 // active (an active lexer would return EOD at EOF if there was no \n in
695 // preprocessor directive mode), so just return EOF as our token.
696 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
697}
698
700 bool ForPragma) {
701 if (!getLangOpts().ModulesLocalVisibility) {
702 // Just track that we entered this submodule.
703 BuildingSubmoduleStack.push_back(
704 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
705 PendingModuleMacroNames.size()));
706 if (Callbacks)
707 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
708 return;
709 }
710
711 // Resolve as much of the module definition as we can now, before we enter
712 // one of its headers.
713 // FIXME: Can we enable Complain here?
714 // FIXME: Can we do this when local visibility is disabled?
716 ModMap.resolveExports(M, /*Complain=*/false);
717 ModMap.resolveUses(M, /*Complain=*/false);
718 ModMap.resolveConflicts(M, /*Complain=*/false);
719
720 // If this is the first time we've entered this module, set up its state.
721 auto R = Submodules.try_emplace(M);
722 auto &State = R.first->second;
723 bool FirstTime = R.second;
724 if (FirstTime) {
725 // Determine the set of starting macros for this submodule; take these
726 // from the "null" module (the predefines buffer).
727 //
728 // FIXME: If we have local visibility but not modules enabled, the
729 // NullSubmoduleState is polluted by #defines in the top-level source
730 // file.
731 auto &StartingMacros = NullSubmoduleState.Macros;
732
733 // Restore to the starting state.
734 // FIXME: Do this lazily, when each macro name is first referenced.
735 for (auto &Macro : StartingMacros) {
736 // Skip uninteresting macros.
737 if (!Macro.second.getLatest() &&
738 Macro.second.getOverriddenMacros().empty())
739 continue;
740
741 MacroState MS(Macro.second.getLatest());
742 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
743 State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
744 }
745 }
746
747 // Track that we entered this module.
748 BuildingSubmoduleStack.push_back(
749 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
750 PendingModuleMacroNames.size()));
751
752 if (Callbacks)
753 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
754
755 // Switch to this submodule as the current submodule.
756 CurSubmoduleState = &State;
757
758 // This module is visible to itself, but exports should not be made visible
759 // until they are imported.
760 if (FirstTime)
761 makeModuleVisible(M, ImportLoc, /*IncludeExports=*/false);
762}
763
764bool Preprocessor::needModuleMacros() const {
765 // If we're not within a submodule, we never need to create ModuleMacros.
766 if (BuildingSubmoduleStack.empty())
767 return false;
768 // If we are tracking module macro visibility even for textually-included
769 // headers, we need ModuleMacros.
770 if (getLangOpts().ModulesLocalVisibility)
771 return true;
772 // Otherwise, we only need module macros if we're actually compiling a module
773 // interface.
775}
776
778 if (BuildingSubmoduleStack.empty() ||
779 BuildingSubmoduleStack.back().IsPragma != ForPragma) {
780 assert(ForPragma && "non-pragma module enter/leave mismatch");
781 return nullptr;
782 }
783
784 auto &Info = BuildingSubmoduleStack.back();
785
786 Module *LeavingMod = Info.M;
787 SourceLocation ImportLoc = Info.ImportLoc;
788
789 if (!needModuleMacros() ||
790 (!getLangOpts().ModulesLocalVisibility &&
791 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
792 // If we don't need module macros, or this is not a module for which we
793 // are tracking macro visibility, don't build any, and preserve the list
794 // of pending names for the surrounding submodule.
795 BuildingSubmoduleStack.pop_back();
796
797 if (Callbacks)
798 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
799
800 makeModuleVisible(LeavingMod, ImportLoc);
801 return LeavingMod;
802 }
803
804 // Create ModuleMacros for any macros defined in this submodule.
806 for (unsigned I = Info.OuterPendingModuleMacroNames;
807 I != PendingModuleMacroNames.size(); ++I) {
808 auto *II = PendingModuleMacroNames[I];
809 if (!VisitedMacros.insert(II).second)
810 continue;
811
812 auto MacroIt = CurSubmoduleState->Macros.find(II);
813 if (MacroIt == CurSubmoduleState->Macros.end())
814 continue;
815 auto &Macro = MacroIt->second;
816
817 // Find the starting point for the MacroDirective chain in this submodule.
818 MacroDirective *OldMD = nullptr;
819 auto *OldState = Info.OuterSubmoduleState;
820 if (getLangOpts().ModulesLocalVisibility)
821 OldState = &NullSubmoduleState;
822 if (OldState && OldState != CurSubmoduleState) {
823 // FIXME: It'd be better to start at the state from when we most recently
824 // entered this submodule, but it doesn't really matter.
825 auto &OldMacros = OldState->Macros;
826 auto OldMacroIt = OldMacros.find(II);
827 if (OldMacroIt == OldMacros.end())
828 OldMD = nullptr;
829 else
830 OldMD = OldMacroIt->second.getLatest();
831 }
832
833 // This module may have exported a new macro. If so, create a ModuleMacro
834 // representing that fact.
835 bool ExplicitlyPublic = false;
836 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
837 assert(MD && "broken macro directive chain");
838
839 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
840 // The latest visibility directive for a name in a submodule affects
841 // all the directives that come before it.
842 if (VisMD->isPublic())
843 ExplicitlyPublic = true;
844 else if (!ExplicitlyPublic)
845 // Private with no following public directive: not exported.
846 break;
847 } else {
848 MacroInfo *Def = nullptr;
849 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
850 Def = DefMD->getInfo();
851
852 // FIXME: Issue a warning if multiple headers for the same submodule
853 // define a macro, rather than silently ignoring all but the first.
854 bool IsNew;
855 // Don't bother creating a module macro if it would represent a #undef
856 // that doesn't override anything.
857 if (Def || !Macro.getOverriddenMacros().empty())
858 addModuleMacro(LeavingMod, II, Def, Macro.getOverriddenMacros(),
859 IsNew);
860
861 if (!getLangOpts().ModulesLocalVisibility) {
862 // This macro is exposed to the rest of this compilation as a
863 // ModuleMacro; we don't need to track its MacroDirective any more.
864 Macro.setLatest(nullptr);
865 Macro.setOverriddenMacros(*this, {});
866 }
867 break;
868 }
869 }
870 }
871 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
872
873 // FIXME: Before we leave this submodule, we should parse all the other
874 // headers within it. Otherwise, we're left with an inconsistent state
875 // where we've made the module visible but don't yet have its complete
876 // contents.
877
878 // Put back the outer module's state, if we're tracking it.
879 if (getLangOpts().ModulesLocalVisibility)
880 CurSubmoduleState = Info.OuterSubmoduleState;
881
882 BuildingSubmoduleStack.pop_back();
883
884 if (Callbacks)
885 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
886
887 // A nested #include makes the included submodule visible.
888 makeModuleVisible(LeavingMod, ImportLoc);
889 return LeavingMod;
890}
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:142
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:950
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:1067
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:985
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:240
OptionalDirectoryEntryRef getEffectiveUmbrellaDir() const
Get the effective umbrella directory for this module: either the one explicitly written in the module...
Definition Module.cpp:264
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:1256