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 CurLexer->FormTokenWithChars(Result, TokEnd: EndPos, Kind: tok::eof);
536
537 if (isCodeCompletionEnabled()) {
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(Offset: -1));
546 }
547
548 if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
549 // Reached the end of the compilation without finding the through header.
550 Diag(Loc: CurLexer->getFileLoc(), DiagID: diag::err_pp_through_header_not_seen)
551 << PPOpts.PCHThroughHeader << 0;
552 }
553
554 if (!isIncrementalProcessingEnabled()) {
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(Elt: std::move(CurLexer));
561 } else {
562 CurLexer.reset();
563 }
564 }
565
566 if (!isIncrementalProcessingEnabled())
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(Loc: *I, DiagID: 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()) {
584 llvm::SmallVector<const Module *, 4> AllMods;
585 collectAllSubModulesWithUmbrellaHeader(Mod: *Mod, SubMods&: AllMods);
586 for (auto *M : AllMods)
587 diagnoseMissingHeaderInUmbrellaDir(Mod: *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.
595bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
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, isEndOfMacro: 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.
616void Preprocessor::RemoveTopOfLexerStack() {
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.
633void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
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(C&: 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.
660 if (!HandleEndOfTokenLexer(Result&: Tok)) Lex(Result&: Tok);
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(K: tok::eod) && Tok.isNot(K: tok::eof))
669 Lex(Result&: Tok);
670
671 // If we got an eod token, then we successfully found the end of the line.
672 if (Tok.is(K: 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(Result&: 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
693void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
694 bool ForPragma) {
695 if (!getLangOpts().ModulesLocalVisibility) {
696 // Just track that we entered this submodule.
697 BuildingSubmoduleStack.push_back(
698 Elt: 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?
709 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
710 ModMap.resolveExports(Mod: M, /*Complain=*/false);
711 ModMap.resolveUses(Mod: M, /*Complain=*/false);
712 ModMap.resolveConflicts(Mod: 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(k: 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(PP&: *this, Overrides: Macro.second.getOverriddenMacros());
737 State.Macros.insert(KV: std::make_pair(x&: Macro.first, y: std::move(MS)));
738 }
739 }
740
741 // Track that we entered this module.
742 BuildingSubmoduleStack.push_back(
743 Elt: 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, Loc: 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.
768 return getLangOpts().isCompilingModule();
769}
770
771Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
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(M: LeavingMod, ImportLoc, ForPragma);
793
794 makeModuleVisible(M: LeavingMod, Loc: ImportLoc);
795 return LeavingMod;
796 }
797
798 // Create ModuleMacros for any macros defined in this submodule.
799 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
800 for (unsigned I = Info.OuterPendingModuleMacroNames;
801 I != PendingModuleMacroNames.size(); ++I) {
802 auto *II = PendingModuleMacroNames[I];
803 if (!VisitedMacros.insert(Ptr: II).second)
804 continue;
805
806 auto MacroIt = CurSubmoduleState->Macros.find(Val: 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(Val: 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>(Val: 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>(Val: 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(Mod: LeavingMod, II, Macro: Def, Overrides: 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(PP&: *this, Overrides: {});
860 }
861 break;
862 }
863 }
864 }
865 PendingModuleMacroNames.resize(N: 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(M: LeavingMod, ImportLoc, ForPragma);
880
881 // A nested #include makes the included submodule visible.
882 makeModuleVisible(M: LeavingMod, Loc: ImportLoc);
883 return LeavingMod;
884}
885