blob: e484e9c4c3a384813b3307447abd01e315428ac7 [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"
Douglas Gregorebf00492011-10-17 15:32:29 +000016#include "clang/Basic/FileManager.h"
Chris Lattner1eed7342008-03-09 04:10:46 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/HeaderSearch.h"
19#include "clang/Lex/LexDiagnostic.h"
20#include "clang/Lex/MacroInfo.h"
Reid Kleckner738d48d2015-11-02 17:53:55 +000021#include "clang/Lex/PTHManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/ADT/StringSwitch.h"
Douglas Gregorfe76cfd2011-12-23 00:23:59 +000023#include "llvm/Support/FileSystem.h"
Ted Kremenek85b48c62008-11-20 07:56:33 +000024#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola552c1692013-06-11 22:15:02 +000025#include "llvm/Support/Path.h"
Chris Lattner1eed7342008-03-09 04:10:46 +000026using namespace clang;
27
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000028PPCallbacks::~PPCallbacks() {}
Chris Lattner1eed7342008-03-09 04:10:46 +000029
30//===----------------------------------------------------------------------===//
Chris Lattner3e468322008-03-10 06:06:04 +000031// Miscellaneous Methods.
Chris Lattner1eed7342008-03-09 04:10:46 +000032//===----------------------------------------------------------------------===//
33
Chris Lattner1eed7342008-03-09 04:10:46 +000034/// isInPrimaryFile - Return true if we're in the top-level file, not in a
James Dennett1244a0d2012-06-22 05:36:05 +000035/// \#include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner1eed7342008-03-09 04:10:46 +000036bool Preprocessor::isInPrimaryFile() const {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000037 if (IsFileLexer())
Chris Lattner1eed7342008-03-09 04:10:46 +000038 return IncludeMacroStack.empty();
Mike Stump11289f42009-09-09 15:08:12 +000039
Chris Lattner1eed7342008-03-09 04:10:46 +000040 // If there are any stacked lexers, we're in a #include.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000041 assert(IsFileLexer(IncludeMacroStack[0]) &&
Chris Lattner1eed7342008-03-09 04:10:46 +000042 "Top level include stack isn't our primary lexer?");
NAKAMURA Takumia5b348be2017-09-18 04:55:31 +000043 return std::none_of(
44 IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
Vitaly Buka55a27d32017-09-18 08:26:01 +000045 [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });
Chris Lattner1eed7342008-03-09 04:10:46 +000046}
47
48/// getCurrentLexer - Return the current file lexer being lexed from. Note
49/// that this ignores any potentially active macro expansions and _Pragma
50/// expansions going on at the time.
Ted Kremenekb33ce322008-11-20 01:49:44 +000051PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000052 if (IsFileLexer())
Ted Kremenekb33ce322008-11-20 01:49:44 +000053 return CurPPLexer;
Mike Stump11289f42009-09-09 15:08:12 +000054
Chris Lattner1eed7342008-03-09 04:10:46 +000055 // Look for a stacked lexer.
Erik Verbruggene4fd6522016-10-26 13:06:13 +000056 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000057 if (IsFileLexer(ISI))
Ted Kremenekb33ce322008-11-20 01:49:44 +000058 return ISI.ThePPLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +000059 }
Craig Topperd2d442c2014-05-17 23:10:59 +000060 return nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +000061}
62
Chris Lattner3e468322008-03-10 06:06:04 +000063
64//===----------------------------------------------------------------------===//
65// Methods for Entering and Callbacks for leaving various contexts
66//===----------------------------------------------------------------------===//
Chris Lattner1eed7342008-03-09 04:10:46 +000067
68/// EnterSourceFile - Add a source file to the top of the include stack and
Nuno Lopes0e5d13e2009-11-29 17:07:16 +000069/// start lexing tokens from it instead of the current buffer.
Richard Smith67294e22014-01-31 20:47:44 +000070bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
71 SourceLocation Loc) {
David Blaikie7d170102013-05-15 07:37:26 +000072 assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
Chris Lattner1eed7342008-03-09 04:10:46 +000073 ++NumEnteredSourceFiles;
Mike Stump11289f42009-09-09 15:08:12 +000074
Chris Lattner1eed7342008-03-09 04:10:46 +000075 if (MaxIncludeStackDepth < IncludeMacroStack.size())
76 MaxIncludeStackDepth = IncludeMacroStack.size();
77
Ted Kremenekaf058b52008-12-02 19:46:31 +000078 if (PTH) {
Chris Lattner710bb872009-11-30 04:18:44 +000079 if (PTHLexer *PL = PTH->CreateLexer(FID)) {
Richard Smith67294e22014-01-31 20:47:44 +000080 EnterSourceFileWithPTH(PL, CurDir);
81 return false;
Chris Lattner710bb872009-11-30 04:18:44 +000082 }
Ted Kremenekaf058b52008-12-02 19:46:31 +000083 }
Chris Lattner710bb872009-11-30 04:18:44 +000084
85 // Get the MemoryBuffer for this FID, if it fails, we fail.
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +000086 bool Invalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000087 const llvm::MemoryBuffer *InputFile =
88 getSourceManager().getBuffer(FID, Loc, &Invalid);
89 if (Invalid) {
90 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
91 Diag(Loc, diag::err_pp_error_opening_file)
92 << std::string(SourceMgr.getBufferName(FileStart)) << "";
Richard Smith67294e22014-01-31 20:47:44 +000093 return true;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000094 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000095
96 if (isCodeCompletionEnabled() &&
97 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
98 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
99 CodeCompletionLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000100 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000101 }
102
Richard Smith67294e22014-01-31 20:47:44 +0000103 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
104 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000105}
Chris Lattnerc88a23e2008-09-26 20:12:23 +0000106
Ted Kremenekaf058b52008-12-02 19:46:31 +0000107/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
108/// and start lexing tokens from it instead of the current buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000109void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
Richard Smith67294e22014-01-31 20:47:44 +0000110 const DirectoryLookup *CurDir) {
Mike Stump11289f42009-09-09 15:08:12 +0000111
Chris Lattner1eed7342008-03-09 04:10:46 +0000112 // Add the current lexer to the include stack.
Ted Kremenek45245212008-11-19 21:57:25 +0000113 if (CurPPLexer || CurTokenLexer)
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000114 PushIncludeMacroStack();
115
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000116 CurLexer.reset(TheLexer);
Ted Kremenek68ef9fc2008-11-18 00:12:49 +0000117 CurPPLexer = TheLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000118 CurDirLookup = CurDir;
Richard Smithd1386302017-05-04 00:29:54 +0000119 CurLexerSubmodule = nullptr;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000120 if (CurLexerKind != CLK_LexAfterModuleImport)
121 CurLexerKind = CLK_Lexer;
Yaron Kerene02bcdc2015-11-07 16:35:07 +0000122
Chris Lattner1eed7342008-03-09 04:10:46 +0000123 // Notify the client, if desired, that we are in a new source file.
124 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000125 SrcMgr::CharacteristicKind FileType =
Chris Lattnerb03dc762008-09-26 21:18:42 +0000126 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Mike Stump11289f42009-09-09 15:08:12 +0000127
Chris Lattner1eed7342008-03-09 04:10:46 +0000128 Callbacks->FileChanged(CurLexer->getFileLoc(),
129 PPCallbacks::EnterFile, FileType);
130 }
131}
132
Ted Kremenekaf058b52008-12-02 19:46:31 +0000133/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
134/// and start getting tokens from it using the PTH cache.
Mike Stump11289f42009-09-09 15:08:12 +0000135void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
Richard Smith67294e22014-01-31 20:47:44 +0000136 const DirectoryLookup *CurDir) {
Mike Stump11289f42009-09-09 15:08:12 +0000137
Ted Kremenekaf058b52008-12-02 19:46:31 +0000138 if (CurPPLexer || CurTokenLexer)
139 PushIncludeMacroStack();
Chris Lattner1eed7342008-03-09 04:10:46 +0000140
Ted Kremenekaf058b52008-12-02 19:46:31 +0000141 CurDirLookup = CurDir;
142 CurPTHLexer.reset(PL);
143 CurPPLexer = CurPTHLexer.get();
Richard Smithd1386302017-05-04 00:29:54 +0000144 CurLexerSubmodule = nullptr;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000145 if (CurLexerKind != CLK_LexAfterModuleImport)
146 CurLexerKind = CLK_PTHLexer;
147
Ted Kremenekaf058b52008-12-02 19:46:31 +0000148 // Notify the client, if desired, that we are in a new source file.
149 if (Callbacks) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000150 FileID FID = CurPPLexer->getFileID();
Chris Lattner4fd8b952009-01-19 08:01:53 +0000151 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
152 SrcMgr::CharacteristicKind FileType =
153 SourceMgr.getFileCharacteristic(EnterLoc);
154 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
Ted Kremenekaf058b52008-12-02 19:46:31 +0000155 }
156}
Chris Lattner1eed7342008-03-09 04:10:46 +0000157
158/// EnterMacro - Add a Macro to the top of the include stack and start lexing
159/// tokens from it instead of the current buffer.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000160void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
Richard Smith5edd5832012-08-30 13:38:46 +0000161 MacroInfo *Macro, MacroArgs *Args) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000162 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000163 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000164 TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000165 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000166 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000167 TokLexer->Init(Tok, ILEnd, Macro, Args);
168 }
169
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000170 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000171 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000172 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000173 if (CurLexerKind != CLK_LexAfterModuleImport)
174 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000175}
176
177/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner3e468322008-03-10 06:06:04 +0000178/// which will cause the lexer to start returning the specified tokens.
179///
180/// If DisableMacroExpansion is true, tokens lexed from the token stream will
181/// not be subject to further macro expansion. Otherwise, these tokens will
182/// be re-macro-expanded when/if expansion is enabled.
183///
184/// If OwnsTokens is false, this method assumes that the specified stream of
185/// tokens has a permanent owner somewhere, so they do not need to be copied.
186/// If it is true, it assumes the array of tokens is allocated with new[] and
187/// must be freed.
188///
189void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
190 bool DisableMacroExpansion,
191 bool OwnsTokens) {
Richard Smithbdf54a212014-09-23 21:05:52 +0000192 if (CurLexerKind == CLK_CachingLexer) {
193 if (CachedLexPos < CachedTokens.size()) {
194 // We're entering tokens into the middle of our cached token stream. We
195 // can't represent that, so just insert the tokens into the buffer.
196 CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
197 Toks, Toks + NumToks);
198 if (OwnsTokens)
199 delete [] Toks;
200 return;
201 }
202
203 // New tokens are at the end of the cached token sequnece; insert the
204 // token stream underneath the caching lexer.
205 ExitCachingLexMode();
206 EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
207 EnterCachingLexMode();
208 return;
209 }
210
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000211 // Create a macro expander to expand from the specified token stream.
David Blaikie6d5038c2014-08-29 19:36:52 +0000212 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000213 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000214 TokLexer = llvm::make_unique<TokenLexer>(
215 Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000216 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000217 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000218 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
219 }
220
Chris Lattner1eed7342008-03-09 04:10:46 +0000221 // Save our current state.
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000222 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000223 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000224 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000225 if (CurLexerKind != CLK_LexAfterModuleImport)
226 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000227}
228
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000229/// \brief Compute the relative path that names the given file relative to
230/// the given directory.
231static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
232 const FileEntry *File,
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000233 SmallString<128> &Result) {
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000234 Result.clear();
235
236 StringRef FilePath = File->getDir()->getName();
237 StringRef Path = FilePath;
238 while (!Path.empty()) {
239 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
240 if (CurDir == Dir) {
241 Result = FilePath.substr(Path.size());
242 llvm::sys::path::append(Result,
243 llvm::sys::path::filename(File->getName()));
244 return;
245 }
246 }
247
248 Path = llvm::sys::path::parent_path(Path);
249 }
250
251 Result = File->getName();
252}
253
Eli Friedman0834a4b2013-09-19 00:41:32 +0000254void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
255 if (CurTokenLexer) {
256 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
257 return;
258 }
259 if (CurLexer) {
260 CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
261 return;
262 }
263 // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
264 // but it might if they're empty?
265}
266
Richard Smith34f30512013-11-23 04:06:09 +0000267/// \brief Determine the location to use as the end of the buffer for a lexer.
268///
269/// If the file ends with a newline, form the EOF token on the newline itself,
270/// rather than "on the line following it", which doesn't exist. This makes
271/// diagnostics relating to the end of file include the last file that the user
272/// actually typed, which is goodness.
273const char *Preprocessor::getCurLexerEndPos() {
274 const char *EndPos = CurLexer->BufferEnd;
275 if (EndPos != CurLexer->BufferStart &&
276 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
277 --EndPos;
278
279 // Handle \n\r and \r\n:
280 if (EndPos != CurLexer->BufferStart &&
281 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
282 EndPos[-1] != EndPos[0])
283 --EndPos;
284 }
285
286 return EndPos;
287}
288
Bruno Cardoso Lopesb9075632017-04-27 22:29:14 +0000289static void collectAllSubModulesWithUmbrellaHeader(
290 const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
291 if (Mod.getUmbrellaHeader())
292 SubMods.push_back(&Mod);
293 for (auto *M : Mod.submodules())
294 collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
295}
296
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000297void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
298 assert(Mod.getUmbrellaHeader() && "Module must use umbrella header");
299 SourceLocation StartLoc =
300 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
301 if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header, StartLoc))
302 return;
303
304 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
305 const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
306 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
307 std::error_code EC;
308 for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End;
309 Entry != End && !EC; Entry.increment(EC)) {
310 using llvm::StringSwitch;
311
312 // Check whether this entry has an extension typically associated with
313 // headers.
314 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName()))
315 .Cases(".h", ".H", ".hh", ".hpp", true)
316 .Default(false))
317 continue;
318
319 if (const FileEntry *Header = getFileManager().getFile(Entry->getName()))
320 if (!getSourceManager().hasFileInfo(Header)) {
321 if (!ModMap.isHeaderInUnavailableModule(Header)) {
322 // Find the relative path that would access this header.
323 SmallString<128> RelativePath;
324 computeRelativePath(FileMgr, Dir, Header, RelativePath);
325 Diag(StartLoc, diag::warn_uncovered_module_header)
326 << Mod.getFullModuleName() << RelativePath;
327 }
328 }
329 }
330}
Richard Smith34f30512013-11-23 04:06:09 +0000331
Chris Lattner1eed7342008-03-09 04:10:46 +0000332/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
333/// the current file. This either returns the EOF token or pops a level off
334/// the include stack and keeps going.
335bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
336 assert(!CurTokenLexer &&
337 "Ending a file when currently in a macro!");
Mike Stump11289f42009-09-09 15:08:12 +0000338
Richard Smithd1386302017-05-04 00:29:54 +0000339 // If we have an unclosed module region from a pragma at the end of a
340 // module, complain and close it now.
341 // FIXME: This is not correct if we are building a module from PTH.
342 const bool LeavingSubmodule = CurLexer && CurLexerSubmodule;
343 if ((LeavingSubmodule || IncludeMacroStack.empty()) &&
344 !BuildingSubmoduleStack.empty() &&
345 BuildingSubmoduleStack.back().IsPragma) {
346 Diag(BuildingSubmoduleStack.back().ImportLoc,
347 diag::err_pp_module_begin_without_module_end);
348 Module *M = LeaveSubmodule(/*ForPragma*/true);
349
350 Result.startToken();
351 const char *EndPos = getCurLexerEndPos();
352 CurLexer->BufferPtr = EndPos;
353 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
354 Result.setAnnotationEndLoc(Result.getLocation());
355 Result.setAnnotationValue(M);
356 return true;
357 }
358
Chris Lattner1eed7342008-03-09 04:10:46 +0000359 // See if this file had a controlling macro.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000360 if (CurPPLexer) { // Not ending a macro, ignore it.
Mike Stump11289f42009-09-09 15:08:12 +0000361 if (const IdentifierInfo *ControllingMacro =
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000362 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Steve Naroff3fa455a2009-04-24 20:03:17 +0000363 // Okay, this has a controlling macro, remember in HeaderFileInfo.
Yaron Keren65224612015-12-18 10:30:12 +0000364 if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000365 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +0000366 if (MacroInfo *MI =
Yaron Keren9370ea22017-04-16 15:53:19 +0000367 getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
368 MI->setUsedForHeaderGuard(true);
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000369 if (const IdentifierInfo *DefinedMacro =
370 CurPPLexer->MIOpt.GetDefinedMacro()) {
Richard Smith20e883e2015-04-29 23:20:19 +0000371 if (!isMacroDefined(ControllingMacro) &&
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000372 DefinedMacro != ControllingMacro &&
373 HeaderInfo.FirstTimeLexingFile(FE)) {
Ismail Pazarbasi8d0f2f32013-10-12 23:17:37 +0000374
375 // If the edit distance between the two macros is more than 50%,
376 // DefinedMacro may not be header guard, or can be header guard of
377 // another header file. Therefore, it maybe defining something
378 // completely different. This can be observed in the wild when
379 // handling feature macros or header guards in different files.
380
381 const StringRef ControllingMacroName = ControllingMacro->getName();
382 const StringRef DefinedMacroName = DefinedMacro->getName();
383 const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
384 DefinedMacroName.size()) / 2;
385 const unsigned ED = ControllingMacroName.edit_distance(
386 DefinedMacroName, true, MaxHalfLength);
387 if (ED <= MaxHalfLength) {
388 // Emit a warning for a bad header guard.
389 Diag(CurPPLexer->MIOpt.GetMacroLocation(),
390 diag::warn_header_guard)
391 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
392 Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
393 diag::note_header_guard)
394 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
395 << ControllingMacro
396 << FixItHint::CreateReplacement(
397 CurPPLexer->MIOpt.GetDefinedLocation(),
398 ControllingMacro->getName());
399 }
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000400 }
401 }
402 }
Chris Lattner1eed7342008-03-09 04:10:46 +0000403 }
404 }
Mike Stump11289f42009-09-09 15:08:12 +0000405
John McCall95ff2702011-10-18 00:44:04 +0000406 // Complain about reaching a true EOF within arc_cf_code_audited.
407 // We don't want to complain about reaching the end of a macro
408 // instantiation or a _Pragma.
409 if (PragmaARCCFCodeAuditedLoc.isValid() &&
John McCall43d4dd42011-10-18 01:36:41 +0000410 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
John McCall32f5fe12011-09-30 05:12:12 +0000411 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
412
413 // Recover by leaving immediately.
414 PragmaARCCFCodeAuditedLoc = SourceLocation();
415 }
416
Douglas Gregor2a20bd12015-06-19 18:25:57 +0000417 // Complain about reaching a true EOF within assume_nonnull.
418 // We don't want to complain about reaching the end of a macro
419 // instantiation or a _Pragma.
420 if (PragmaAssumeNonNullLoc.isValid() &&
421 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
422 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
423
424 // Recover by leaving immediately.
425 PragmaAssumeNonNullLoc = SourceLocation();
426 }
427
Chris Lattner1eed7342008-03-09 04:10:46 +0000428 // If this is a #include'd file, pop it off the include stack and continue
429 // lexing the #includer file.
430 if (!IncludeMacroStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000431
432 // If we lexed the code-completion file, act as if we reached EOF.
433 if (isCodeCompletionEnabled() && CurPPLexer &&
434 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
435 CodeCompletionFileLoc) {
436 if (CurLexer) {
437 Result.startToken();
438 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
439 CurLexer.reset();
440 } else {
441 assert(CurPTHLexer && "Got EOF but no current lexer set!");
442 CurPTHLexer->getEOF(Result);
443 CurPTHLexer.reset();
444 }
445
Craig Topperd2d442c2014-05-17 23:10:59 +0000446 CurPPLexer = nullptr;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000447 return true;
448 }
449
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +0000450 if (!isEndOfMacro && CurPPLexer &&
451 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
452 // Notify SourceManager to record the number of FileIDs that were created
453 // during lexing of the #include'd file.
454 unsigned NumFIDs =
455 SourceMgr.local_sloc_entry_size() -
456 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
457 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
458 }
459
Ilya Biryukovf3150002017-08-21 12:03:08 +0000460 bool ExitedFromPredefinesFile = false;
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000461 FileID ExitedFID;
Ilya Biryukovf3150002017-08-21 12:03:08 +0000462 if (!isEndOfMacro && CurPPLexer) {
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000463 ExitedFID = CurPPLexer->getFileID();
Richard Smith34f30512013-11-23 04:06:09 +0000464
Ilya Biryukovf3150002017-08-21 12:03:08 +0000465 assert(PredefinesFileID.isValid() &&
466 "HandleEndOfFile is called before PredefinesFileId is set");
467 ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
468 }
469
Richard Smith34f30512013-11-23 04:06:09 +0000470 if (LeavingSubmodule) {
Richard Smithd1386302017-05-04 00:29:54 +0000471 // We're done with this submodule.
472 Module *M = LeaveSubmodule(/*ForPragma*/false);
473
Richard Smith67294e22014-01-31 20:47:44 +0000474 // Notify the parser that we've left the module.
Richard Smith34f30512013-11-23 04:06:09 +0000475 const char *EndPos = getCurLexerEndPos();
476 Result.startToken();
477 CurLexer->BufferPtr = EndPos;
478 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
479 Result.setAnnotationEndLoc(Result.getLocation());
Richard Smithd1386302017-05-04 00:29:54 +0000480 Result.setAnnotationValue(M);
Richard Smith34f30512013-11-23 04:06:09 +0000481 }
482
Chris Lattner1eed7342008-03-09 04:10:46 +0000483 // We're done with the #included file.
484 RemoveTopOfLexerStack();
485
Eli Friedman0834a4b2013-09-19 00:41:32 +0000486 // Propagate info about start-of-line/leading white-space/etc.
487 PropagateLineStartLeadingSpaceInfo(Result);
488
Chris Lattner1eed7342008-03-09 04:10:46 +0000489 // Notify the client, if desired, that we are in a new source file.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000490 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000491 SrcMgr::CharacteristicKind FileType =
Chris Lattner4fd8b952009-01-19 08:01:53 +0000492 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
493 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000494 PPCallbacks::ExitFile, FileType, ExitedFID);
Chris Lattner1eed7342008-03-09 04:10:46 +0000495 }
496
Ilya Biryukovf3150002017-08-21 12:03:08 +0000497 // Restore conditional stack from the preamble right after exiting from the
498 // predefines file.
499 if (ExitedFromPredefinesFile)
500 replayPreambleConditionalStack();
501
Richard Smith34f30512013-11-23 04:06:09 +0000502 // Client should lex another token unless we generated an EOM.
503 return LeavingSubmodule;
Chris Lattner1eed7342008-03-09 04:10:46 +0000504 }
505
Richard Smith34f30512013-11-23 04:06:09 +0000506 // If this is the end of the main file, form an EOF token.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000507 if (CurLexer) {
Richard Smith34f30512013-11-23 04:06:09 +0000508 const char *EndPos = getCurLexerEndPos();
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000509 Result.startToken();
510 CurLexer->BufferPtr = EndPos;
511 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Mike Stump11289f42009-09-09 15:08:12 +0000512
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000513 if (isCodeCompletionEnabled()) {
514 // Inserting the code-completion point increases the source buffer by 1,
515 // but the main FileID was created before inserting the point.
516 // Compensate by reducing the EOF location by 1, otherwise the location
517 // will point to the next FileID.
518 // FIXME: This is hacky, the code-completion point should probably be
519 // inserted before the main FileID is created.
520 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
521 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
522 }
523
Axel Naumann2eb1d902012-03-16 10:40:17 +0000524 if (!isIncrementalProcessingEnabled())
525 // We're done with lexing.
526 CurLexer.reset();
Chris Lattner190f64e2009-02-13 23:06:48 +0000527 } else {
528 assert(CurPTHLexer && "Got EOF but no current lexer set!");
Ted Kremenek78cc2472008-12-23 19:24:24 +0000529 CurPTHLexer->getEOF(Result);
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000530 CurPTHLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000531 }
Axel Naumann2eb1d902012-03-16 10:40:17 +0000532
533 if (!isIncrementalProcessingEnabled())
Craig Topperd2d442c2014-05-17 23:10:59 +0000534 CurPPLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000535
Argyrios Kyrtzidis8ed74142014-03-08 21:18:26 +0000536 if (TUKind == TU_Complete) {
Argyrios Kyrtzidise1974dc2014-03-07 07:47:58 +0000537 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
538 // collected all macro locations that we need to warn because they are not
539 // used.
540 for (WarnUnusedMacroLocsTy::iterator
541 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
542 I!=E; ++I)
543 Diag(*I, diag::pp_macro_not_used);
544 }
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000545
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000546 // If we are building a module that has an umbrella header, make sure that
Bruno Cardoso Lopesb9075632017-04-27 22:29:14 +0000547 // each of the headers within the directory, including all submodules, is
548 // covered by the umbrella header was actually included by the umbrella
549 // header.
550 if (Module *Mod = getCurrentModule()) {
551 llvm::SmallVector<const Module *, 4> AllMods;
552 collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
553 for (auto *M : AllMods)
554 diagnoseMissingHeaderInUmbrellaDir(*M);
555 }
Douglas Gregorf4e76b82013-05-20 13:49:41 +0000556
Chris Lattner1eed7342008-03-09 04:10:46 +0000557 return true;
558}
559
560/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
561/// hits the end of its token stream.
562bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000563 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000564 "Ending a macro when currently in a #include file!");
565
Argyrios Kyrtzidis8cc04592011-06-29 22:20:11 +0000566 if (!MacroExpandingLexersStack.empty() &&
567 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
568 removeCachedMacroExpandedTokensOfLastLexer();
569
Chris Lattner1eed7342008-03-09 04:10:46 +0000570 // Delete or cache the now-dead macro expander.
571 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000572 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000573 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000574 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Chris Lattner1eed7342008-03-09 04:10:46 +0000575
576 // Handle this like a #include file being popped off the stack.
Chris Lattner1eed7342008-03-09 04:10:46 +0000577 return HandleEndOfFile(Result, true);
578}
579
580/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
581/// lexer stack. This should only be used in situations where the current
582/// state of the top-of-stack lexer is unknown.
583void Preprocessor::RemoveTopOfLexerStack() {
584 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Mike Stump11289f42009-09-09 15:08:12 +0000585
Chris Lattner1eed7342008-03-09 04:10:46 +0000586 if (CurTokenLexer) {
587 // Delete or cache the now-dead macro expander.
588 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000589 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000590 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000591 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Mike Stump11289f42009-09-09 15:08:12 +0000592 }
593
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000594 PopIncludeMacroStack();
Chris Lattner1eed7342008-03-09 04:10:46 +0000595}
596
597/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
598/// comment (/##/) in microsoft mode, this method handles updating the current
599/// state, returning the token on the next source line.
600void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000601 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000602 "Pasted comment can only be formed from macro");
Chris Lattner1eed7342008-03-09 04:10:46 +0000603 // We handle this by scanning for the closest real lexer, switching it to
604 // raw mode and preprocessor mode. This will cause it to return \n as an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000605 // explicit EOD token.
Craig Topperd2d442c2014-05-17 23:10:59 +0000606 PreprocessorLexer *FoundLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000607 bool LexerWasInPPMode = false;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000608 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000609 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
Mike Stump11289f42009-09-09 15:08:12 +0000610
Chris Lattner1eed7342008-03-09 04:10:46 +0000611 // Once we find a real lexer, mark it as raw mode (disabling macro
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000612 // expansions) and preprocessor mode (return EOD). We know that the lexer
Chris Lattner1eed7342008-03-09 04:10:46 +0000613 // was *not* in raw mode before, because the macro that the comment came
614 // from was expanded. However, it could have already been in preprocessor
615 // mode (#if COMMENT) in which case we have to return it to that mode and
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000616 // return EOD.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000617 FoundLexer = ISI.ThePPLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000618 FoundLexer->LexingRawMode = true;
619 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
620 FoundLexer->ParsingPreprocessorDirective = true;
621 break;
622 }
Mike Stump11289f42009-09-09 15:08:12 +0000623
Chris Lattner1eed7342008-03-09 04:10:46 +0000624 // Okay, we either found and switched over the lexer, or we didn't find a
625 // lexer. In either case, finish off the macro the comment came from, getting
626 // the next token.
627 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000628
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000629 // Discarding comments as long as we don't have EOF or EOD. This 'comments
Chris Lattner1eed7342008-03-09 04:10:46 +0000630 // out' the rest of the line, including any tokens that came from other macros
631 // that were active, as in:
632 // #define submacro a COMMENT b
633 // submacro c
634 // which should lex to 'a' only: 'b' and 'c' should be removed.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000635 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
Chris Lattner1eed7342008-03-09 04:10:46 +0000636 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000637
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000638 // If we got an eod token, then we successfully found the end of the line.
639 if (Tok.is(tok::eod)) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000640 assert(FoundLexer && "Can't get end of line without an active lexer");
641 // Restore the lexer back to normal mode instead of raw mode.
642 FoundLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000643
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000644 // If the lexer was already in preprocessor mode, just return the EOD token
Chris Lattner1eed7342008-03-09 04:10:46 +0000645 // to finish the preprocessor line.
646 if (LexerWasInPPMode) return;
Mike Stump11289f42009-09-09 15:08:12 +0000647
Chris Lattner1eed7342008-03-09 04:10:46 +0000648 // Otherwise, switch out of PP mode and return the next lexed token.
649 FoundLexer->ParsingPreprocessorDirective = false;
650 return Lex(Tok);
651 }
Mike Stump11289f42009-09-09 15:08:12 +0000652
Chris Lattner1eed7342008-03-09 04:10:46 +0000653 // If we got an EOF token, then we reached the end of the token stream but
654 // didn't find an explicit \n. This can only happen if there was no lexer
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000655 // active (an active lexer would return EOD at EOF if there was no \n in
Chris Lattner1eed7342008-03-09 04:10:46 +0000656 // preprocessor directive mode), so just return EOF as our token.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000657 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
Chris Lattner1eed7342008-03-09 04:10:46 +0000658}
Richard Smithb8b2ed62015-04-23 18:18:26 +0000659
Richard Smithd1386302017-05-04 00:29:54 +0000660void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
661 bool ForPragma) {
Richard Smith04765ae2015-05-21 01:20:10 +0000662 if (!getLangOpts().ModulesLocalVisibility) {
663 // Just track that we entered this submodule.
Richard Smithd1386302017-05-04 00:29:54 +0000664 BuildingSubmoduleStack.push_back(
665 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
666 PendingModuleMacroNames.size()));
Richard Smith04765ae2015-05-21 01:20:10 +0000667 return;
668 }
Richard Smithee977932015-05-01 21:22:17 +0000669
Richard Smith04765ae2015-05-21 01:20:10 +0000670 // Resolve as much of the module definition as we can now, before we enter
671 // one of its headers.
672 // FIXME: Can we enable Complain here?
673 // FIXME: Can we do this when local visibility is disabled?
674 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
675 ModMap.resolveExports(M, /*Complain=*/false);
676 ModMap.resolveUses(M, /*Complain=*/false);
677 ModMap.resolveConflicts(M, /*Complain=*/false);
Richard Smith42413142015-05-15 20:05:43 +0000678
Richard Smith04765ae2015-05-21 01:20:10 +0000679 // If this is the first time we've entered this module, set up its state.
Richard Smithe5202932015-05-21 01:26:53 +0000680 auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
Richard Smith04765ae2015-05-21 01:20:10 +0000681 auto &State = R.first->second;
682 bool FirstTime = R.second;
683 if (FirstTime) {
684 // Determine the set of starting macros for this submodule; take these
685 // from the "null" module (the predefines buffer).
Richard Smith4df60932015-06-30 21:29:55 +0000686 //
687 // FIXME: If we have local visibility but not modules enabled, the
688 // NullSubmoduleState is polluted by #defines in the top-level source
689 // file.
Richard Smith04765ae2015-05-21 01:20:10 +0000690 auto &StartingMacros = NullSubmoduleState.Macros;
691
692 // Restore to the starting state.
693 // FIXME: Do this lazily, when each macro name is first referenced.
694 for (auto &Macro : StartingMacros) {
Richard Smith4df60932015-06-30 21:29:55 +0000695 // Skip uninteresting macros.
696 if (!Macro.second.getLatest() &&
697 Macro.second.getOverriddenMacros().empty())
698 continue;
699
Richard Smith04765ae2015-05-21 01:20:10 +0000700 MacroState MS(Macro.second.getLatest());
701 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
702 State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
703 }
704 }
705
706 // Track that we entered this module.
Richard Smithd1386302017-05-04 00:29:54 +0000707 BuildingSubmoduleStack.push_back(
708 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
709 PendingModuleMacroNames.size()));
Richard Smith04765ae2015-05-21 01:20:10 +0000710
711 // Switch to this submodule as the current submodule.
712 CurSubmoduleState = &State;
713
714 // This module is visible to itself.
715 if (FirstTime)
Richard Smith42413142015-05-15 20:05:43 +0000716 makeModuleVisible(M, ImportLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000717}
718
Richard Smith802182f2016-02-23 23:20:51 +0000719bool Preprocessor::needModuleMacros() const {
720 // If we're not within a submodule, we never need to create ModuleMacros.
721 if (BuildingSubmoduleStack.empty())
722 return false;
723 // If we are tracking module macro visibility even for textually-included
724 // headers, we need ModuleMacros.
725 if (getLangOpts().ModulesLocalVisibility)
726 return true;
727 // Otherwise, we only need module macros if we're actually compiling a module
728 // interface.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000729 return getLangOpts().isCompilingModule();
Richard Smith802182f2016-02-23 23:20:51 +0000730}
731
Richard Smithd1386302017-05-04 00:29:54 +0000732Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
733 if (BuildingSubmoduleStack.empty() ||
734 BuildingSubmoduleStack.back().IsPragma != ForPragma) {
735 assert(ForPragma && "non-pragma module enter/leave mismatch");
736 return nullptr;
737 }
738
Richard Smithb8b2ed62015-04-23 18:18:26 +0000739 auto &Info = BuildingSubmoduleStack.back();
740
Richard Smithdbbc5232015-05-14 02:25:44 +0000741 Module *LeavingMod = Info.M;
742 SourceLocation ImportLoc = Info.ImportLoc;
743
Richard Smith4971ed02017-05-19 23:32:38 +0000744 if (!needModuleMacros() ||
Richard Smith802182f2016-02-23 23:20:51 +0000745 (!getLangOpts().ModulesLocalVisibility &&
746 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
747 // If we don't need module macros, or this is not a module for which we
748 // are tracking macro visibility, don't build any, and preserve the list
749 // of pending names for the surrounding submodule.
Richard Smithe5b53502016-02-19 22:43:58 +0000750 BuildingSubmoduleStack.pop_back();
751 makeModuleVisible(LeavingMod, ImportLoc);
Richard Smithd1386302017-05-04 00:29:54 +0000752 return LeavingMod;
Richard Smithe5b53502016-02-19 22:43:58 +0000753 }
754
Richard Smithb8b2ed62015-04-23 18:18:26 +0000755 // Create ModuleMacros for any macros defined in this submodule.
Richard Smith802182f2016-02-23 23:20:51 +0000756 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
757 for (unsigned I = Info.OuterPendingModuleMacroNames;
758 I != PendingModuleMacroNames.size(); ++I) {
759 auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
760 if (!VisitedMacros.insert(II).second)
761 continue;
762
763 auto MacroIt = CurSubmoduleState->Macros.find(II);
764 if (MacroIt == CurSubmoduleState->Macros.end())
765 continue;
766 auto &Macro = MacroIt->second;
Richard Smithee977932015-05-01 21:22:17 +0000767
768 // Find the starting point for the MacroDirective chain in this submodule.
Richard Smith04765ae2015-05-21 01:20:10 +0000769 MacroDirective *OldMD = nullptr;
Richard Smithe5b53502016-02-19 22:43:58 +0000770 auto *OldState = Info.OuterSubmoduleState;
771 if (getLangOpts().ModulesLocalVisibility)
772 OldState = &NullSubmoduleState;
773 if (OldState && OldState != CurSubmoduleState) {
Richard Smith04765ae2015-05-21 01:20:10 +0000774 // FIXME: It'd be better to start at the state from when we most recently
775 // entered this submodule, but it doesn't really matter.
Richard Smithe5b53502016-02-19 22:43:58 +0000776 auto &OldMacros = OldState->Macros;
Richard Smith802182f2016-02-23 23:20:51 +0000777 auto OldMacroIt = OldMacros.find(II);
Richard Smithe5b53502016-02-19 22:43:58 +0000778 if (OldMacroIt == OldMacros.end())
Richard Smithee977932015-05-01 21:22:17 +0000779 OldMD = nullptr;
780 else
Richard Smithe5b53502016-02-19 22:43:58 +0000781 OldMD = OldMacroIt->second.getLatest();
Richard Smithee977932015-05-01 21:22:17 +0000782 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000783
784 // This module may have exported a new macro. If so, create a ModuleMacro
785 // representing that fact.
786 bool ExplicitlyPublic = false;
Richard Smith802182f2016-02-23 23:20:51 +0000787 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
Richard Smith1e172852015-04-28 21:05:07 +0000788 assert(MD && "broken macro directive chain");
789
Richard Smithb8b2ed62015-04-23 18:18:26 +0000790 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
791 // The latest visibility directive for a name in a submodule affects
792 // all the directives that come before it.
793 if (VisMD->isPublic())
794 ExplicitlyPublic = true;
795 else if (!ExplicitlyPublic)
796 // Private with no following public directive: not exported.
797 break;
798 } else {
799 MacroInfo *Def = nullptr;
800 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
801 Def = DefMD->getInfo();
802
803 // FIXME: Issue a warning if multiple headers for the same submodule
804 // define a macro, rather than silently ignoring all but the first.
805 bool IsNew;
Richard Smith32dbd692015-05-02 01:14:40 +0000806 // Don't bother creating a module macro if it would represent a #undef
807 // that doesn't override anything.
Richard Smith802182f2016-02-23 23:20:51 +0000808 if (Def || !Macro.getOverriddenMacros().empty())
Richard Smithdbbc5232015-05-14 02:25:44 +0000809 addModuleMacro(LeavingMod, II, Def,
Richard Smith802182f2016-02-23 23:20:51 +0000810 Macro.getOverriddenMacros(), IsNew);
Richard Smith4971ed02017-05-19 23:32:38 +0000811
812 if (!getLangOpts().ModulesLocalVisibility) {
813 // This macro is exposed to the rest of this compilation as a
814 // ModuleMacro; we don't need to track its MacroDirective any more.
815 Macro.setLatest(nullptr);
816 Macro.setOverriddenMacros(*this, {});
817 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000818 break;
819 }
820 }
Richard Smith753e0072015-04-27 23:21:38 +0000821 }
Richard Smith802182f2016-02-23 23:20:51 +0000822 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000823
Richard Smith4df60932015-06-30 21:29:55 +0000824 // FIXME: Before we leave this submodule, we should parse all the other
825 // headers within it. Otherwise, we're left with an inconsistent state
826 // where we've made the module visible but don't yet have its complete
827 // contents.
828
Richard Smith04765ae2015-05-21 01:20:10 +0000829 // Put back the outer module's state, if we're tracking it.
Richard Smithee977932015-05-01 21:22:17 +0000830 if (getLangOpts().ModulesLocalVisibility)
Richard Smith04765ae2015-05-21 01:20:10 +0000831 CurSubmoduleState = Info.OuterSubmoduleState;
Richard Smithee977932015-05-01 21:22:17 +0000832
Richard Smithb8b2ed62015-04-23 18:18:26 +0000833 BuildingSubmoduleStack.pop_back();
Richard Smithdbbc5232015-05-14 02:25:44 +0000834
835 // A nested #include makes the included submodule visible.
Richard Smith4df60932015-06-30 21:29:55 +0000836 makeModuleVisible(LeavingMod, ImportLoc);
Richard Smithd1386302017-05-04 00:29:54 +0000837 return LeavingMod;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000838}