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