blob: e321dd38fed6d12e0a142ceaaaa0585684273ee4 [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"
22#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
Chris Lattner710bb872009-11-30 04:18:44 +000078 // Get the MemoryBuffer for this FID, if it fails, we fail.
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +000079 bool Invalid = false;
Fangrui Song6907ce22018-07-30 19:24:48 +000080 const llvm::MemoryBuffer *InputFile =
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000081 getSourceManager().getBuffer(FID, Loc, &Invalid);
82 if (Invalid) {
83 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
84 Diag(Loc, diag::err_pp_error_opening_file)
85 << std::string(SourceMgr.getBufferName(FileStart)) << "";
Richard Smith67294e22014-01-31 20:47:44 +000086 return true;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000087 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000088
89 if (isCodeCompletionEnabled() &&
90 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
91 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
92 CodeCompletionLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000093 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000094 }
95
Richard Smith67294e22014-01-31 20:47:44 +000096 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
97 return false;
Mike Stump11289f42009-09-09 15:08:12 +000098}
Chris Lattnerc88a23e2008-09-26 20:12:23 +000099
Ted Kremenekaf058b52008-12-02 19:46:31 +0000100/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
101/// and start lexing tokens from it instead of the current buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000102void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
Richard Smith67294e22014-01-31 20:47:44 +0000103 const DirectoryLookup *CurDir) {
Mike Stump11289f42009-09-09 15:08:12 +0000104
Chris Lattner1eed7342008-03-09 04:10:46 +0000105 // Add the current lexer to the include stack.
Ted Kremenek45245212008-11-19 21:57:25 +0000106 if (CurPPLexer || CurTokenLexer)
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000107 PushIncludeMacroStack();
108
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000109 CurLexer.reset(TheLexer);
Ted Kremenek68ef9fc2008-11-18 00:12:49 +0000110 CurPPLexer = TheLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000111 CurDirLookup = CurDir;
Richard Smithd1386302017-05-04 00:29:54 +0000112 CurLexerSubmodule = nullptr;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000113 if (CurLexerKind != CLK_LexAfterModuleImport)
114 CurLexerKind = CLK_Lexer;
Yaron Kerene02bcdc2015-11-07 16:35:07 +0000115
Chris Lattner1eed7342008-03-09 04:10:46 +0000116 // Notify the client, if desired, that we are in a new source file.
117 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000118 SrcMgr::CharacteristicKind FileType =
Chris Lattnerb03dc762008-09-26 21:18:42 +0000119 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Mike Stump11289f42009-09-09 15:08:12 +0000120
Chris Lattner1eed7342008-03-09 04:10:46 +0000121 Callbacks->FileChanged(CurLexer->getFileLoc(),
122 PPCallbacks::EnterFile, FileType);
123 }
124}
125
Chris Lattner1eed7342008-03-09 04:10:46 +0000126/// EnterMacro - Add a Macro to the top of the include stack and start lexing
127/// tokens from it instead of the current buffer.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000128void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
Richard Smith5edd5832012-08-30 13:38:46 +0000129 MacroInfo *Macro, MacroArgs *Args) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000130 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000131 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000132 TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000133 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000134 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000135 TokLexer->Init(Tok, ILEnd, Macro, Args);
136 }
137
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000138 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000139 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000140 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000141 if (CurLexerKind != CLK_LexAfterModuleImport)
142 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000143}
144
145/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner3e468322008-03-10 06:06:04 +0000146/// which will cause the lexer to start returning the specified tokens.
147///
148/// If DisableMacroExpansion is true, tokens lexed from the token stream will
149/// not be subject to further macro expansion. Otherwise, these tokens will
150/// be re-macro-expanded when/if expansion is enabled.
151///
152/// If OwnsTokens is false, this method assumes that the specified stream of
153/// tokens has a permanent owner somewhere, so they do not need to be copied.
154/// If it is true, it assumes the array of tokens is allocated with new[] and
155/// must be freed.
156///
157void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
158 bool DisableMacroExpansion,
159 bool OwnsTokens) {
Richard Smithbdf54a212014-09-23 21:05:52 +0000160 if (CurLexerKind == CLK_CachingLexer) {
161 if (CachedLexPos < CachedTokens.size()) {
162 // We're entering tokens into the middle of our cached token stream. We
163 // can't represent that, so just insert the tokens into the buffer.
164 CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
165 Toks, Toks + NumToks);
166 if (OwnsTokens)
167 delete [] Toks;
168 return;
169 }
170
171 // New tokens are at the end of the cached token sequnece; insert the
172 // token stream underneath the caching lexer.
173 ExitCachingLexMode();
174 EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
175 EnterCachingLexMode();
176 return;
177 }
178
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000179 // Create a macro expander to expand from the specified token stream.
David Blaikie6d5038c2014-08-29 19:36:52 +0000180 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000181 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000182 TokLexer = llvm::make_unique<TokenLexer>(
183 Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000184 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000185 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000186 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
187 }
188
Chris Lattner1eed7342008-03-09 04:10:46 +0000189 // Save our current state.
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000190 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000191 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000192 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000193 if (CurLexerKind != CLK_LexAfterModuleImport)
194 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000195}
196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000197/// Compute the relative path that names the given file relative to
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000198/// the given directory.
199static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
200 const FileEntry *File,
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000201 SmallString<128> &Result) {
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000202 Result.clear();
203
204 StringRef FilePath = File->getDir()->getName();
205 StringRef Path = FilePath;
206 while (!Path.empty()) {
207 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
208 if (CurDir == Dir) {
209 Result = FilePath.substr(Path.size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000210 llvm::sys::path::append(Result,
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000211 llvm::sys::path::filename(File->getName()));
212 return;
213 }
214 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000215
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000216 Path = llvm::sys::path::parent_path(Path);
217 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000218
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000219 Result = File->getName();
220}
221
Eli Friedman0834a4b2013-09-19 00:41:32 +0000222void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
223 if (CurTokenLexer) {
224 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
225 return;
226 }
227 if (CurLexer) {
228 CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
229 return;
230 }
231 // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
232 // but it might if they're empty?
233}
234
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000235/// Determine the location to use as the end of the buffer for a lexer.
Richard Smith34f30512013-11-23 04:06:09 +0000236///
237/// If the file ends with a newline, form the EOF token on the newline itself,
238/// rather than "on the line following it", which doesn't exist. This makes
239/// diagnostics relating to the end of file include the last file that the user
240/// actually typed, which is goodness.
241const char *Preprocessor::getCurLexerEndPos() {
242 const char *EndPos = CurLexer->BufferEnd;
243 if (EndPos != CurLexer->BufferStart &&
244 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
245 --EndPos;
246
247 // Handle \n\r and \r\n:
248 if (EndPos != CurLexer->BufferStart &&
249 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
250 EndPos[-1] != EndPos[0])
251 --EndPos;
252 }
253
254 return EndPos;
255}
256
Bruno Cardoso Lopesb9075632017-04-27 22:29:14 +0000257static void collectAllSubModulesWithUmbrellaHeader(
258 const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
259 if (Mod.getUmbrellaHeader())
260 SubMods.push_back(&Mod);
261 for (auto *M : Mod.submodules())
262 collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
263}
264
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000265void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
266 assert(Mod.getUmbrellaHeader() && "Module must use umbrella header");
267 SourceLocation StartLoc =
268 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
269 if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header, StartLoc))
270 return;
271
272 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
273 const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
Jonas Devliegherefc514902018-10-10 13:27:25 +0000274 llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000275 std::error_code EC;
Jonas Devliegherefc514902018-10-10 13:27:25 +0000276 for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
277 End;
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000278 Entry != End && !EC; Entry.increment(EC)) {
279 using llvm::StringSwitch;
280
281 // Check whether this entry has an extension typically associated with
282 // headers.
Sam McCall0ae00562018-09-14 12:47:38 +0000283 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000284 .Cases(".h", ".H", ".hh", ".hpp", true)
285 .Default(false))
286 continue;
287
Sam McCall0ae00562018-09-14 12:47:38 +0000288 if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000289 if (!getSourceManager().hasFileInfo(Header)) {
290 if (!ModMap.isHeaderInUnavailableModule(Header)) {
291 // Find the relative path that would access this header.
292 SmallString<128> RelativePath;
293 computeRelativePath(FileMgr, Dir, Header, RelativePath);
294 Diag(StartLoc, diag::warn_uncovered_module_header)
295 << Mod.getFullModuleName() << RelativePath;
296 }
297 }
298 }
299}
Richard Smith34f30512013-11-23 04:06:09 +0000300
Chris Lattner1eed7342008-03-09 04:10:46 +0000301/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
302/// the current file. This either returns the EOF token or pops a level off
303/// the include stack and keeps going.
304bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
305 assert(!CurTokenLexer &&
306 "Ending a file when currently in a macro!");
Mike Stump11289f42009-09-09 15:08:12 +0000307
Richard Smithd1386302017-05-04 00:29:54 +0000308 // If we have an unclosed module region from a pragma at the end of a
309 // module, complain and close it now.
Richard Smithd1386302017-05-04 00:29:54 +0000310 const bool LeavingSubmodule = CurLexer && CurLexerSubmodule;
311 if ((LeavingSubmodule || IncludeMacroStack.empty()) &&
312 !BuildingSubmoduleStack.empty() &&
313 BuildingSubmoduleStack.back().IsPragma) {
314 Diag(BuildingSubmoduleStack.back().ImportLoc,
315 diag::err_pp_module_begin_without_module_end);
316 Module *M = LeaveSubmodule(/*ForPragma*/true);
317
318 Result.startToken();
319 const char *EndPos = getCurLexerEndPos();
320 CurLexer->BufferPtr = EndPos;
321 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
322 Result.setAnnotationEndLoc(Result.getLocation());
323 Result.setAnnotationValue(M);
324 return true;
325 }
326
Chris Lattner1eed7342008-03-09 04:10:46 +0000327 // See if this file had a controlling macro.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000328 if (CurPPLexer) { // Not ending a macro, ignore it.
Mike Stump11289f42009-09-09 15:08:12 +0000329 if (const IdentifierInfo *ControllingMacro =
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000330 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Steve Naroff3fa455a2009-04-24 20:03:17 +0000331 // Okay, this has a controlling macro, remember in HeaderFileInfo.
Yaron Keren65224612015-12-18 10:30:12 +0000332 if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000333 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +0000334 if (MacroInfo *MI =
Yaron Keren9370ea22017-04-16 15:53:19 +0000335 getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
336 MI->setUsedForHeaderGuard(true);
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000337 if (const IdentifierInfo *DefinedMacro =
338 CurPPLexer->MIOpt.GetDefinedMacro()) {
Richard Smith20e883e2015-04-29 23:20:19 +0000339 if (!isMacroDefined(ControllingMacro) &&
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000340 DefinedMacro != ControllingMacro &&
341 HeaderInfo.FirstTimeLexingFile(FE)) {
Ismail Pazarbasi8d0f2f32013-10-12 23:17:37 +0000342
343 // If the edit distance between the two macros is more than 50%,
344 // DefinedMacro may not be header guard, or can be header guard of
345 // another header file. Therefore, it maybe defining something
346 // completely different. This can be observed in the wild when
347 // handling feature macros or header guards in different files.
348
349 const StringRef ControllingMacroName = ControllingMacro->getName();
350 const StringRef DefinedMacroName = DefinedMacro->getName();
351 const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
352 DefinedMacroName.size()) / 2;
353 const unsigned ED = ControllingMacroName.edit_distance(
354 DefinedMacroName, true, MaxHalfLength);
355 if (ED <= MaxHalfLength) {
356 // Emit a warning for a bad header guard.
357 Diag(CurPPLexer->MIOpt.GetMacroLocation(),
358 diag::warn_header_guard)
359 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
360 Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
361 diag::note_header_guard)
362 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
363 << ControllingMacro
364 << FixItHint::CreateReplacement(
365 CurPPLexer->MIOpt.GetDefinedLocation(),
366 ControllingMacro->getName());
367 }
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000368 }
369 }
370 }
Chris Lattner1eed7342008-03-09 04:10:46 +0000371 }
372 }
Mike Stump11289f42009-09-09 15:08:12 +0000373
John McCall95ff2702011-10-18 00:44:04 +0000374 // Complain about reaching a true EOF within arc_cf_code_audited.
375 // We don't want to complain about reaching the end of a macro
376 // instantiation or a _Pragma.
377 if (PragmaARCCFCodeAuditedLoc.isValid() &&
John McCall43d4dd42011-10-18 01:36:41 +0000378 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
John McCall32f5fe12011-09-30 05:12:12 +0000379 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
380
381 // Recover by leaving immediately.
382 PragmaARCCFCodeAuditedLoc = SourceLocation();
383 }
384
Douglas Gregor2a20bd12015-06-19 18:25:57 +0000385 // Complain about reaching a true EOF within assume_nonnull.
386 // We don't want to complain about reaching the end of a macro
387 // instantiation or a _Pragma.
388 if (PragmaAssumeNonNullLoc.isValid() &&
389 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
390 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
391
392 // Recover by leaving immediately.
393 PragmaAssumeNonNullLoc = SourceLocation();
394 }
395
Erich Keane76675de2018-07-05 17:22:13 +0000396 bool LeavingPCHThroughHeader = false;
397
Chris Lattner1eed7342008-03-09 04:10:46 +0000398 // If this is a #include'd file, pop it off the include stack and continue
399 // lexing the #includer file.
400 if (!IncludeMacroStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000401
402 // If we lexed the code-completion file, act as if we reached EOF.
403 if (isCodeCompletionEnabled() && CurPPLexer &&
404 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
405 CodeCompletionFileLoc) {
Erich Keane0a6b5b62018-12-04 14:34:09 +0000406 assert(CurLexer && "Got EOF but no current lexer set!");
407 Result.startToken();
408 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
409 CurLexer.reset();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000410
Craig Topperd2d442c2014-05-17 23:10:59 +0000411 CurPPLexer = nullptr;
Volodymyr Sapsai9d540f12018-01-19 23:41:47 +0000412 recomputeCurLexerKind();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000413 return true;
414 }
415
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +0000416 if (!isEndOfMacro && CurPPLexer &&
417 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
418 // Notify SourceManager to record the number of FileIDs that were created
419 // during lexing of the #include'd file.
420 unsigned NumFIDs =
421 SourceMgr.local_sloc_entry_size() -
422 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
423 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
424 }
425
Ilya Biryukovf3150002017-08-21 12:03:08 +0000426 bool ExitedFromPredefinesFile = false;
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000427 FileID ExitedFID;
Ilya Biryukovf3150002017-08-21 12:03:08 +0000428 if (!isEndOfMacro && CurPPLexer) {
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000429 ExitedFID = CurPPLexer->getFileID();
Richard Smith34f30512013-11-23 04:06:09 +0000430
Ilya Biryukovf3150002017-08-21 12:03:08 +0000431 assert(PredefinesFileID.isValid() &&
432 "HandleEndOfFile is called before PredefinesFileId is set");
433 ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
434 }
435
Richard Smith34f30512013-11-23 04:06:09 +0000436 if (LeavingSubmodule) {
Richard Smithd1386302017-05-04 00:29:54 +0000437 // We're done with this submodule.
438 Module *M = LeaveSubmodule(/*ForPragma*/false);
439
Richard Smith67294e22014-01-31 20:47:44 +0000440 // Notify the parser that we've left the module.
Richard Smith34f30512013-11-23 04:06:09 +0000441 const char *EndPos = getCurLexerEndPos();
442 Result.startToken();
443 CurLexer->BufferPtr = EndPos;
444 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
445 Result.setAnnotationEndLoc(Result.getLocation());
Richard Smithd1386302017-05-04 00:29:54 +0000446 Result.setAnnotationValue(M);
Richard Smith34f30512013-11-23 04:06:09 +0000447 }
448
Erich Keane76675de2018-07-05 17:22:13 +0000449 bool FoundPCHThroughHeader = false;
450 if (CurPPLexer && creatingPCHWithThroughHeader() &&
451 isPCHThroughHeader(
452 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
453 FoundPCHThroughHeader = true;
454
Chris Lattner1eed7342008-03-09 04:10:46 +0000455 // We're done with the #included file.
456 RemoveTopOfLexerStack();
457
Eli Friedman0834a4b2013-09-19 00:41:32 +0000458 // Propagate info about start-of-line/leading white-space/etc.
459 PropagateLineStartLeadingSpaceInfo(Result);
460
Chris Lattner1eed7342008-03-09 04:10:46 +0000461 // Notify the client, if desired, that we are in a new source file.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000462 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000463 SrcMgr::CharacteristicKind FileType =
Chris Lattner4fd8b952009-01-19 08:01:53 +0000464 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
465 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000466 PPCallbacks::ExitFile, FileType, ExitedFID);
Chris Lattner1eed7342008-03-09 04:10:46 +0000467 }
468
Ilya Biryukovf3150002017-08-21 12:03:08 +0000469 // Restore conditional stack from the preamble right after exiting from the
470 // predefines file.
471 if (ExitedFromPredefinesFile)
472 replayPreambleConditionalStack();
473
Erich Keane76675de2018-07-05 17:22:13 +0000474 if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
475 (isInPrimaryFile() ||
476 CurPPLexer->getFileID() == getPredefinesFileID())) {
477 // Leaving the through header. Continue directly to end of main file
478 // processing.
479 LeavingPCHThroughHeader = true;
480 } else {
481 // Client should lex another token unless we generated an EOM.
482 return LeavingSubmodule;
483 }
Chris Lattner1eed7342008-03-09 04:10:46 +0000484 }
485
Richard Smith34f30512013-11-23 04:06:09 +0000486 // If this is the end of the main file, form an EOF token.
Erich Keane0a6b5b62018-12-04 14:34:09 +0000487 assert(CurLexer && "Got EOF but no current lexer set!");
488 const char *EndPos = getCurLexerEndPos();
489 Result.startToken();
490 CurLexer->BufferPtr = EndPos;
491 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Mike Stump11289f42009-09-09 15:08:12 +0000492
Erich Keane0a6b5b62018-12-04 14:34:09 +0000493 if (isCodeCompletionEnabled()) {
494 // Inserting the code-completion point increases the source buffer by 1,
495 // but the main FileID was created before inserting the point.
496 // Compensate by reducing the EOF location by 1, otherwise the location
497 // will point to the next FileID.
498 // FIXME: This is hacky, the code-completion point should probably be
499 // inserted before the main FileID is created.
500 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
501 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
Chris Lattner1eed7342008-03-09 04:10:46 +0000502 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000503
Erich Keane0a6b5b62018-12-04 14:34:09 +0000504 if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
505 // Reached the end of the compilation without finding the through header.
506 Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
507 << PPOpts->PCHThroughHeader << 0;
508 }
509
510 if (!isIncrementalProcessingEnabled())
511 // We're done with lexing.
512 CurLexer.reset();
513
Axel Naumann2eb1d902012-03-16 10:40:17 +0000514 if (!isIncrementalProcessingEnabled())
Craig Topperd2d442c2014-05-17 23:10:59 +0000515 CurPPLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000516
Argyrios Kyrtzidis8ed74142014-03-08 21:18:26 +0000517 if (TUKind == TU_Complete) {
Argyrios Kyrtzidise1974dc2014-03-07 07:47:58 +0000518 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
519 // collected all macro locations that we need to warn because they are not
520 // used.
521 for (WarnUnusedMacroLocsTy::iterator
522 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
523 I!=E; ++I)
524 Diag(*I, diag::pp_macro_not_used);
525 }
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000526
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000527 // If we are building a module that has an umbrella header, make sure that
Bruno Cardoso Lopesb9075632017-04-27 22:29:14 +0000528 // each of the headers within the directory, including all submodules, is
529 // covered by the umbrella header was actually included by the umbrella
530 // header.
531 if (Module *Mod = getCurrentModule()) {
532 llvm::SmallVector<const Module *, 4> AllMods;
533 collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
534 for (auto *M : AllMods)
535 diagnoseMissingHeaderInUmbrellaDir(*M);
536 }
Douglas Gregorf4e76b82013-05-20 13:49:41 +0000537
Chris Lattner1eed7342008-03-09 04:10:46 +0000538 return true;
539}
540
541/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
542/// hits the end of its token stream.
543bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000544 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000545 "Ending a macro when currently in a #include file!");
546
Argyrios Kyrtzidis8cc04592011-06-29 22:20:11 +0000547 if (!MacroExpandingLexersStack.empty() &&
548 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
549 removeCachedMacroExpandedTokensOfLastLexer();
550
Chris Lattner1eed7342008-03-09 04:10:46 +0000551 // Delete or cache the now-dead macro expander.
552 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000553 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000554 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000555 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Chris Lattner1eed7342008-03-09 04:10:46 +0000556
557 // Handle this like a #include file being popped off the stack.
Chris Lattner1eed7342008-03-09 04:10:46 +0000558 return HandleEndOfFile(Result, true);
559}
560
561/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
562/// lexer stack. This should only be used in situations where the current
563/// state of the top-of-stack lexer is unknown.
564void Preprocessor::RemoveTopOfLexerStack() {
565 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Mike Stump11289f42009-09-09 15:08:12 +0000566
Chris Lattner1eed7342008-03-09 04:10:46 +0000567 if (CurTokenLexer) {
568 // Delete or cache the now-dead macro expander.
569 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000570 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000571 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000572 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Mike Stump11289f42009-09-09 15:08:12 +0000573 }
574
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000575 PopIncludeMacroStack();
Chris Lattner1eed7342008-03-09 04:10:46 +0000576}
577
578/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
579/// comment (/##/) in microsoft mode, this method handles updating the current
580/// state, returning the token on the next source line.
581void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000582 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000583 "Pasted comment can only be formed from macro");
Chris Lattner1eed7342008-03-09 04:10:46 +0000584 // We handle this by scanning for the closest real lexer, switching it to
585 // raw mode and preprocessor mode. This will cause it to return \n as an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000586 // explicit EOD token.
Craig Topperd2d442c2014-05-17 23:10:59 +0000587 PreprocessorLexer *FoundLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000588 bool LexerWasInPPMode = false;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000589 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000590 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
Mike Stump11289f42009-09-09 15:08:12 +0000591
Chris Lattner1eed7342008-03-09 04:10:46 +0000592 // Once we find a real lexer, mark it as raw mode (disabling macro
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000593 // expansions) and preprocessor mode (return EOD). We know that the lexer
Chris Lattner1eed7342008-03-09 04:10:46 +0000594 // was *not* in raw mode before, because the macro that the comment came
595 // from was expanded. However, it could have already been in preprocessor
596 // mode (#if COMMENT) in which case we have to return it to that mode and
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000597 // return EOD.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000598 FoundLexer = ISI.ThePPLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000599 FoundLexer->LexingRawMode = true;
600 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
601 FoundLexer->ParsingPreprocessorDirective = true;
602 break;
603 }
Mike Stump11289f42009-09-09 15:08:12 +0000604
Chris Lattner1eed7342008-03-09 04:10:46 +0000605 // Okay, we either found and switched over the lexer, or we didn't find a
606 // lexer. In either case, finish off the macro the comment came from, getting
607 // the next token.
608 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000609
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000610 // Discarding comments as long as we don't have EOF or EOD. This 'comments
Chris Lattner1eed7342008-03-09 04:10:46 +0000611 // out' the rest of the line, including any tokens that came from other macros
612 // that were active, as in:
613 // #define submacro a COMMENT b
614 // submacro c
615 // which should lex to 'a' only: 'b' and 'c' should be removed.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000616 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
Chris Lattner1eed7342008-03-09 04:10:46 +0000617 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000618
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000619 // If we got an eod token, then we successfully found the end of the line.
620 if (Tok.is(tok::eod)) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000621 assert(FoundLexer && "Can't get end of line without an active lexer");
622 // Restore the lexer back to normal mode instead of raw mode.
623 FoundLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000624
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000625 // If the lexer was already in preprocessor mode, just return the EOD token
Chris Lattner1eed7342008-03-09 04:10:46 +0000626 // to finish the preprocessor line.
627 if (LexerWasInPPMode) return;
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattner1eed7342008-03-09 04:10:46 +0000629 // Otherwise, switch out of PP mode and return the next lexed token.
630 FoundLexer->ParsingPreprocessorDirective = false;
631 return Lex(Tok);
632 }
Mike Stump11289f42009-09-09 15:08:12 +0000633
Chris Lattner1eed7342008-03-09 04:10:46 +0000634 // If we got an EOF token, then we reached the end of the token stream but
635 // didn't find an explicit \n. This can only happen if there was no lexer
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000636 // active (an active lexer would return EOD at EOF if there was no \n in
Chris Lattner1eed7342008-03-09 04:10:46 +0000637 // preprocessor directive mode), so just return EOF as our token.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000638 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
Chris Lattner1eed7342008-03-09 04:10:46 +0000639}
Richard Smithb8b2ed62015-04-23 18:18:26 +0000640
Richard Smithd1386302017-05-04 00:29:54 +0000641void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
642 bool ForPragma) {
Richard Smith04765ae2015-05-21 01:20:10 +0000643 if (!getLangOpts().ModulesLocalVisibility) {
644 // Just track that we entered this submodule.
Richard Smithd1386302017-05-04 00:29:54 +0000645 BuildingSubmoduleStack.push_back(
646 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
647 PendingModuleMacroNames.size()));
Richard Smith04765ae2015-05-21 01:20:10 +0000648 return;
649 }
Richard Smithee977932015-05-01 21:22:17 +0000650
Richard Smith04765ae2015-05-21 01:20:10 +0000651 // Resolve as much of the module definition as we can now, before we enter
652 // one of its headers.
653 // FIXME: Can we enable Complain here?
654 // FIXME: Can we do this when local visibility is disabled?
655 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
656 ModMap.resolveExports(M, /*Complain=*/false);
657 ModMap.resolveUses(M, /*Complain=*/false);
658 ModMap.resolveConflicts(M, /*Complain=*/false);
Richard Smith42413142015-05-15 20:05:43 +0000659
Richard Smith04765ae2015-05-21 01:20:10 +0000660 // If this is the first time we've entered this module, set up its state.
Richard Smithe5202932015-05-21 01:26:53 +0000661 auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
Richard Smith04765ae2015-05-21 01:20:10 +0000662 auto &State = R.first->second;
663 bool FirstTime = R.second;
664 if (FirstTime) {
665 // Determine the set of starting macros for this submodule; take these
666 // from the "null" module (the predefines buffer).
Richard Smith4df60932015-06-30 21:29:55 +0000667 //
668 // FIXME: If we have local visibility but not modules enabled, the
669 // NullSubmoduleState is polluted by #defines in the top-level source
670 // file.
Richard Smith04765ae2015-05-21 01:20:10 +0000671 auto &StartingMacros = NullSubmoduleState.Macros;
672
673 // Restore to the starting state.
674 // FIXME: Do this lazily, when each macro name is first referenced.
675 for (auto &Macro : StartingMacros) {
Richard Smith4df60932015-06-30 21:29:55 +0000676 // Skip uninteresting macros.
677 if (!Macro.second.getLatest() &&
678 Macro.second.getOverriddenMacros().empty())
679 continue;
680
Richard Smith04765ae2015-05-21 01:20:10 +0000681 MacroState MS(Macro.second.getLatest());
682 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
683 State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
684 }
685 }
686
687 // Track that we entered this module.
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
692 // Switch to this submodule as the current submodule.
693 CurSubmoduleState = &State;
694
695 // This module is visible to itself.
696 if (FirstTime)
Richard Smith42413142015-05-15 20:05:43 +0000697 makeModuleVisible(M, ImportLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000698}
699
Richard Smith802182f2016-02-23 23:20:51 +0000700bool Preprocessor::needModuleMacros() const {
701 // If we're not within a submodule, we never need to create ModuleMacros.
702 if (BuildingSubmoduleStack.empty())
703 return false;
704 // If we are tracking module macro visibility even for textually-included
705 // headers, we need ModuleMacros.
706 if (getLangOpts().ModulesLocalVisibility)
707 return true;
708 // Otherwise, we only need module macros if we're actually compiling a module
709 // interface.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000710 return getLangOpts().isCompilingModule();
Richard Smith802182f2016-02-23 23:20:51 +0000711}
712
Richard Smithd1386302017-05-04 00:29:54 +0000713Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
714 if (BuildingSubmoduleStack.empty() ||
715 BuildingSubmoduleStack.back().IsPragma != ForPragma) {
716 assert(ForPragma && "non-pragma module enter/leave mismatch");
717 return nullptr;
718 }
719
Richard Smithb8b2ed62015-04-23 18:18:26 +0000720 auto &Info = BuildingSubmoduleStack.back();
721
Richard Smithdbbc5232015-05-14 02:25:44 +0000722 Module *LeavingMod = Info.M;
723 SourceLocation ImportLoc = Info.ImportLoc;
724
Richard Smith4971ed02017-05-19 23:32:38 +0000725 if (!needModuleMacros() ||
Richard Smith802182f2016-02-23 23:20:51 +0000726 (!getLangOpts().ModulesLocalVisibility &&
727 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
728 // If we don't need module macros, or this is not a module for which we
729 // are tracking macro visibility, don't build any, and preserve the list
730 // of pending names for the surrounding submodule.
Richard Smithe5b53502016-02-19 22:43:58 +0000731 BuildingSubmoduleStack.pop_back();
732 makeModuleVisible(LeavingMod, ImportLoc);
Richard Smithd1386302017-05-04 00:29:54 +0000733 return LeavingMod;
Richard Smithe5b53502016-02-19 22:43:58 +0000734 }
735
Richard Smithb8b2ed62015-04-23 18:18:26 +0000736 // Create ModuleMacros for any macros defined in this submodule.
Richard Smith802182f2016-02-23 23:20:51 +0000737 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
738 for (unsigned I = Info.OuterPendingModuleMacroNames;
739 I != PendingModuleMacroNames.size(); ++I) {
740 auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
741 if (!VisitedMacros.insert(II).second)
742 continue;
743
744 auto MacroIt = CurSubmoduleState->Macros.find(II);
745 if (MacroIt == CurSubmoduleState->Macros.end())
746 continue;
747 auto &Macro = MacroIt->second;
Richard Smithee977932015-05-01 21:22:17 +0000748
749 // Find the starting point for the MacroDirective chain in this submodule.
Richard Smith04765ae2015-05-21 01:20:10 +0000750 MacroDirective *OldMD = nullptr;
Richard Smithe5b53502016-02-19 22:43:58 +0000751 auto *OldState = Info.OuterSubmoduleState;
752 if (getLangOpts().ModulesLocalVisibility)
753 OldState = &NullSubmoduleState;
754 if (OldState && OldState != CurSubmoduleState) {
Richard Smith04765ae2015-05-21 01:20:10 +0000755 // FIXME: It'd be better to start at the state from when we most recently
756 // entered this submodule, but it doesn't really matter.
Richard Smithe5b53502016-02-19 22:43:58 +0000757 auto &OldMacros = OldState->Macros;
Richard Smith802182f2016-02-23 23:20:51 +0000758 auto OldMacroIt = OldMacros.find(II);
Richard Smithe5b53502016-02-19 22:43:58 +0000759 if (OldMacroIt == OldMacros.end())
Richard Smithee977932015-05-01 21:22:17 +0000760 OldMD = nullptr;
761 else
Richard Smithe5b53502016-02-19 22:43:58 +0000762 OldMD = OldMacroIt->second.getLatest();
Richard Smithee977932015-05-01 21:22:17 +0000763 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000764
765 // This module may have exported a new macro. If so, create a ModuleMacro
766 // representing that fact.
767 bool ExplicitlyPublic = false;
Richard Smith802182f2016-02-23 23:20:51 +0000768 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
Richard Smith1e172852015-04-28 21:05:07 +0000769 assert(MD && "broken macro directive chain");
770
Richard Smithb8b2ed62015-04-23 18:18:26 +0000771 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
772 // The latest visibility directive for a name in a submodule affects
773 // all the directives that come before it.
774 if (VisMD->isPublic())
775 ExplicitlyPublic = true;
776 else if (!ExplicitlyPublic)
777 // Private with no following public directive: not exported.
778 break;
779 } else {
780 MacroInfo *Def = nullptr;
781 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
782 Def = DefMD->getInfo();
783
784 // FIXME: Issue a warning if multiple headers for the same submodule
785 // define a macro, rather than silently ignoring all but the first.
786 bool IsNew;
Richard Smith32dbd692015-05-02 01:14:40 +0000787 // Don't bother creating a module macro if it would represent a #undef
788 // that doesn't override anything.
Richard Smith802182f2016-02-23 23:20:51 +0000789 if (Def || !Macro.getOverriddenMacros().empty())
Richard Smithdbbc5232015-05-14 02:25:44 +0000790 addModuleMacro(LeavingMod, II, Def,
Richard Smith802182f2016-02-23 23:20:51 +0000791 Macro.getOverriddenMacros(), IsNew);
Richard Smith4971ed02017-05-19 23:32:38 +0000792
793 if (!getLangOpts().ModulesLocalVisibility) {
794 // This macro is exposed to the rest of this compilation as a
795 // ModuleMacro; we don't need to track its MacroDirective any more.
796 Macro.setLatest(nullptr);
797 Macro.setOverriddenMacros(*this, {});
798 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000799 break;
800 }
801 }
Richard Smith753e0072015-04-27 23:21:38 +0000802 }
Richard Smith802182f2016-02-23 23:20:51 +0000803 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000804
Richard Smith4df60932015-06-30 21:29:55 +0000805 // FIXME: Before we leave this submodule, we should parse all the other
806 // headers within it. Otherwise, we're left with an inconsistent state
807 // where we've made the module visible but don't yet have its complete
808 // contents.
809
Richard Smith04765ae2015-05-21 01:20:10 +0000810 // Put back the outer module's state, if we're tracking it.
Richard Smithee977932015-05-01 21:22:17 +0000811 if (getLangOpts().ModulesLocalVisibility)
Richard Smith04765ae2015-05-21 01:20:10 +0000812 CurSubmoduleState = Info.OuterSubmoduleState;
Richard Smithee977932015-05-01 21:22:17 +0000813
Richard Smithb8b2ed62015-04-23 18:18:26 +0000814 BuildingSubmoduleStack.pop_back();
Richard Smithdbbc5232015-05-14 02:25:44 +0000815
816 // A nested #include makes the included submodule visible.
Richard Smith4df60932015-06-30 21:29:55 +0000817 makeModuleVisible(LeavingMod, ImportLoc);
Richard Smithd1386302017-05-04 00:29:54 +0000818 return LeavingMod;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000819}