blob: 5f547d9f1cc92cd46a968bdcfd93781f6198a4b0 [file] [log] [blame]
Chris Lattner1eed7342008-03-09 04:10:46 +00001//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner1eed7342008-03-09 04:10:46 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements pieces of the Preprocessor interface that manage the
10// current lexer stack.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Erich Keane76675de2018-07-05 17:22:13 +000015#include "clang/Lex/PreprocessorOptions.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"
21#include "llvm/ADT/StringSwitch.h"
Douglas Gregorfe76cfd2011-12-23 00:23:59 +000022#include "llvm/Support/FileSystem.h"
Ted Kremenek85b48c62008-11-20 07:56:33 +000023#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola552c1692013-06-11 22:15:02 +000024#include "llvm/Support/Path.h"
Chris Lattner1eed7342008-03-09 04:10:46 +000025using namespace clang;
26
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000027PPCallbacks::~PPCallbacks() {}
Chris Lattner1eed7342008-03-09 04:10:46 +000028
29//===----------------------------------------------------------------------===//
Chris Lattner3e468322008-03-10 06:06:04 +000030// Miscellaneous Methods.
Chris Lattner1eed7342008-03-09 04:10:46 +000031//===----------------------------------------------------------------------===//
32
Chris Lattner1eed7342008-03-09 04:10:46 +000033/// isInPrimaryFile - Return true if we're in the top-level file, not in a
James Dennett1244a0d2012-06-22 05:36:05 +000034/// \#include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner1eed7342008-03-09 04:10:46 +000035bool Preprocessor::isInPrimaryFile() const {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000036 if (IsFileLexer())
Chris Lattner1eed7342008-03-09 04:10:46 +000037 return IncludeMacroStack.empty();
Mike Stump11289f42009-09-09 15:08:12 +000038
Chris Lattner1eed7342008-03-09 04:10:46 +000039 // If there are any stacked lexers, we're in a #include.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000040 assert(IsFileLexer(IncludeMacroStack[0]) &&
Chris Lattner1eed7342008-03-09 04:10:46 +000041 "Top level include stack isn't our primary lexer?");
NAKAMURA Takumia5b348be2017-09-18 04:55:31 +000042 return std::none_of(
43 IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
Vitaly Buka55a27d32017-09-18 08:26:01 +000044 [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });
Chris Lattner1eed7342008-03-09 04:10:46 +000045}
46
47/// getCurrentLexer - Return the current file lexer being lexed from. Note
48/// that this ignores any potentially active macro expansions and _Pragma
49/// expansions going on at the time.
Ted Kremenekb33ce322008-11-20 01:49:44 +000050PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000051 if (IsFileLexer())
Ted Kremenekb33ce322008-11-20 01:49:44 +000052 return CurPPLexer;
Mike Stump11289f42009-09-09 15:08:12 +000053
Chris Lattner1eed7342008-03-09 04:10:46 +000054 // Look for a stacked lexer.
Erik Verbruggene4fd6522016-10-26 13:06:13 +000055 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000056 if (IsFileLexer(ISI))
Ted Kremenekb33ce322008-11-20 01:49:44 +000057 return ISI.ThePPLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +000058 }
Craig Topperd2d442c2014-05-17 23:10:59 +000059 return nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +000060}
61
Chris Lattner3e468322008-03-10 06:06:04 +000062
63//===----------------------------------------------------------------------===//
64// Methods for Entering and Callbacks for leaving various contexts
65//===----------------------------------------------------------------------===//
Chris Lattner1eed7342008-03-09 04:10:46 +000066
67/// EnterSourceFile - Add a source file to the top of the include stack and
Nuno Lopes0e5d13e2009-11-29 17:07:16 +000068/// start lexing tokens from it instead of the current buffer.
Richard Smith67294e22014-01-31 20:47:44 +000069bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
70 SourceLocation Loc) {
David Blaikie7d170102013-05-15 07:37:26 +000071 assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
Chris Lattner1eed7342008-03-09 04:10:46 +000072 ++NumEnteredSourceFiles;
Mike Stump11289f42009-09-09 15:08:12 +000073
Chris Lattner1eed7342008-03-09 04:10:46 +000074 if (MaxIncludeStackDepth < IncludeMacroStack.size())
75 MaxIncludeStackDepth = IncludeMacroStack.size();
76
Chris Lattner710bb872009-11-30 04:18:44 +000077 // Get the MemoryBuffer for this FID, if it fails, we fail.
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +000078 bool Invalid = false;
Fangrui Song6907ce22018-07-30 19:24:48 +000079 const llvm::MemoryBuffer *InputFile =
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000080 getSourceManager().getBuffer(FID, Loc, &Invalid);
81 if (Invalid) {
82 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
83 Diag(Loc, diag::err_pp_error_opening_file)
84 << std::string(SourceMgr.getBufferName(FileStart)) << "";
Richard Smith67294e22014-01-31 20:47:44 +000085 return true;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000086 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000087
88 if (isCodeCompletionEnabled() &&
89 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
90 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
91 CodeCompletionLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000092 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000093 }
94
Richard Smith67294e22014-01-31 20:47:44 +000095 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
96 return false;
Mike Stump11289f42009-09-09 15:08:12 +000097}
Chris Lattnerc88a23e2008-09-26 20:12:23 +000098
Ted Kremenekaf058b52008-12-02 19:46:31 +000099/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
100/// and start lexing tokens from it instead of the current buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000101void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
Richard Smith67294e22014-01-31 20:47:44 +0000102 const DirectoryLookup *CurDir) {
Mike Stump11289f42009-09-09 15:08:12 +0000103
Chris Lattner1eed7342008-03-09 04:10:46 +0000104 // Add the current lexer to the include stack.
Ted Kremenek45245212008-11-19 21:57:25 +0000105 if (CurPPLexer || CurTokenLexer)
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000106 PushIncludeMacroStack();
107
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000108 CurLexer.reset(TheLexer);
Ted Kremenek68ef9fc2008-11-18 00:12:49 +0000109 CurPPLexer = TheLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000110 CurDirLookup = CurDir;
Richard Smithd1386302017-05-04 00:29:54 +0000111 CurLexerSubmodule = nullptr;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000112 if (CurLexerKind != CLK_LexAfterModuleImport)
113 CurLexerKind = CLK_Lexer;
Yaron Kerene02bcdc2015-11-07 16:35:07 +0000114
Chris Lattner1eed7342008-03-09 04:10:46 +0000115 // Notify the client, if desired, that we are in a new source file.
116 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000117 SrcMgr::CharacteristicKind FileType =
Chris Lattnerb03dc762008-09-26 21:18:42 +0000118 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Mike Stump11289f42009-09-09 15:08:12 +0000119
Chris Lattner1eed7342008-03-09 04:10:46 +0000120 Callbacks->FileChanged(CurLexer->getFileLoc(),
121 PPCallbacks::EnterFile, FileType);
122 }
123}
124
Chris Lattner1eed7342008-03-09 04:10:46 +0000125/// EnterMacro - Add a Macro to the top of the include stack and start lexing
126/// tokens from it instead of the current buffer.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000127void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
Richard Smith5edd5832012-08-30 13:38:46 +0000128 MacroInfo *Macro, MacroArgs *Args) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000129 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000130 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000131 TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000132 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000133 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000134 TokLexer->Init(Tok, ILEnd, Macro, Args);
135 }
136
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000137 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000138 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000139 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000140 if (CurLexerKind != CLK_LexAfterModuleImport)
141 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000142}
143
144/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner3e468322008-03-10 06:06:04 +0000145/// which will cause the lexer to start returning the specified tokens.
146///
147/// If DisableMacroExpansion is true, tokens lexed from the token stream will
148/// not be subject to further macro expansion. Otherwise, these tokens will
149/// be re-macro-expanded when/if expansion is enabled.
150///
151/// If OwnsTokens is false, this method assumes that the specified stream of
152/// tokens has a permanent owner somewhere, so they do not need to be copied.
153/// If it is true, it assumes the array of tokens is allocated with new[] and
154/// must be freed.
155///
156void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
157 bool DisableMacroExpansion,
158 bool OwnsTokens) {
Richard Smithbdf54a212014-09-23 21:05:52 +0000159 if (CurLexerKind == CLK_CachingLexer) {
160 if (CachedLexPos < CachedTokens.size()) {
161 // We're entering tokens into the middle of our cached token stream. We
162 // can't represent that, so just insert the tokens into the buffer.
163 CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
164 Toks, Toks + NumToks);
165 if (OwnsTokens)
166 delete [] Toks;
167 return;
168 }
169
170 // New tokens are at the end of the cached token sequnece; insert the
171 // token stream underneath the caching lexer.
172 ExitCachingLexMode();
173 EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
174 EnterCachingLexMode();
175 return;
176 }
177
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000178 // Create a macro expander to expand from the specified token stream.
David Blaikie6d5038c2014-08-29 19:36:52 +0000179 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000180 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000181 TokLexer = llvm::make_unique<TokenLexer>(
182 Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000183 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000184 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000185 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
186 }
187
Chris Lattner1eed7342008-03-09 04:10:46 +0000188 // Save our current state.
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000189 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000190 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000191 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000192 if (CurLexerKind != CLK_LexAfterModuleImport)
193 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000194}
195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000196/// Compute the relative path that names the given file relative to
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000197/// the given directory.
198static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
199 const FileEntry *File,
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000200 SmallString<128> &Result) {
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000201 Result.clear();
202
203 StringRef FilePath = File->getDir()->getName();
204 StringRef Path = FilePath;
205 while (!Path.empty()) {
206 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
207 if (CurDir == Dir) {
208 Result = FilePath.substr(Path.size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000209 llvm::sys::path::append(Result,
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000210 llvm::sys::path::filename(File->getName()));
211 return;
212 }
213 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000214
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000215 Path = llvm::sys::path::parent_path(Path);
216 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000217
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000218 Result = File->getName();
219}
220
Eli Friedman0834a4b2013-09-19 00:41:32 +0000221void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
222 if (CurTokenLexer) {
223 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
224 return;
225 }
226 if (CurLexer) {
227 CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
228 return;
229 }
230 // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
231 // but it might if they're empty?
232}
233
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000234/// Determine the location to use as the end of the buffer for a lexer.
Richard Smith34f30512013-11-23 04:06:09 +0000235///
236/// If the file ends with a newline, form the EOF token on the newline itself,
237/// rather than "on the line following it", which doesn't exist. This makes
238/// diagnostics relating to the end of file include the last file that the user
239/// actually typed, which is goodness.
240const char *Preprocessor::getCurLexerEndPos() {
241 const char *EndPos = CurLexer->BufferEnd;
242 if (EndPos != CurLexer->BufferStart &&
243 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
244 --EndPos;
245
246 // Handle \n\r and \r\n:
247 if (EndPos != CurLexer->BufferStart &&
248 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
249 EndPos[-1] != EndPos[0])
250 --EndPos;
251 }
252
253 return EndPos;
254}
255
Bruno Cardoso Lopesb9075632017-04-27 22:29:14 +0000256static void collectAllSubModulesWithUmbrellaHeader(
257 const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
258 if (Mod.getUmbrellaHeader())
259 SubMods.push_back(&Mod);
260 for (auto *M : Mod.submodules())
261 collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
262}
263
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000264void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
265 assert(Mod.getUmbrellaHeader() && "Module must use umbrella header");
266 SourceLocation StartLoc =
267 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
268 if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header, StartLoc))
269 return;
270
271 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
272 const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +0000273 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000274 std::error_code EC;
Jonas Devliegherefc514902018-10-10 13:27:25 +0000275 for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
276 End;
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000277 Entry != End && !EC; Entry.increment(EC)) {
278 using llvm::StringSwitch;
279
280 // Check whether this entry has an extension typically associated with
281 // headers.
Sam McCall0ae00562018-09-14 12:47:38 +0000282 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000283 .Cases(".h", ".H", ".hh", ".hpp", true)
284 .Default(false))
285 continue;
286
Sam McCall0ae00562018-09-14 12:47:38 +0000287 if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
Bruno Cardoso Lopesce9a8102017-04-27 22:29:10 +0000288 if (!getSourceManager().hasFileInfo(Header)) {
289 if (!ModMap.isHeaderInUnavailableModule(Header)) {
290 // Find the relative path that would access this header.
291 SmallString<128> RelativePath;
292 computeRelativePath(FileMgr, Dir, Header, RelativePath);
293 Diag(StartLoc, diag::warn_uncovered_module_header)
294 << Mod.getFullModuleName() << RelativePath;
295 }
296 }
297 }
298}
Richard Smith34f30512013-11-23 04:06:09 +0000299
Chris Lattner1eed7342008-03-09 04:10:46 +0000300/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
301/// the current file. This either returns the EOF token or pops a level off
302/// the include stack and keeps going.
303bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
304 assert(!CurTokenLexer &&
305 "Ending a file when currently in a macro!");
Mike Stump11289f42009-09-09 15:08:12 +0000306
Richard Smithd1386302017-05-04 00:29:54 +0000307 // If we have an unclosed module region from a pragma at the end of a
308 // module, complain and close it now.
Richard Smithd1386302017-05-04 00:29:54 +0000309 const bool LeavingSubmodule = CurLexer && CurLexerSubmodule;
310 if ((LeavingSubmodule || IncludeMacroStack.empty()) &&
311 !BuildingSubmoduleStack.empty() &&
312 BuildingSubmoduleStack.back().IsPragma) {
313 Diag(BuildingSubmoduleStack.back().ImportLoc,
314 diag::err_pp_module_begin_without_module_end);
315 Module *M = LeaveSubmodule(/*ForPragma*/true);
316
317 Result.startToken();
318 const char *EndPos = getCurLexerEndPos();
319 CurLexer->BufferPtr = EndPos;
320 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
321 Result.setAnnotationEndLoc(Result.getLocation());
322 Result.setAnnotationValue(M);
323 return true;
324 }
325
Chris Lattner1eed7342008-03-09 04:10:46 +0000326 // See if this file had a controlling macro.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000327 if (CurPPLexer) { // Not ending a macro, ignore it.
Mike Stump11289f42009-09-09 15:08:12 +0000328 if (const IdentifierInfo *ControllingMacro =
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000329 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Steve Naroff3fa455a2009-04-24 20:03:17 +0000330 // Okay, this has a controlling macro, remember in HeaderFileInfo.
Yaron Keren65224612015-12-18 10:30:12 +0000331 if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000332 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +0000333 if (MacroInfo *MI =
Yaron Keren9370ea22017-04-16 15:53:19 +0000334 getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
335 MI->setUsedForHeaderGuard(true);
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000336 if (const IdentifierInfo *DefinedMacro =
337 CurPPLexer->MIOpt.GetDefinedMacro()) {
Richard Smith20e883e2015-04-29 23:20:19 +0000338 if (!isMacroDefined(ControllingMacro) &&
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000339 DefinedMacro != ControllingMacro &&
340 HeaderInfo.FirstTimeLexingFile(FE)) {
Ismail Pazarbasi8d0f2f32013-10-12 23:17:37 +0000341
342 // If the edit distance between the two macros is more than 50%,
343 // DefinedMacro may not be header guard, or can be header guard of
344 // another header file. Therefore, it maybe defining something
345 // completely different. This can be observed in the wild when
346 // handling feature macros or header guards in different files.
347
348 const StringRef ControllingMacroName = ControllingMacro->getName();
349 const StringRef DefinedMacroName = DefinedMacro->getName();
350 const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
351 DefinedMacroName.size()) / 2;
352 const unsigned ED = ControllingMacroName.edit_distance(
353 DefinedMacroName, true, MaxHalfLength);
354 if (ED <= MaxHalfLength) {
355 // Emit a warning for a bad header guard.
356 Diag(CurPPLexer->MIOpt.GetMacroLocation(),
357 diag::warn_header_guard)
358 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
359 Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
360 diag::note_header_guard)
361 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
362 << ControllingMacro
363 << FixItHint::CreateReplacement(
364 CurPPLexer->MIOpt.GetDefinedLocation(),
365 ControllingMacro->getName());
366 }
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000367 }
368 }
369 }
Chris Lattner1eed7342008-03-09 04:10:46 +0000370 }
371 }
Mike Stump11289f42009-09-09 15:08:12 +0000372
John McCall95ff2702011-10-18 00:44:04 +0000373 // Complain about reaching a true EOF within arc_cf_code_audited.
374 // We don't want to complain about reaching the end of a macro
375 // instantiation or a _Pragma.
376 if (PragmaARCCFCodeAuditedLoc.isValid() &&
John McCall43d4dd42011-10-18 01:36:41 +0000377 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
John McCall32f5fe12011-09-30 05:12:12 +0000378 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
379
380 // Recover by leaving immediately.
381 PragmaARCCFCodeAuditedLoc = SourceLocation();
382 }
383
Douglas Gregor2a20bd12015-06-19 18:25:57 +0000384 // Complain about reaching a true EOF within assume_nonnull.
385 // We don't want to complain about reaching the end of a macro
386 // instantiation or a _Pragma.
387 if (PragmaAssumeNonNullLoc.isValid() &&
388 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
389 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
390
391 // Recover by leaving immediately.
392 PragmaAssumeNonNullLoc = SourceLocation();
393 }
394
Erich Keane76675de2018-07-05 17:22:13 +0000395 bool LeavingPCHThroughHeader = false;
396
Chris Lattner1eed7342008-03-09 04:10:46 +0000397 // If this is a #include'd file, pop it off the include stack and continue
398 // lexing the #includer file.
399 if (!IncludeMacroStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000400
401 // If we lexed the code-completion file, act as if we reached EOF.
402 if (isCodeCompletionEnabled() && CurPPLexer &&
403 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
404 CodeCompletionFileLoc) {
Erich Keane0a6b5b62018-12-04 14:34:09 +0000405 assert(CurLexer && "Got EOF but no current lexer set!");
406 Result.startToken();
407 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
408 CurLexer.reset();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000409
Craig Topperd2d442c2014-05-17 23:10:59 +0000410 CurPPLexer = nullptr;
Volodymyr Sapsai9d540f12018-01-19 23:41:47 +0000411 recomputeCurLexerKind();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000412 return true;
413 }
414
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +0000415 if (!isEndOfMacro && CurPPLexer &&
416 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
417 // Notify SourceManager to record the number of FileIDs that were created
418 // during lexing of the #include'd file.
419 unsigned NumFIDs =
420 SourceMgr.local_sloc_entry_size() -
421 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
422 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
423 }
424
Ilya Biryukovf3150002017-08-21 12:03:08 +0000425 bool ExitedFromPredefinesFile = false;
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000426 FileID ExitedFID;
Ilya Biryukovf3150002017-08-21 12:03:08 +0000427 if (!isEndOfMacro && CurPPLexer) {
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000428 ExitedFID = CurPPLexer->getFileID();
Richard Smith34f30512013-11-23 04:06:09 +0000429
Ilya Biryukovf3150002017-08-21 12:03:08 +0000430 assert(PredefinesFileID.isValid() &&
431 "HandleEndOfFile is called before PredefinesFileId is set");
432 ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
433 }
434
Richard Smith34f30512013-11-23 04:06:09 +0000435 if (LeavingSubmodule) {
Richard Smithd1386302017-05-04 00:29:54 +0000436 // We're done with this submodule.
437 Module *M = LeaveSubmodule(/*ForPragma*/false);
438
Richard Smith67294e22014-01-31 20:47:44 +0000439 // Notify the parser that we've left the module.
Richard Smith34f30512013-11-23 04:06:09 +0000440 const char *EndPos = getCurLexerEndPos();
441 Result.startToken();
442 CurLexer->BufferPtr = EndPos;
443 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
444 Result.setAnnotationEndLoc(Result.getLocation());
Richard Smithd1386302017-05-04 00:29:54 +0000445 Result.setAnnotationValue(M);
Richard Smith34f30512013-11-23 04:06:09 +0000446 }
447
Erich Keane76675de2018-07-05 17:22:13 +0000448 bool FoundPCHThroughHeader = false;
449 if (CurPPLexer && creatingPCHWithThroughHeader() &&
450 isPCHThroughHeader(
451 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
452 FoundPCHThroughHeader = true;
453
Chris Lattner1eed7342008-03-09 04:10:46 +0000454 // We're done with the #included file.
455 RemoveTopOfLexerStack();
456
Eli Friedman0834a4b2013-09-19 00:41:32 +0000457 // Propagate info about start-of-line/leading white-space/etc.
458 PropagateLineStartLeadingSpaceInfo(Result);
459
Chris Lattner1eed7342008-03-09 04:10:46 +0000460 // Notify the client, if desired, that we are in a new source file.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000461 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000462 SrcMgr::CharacteristicKind FileType =
Chris Lattner4fd8b952009-01-19 08:01:53 +0000463 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
464 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000465 PPCallbacks::ExitFile, FileType, ExitedFID);
Chris Lattner1eed7342008-03-09 04:10:46 +0000466 }
467
Ilya Biryukovf3150002017-08-21 12:03:08 +0000468 // Restore conditional stack from the preamble right after exiting from the
469 // predefines file.
470 if (ExitedFromPredefinesFile)
471 replayPreambleConditionalStack();
472
Erich Keane76675de2018-07-05 17:22:13 +0000473 if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
474 (isInPrimaryFile() ||
475 CurPPLexer->getFileID() == getPredefinesFileID())) {
476 // Leaving the through header. Continue directly to end of main file
477 // processing.
478 LeavingPCHThroughHeader = true;
479 } else {
480 // Client should lex another token unless we generated an EOM.
481 return LeavingSubmodule;
482 }
Chris Lattner1eed7342008-03-09 04:10:46 +0000483 }
484
Richard Smith34f30512013-11-23 04:06:09 +0000485 // If this is the end of the main file, form an EOF token.
Erich Keane0a6b5b62018-12-04 14:34:09 +0000486 assert(CurLexer && "Got EOF but no current lexer set!");
487 const char *EndPos = getCurLexerEndPos();
488 Result.startToken();
489 CurLexer->BufferPtr = EndPos;
490 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Mike Stump11289f42009-09-09 15:08:12 +0000491
Erich Keane0a6b5b62018-12-04 14:34:09 +0000492 if (isCodeCompletionEnabled()) {
493 // Inserting the code-completion point increases the source buffer by 1,
494 // but the main FileID was created before inserting the point.
495 // Compensate by reducing the EOF location by 1, otherwise the location
496 // will point to the next FileID.
497 // FIXME: This is hacky, the code-completion point should probably be
498 // inserted before the main FileID is created.
499 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
500 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
Chris Lattner1eed7342008-03-09 04:10:46 +0000501 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000502
Erich Keane0a6b5b62018-12-04 14:34:09 +0000503 if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
504 // Reached the end of the compilation without finding the through header.
505 Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
506 << PPOpts->PCHThroughHeader << 0;
507 }
508
509 if (!isIncrementalProcessingEnabled())
510 // We're done with lexing.
511 CurLexer.reset();
512
Axel Naumann2eb1d902012-03-16 10:40:17 +0000513 if (!isIncrementalProcessingEnabled())
Craig Topperd2d442c2014-05-17 23:10:59 +0000514 CurPPLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000515
Argyrios Kyrtzidis8ed74142014-03-08 21:18:26 +0000516 if (TUKind == TU_Complete) {
Argyrios Kyrtzidise1974dc2014-03-07 07:47:58 +0000517 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
518 // collected all macro locations that we need to warn because they are not
519 // used.
520 for (WarnUnusedMacroLocsTy::iterator
521 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
522 I!=E; ++I)
523 Diag(*I, diag::pp_macro_not_used);
524 }
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000525
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000526 // If we are building a module that has an umbrella header, make sure that
Bruno Cardoso Lopesb9075632017-04-27 22:29:14 +0000527 // each of the headers within the directory, including all submodules, is
528 // covered by the umbrella header was actually included by the umbrella
529 // header.
530 if (Module *Mod = getCurrentModule()) {
531 llvm::SmallVector<const Module *, 4> AllMods;
532 collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
533 for (auto *M : AllMods)
534 diagnoseMissingHeaderInUmbrellaDir(*M);
535 }
Douglas Gregorf4e76b82013-05-20 13:49:41 +0000536
Chris Lattner1eed7342008-03-09 04:10:46 +0000537 return true;
538}
539
540/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
541/// hits the end of its token stream.
542bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000543 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000544 "Ending a macro when currently in a #include file!");
545
Argyrios Kyrtzidis8cc04592011-06-29 22:20:11 +0000546 if (!MacroExpandingLexersStack.empty() &&
547 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
548 removeCachedMacroExpandedTokensOfLastLexer();
549
Chris Lattner1eed7342008-03-09 04:10:46 +0000550 // Delete or cache the now-dead macro expander.
551 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000552 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000553 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000554 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Chris Lattner1eed7342008-03-09 04:10:46 +0000555
556 // Handle this like a #include file being popped off the stack.
Chris Lattner1eed7342008-03-09 04:10:46 +0000557 return HandleEndOfFile(Result, true);
558}
559
560/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
561/// lexer stack. This should only be used in situations where the current
562/// state of the top-of-stack lexer is unknown.
563void Preprocessor::RemoveTopOfLexerStack() {
564 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Mike Stump11289f42009-09-09 15:08:12 +0000565
Chris Lattner1eed7342008-03-09 04:10:46 +0000566 if (CurTokenLexer) {
567 // Delete or cache the now-dead macro expander.
568 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000569 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000570 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000571 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Mike Stump11289f42009-09-09 15:08:12 +0000572 }
573
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000574 PopIncludeMacroStack();
Chris Lattner1eed7342008-03-09 04:10:46 +0000575}
576
577/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
578/// comment (/##/) in microsoft mode, this method handles updating the current
579/// state, returning the token on the next source line.
580void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000581 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000582 "Pasted comment can only be formed from macro");
Chris Lattner1eed7342008-03-09 04:10:46 +0000583 // We handle this by scanning for the closest real lexer, switching it to
584 // raw mode and preprocessor mode. This will cause it to return \n as an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000585 // explicit EOD token.
Craig Topperd2d442c2014-05-17 23:10:59 +0000586 PreprocessorLexer *FoundLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000587 bool LexerWasInPPMode = false;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000588 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000589 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
Mike Stump11289f42009-09-09 15:08:12 +0000590
Chris Lattner1eed7342008-03-09 04:10:46 +0000591 // Once we find a real lexer, mark it as raw mode (disabling macro
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000592 // expansions) and preprocessor mode (return EOD). We know that the lexer
Chris Lattner1eed7342008-03-09 04:10:46 +0000593 // was *not* in raw mode before, because the macro that the comment came
594 // from was expanded. However, it could have already been in preprocessor
595 // mode (#if COMMENT) in which case we have to return it to that mode and
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000596 // return EOD.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000597 FoundLexer = ISI.ThePPLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000598 FoundLexer->LexingRawMode = true;
599 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
600 FoundLexer->ParsingPreprocessorDirective = true;
601 break;
602 }
Mike Stump11289f42009-09-09 15:08:12 +0000603
Chris Lattner1eed7342008-03-09 04:10:46 +0000604 // Okay, we either found and switched over the lexer, or we didn't find a
605 // lexer. In either case, finish off the macro the comment came from, getting
606 // the next token.
607 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000608
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000609 // Discarding comments as long as we don't have EOF or EOD. This 'comments
Chris Lattner1eed7342008-03-09 04:10:46 +0000610 // out' the rest of the line, including any tokens that came from other macros
611 // that were active, as in:
612 // #define submacro a COMMENT b
613 // submacro c
614 // which should lex to 'a' only: 'b' and 'c' should be removed.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000615 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
Chris Lattner1eed7342008-03-09 04:10:46 +0000616 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000617
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000618 // If we got an eod token, then we successfully found the end of the line.
619 if (Tok.is(tok::eod)) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000620 assert(FoundLexer && "Can't get end of line without an active lexer");
621 // Restore the lexer back to normal mode instead of raw mode.
622 FoundLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000623
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000624 // If the lexer was already in preprocessor mode, just return the EOD token
Chris Lattner1eed7342008-03-09 04:10:46 +0000625 // to finish the preprocessor line.
626 if (LexerWasInPPMode) return;
Mike Stump11289f42009-09-09 15:08:12 +0000627
Chris Lattner1eed7342008-03-09 04:10:46 +0000628 // Otherwise, switch out of PP mode and return the next lexed token.
629 FoundLexer->ParsingPreprocessorDirective = false;
630 return Lex(Tok);
631 }
Mike Stump11289f42009-09-09 15:08:12 +0000632
Chris Lattner1eed7342008-03-09 04:10:46 +0000633 // If we got an EOF token, then we reached the end of the token stream but
634 // didn't find an explicit \n. This can only happen if there was no lexer
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000635 // active (an active lexer would return EOD at EOF if there was no \n in
Chris Lattner1eed7342008-03-09 04:10:46 +0000636 // preprocessor directive mode), so just return EOF as our token.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000637 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
Chris Lattner1eed7342008-03-09 04:10:46 +0000638}
Richard Smithb8b2ed62015-04-23 18:18:26 +0000639
Richard Smithd1386302017-05-04 00:29:54 +0000640void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
641 bool ForPragma) {
Richard Smith04765ae2015-05-21 01:20:10 +0000642 if (!getLangOpts().ModulesLocalVisibility) {
643 // Just track that we entered this submodule.
Richard Smithd1386302017-05-04 00:29:54 +0000644 BuildingSubmoduleStack.push_back(
645 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
646 PendingModuleMacroNames.size()));
Richard Smith04765ae2015-05-21 01:20:10 +0000647 return;
648 }
Richard Smithee977932015-05-01 21:22:17 +0000649
Richard Smith04765ae2015-05-21 01:20:10 +0000650 // Resolve as much of the module definition as we can now, before we enter
651 // one of its headers.
652 // FIXME: Can we enable Complain here?
653 // FIXME: Can we do this when local visibility is disabled?
654 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
655 ModMap.resolveExports(M, /*Complain=*/false);
656 ModMap.resolveUses(M, /*Complain=*/false);
657 ModMap.resolveConflicts(M, /*Complain=*/false);
Richard Smith42413142015-05-15 20:05:43 +0000658
Richard Smith04765ae2015-05-21 01:20:10 +0000659 // If this is the first time we've entered this module, set up its state.
Richard Smithe5202932015-05-21 01:26:53 +0000660 auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
Richard Smith04765ae2015-05-21 01:20:10 +0000661 auto &State = R.first->second;
662 bool FirstTime = R.second;
663 if (FirstTime) {
664 // Determine the set of starting macros for this submodule; take these
665 // from the "null" module (the predefines buffer).
Richard Smith4df60932015-06-30 21:29:55 +0000666 //
667 // FIXME: If we have local visibility but not modules enabled, the
668 // NullSubmoduleState is polluted by #defines in the top-level source
669 // file.
Richard Smith04765ae2015-05-21 01:20:10 +0000670 auto &StartingMacros = NullSubmoduleState.Macros;
671
672 // Restore to the starting state.
673 // FIXME: Do this lazily, when each macro name is first referenced.
674 for (auto &Macro : StartingMacros) {
Richard Smith4df60932015-06-30 21:29:55 +0000675 // Skip uninteresting macros.
676 if (!Macro.second.getLatest() &&
677 Macro.second.getOverriddenMacros().empty())
678 continue;
679
Richard Smith04765ae2015-05-21 01:20:10 +0000680 MacroState MS(Macro.second.getLatest());
681 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
682 State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
683 }
684 }
685
686 // Track that we entered this module.
Richard Smithd1386302017-05-04 00:29:54 +0000687 BuildingSubmoduleStack.push_back(
688 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
689 PendingModuleMacroNames.size()));
Richard Smith04765ae2015-05-21 01:20:10 +0000690
691 // Switch to this submodule as the current submodule.
692 CurSubmoduleState = &State;
693
694 // This module is visible to itself.
695 if (FirstTime)
Richard Smith42413142015-05-15 20:05:43 +0000696 makeModuleVisible(M, ImportLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000697}
698
Richard Smith802182f2016-02-23 23:20:51 +0000699bool Preprocessor::needModuleMacros() const {
700 // If we're not within a submodule, we never need to create ModuleMacros.
701 if (BuildingSubmoduleStack.empty())
702 return false;
703 // If we are tracking module macro visibility even for textually-included
704 // headers, we need ModuleMacros.
705 if (getLangOpts().ModulesLocalVisibility)
706 return true;
707 // Otherwise, we only need module macros if we're actually compiling a module
708 // interface.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000709 return getLangOpts().isCompilingModule();
Richard Smith802182f2016-02-23 23:20:51 +0000710}
711
Richard Smithd1386302017-05-04 00:29:54 +0000712Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
713 if (BuildingSubmoduleStack.empty() ||
714 BuildingSubmoduleStack.back().IsPragma != ForPragma) {
715 assert(ForPragma && "non-pragma module enter/leave mismatch");
716 return nullptr;
717 }
718
Richard Smithb8b2ed62015-04-23 18:18:26 +0000719 auto &Info = BuildingSubmoduleStack.back();
720
Richard Smithdbbc5232015-05-14 02:25:44 +0000721 Module *LeavingMod = Info.M;
722 SourceLocation ImportLoc = Info.ImportLoc;
723
Richard Smith4971ed02017-05-19 23:32:38 +0000724 if (!needModuleMacros() ||
Richard Smith802182f2016-02-23 23:20:51 +0000725 (!getLangOpts().ModulesLocalVisibility &&
726 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
727 // If we don't need module macros, or this is not a module for which we
728 // are tracking macro visibility, don't build any, and preserve the list
729 // of pending names for the surrounding submodule.
Richard Smithe5b53502016-02-19 22:43:58 +0000730 BuildingSubmoduleStack.pop_back();
731 makeModuleVisible(LeavingMod, ImportLoc);
Richard Smithd1386302017-05-04 00:29:54 +0000732 return LeavingMod;
Richard Smithe5b53502016-02-19 22:43:58 +0000733 }
734
Richard Smithb8b2ed62015-04-23 18:18:26 +0000735 // Create ModuleMacros for any macros defined in this submodule.
Richard Smith802182f2016-02-23 23:20:51 +0000736 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
737 for (unsigned I = Info.OuterPendingModuleMacroNames;
738 I != PendingModuleMacroNames.size(); ++I) {
739 auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
740 if (!VisitedMacros.insert(II).second)
741 continue;
742
743 auto MacroIt = CurSubmoduleState->Macros.find(II);
744 if (MacroIt == CurSubmoduleState->Macros.end())
745 continue;
746 auto &Macro = MacroIt->second;
Richard Smithee977932015-05-01 21:22:17 +0000747
748 // Find the starting point for the MacroDirective chain in this submodule.
Richard Smith04765ae2015-05-21 01:20:10 +0000749 MacroDirective *OldMD = nullptr;
Richard Smithe5b53502016-02-19 22:43:58 +0000750 auto *OldState = Info.OuterSubmoduleState;
751 if (getLangOpts().ModulesLocalVisibility)
752 OldState = &NullSubmoduleState;
753 if (OldState && OldState != CurSubmoduleState) {
Richard Smith04765ae2015-05-21 01:20:10 +0000754 // FIXME: It'd be better to start at the state from when we most recently
755 // entered this submodule, but it doesn't really matter.
Richard Smithe5b53502016-02-19 22:43:58 +0000756 auto &OldMacros = OldState->Macros;
Richard Smith802182f2016-02-23 23:20:51 +0000757 auto OldMacroIt = OldMacros.find(II);
Richard Smithe5b53502016-02-19 22:43:58 +0000758 if (OldMacroIt == OldMacros.end())
Richard Smithee977932015-05-01 21:22:17 +0000759 OldMD = nullptr;
760 else
Richard Smithe5b53502016-02-19 22:43:58 +0000761 OldMD = OldMacroIt->second.getLatest();
Richard Smithee977932015-05-01 21:22:17 +0000762 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000763
764 // This module may have exported a new macro. If so, create a ModuleMacro
765 // representing that fact.
766 bool ExplicitlyPublic = false;
Richard Smith802182f2016-02-23 23:20:51 +0000767 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
Richard Smith1e172852015-04-28 21:05:07 +0000768 assert(MD && "broken macro directive chain");
769
Richard Smithb8b2ed62015-04-23 18:18:26 +0000770 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
771 // The latest visibility directive for a name in a submodule affects
772 // all the directives that come before it.
773 if (VisMD->isPublic())
774 ExplicitlyPublic = true;
775 else if (!ExplicitlyPublic)
776 // Private with no following public directive: not exported.
777 break;
778 } else {
779 MacroInfo *Def = nullptr;
780 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
781 Def = DefMD->getInfo();
782
783 // FIXME: Issue a warning if multiple headers for the same submodule
784 // define a macro, rather than silently ignoring all but the first.
785 bool IsNew;
Richard Smith32dbd692015-05-02 01:14:40 +0000786 // Don't bother creating a module macro if it would represent a #undef
787 // that doesn't override anything.
Richard Smith802182f2016-02-23 23:20:51 +0000788 if (Def || !Macro.getOverriddenMacros().empty())
Richard Smithdbbc5232015-05-14 02:25:44 +0000789 addModuleMacro(LeavingMod, II, Def,
Richard Smith802182f2016-02-23 23:20:51 +0000790 Macro.getOverriddenMacros(), IsNew);
Richard Smith4971ed02017-05-19 23:32:38 +0000791
792 if (!getLangOpts().ModulesLocalVisibility) {
793 // This macro is exposed to the rest of this compilation as a
794 // ModuleMacro; we don't need to track its MacroDirective any more.
795 Macro.setLatest(nullptr);
796 Macro.setOverriddenMacros(*this, {});
797 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000798 break;
799 }
800 }
Richard Smith753e0072015-04-27 23:21:38 +0000801 }
Richard Smith802182f2016-02-23 23:20:51 +0000802 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000803
Richard Smith4df60932015-06-30 21:29:55 +0000804 // FIXME: Before we leave this submodule, we should parse all the other
805 // headers within it. Otherwise, we're left with an inconsistent state
806 // where we've made the module visible but don't yet have its complete
807 // contents.
808
Richard Smith04765ae2015-05-21 01:20:10 +0000809 // Put back the outer module's state, if we're tracking it.
Richard Smithee977932015-05-01 21:22:17 +0000810 if (getLangOpts().ModulesLocalVisibility)
Richard Smith04765ae2015-05-21 01:20:10 +0000811 CurSubmoduleState = Info.OuterSubmoduleState;
Richard Smithee977932015-05-01 21:22:17 +0000812
Richard Smithb8b2ed62015-04-23 18:18:26 +0000813 BuildingSubmoduleStack.pop_back();
Richard Smithdbbc5232015-05-14 02:25:44 +0000814
815 // A nested #include makes the included submodule visible.
Richard Smith4df60932015-06-30 21:29:55 +0000816 makeModuleVisible(LeavingMod, ImportLoc);
Richard Smithd1386302017-05-04 00:29:54 +0000817 return LeavingMod;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000818}