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