blob: 2ec075fa348bcfb5a97e5f709ffbeffb1d10db2a [file] [log] [blame]
Chris Lattner1eed7342008-03-09 04:10:46 +00001//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements pieces of the Preprocessor interface that manage the
11// current lexer stack.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Erich Keane76675de2018-07-05 17:22:13 +000016#include "clang/Lex/PreprocessorOptions.h"
Douglas Gregorebf00492011-10-17 15:32:29 +000017#include "clang/Basic/FileManager.h"
Chris Lattner1eed7342008-03-09 04:10:46 +000018#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/LexDiagnostic.h"
21#include "clang/Lex/MacroInfo.h"
Reid Kleckner738d48d2015-11-02 17:53:55 +000022#include "clang/Lex/PTHManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "llvm/ADT/StringSwitch.h"
Douglas Gregorfe76cfd2011-12-23 00:23:59 +000024#include "llvm/Support/FileSystem.h"
Ted Kremenek85b48c62008-11-20 07:56:33 +000025#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola552c1692013-06-11 22:15:02 +000026#include "llvm/Support/Path.h"
Chris Lattner1eed7342008-03-09 04:10:46 +000027using namespace clang;
28
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000029PPCallbacks::~PPCallbacks() {}
Chris Lattner1eed7342008-03-09 04:10:46 +000030
31//===----------------------------------------------------------------------===//
Chris Lattner3e468322008-03-10 06:06:04 +000032// Miscellaneous Methods.
Chris Lattner1eed7342008-03-09 04:10:46 +000033//===----------------------------------------------------------------------===//
34
Chris Lattner1eed7342008-03-09 04:10:46 +000035/// isInPrimaryFile - Return true if we're in the top-level file, not in a
James Dennett1244a0d2012-06-22 05:36:05 +000036/// \#include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner1eed7342008-03-09 04:10:46 +000037bool Preprocessor::isInPrimaryFile() const {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000038 if (IsFileLexer())
Chris Lattner1eed7342008-03-09 04:10:46 +000039 return IncludeMacroStack.empty();
Mike Stump11289f42009-09-09 15:08:12 +000040
Chris Lattner1eed7342008-03-09 04:10:46 +000041 // If there are any stacked lexers, we're in a #include.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000042 assert(IsFileLexer(IncludeMacroStack[0]) &&
Chris Lattner1eed7342008-03-09 04:10:46 +000043 "Top level include stack isn't our primary lexer?");
NAKAMURA Takumia5b348be2017-09-18 04:55:31 +000044 return std::none_of(
45 IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
Vitaly Buka55a27d32017-09-18 08:26:01 +000046 [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });
Chris Lattner1eed7342008-03-09 04:10:46 +000047}
48
49/// getCurrentLexer - Return the current file lexer being lexed from. Note
50/// that this ignores any potentially active macro expansions and _Pragma
51/// expansions going on at the time.
Ted Kremenekb33ce322008-11-20 01:49:44 +000052PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000053 if (IsFileLexer())
Ted Kremenekb33ce322008-11-20 01:49:44 +000054 return CurPPLexer;
Mike Stump11289f42009-09-09 15:08:12 +000055
Chris Lattner1eed7342008-03-09 04:10:46 +000056 // Look for a stacked lexer.
Erik Verbruggene4fd6522016-10-26 13:06:13 +000057 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000058 if (IsFileLexer(ISI))
Ted Kremenekb33ce322008-11-20 01:49:44 +000059 return ISI.ThePPLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +000060 }
Craig Topperd2d442c2014-05-17 23:10:59 +000061 return nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +000062}
63
Chris Lattner3e468322008-03-10 06:06:04 +000064
65//===----------------------------------------------------------------------===//
66// Methods for Entering and Callbacks for leaving various contexts
67//===----------------------------------------------------------------------===//
Chris Lattner1eed7342008-03-09 04:10:46 +000068
69/// EnterSourceFile - Add a source file to the top of the include stack and
Nuno Lopes0e5d13e2009-11-29 17:07:16 +000070/// start lexing tokens from it instead of the current buffer.
Richard Smith67294e22014-01-31 20:47:44 +000071bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
72 SourceLocation Loc) {
David Blaikie7d170102013-05-15 07:37:26 +000073 assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
Chris Lattner1eed7342008-03-09 04:10:46 +000074 ++NumEnteredSourceFiles;
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattner1eed7342008-03-09 04:10:46 +000076 if (MaxIncludeStackDepth < IncludeMacroStack.size())
77 MaxIncludeStackDepth = IncludeMacroStack.size();
78
Ted Kremenekaf058b52008-12-02 19:46:31 +000079 if (PTH) {
Chris Lattner710bb872009-11-30 04:18:44 +000080 if (PTHLexer *PL = PTH->CreateLexer(FID)) {
Richard Smith67294e22014-01-31 20:47:44 +000081 EnterSourceFileWithPTH(PL, CurDir);
82 return false;
Chris Lattner710bb872009-11-30 04:18:44 +000083 }
Ted Kremenekaf058b52008-12-02 19:46:31 +000084 }
Fangrui Song6907ce22018-07-30 19:24:48 +000085
Chris Lattner710bb872009-11-30 04:18:44 +000086 // Get the MemoryBuffer for this FID, if it fails, we fail.
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +000087 bool Invalid = false;
Fangrui Song6907ce22018-07-30 19:24:48 +000088 const llvm::MemoryBuffer *InputFile =
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000089 getSourceManager().getBuffer(FID, Loc, &Invalid);
90 if (Invalid) {
91 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
92 Diag(Loc, diag::err_pp_error_opening_file)
93 << std::string(SourceMgr.getBufferName(FileStart)) << "";
Richard Smith67294e22014-01-31 20:47:44 +000094 return true;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000095 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000096
97 if (isCodeCompletionEnabled() &&
98 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
99 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
100 CodeCompletionLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000101 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000102 }
103
Richard Smith67294e22014-01-31 20:47:44 +0000104 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
105 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000106}
Chris Lattnerc88a23e2008-09-26 20:12:23 +0000107
Ted Kremenekaf058b52008-12-02 19:46:31 +0000108/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
109/// and start lexing tokens from it instead of the current buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000110void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
Richard Smith67294e22014-01-31 20:47:44 +0000111 const DirectoryLookup *CurDir) {
Mike Stump11289f42009-09-09 15:08:12 +0000112
Chris Lattner1eed7342008-03-09 04:10:46 +0000113 // Add the current lexer to the include stack.
Ted Kremenek45245212008-11-19 21:57:25 +0000114 if (CurPPLexer || CurTokenLexer)
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000115 PushIncludeMacroStack();
116
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000117 CurLexer.reset(TheLexer);
Ted Kremenek68ef9fc2008-11-18 00:12:49 +0000118 CurPPLexer = TheLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000119 CurDirLookup = CurDir;
Richard Smithd1386302017-05-04 00:29:54 +0000120 CurLexerSubmodule = nullptr;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000121 if (CurLexerKind != CLK_LexAfterModuleImport)
122 CurLexerKind = CLK_Lexer;
Yaron Kerene02bcdc2015-11-07 16:35:07 +0000123
Chris Lattner1eed7342008-03-09 04:10:46 +0000124 // Notify the client, if desired, that we are in a new source file.
125 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000126 SrcMgr::CharacteristicKind FileType =
Chris Lattnerb03dc762008-09-26 21:18:42 +0000127 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Mike Stump11289f42009-09-09 15:08:12 +0000128
Chris Lattner1eed7342008-03-09 04:10:46 +0000129 Callbacks->FileChanged(CurLexer->getFileLoc(),
130 PPCallbacks::EnterFile, FileType);
131 }
132}
133
Ted Kremenekaf058b52008-12-02 19:46:31 +0000134/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
135/// and start getting tokens from it using the PTH cache.
Mike Stump11289f42009-09-09 15:08:12 +0000136void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
Richard Smith67294e22014-01-31 20:47:44 +0000137 const DirectoryLookup *CurDir) {
Mike Stump11289f42009-09-09 15:08:12 +0000138
Ted Kremenekaf058b52008-12-02 19:46:31 +0000139 if (CurPPLexer || CurTokenLexer)
140 PushIncludeMacroStack();
Chris Lattner1eed7342008-03-09 04:10:46 +0000141
Ted Kremenekaf058b52008-12-02 19:46:31 +0000142 CurDirLookup = CurDir;
143 CurPTHLexer.reset(PL);
144 CurPPLexer = CurPTHLexer.get();
Richard Smithd1386302017-05-04 00:29:54 +0000145 CurLexerSubmodule = nullptr;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000146 if (CurLexerKind != CLK_LexAfterModuleImport)
147 CurLexerKind = CLK_PTHLexer;
Fangrui Song6907ce22018-07-30 19:24:48 +0000148
Ted Kremenekaf058b52008-12-02 19:46:31 +0000149 // Notify the client, if desired, that we are in a new source file.
150 if (Callbacks) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000151 FileID FID = CurPPLexer->getFileID();
Chris Lattner4fd8b952009-01-19 08:01:53 +0000152 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
153 SrcMgr::CharacteristicKind FileType =
154 SourceMgr.getFileCharacteristic(EnterLoc);
155 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
Ted Kremenekaf058b52008-12-02 19:46:31 +0000156 }
157}
Chris Lattner1eed7342008-03-09 04:10:46 +0000158
159/// EnterMacro - Add a Macro to the top of the include stack and start lexing
160/// tokens from it instead of the current buffer.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000161void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
Richard Smith5edd5832012-08-30 13:38:46 +0000162 MacroInfo *Macro, MacroArgs *Args) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000163 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000164 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000165 TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000166 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000167 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000168 TokLexer->Init(Tok, ILEnd, Macro, Args);
169 }
170
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000171 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000172 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000173 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000174 if (CurLexerKind != CLK_LexAfterModuleImport)
175 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000176}
177
178/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner3e468322008-03-10 06:06:04 +0000179/// which will cause the lexer to start returning the specified tokens.
180///
181/// If DisableMacroExpansion is true, tokens lexed from the token stream will
182/// not be subject to further macro expansion. Otherwise, these tokens will
183/// be re-macro-expanded when/if expansion is enabled.
184///
185/// If OwnsTokens is false, this method assumes that the specified stream of
186/// tokens has a permanent owner somewhere, so they do not need to be copied.
187/// If it is true, it assumes the array of tokens is allocated with new[] and
188/// must be freed.
189///
190void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
191 bool DisableMacroExpansion,
192 bool OwnsTokens) {
Richard Smithbdf54a212014-09-23 21:05:52 +0000193 if (CurLexerKind == CLK_CachingLexer) {
194 if (CachedLexPos < CachedTokens.size()) {
195 // We're entering tokens into the middle of our cached token stream. We
196 // can't represent that, so just insert the tokens into the buffer.
197 CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
198 Toks, Toks + NumToks);
199 if (OwnsTokens)
200 delete [] Toks;
201 return;
202 }
203
204 // New tokens are at the end of the cached token sequnece; insert the
205 // token stream underneath the caching lexer.
206 ExitCachingLexMode();
207 EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
208 EnterCachingLexMode();
209 return;
210 }
211
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000212 // Create a macro expander to expand from the specified token stream.
David Blaikie6d5038c2014-08-29 19:36:52 +0000213 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000214 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000215 TokLexer = llvm::make_unique<TokenLexer>(
216 Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000217 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000218 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000219 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
220 }
221
Chris Lattner1eed7342008-03-09 04:10:46 +0000222 // Save our current state.
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000223 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000224 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000225 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000226 if (CurLexerKind != CLK_LexAfterModuleImport)
227 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000228}
229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000230/// Compute the relative path that names the given file relative to
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000231/// the given directory.
232static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
233 const FileEntry *File,
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000234 SmallString<128> &Result) {
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000235 Result.clear();
236
237 StringRef FilePath = File->getDir()->getName();
238 StringRef Path = FilePath;
239 while (!Path.empty()) {
240 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
241 if (CurDir == Dir) {
242 Result = FilePath.substr(Path.size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000243 llvm::sys::path::append(Result,
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000244 llvm::sys::path::filename(File->getName()));
245 return;
246 }
247 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000248
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000249 Path = llvm::sys::path::parent_path(Path);
250 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000251
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000252 Result = File->getName();
253}
254
Eli Friedman0834a4b2013-09-19 00:41:32 +0000255void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
256 if (CurTokenLexer) {
257 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
258 return;
259 }
260 if (CurLexer) {
261 CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
262 return;
263 }
264 // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
265 // but it might if they're empty?
266}
267
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000268/// Determine the location to use as the end of the buffer for a lexer.
Richard Smith34f30512013-11-23 04:06:09 +0000269///
270/// If the file ends with a newline, form the EOF token on the newline itself,
271/// rather than "on the line following it", which doesn't exist. This makes
272/// diagnostics relating to the end of file include the last file that the user
273/// actually typed, which is goodness.
274const char *Preprocessor::getCurLexerEndPos() {
275 const char *EndPos = CurLexer->BufferEnd;
276 if (EndPos != CurLexer->BufferStart &&
277 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
278 --EndPos;
279
280 // Handle \n\r and \r\n:
281 if (EndPos != CurLexer->BufferStart &&
282 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
283 EndPos[-1] != EndPos[0])
284 --EndPos;
285 }
286
287 return EndPos;
288}
289
Bruno Cardoso Lopesb9075632017-04-27 22:29:14 +0000290static void collectAllSubModulesWithUmbrellaHeader(
291 const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
292 if (Mod.getUmbrellaHeader())
293 SubMods.push_back(&Mod);
294 for (auto *M : Mod.submodules())
295 collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
296}
297
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000298void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
299 assert(Mod.getUmbrellaHeader() && "Module must use umbrella header");
300 SourceLocation StartLoc =
301 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
302 if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header, StartLoc))
303 return;
304
305 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
306 const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
307 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
308 std::error_code EC;
309 for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End;
310 Entry != End && !EC; Entry.increment(EC)) {
311 using llvm::StringSwitch;
312
313 // Check whether this entry has an extension typically associated with
314 // headers.
Sam McCall0ae00562018-09-14 12:47:38 +0000315 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000316 .Cases(".h", ".H", ".hh", ".hpp", true)
317 .Default(false))
318 continue;
319
Sam McCall0ae00562018-09-14 12:47:38 +0000320 if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000321 if (!getSourceManager().hasFileInfo(Header)) {
322 if (!ModMap.isHeaderInUnavailableModule(Header)) {
323 // Find the relative path that would access this header.
324 SmallString<128> RelativePath;
325 computeRelativePath(FileMgr, Dir, Header, RelativePath);
326 Diag(StartLoc, diag::warn_uncovered_module_header)
327 << Mod.getFullModuleName() << RelativePath;
328 }
329 }
330 }
331}
Richard Smith34f30512013-11-23 04:06:09 +0000332
Chris Lattner1eed7342008-03-09 04:10:46 +0000333/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
334/// the current file. This either returns the EOF token or pops a level off
335/// the include stack and keeps going.
336bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
337 assert(!CurTokenLexer &&
338 "Ending a file when currently in a macro!");
Mike Stump11289f42009-09-09 15:08:12 +0000339
Richard Smithd1386302017-05-04 00:29:54 +0000340 // If we have an unclosed module region from a pragma at the end of a
341 // module, complain and close it now.
342 // FIXME: This is not correct if we are building a module from PTH.
343 const bool LeavingSubmodule = CurLexer && CurLexerSubmodule;
344 if ((LeavingSubmodule || IncludeMacroStack.empty()) &&
345 !BuildingSubmoduleStack.empty() &&
346 BuildingSubmoduleStack.back().IsPragma) {
347 Diag(BuildingSubmoduleStack.back().ImportLoc,
348 diag::err_pp_module_begin_without_module_end);
349 Module *M = LeaveSubmodule(/*ForPragma*/true);
350
351 Result.startToken();
352 const char *EndPos = getCurLexerEndPos();
353 CurLexer->BufferPtr = EndPos;
354 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
355 Result.setAnnotationEndLoc(Result.getLocation());
356 Result.setAnnotationValue(M);
357 return true;
358 }
359
Chris Lattner1eed7342008-03-09 04:10:46 +0000360 // See if this file had a controlling macro.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000361 if (CurPPLexer) { // Not ending a macro, ignore it.
Mike Stump11289f42009-09-09 15:08:12 +0000362 if (const IdentifierInfo *ControllingMacro =
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000363 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Steve Naroff3fa455a2009-04-24 20:03:17 +0000364 // Okay, this has a controlling macro, remember in HeaderFileInfo.
Yaron Keren65224612015-12-18 10:30:12 +0000365 if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000366 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +0000367 if (MacroInfo *MI =
Yaron Keren9370ea22017-04-16 15:53:19 +0000368 getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
369 MI->setUsedForHeaderGuard(true);
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000370 if (const IdentifierInfo *DefinedMacro =
371 CurPPLexer->MIOpt.GetDefinedMacro()) {
Richard Smith20e883e2015-04-29 23:20:19 +0000372 if (!isMacroDefined(ControllingMacro) &&
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000373 DefinedMacro != ControllingMacro &&
374 HeaderInfo.FirstTimeLexingFile(FE)) {
Ismail Pazarbasi8d0f2f32013-10-12 23:17:37 +0000375
376 // If the edit distance between the two macros is more than 50%,
377 // DefinedMacro may not be header guard, or can be header guard of
378 // another header file. Therefore, it maybe defining something
379 // completely different. This can be observed in the wild when
380 // handling feature macros or header guards in different files.
381
382 const StringRef ControllingMacroName = ControllingMacro->getName();
383 const StringRef DefinedMacroName = DefinedMacro->getName();
384 const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
385 DefinedMacroName.size()) / 2;
386 const unsigned ED = ControllingMacroName.edit_distance(
387 DefinedMacroName, true, MaxHalfLength);
388 if (ED <= MaxHalfLength) {
389 // Emit a warning for a bad header guard.
390 Diag(CurPPLexer->MIOpt.GetMacroLocation(),
391 diag::warn_header_guard)
392 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
393 Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
394 diag::note_header_guard)
395 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
396 << ControllingMacro
397 << FixItHint::CreateReplacement(
398 CurPPLexer->MIOpt.GetDefinedLocation(),
399 ControllingMacro->getName());
400 }
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000401 }
402 }
403 }
Chris Lattner1eed7342008-03-09 04:10:46 +0000404 }
405 }
Mike Stump11289f42009-09-09 15:08:12 +0000406
John McCall95ff2702011-10-18 00:44:04 +0000407 // Complain about reaching a true EOF within arc_cf_code_audited.
408 // We don't want to complain about reaching the end of a macro
409 // instantiation or a _Pragma.
410 if (PragmaARCCFCodeAuditedLoc.isValid() &&
John McCall43d4dd42011-10-18 01:36:41 +0000411 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
John McCall32f5fe12011-09-30 05:12:12 +0000412 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
413
414 // Recover by leaving immediately.
415 PragmaARCCFCodeAuditedLoc = SourceLocation();
416 }
417
Douglas Gregor2a20bd12015-06-19 18:25:57 +0000418 // Complain about reaching a true EOF within assume_nonnull.
419 // We don't want to complain about reaching the end of a macro
420 // instantiation or a _Pragma.
421 if (PragmaAssumeNonNullLoc.isValid() &&
422 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
423 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
424
425 // Recover by leaving immediately.
426 PragmaAssumeNonNullLoc = SourceLocation();
427 }
428
Erich Keane76675de2018-07-05 17:22:13 +0000429 bool LeavingPCHThroughHeader = false;
430
Chris Lattner1eed7342008-03-09 04:10:46 +0000431 // If this is a #include'd file, pop it off the include stack and continue
432 // lexing the #includer file.
433 if (!IncludeMacroStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000434
435 // If we lexed the code-completion file, act as if we reached EOF.
436 if (isCodeCompletionEnabled() && CurPPLexer &&
437 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
438 CodeCompletionFileLoc) {
439 if (CurLexer) {
440 Result.startToken();
441 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
442 CurLexer.reset();
443 } else {
444 assert(CurPTHLexer && "Got EOF but no current lexer set!");
445 CurPTHLexer->getEOF(Result);
446 CurPTHLexer.reset();
447 }
448
Craig Topperd2d442c2014-05-17 23:10:59 +0000449 CurPPLexer = nullptr;
Volodymyr Sapsai9d540f12018-01-19 23:41:47 +0000450 recomputeCurLexerKind();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000451 return true;
452 }
453
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +0000454 if (!isEndOfMacro && CurPPLexer &&
455 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
456 // Notify SourceManager to record the number of FileIDs that were created
457 // during lexing of the #include'd file.
458 unsigned NumFIDs =
459 SourceMgr.local_sloc_entry_size() -
460 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
461 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
462 }
463
Ilya Biryukovf3150002017-08-21 12:03:08 +0000464 bool ExitedFromPredefinesFile = false;
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000465 FileID ExitedFID;
Ilya Biryukovf3150002017-08-21 12:03:08 +0000466 if (!isEndOfMacro && CurPPLexer) {
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000467 ExitedFID = CurPPLexer->getFileID();
Richard Smith34f30512013-11-23 04:06:09 +0000468
Ilya Biryukovf3150002017-08-21 12:03:08 +0000469 assert(PredefinesFileID.isValid() &&
470 "HandleEndOfFile is called before PredefinesFileId is set");
471 ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
472 }
473
Richard Smith34f30512013-11-23 04:06:09 +0000474 if (LeavingSubmodule) {
Richard Smithd1386302017-05-04 00:29:54 +0000475 // We're done with this submodule.
476 Module *M = LeaveSubmodule(/*ForPragma*/false);
477
Richard Smith67294e22014-01-31 20:47:44 +0000478 // Notify the parser that we've left the module.
Richard Smith34f30512013-11-23 04:06:09 +0000479 const char *EndPos = getCurLexerEndPos();
480 Result.startToken();
481 CurLexer->BufferPtr = EndPos;
482 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
483 Result.setAnnotationEndLoc(Result.getLocation());
Richard Smithd1386302017-05-04 00:29:54 +0000484 Result.setAnnotationValue(M);
Richard Smith34f30512013-11-23 04:06:09 +0000485 }
486
Erich Keane76675de2018-07-05 17:22:13 +0000487 bool FoundPCHThroughHeader = false;
488 if (CurPPLexer && creatingPCHWithThroughHeader() &&
489 isPCHThroughHeader(
490 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
491 FoundPCHThroughHeader = true;
492
Chris Lattner1eed7342008-03-09 04:10:46 +0000493 // We're done with the #included file.
494 RemoveTopOfLexerStack();
495
Eli Friedman0834a4b2013-09-19 00:41:32 +0000496 // Propagate info about start-of-line/leading white-space/etc.
497 PropagateLineStartLeadingSpaceInfo(Result);
498
Chris Lattner1eed7342008-03-09 04:10:46 +0000499 // Notify the client, if desired, that we are in a new source file.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000500 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000501 SrcMgr::CharacteristicKind FileType =
Chris Lattner4fd8b952009-01-19 08:01:53 +0000502 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
503 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000504 PPCallbacks::ExitFile, FileType, ExitedFID);
Chris Lattner1eed7342008-03-09 04:10:46 +0000505 }
506
Ilya Biryukovf3150002017-08-21 12:03:08 +0000507 // Restore conditional stack from the preamble right after exiting from the
508 // predefines file.
509 if (ExitedFromPredefinesFile)
510 replayPreambleConditionalStack();
511
Erich Keane76675de2018-07-05 17:22:13 +0000512 if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
513 (isInPrimaryFile() ||
514 CurPPLexer->getFileID() == getPredefinesFileID())) {
515 // Leaving the through header. Continue directly to end of main file
516 // processing.
517 LeavingPCHThroughHeader = true;
518 } else {
519 // Client should lex another token unless we generated an EOM.
520 return LeavingSubmodule;
521 }
Chris Lattner1eed7342008-03-09 04:10:46 +0000522 }
523
Richard Smith34f30512013-11-23 04:06:09 +0000524 // If this is the end of the main file, form an EOF token.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000525 if (CurLexer) {
Richard Smith34f30512013-11-23 04:06:09 +0000526 const char *EndPos = getCurLexerEndPos();
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000527 Result.startToken();
528 CurLexer->BufferPtr = EndPos;
529 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Mike Stump11289f42009-09-09 15:08:12 +0000530
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000531 if (isCodeCompletionEnabled()) {
532 // Inserting the code-completion point increases the source buffer by 1,
533 // but the main FileID was created before inserting the point.
534 // Compensate by reducing the EOF location by 1, otherwise the location
535 // will point to the next FileID.
536 // FIXME: This is hacky, the code-completion point should probably be
537 // inserted before the main FileID is created.
538 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
539 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
540 }
541
Erich Keane76675de2018-07-05 17:22:13 +0000542 if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
543 // Reached the end of the compilation without finding the through header.
544 Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
545 << PPOpts->PCHThroughHeader << 0;
546 }
547
Axel Naumann2eb1d902012-03-16 10:40:17 +0000548 if (!isIncrementalProcessingEnabled())
549 // We're done with lexing.
550 CurLexer.reset();
Chris Lattner190f64e2009-02-13 23:06:48 +0000551 } else {
552 assert(CurPTHLexer && "Got EOF but no current lexer set!");
Ted Kremenek78cc2472008-12-23 19:24:24 +0000553 CurPTHLexer->getEOF(Result);
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000554 CurPTHLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000555 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000556
Axel Naumann2eb1d902012-03-16 10:40:17 +0000557 if (!isIncrementalProcessingEnabled())
Craig Topperd2d442c2014-05-17 23:10:59 +0000558 CurPPLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000559
Argyrios Kyrtzidis8ed74142014-03-08 21:18:26 +0000560 if (TUKind == TU_Complete) {
Argyrios Kyrtzidise1974dc2014-03-07 07:47:58 +0000561 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
562 // collected all macro locations that we need to warn because they are not
563 // used.
564 for (WarnUnusedMacroLocsTy::iterator
565 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
566 I!=E; ++I)
567 Diag(*I, diag::pp_macro_not_used);
568 }
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000569
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000570 // If we are building a module that has an umbrella header, make sure that
Bruno Cardoso Lopesb9075632017-04-27 22:29:14 +0000571 // each of the headers within the directory, including all submodules, is
572 // covered by the umbrella header was actually included by the umbrella
573 // header.
574 if (Module *Mod = getCurrentModule()) {
575 llvm::SmallVector<const Module *, 4> AllMods;
576 collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
577 for (auto *M : AllMods)
578 diagnoseMissingHeaderInUmbrellaDir(*M);
579 }
Douglas Gregorf4e76b82013-05-20 13:49:41 +0000580
Chris Lattner1eed7342008-03-09 04:10:46 +0000581 return true;
582}
583
584/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
585/// hits the end of its token stream.
586bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000587 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000588 "Ending a macro when currently in a #include file!");
589
Argyrios Kyrtzidis8cc04592011-06-29 22:20:11 +0000590 if (!MacroExpandingLexersStack.empty() &&
591 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
592 removeCachedMacroExpandedTokensOfLastLexer();
593
Chris Lattner1eed7342008-03-09 04:10:46 +0000594 // Delete or cache the now-dead macro expander.
595 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000596 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000597 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000598 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Chris Lattner1eed7342008-03-09 04:10:46 +0000599
600 // Handle this like a #include file being popped off the stack.
Chris Lattner1eed7342008-03-09 04:10:46 +0000601 return HandleEndOfFile(Result, true);
602}
603
604/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
605/// lexer stack. This should only be used in situations where the current
606/// state of the top-of-stack lexer is unknown.
607void Preprocessor::RemoveTopOfLexerStack() {
608 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattner1eed7342008-03-09 04:10:46 +0000610 if (CurTokenLexer) {
611 // Delete or cache the now-dead macro expander.
612 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000613 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000614 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000615 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Mike Stump11289f42009-09-09 15:08:12 +0000616 }
617
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000618 PopIncludeMacroStack();
Chris Lattner1eed7342008-03-09 04:10:46 +0000619}
620
621/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
622/// comment (/##/) in microsoft mode, this method handles updating the current
623/// state, returning the token on the next source line.
624void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000625 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000626 "Pasted comment can only be formed from macro");
Chris Lattner1eed7342008-03-09 04:10:46 +0000627 // We handle this by scanning for the closest real lexer, switching it to
628 // raw mode and preprocessor mode. This will cause it to return \n as an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000629 // explicit EOD token.
Craig Topperd2d442c2014-05-17 23:10:59 +0000630 PreprocessorLexer *FoundLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000631 bool LexerWasInPPMode = false;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000632 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000633 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
Mike Stump11289f42009-09-09 15:08:12 +0000634
Chris Lattner1eed7342008-03-09 04:10:46 +0000635 // Once we find a real lexer, mark it as raw mode (disabling macro
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000636 // expansions) and preprocessor mode (return EOD). We know that the lexer
Chris Lattner1eed7342008-03-09 04:10:46 +0000637 // was *not* in raw mode before, because the macro that the comment came
638 // from was expanded. However, it could have already been in preprocessor
639 // mode (#if COMMENT) in which case we have to return it to that mode and
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000640 // return EOD.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000641 FoundLexer = ISI.ThePPLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000642 FoundLexer->LexingRawMode = true;
643 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
644 FoundLexer->ParsingPreprocessorDirective = true;
645 break;
646 }
Mike Stump11289f42009-09-09 15:08:12 +0000647
Chris Lattner1eed7342008-03-09 04:10:46 +0000648 // Okay, we either found and switched over the lexer, or we didn't find a
649 // lexer. In either case, finish off the macro the comment came from, getting
650 // the next token.
651 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000652
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000653 // Discarding comments as long as we don't have EOF or EOD. This 'comments
Chris Lattner1eed7342008-03-09 04:10:46 +0000654 // out' the rest of the line, including any tokens that came from other macros
655 // that were active, as in:
656 // #define submacro a COMMENT b
657 // submacro c
658 // which should lex to 'a' only: 'b' and 'c' should be removed.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000659 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
Chris Lattner1eed7342008-03-09 04:10:46 +0000660 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000661
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000662 // If we got an eod token, then we successfully found the end of the line.
663 if (Tok.is(tok::eod)) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000664 assert(FoundLexer && "Can't get end of line without an active lexer");
665 // Restore the lexer back to normal mode instead of raw mode.
666 FoundLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000667
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000668 // If the lexer was already in preprocessor mode, just return the EOD token
Chris Lattner1eed7342008-03-09 04:10:46 +0000669 // to finish the preprocessor line.
670 if (LexerWasInPPMode) return;
Mike Stump11289f42009-09-09 15:08:12 +0000671
Chris Lattner1eed7342008-03-09 04:10:46 +0000672 // Otherwise, switch out of PP mode and return the next lexed token.
673 FoundLexer->ParsingPreprocessorDirective = false;
674 return Lex(Tok);
675 }
Mike Stump11289f42009-09-09 15:08:12 +0000676
Chris Lattner1eed7342008-03-09 04:10:46 +0000677 // If we got an EOF token, then we reached the end of the token stream but
678 // didn't find an explicit \n. This can only happen if there was no lexer
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000679 // active (an active lexer would return EOD at EOF if there was no \n in
Chris Lattner1eed7342008-03-09 04:10:46 +0000680 // preprocessor directive mode), so just return EOF as our token.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000681 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
Chris Lattner1eed7342008-03-09 04:10:46 +0000682}
Richard Smithb8b2ed62015-04-23 18:18:26 +0000683
Richard Smithd1386302017-05-04 00:29:54 +0000684void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
685 bool ForPragma) {
Richard Smith04765ae2015-05-21 01:20:10 +0000686 if (!getLangOpts().ModulesLocalVisibility) {
687 // Just track that we entered this submodule.
Richard Smithd1386302017-05-04 00:29:54 +0000688 BuildingSubmoduleStack.push_back(
689 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
690 PendingModuleMacroNames.size()));
Richard Smith04765ae2015-05-21 01:20:10 +0000691 return;
692 }
Richard Smithee977932015-05-01 21:22:17 +0000693
Richard Smith04765ae2015-05-21 01:20:10 +0000694 // Resolve as much of the module definition as we can now, before we enter
695 // one of its headers.
696 // FIXME: Can we enable Complain here?
697 // FIXME: Can we do this when local visibility is disabled?
698 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
699 ModMap.resolveExports(M, /*Complain=*/false);
700 ModMap.resolveUses(M, /*Complain=*/false);
701 ModMap.resolveConflicts(M, /*Complain=*/false);
Richard Smith42413142015-05-15 20:05:43 +0000702
Richard Smith04765ae2015-05-21 01:20:10 +0000703 // If this is the first time we've entered this module, set up its state.
Richard Smithe5202932015-05-21 01:26:53 +0000704 auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
Richard Smith04765ae2015-05-21 01:20:10 +0000705 auto &State = R.first->second;
706 bool FirstTime = R.second;
707 if (FirstTime) {
708 // Determine the set of starting macros for this submodule; take these
709 // from the "null" module (the predefines buffer).
Richard Smith4df60932015-06-30 21:29:55 +0000710 //
711 // FIXME: If we have local visibility but not modules enabled, the
712 // NullSubmoduleState is polluted by #defines in the top-level source
713 // file.
Richard Smith04765ae2015-05-21 01:20:10 +0000714 auto &StartingMacros = NullSubmoduleState.Macros;
715
716 // Restore to the starting state.
717 // FIXME: Do this lazily, when each macro name is first referenced.
718 for (auto &Macro : StartingMacros) {
Richard Smith4df60932015-06-30 21:29:55 +0000719 // Skip uninteresting macros.
720 if (!Macro.second.getLatest() &&
721 Macro.second.getOverriddenMacros().empty())
722 continue;
723
Richard Smith04765ae2015-05-21 01:20:10 +0000724 MacroState MS(Macro.second.getLatest());
725 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
726 State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
727 }
728 }
729
730 // Track that we entered this module.
Richard Smithd1386302017-05-04 00:29:54 +0000731 BuildingSubmoduleStack.push_back(
732 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
733 PendingModuleMacroNames.size()));
Richard Smith04765ae2015-05-21 01:20:10 +0000734
735 // Switch to this submodule as the current submodule.
736 CurSubmoduleState = &State;
737
738 // This module is visible to itself.
739 if (FirstTime)
Richard Smith42413142015-05-15 20:05:43 +0000740 makeModuleVisible(M, ImportLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000741}
742
Richard Smith802182f2016-02-23 23:20:51 +0000743bool Preprocessor::needModuleMacros() const {
744 // If we're not within a submodule, we never need to create ModuleMacros.
745 if (BuildingSubmoduleStack.empty())
746 return false;
747 // If we are tracking module macro visibility even for textually-included
748 // headers, we need ModuleMacros.
749 if (getLangOpts().ModulesLocalVisibility)
750 return true;
751 // Otherwise, we only need module macros if we're actually compiling a module
752 // interface.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000753 return getLangOpts().isCompilingModule();
Richard Smith802182f2016-02-23 23:20:51 +0000754}
755
Richard Smithd1386302017-05-04 00:29:54 +0000756Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
757 if (BuildingSubmoduleStack.empty() ||
758 BuildingSubmoduleStack.back().IsPragma != ForPragma) {
759 assert(ForPragma && "non-pragma module enter/leave mismatch");
760 return nullptr;
761 }
762
Richard Smithb8b2ed62015-04-23 18:18:26 +0000763 auto &Info = BuildingSubmoduleStack.back();
764
Richard Smithdbbc5232015-05-14 02:25:44 +0000765 Module *LeavingMod = Info.M;
766 SourceLocation ImportLoc = Info.ImportLoc;
767
Richard Smith4971ed02017-05-19 23:32:38 +0000768 if (!needModuleMacros() ||
Richard Smith802182f2016-02-23 23:20:51 +0000769 (!getLangOpts().ModulesLocalVisibility &&
770 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
771 // If we don't need module macros, or this is not a module for which we
772 // are tracking macro visibility, don't build any, and preserve the list
773 // of pending names for the surrounding submodule.
Richard Smithe5b53502016-02-19 22:43:58 +0000774 BuildingSubmoduleStack.pop_back();
775 makeModuleVisible(LeavingMod, ImportLoc);
Richard Smithd1386302017-05-04 00:29:54 +0000776 return LeavingMod;
Richard Smithe5b53502016-02-19 22:43:58 +0000777 }
778
Richard Smithb8b2ed62015-04-23 18:18:26 +0000779 // Create ModuleMacros for any macros defined in this submodule.
Richard Smith802182f2016-02-23 23:20:51 +0000780 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
781 for (unsigned I = Info.OuterPendingModuleMacroNames;
782 I != PendingModuleMacroNames.size(); ++I) {
783 auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
784 if (!VisitedMacros.insert(II).second)
785 continue;
786
787 auto MacroIt = CurSubmoduleState->Macros.find(II);
788 if (MacroIt == CurSubmoduleState->Macros.end())
789 continue;
790 auto &Macro = MacroIt->second;
Richard Smithee977932015-05-01 21:22:17 +0000791
792 // Find the starting point for the MacroDirective chain in this submodule.
Richard Smith04765ae2015-05-21 01:20:10 +0000793 MacroDirective *OldMD = nullptr;
Richard Smithe5b53502016-02-19 22:43:58 +0000794 auto *OldState = Info.OuterSubmoduleState;
795 if (getLangOpts().ModulesLocalVisibility)
796 OldState = &NullSubmoduleState;
797 if (OldState && OldState != CurSubmoduleState) {
Richard Smith04765ae2015-05-21 01:20:10 +0000798 // FIXME: It'd be better to start at the state from when we most recently
799 // entered this submodule, but it doesn't really matter.
Richard Smithe5b53502016-02-19 22:43:58 +0000800 auto &OldMacros = OldState->Macros;
Richard Smith802182f2016-02-23 23:20:51 +0000801 auto OldMacroIt = OldMacros.find(II);
Richard Smithe5b53502016-02-19 22:43:58 +0000802 if (OldMacroIt == OldMacros.end())
Richard Smithee977932015-05-01 21:22:17 +0000803 OldMD = nullptr;
804 else
Richard Smithe5b53502016-02-19 22:43:58 +0000805 OldMD = OldMacroIt->second.getLatest();
Richard Smithee977932015-05-01 21:22:17 +0000806 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000807
808 // This module may have exported a new macro. If so, create a ModuleMacro
809 // representing that fact.
810 bool ExplicitlyPublic = false;
Richard Smith802182f2016-02-23 23:20:51 +0000811 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
Richard Smith1e172852015-04-28 21:05:07 +0000812 assert(MD && "broken macro directive chain");
813
Richard Smithb8b2ed62015-04-23 18:18:26 +0000814 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
815 // The latest visibility directive for a name in a submodule affects
816 // all the directives that come before it.
817 if (VisMD->isPublic())
818 ExplicitlyPublic = true;
819 else if (!ExplicitlyPublic)
820 // Private with no following public directive: not exported.
821 break;
822 } else {
823 MacroInfo *Def = nullptr;
824 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
825 Def = DefMD->getInfo();
826
827 // FIXME: Issue a warning if multiple headers for the same submodule
828 // define a macro, rather than silently ignoring all but the first.
829 bool IsNew;
Richard Smith32dbd692015-05-02 01:14:40 +0000830 // Don't bother creating a module macro if it would represent a #undef
831 // that doesn't override anything.
Richard Smith802182f2016-02-23 23:20:51 +0000832 if (Def || !Macro.getOverriddenMacros().empty())
Richard Smithdbbc5232015-05-14 02:25:44 +0000833 addModuleMacro(LeavingMod, II, Def,
Richard Smith802182f2016-02-23 23:20:51 +0000834 Macro.getOverriddenMacros(), IsNew);
Richard Smith4971ed02017-05-19 23:32:38 +0000835
836 if (!getLangOpts().ModulesLocalVisibility) {
837 // This macro is exposed to the rest of this compilation as a
838 // ModuleMacro; we don't need to track its MacroDirective any more.
839 Macro.setLatest(nullptr);
840 Macro.setOverriddenMacros(*this, {});
841 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000842 break;
843 }
844 }
Richard Smith753e0072015-04-27 23:21:38 +0000845 }
Richard Smith802182f2016-02-23 23:20:51 +0000846 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000847
Richard Smith4df60932015-06-30 21:29:55 +0000848 // FIXME: Before we leave this submodule, we should parse all the other
849 // headers within it. Otherwise, we're left with an inconsistent state
850 // where we've made the module visible but don't yet have its complete
851 // contents.
852
Richard Smith04765ae2015-05-21 01:20:10 +0000853 // Put back the outer module's state, if we're tracking it.
Richard Smithee977932015-05-01 21:22:17 +0000854 if (getLangOpts().ModulesLocalVisibility)
Richard Smith04765ae2015-05-21 01:20:10 +0000855 CurSubmoduleState = Info.OuterSubmoduleState;
Richard Smithee977932015-05-01 21:22:17 +0000856
Richard Smithb8b2ed62015-04-23 18:18:26 +0000857 BuildingSubmoduleStack.pop_back();
Richard Smithdbbc5232015-05-14 02:25:44 +0000858
859 // A nested #include makes the included submodule visible.
Richard Smith4df60932015-06-30 21:29:55 +0000860 makeModuleVisible(LeavingMod, ImportLoc);
Richard Smithd1386302017-05-04 00:29:54 +0000861 return LeavingMod;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000862}