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
14#include "clang/Basic/FileManager.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/LexDiagnostic.h"
18#include "clang/Lex/MacroInfo.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/PreprocessorOptions.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.
35bool Preprocessor::isInPrimaryFile() const {
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 Range: llvm::drop_begin(RangeOrContainer: IncludeMacroStack),
44 P: [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(I: 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.
50PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
51 if (IsFileLexer())
52 return CurPPLexer;
53
54 // Look for a stacked lexer.
55 for (const IncludeStackInfo &ISI : llvm::reverse(C: IncludeMacroStack)) {
56 if (IsFileLexer(I: 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.
69bool Preprocessor::EnterSourceFile(FileID FID, ConstSearchDirIterator CurDir,
70 SourceLocation Loc,
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 =
80 getSourceManager().getBufferOrNone(FID, Loc);
81 if (!InputFile) {
82 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
83 Diag(Loc, DiagID: diag::err_pp_error_opening_file)
84 << std::string(SourceMgr.getBufferName(Loc: FileStart)) << "";
85 return true;
86 }
87
88 if (isCodeCompletionEnabled() &&
89 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
90 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
91 CodeCompletionLoc =
92 CodeCompletionFileLoc.getLocWithOffset(Offset: CodeCompletionOffset);
93 }
94
95 auto TheLexer =
96 std::make_unique<Lexer>(args&: FID, args&: *InputFile, args&: *this, args&: 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(TheLexer: std::move(TheLexer), Dir: 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) {
126 SrcMgr::CharacteristicKind FileType =
127 SourceMgr.getFileCharacteristic(Loc: CurLexer->getFileLoc());
128
129 FileID PrevFID;
130 SourceLocation EnterLoc;
131 if (PrevPPLexer) {
132 PrevFID = PrevPPLexer->getFileID();
133 EnterLoc = PrevPPLexer->getSourceLocation();
134 }
135 Callbacks->FileChanged(Loc: CurLexer->getFileLoc(), Reason: PPCallbacks::EnterFile,
136 FileType, PrevFID);
137 Callbacks->LexedFileChanged(FID: CurLexer->getFileID(),
138 Reason: PPCallbacks::LexedFileChangeReason::EnterFile,
139 FileType, PrevFID, Loc: 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.
145void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
146 MacroInfo *Macro, MacroArgs *Args) {
147 std::unique_ptr<TokenLexer> TokLexer;
148 if (NumCachedTokenLexers == 0) {
149 TokLexer = std::make_unique<TokenLexer>(args&: Tok, args&: ILEnd, args&: Macro, args&: Args, args&: *this);
150 } else {
151 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
152 TokLexer->Init(Tok, ELEnd: ILEnd, MI: Macro, Actuals: 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(I: CachedTokens.begin() + CachedLexPos,
182 From: Toks, To: 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 args&: Toks, args&: NumToks, args&: DisableMacroExpansion, args&: OwnsTokens, args&: IsReinject, args&: *this);
202 } else {
203 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
204 TokLexer->Init(TokArray: 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.
217static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
218 FileEntryRef File, SmallString<128> &Result) {
219 Result.clear();
220
221 StringRef FilePath = File.getDir().getName();
222 StringRef Path = FilePath;
223 while (!Path.empty()) {
224 if (auto CurDir = FM.getOptionalDirectoryRef(DirName: Path)) {
225 if (*CurDir == Dir) {
226 Result = FilePath.substr(Start: Path.size());
227 llvm::sys::path::append(path&: Result,
228 a: llvm::sys::path::filename(path: File.getName()));
229 return;
230 }
231 }
232
233 Path = llvm::sys::path::parent_path(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
274static void collectAllSubModulesWithUmbrellaHeader(
275 const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
276 if (Mod.getUmbrellaHeaderAsWritten())
277 SubMods.push_back(Elt: &Mod);
278 for (Module *M : Mod.submodules())
279 collectAllSubModulesWithUmbrellaHeader(Mod: *M, SubMods);
280}
281
282void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
283 std::optional<Module::Header> UmbrellaHeader =
284 Mod.getUmbrellaHeaderAsWritten();
285 assert(UmbrellaHeader && "Module must use umbrella header");
286 const FileID &File = SourceMgr.translateFile(SourceFile: UmbrellaHeader->Entry);
287 SourceLocation ExpectedHeadersLoc = SourceMgr.getLocForEndOfFile(FID: File);
288 if (getDiagnostics().isIgnored(DiagID: diag::warn_uncovered_module_header,
289 Loc: ExpectedHeadersLoc))
290 return;
291
292 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
293 OptionalDirectoryEntryRef Dir = Mod.getEffectiveUmbrellaDir();
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(path: Entry->path()))
304 .Cases(CaseStrings: {".h", ".H", ".hh", ".hpp"}, Value: true)
305 .Default(Value: false))
306 continue;
307
308 if (auto Header = getFileManager().getOptionalFileRef(Filename: Entry->path()))
309 if (!getSourceManager().hasFileInfo(File: *Header)) {
310 if (!ModMap.isHeaderInUnavailableModule(Header: *Header)) {
311 // Find the relative path that would access this header.
312 SmallString<128> RelativePath;
313 computeRelativePath(FM&: FileMgr, Dir: *Dir, File: *Header, Result&: RelativePath);
314 Diag(Loc: ExpectedHeadersLoc, DiagID: 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(StartLoc&: UnclosedSafeBufferOptOutLoc)) {
332 // To warn if a "-Wunsafe-buffer-usage" opt-out region is still open by the
333 // end of a file.
334 Diag(Loc: UnclosedSafeBufferOptOutLoc,
335 DiagID: 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(Loc: BuildingSubmoduleStack.back().ImportLoc,
344 DiagID: 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, TokEnd: EndPos, Kind: 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(File: *FE, ControllingMacro);
363 if (MacroInfo *MI = getMacroInfo(II: ControllingMacro))
364 MI->setUsedForHeaderGuard(true);
365 if (const IdentifierInfo *DefinedMacro =
366 CurPPLexer->MIOpt.GetDefinedMacro()) {
367 if (!isMacroDefined(II: 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(a: ControllingMacroName.size(),
380 b: DefinedMacroName.size()) / 2;
381 const unsigned ED = ControllingMacroName.edit_distance(
382 Other: DefinedMacroName, AllowReplacements: true, MaxEditDistance: MaxHalfLength);
383 if (ED <= MaxHalfLength) {
384 // Emit a warning for a bad header guard.
385 Diag(Loc: CurPPLexer->MIOpt.GetMacroLocation(),
386 DiagID: diag::warn_header_guard)
387 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
388 Diag(Loc: CurPPLexer->MIOpt.GetDefinedLocation(),
389 DiagID: diag::note_header_guard)
390 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
391 << ControllingMacro
392 << FixItHint::CreateReplacement(
393 RemoveRange: CurPPLexer->MIOpt.GetDefinedLocation(),
394 Code: 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(Loc: PragmaARCCFCodeAuditedInfo.getLoc(),
408 DiagID: 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.
422 if (isRecordingPreamble() && isInPrimaryFile())
423 PreambleRecordedPragmaAssumeNonNullLoc = PragmaAssumeNonNullLoc;
424 else
425 Diag(Loc: PragmaAssumeNonNullLoc, DiagID: 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(FID: CurPPLexer->getFileID()) ==
439 CodeCompletionFileLoc) {
440 assert(CurLexer && "Got EOF but no current lexer set!");
441 Result.startToken();
442 CurLexer->FormTokenWithChars(Result, TokEnd: CurLexer->BufferEnd, Kind: tok::eof);
443 PendingDestroyLexers.push_back(Elt: std::move(CurLexer));
444
445 CurPPLexer = nullptr;
446 recomputeCurLexerKind();
447 return true;
448 }
449
450 if (!isEndOfMacro && CurPPLexer &&
451 (SourceMgr.getIncludeLoc(FID: 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(FID: 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, TokEnd: EndPos, Kind: tok::annot_module_end);
482 Result.setAnnotationEndLoc(Result.getLocation());
483 Result.setAnnotationValue(M);
484 }
485
486 bool FoundPCHThroughHeader = false;
487 if (CurPPLexer && creatingPCHWithThroughHeader() &&
488 isPCHThroughHeader(
489 FE: SourceMgr.getFileEntryForID(FID: CurPPLexer->getFileID())))
490 FoundPCHThroughHeader = true;
491
492 // We're done with the #included file.
493 RemoveTopOfLexerStack();
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();
501 SrcMgr::CharacteristicKind FileType =
502 SourceMgr.getFileCharacteristic(Loc);
503 Callbacks->FileChanged(Loc, Reason: PPCallbacks::ExitFile, FileType, PrevFID: ExitedFID);
504 Callbacks->LexedFileChanged(FID: CurPPLexer->getFileID(),
505 Reason: PPCallbacks::LexedFileChangeReason::ExitFile,
506 FileType, PrevFID: 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, TokEnd: EndPos, Kind: tok::annot_repl_input_end);
537 Result.setAnnotationEndLoc(Result.getLocation());
538 Result.setAnnotationValue(nullptr);
539 } else {
540 CurLexer->FormTokenWithChars(Result, TokEnd: EndPos, Kind: tok::eof);
541 }
542
543 if (isCodeCompletionEnabled()) {
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(Offset: -1));
552 }
553
554 if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
555 // Reached the end of the compilation without finding the through header.
556 Diag(Loc: CurLexer->getFileLoc(), DiagID: diag::err_pp_through_header_not_seen)
557 << PPOpts.PCHThroughHeader << 0;
558 }
559
560 if (!isIncrementalProcessingEnabled()) {
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(Elt: std::move(CurLexer));
567 } else {
568 CurLexer.reset();
569 }
570 }
571
572 if (!isIncrementalProcessingEnabled())
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(Loc: *I, DiagID: 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()) {
590 llvm::SmallVector<const Module *, 4> AllMods;
591 collectAllSubModulesWithUmbrellaHeader(Mod: *Mod, SubMods&: AllMods);
592 for (auto *M : AllMods)
593 diagnoseMissingHeaderInUmbrellaDir(Mod: *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.
601bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
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, isEndOfMacro: 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.
622void Preprocessor::RemoveTopOfLexerStack() {
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.
639void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
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(C&: 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.
666 if (!HandleEndOfTokenLexer(Result&: Tok)) Lex(Result&: Tok);
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(K: tok::eod) && Tok.isNot(K: tok::eof))
675 Lex(Result&: Tok);
676
677 // If we got an eod token, then we successfully found the end of the line.
678 if (Tok.is(K: 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(Result&: 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
699void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
700 bool ForPragma) {
701 if (!getLangOpts().ModulesLocalVisibility) {
702 // Just track that we entered this submodule.
703 BuildingSubmoduleStack.push_back(
704 Elt: 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?
715 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
716 ModMap.resolveExports(Mod: M, /*Complain=*/false);
717 ModMap.resolveUses(Mod: M, /*Complain=*/false);
718 ModMap.resolveConflicts(Mod: 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(k: 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(PP&: *this, Overrides: Macro.second.getOverriddenMacros());
743 State.Macros.insert(KV: std::make_pair(x&: Macro.first, y: std::move(MS)));
744 }
745 }
746
747 // Track that we entered this module.
748 BuildingSubmoduleStack.push_back(
749 Elt: 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, Loc: 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.
774 return getLangOpts().isCompilingModule();
775}
776
777Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
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(M: LeavingMod, ImportLoc, ForPragma);
799
800 makeModuleVisible(M: LeavingMod, Loc: ImportLoc);
801 return LeavingMod;
802 }
803
804 // Create ModuleMacros for any macros defined in this submodule.
805 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
806 for (unsigned I = Info.OuterPendingModuleMacroNames;
807 I != PendingModuleMacroNames.size(); ++I) {
808 auto *II = PendingModuleMacroNames[I];
809 if (!VisitedMacros.insert(Ptr: II).second)
810 continue;
811
812 auto MacroIt = CurSubmoduleState->Macros.find(Val: 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(Val: 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>(Val: 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>(Val: 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(Mod: LeavingMod, II, Macro: Def, Overrides: 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(PP&: *this, Overrides: {});
866 }
867 break;
868 }
869 }
870 }
871 PendingModuleMacroNames.resize(N: 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(M: LeavingMod, ImportLoc, ForPragma);
886
887 // A nested #include makes the included submodule visible.
888 makeModuleVisible(M: LeavingMod, Loc: ImportLoc);
889 return LeavingMod;
890}
891