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