blob: 235cc3f463b05536aac2cb1a2f550daba0cb41a4 [file] [log] [blame]
Chris Lattner1eed7342008-03-09 04:10:46 +00001//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements pieces of the Preprocessor interface that manage the
11// current lexer stack.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Douglas Gregorebf00492011-10-17 15:32:29 +000016#include "clang/Basic/FileManager.h"
Chris Lattner1eed7342008-03-09 04:10:46 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/HeaderSearch.h"
19#include "clang/Lex/LexDiagnostic.h"
20#include "clang/Lex/MacroInfo.h"
Reid Kleckner738d48d2015-11-02 17:53:55 +000021#include "clang/Lex/PTHManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/ADT/StringSwitch.h"
Douglas Gregorfe76cfd2011-12-23 00:23:59 +000023#include "llvm/Support/FileSystem.h"
Ted Kremenek85b48c62008-11-20 07:56:33 +000024#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola552c1692013-06-11 22:15:02 +000025#include "llvm/Support/Path.h"
Chris Lattner1eed7342008-03-09 04:10:46 +000026using namespace clang;
27
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000028PPCallbacks::~PPCallbacks() {}
Chris Lattner1eed7342008-03-09 04:10:46 +000029
30//===----------------------------------------------------------------------===//
Chris Lattner3e468322008-03-10 06:06:04 +000031// Miscellaneous Methods.
Chris Lattner1eed7342008-03-09 04:10:46 +000032//===----------------------------------------------------------------------===//
33
Chris Lattner1eed7342008-03-09 04:10:46 +000034/// isInPrimaryFile - Return true if we're in the top-level file, not in a
James Dennett1244a0d2012-06-22 05:36:05 +000035/// \#include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner1eed7342008-03-09 04:10:46 +000036bool Preprocessor::isInPrimaryFile() const {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000037 if (IsFileLexer())
Chris Lattner1eed7342008-03-09 04:10:46 +000038 return IncludeMacroStack.empty();
Mike Stump11289f42009-09-09 15:08:12 +000039
Chris Lattner1eed7342008-03-09 04:10:46 +000040 // If there are any stacked lexers, we're in a #include.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000041 assert(IsFileLexer(IncludeMacroStack[0]) &&
Chris Lattner1eed7342008-03-09 04:10:46 +000042 "Top level include stack isn't our primary lexer?");
43 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000044 if (IsFileLexer(IncludeMacroStack[i]))
Chris Lattner1eed7342008-03-09 04:10:46 +000045 return false;
46 return true;
47}
48
49/// getCurrentLexer - Return the current file lexer being lexed from. Note
50/// that this ignores any potentially active macro expansions and _Pragma
51/// expansions going on at the time.
Ted Kremenekb33ce322008-11-20 01:49:44 +000052PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000053 if (IsFileLexer())
Ted Kremenekb33ce322008-11-20 01:49:44 +000054 return CurPPLexer;
Mike Stump11289f42009-09-09 15:08:12 +000055
Chris Lattner1eed7342008-03-09 04:10:46 +000056 // Look for a stacked lexer.
57 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Ted Kremenekb33ce322008-11-20 01:49:44 +000058 const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +000059 if (IsFileLexer(ISI))
Ted Kremenekb33ce322008-11-20 01:49:44 +000060 return ISI.ThePPLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +000061 }
Craig Topperd2d442c2014-05-17 23:10:59 +000062 return nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +000063}
64
Chris Lattner3e468322008-03-10 06:06:04 +000065
66//===----------------------------------------------------------------------===//
67// Methods for Entering and Callbacks for leaving various contexts
68//===----------------------------------------------------------------------===//
Chris Lattner1eed7342008-03-09 04:10:46 +000069
70/// EnterSourceFile - Add a source file to the top of the include stack and
Nuno Lopes0e5d13e2009-11-29 17:07:16 +000071/// start lexing tokens from it instead of the current buffer.
Richard Smith67294e22014-01-31 20:47:44 +000072bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
73 SourceLocation Loc) {
David Blaikie7d170102013-05-15 07:37:26 +000074 assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
Chris Lattner1eed7342008-03-09 04:10:46 +000075 ++NumEnteredSourceFiles;
Mike Stump11289f42009-09-09 15:08:12 +000076
Chris Lattner1eed7342008-03-09 04:10:46 +000077 if (MaxIncludeStackDepth < IncludeMacroStack.size())
78 MaxIncludeStackDepth = IncludeMacroStack.size();
79
Ted Kremenekaf058b52008-12-02 19:46:31 +000080 if (PTH) {
Chris Lattner710bb872009-11-30 04:18:44 +000081 if (PTHLexer *PL = PTH->CreateLexer(FID)) {
Richard Smith67294e22014-01-31 20:47:44 +000082 EnterSourceFileWithPTH(PL, CurDir);
83 return false;
Chris Lattner710bb872009-11-30 04:18:44 +000084 }
Ted Kremenekaf058b52008-12-02 19:46:31 +000085 }
Chris Lattner710bb872009-11-30 04:18:44 +000086
87 // Get the MemoryBuffer for this FID, if it fails, we fail.
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +000088 bool Invalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000089 const llvm::MemoryBuffer *InputFile =
90 getSourceManager().getBuffer(FID, Loc, &Invalid);
91 if (Invalid) {
92 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
93 Diag(Loc, diag::err_pp_error_opening_file)
94 << std::string(SourceMgr.getBufferName(FileStart)) << "";
Richard Smith67294e22014-01-31 20:47:44 +000095 return true;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000096 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000097
98 if (isCodeCompletionEnabled() &&
99 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
100 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
101 CodeCompletionLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000102 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000103 }
104
Richard Smith67294e22014-01-31 20:47:44 +0000105 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
106 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000107}
Chris Lattnerc88a23e2008-09-26 20:12:23 +0000108
Ted Kremenekaf058b52008-12-02 19:46:31 +0000109/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
110/// and start lexing tokens from it instead of the current buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000111void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
Richard Smith67294e22014-01-31 20:47:44 +0000112 const DirectoryLookup *CurDir) {
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattner1eed7342008-03-09 04:10:46 +0000114 // Add the current lexer to the include stack.
Ted Kremenek45245212008-11-19 21:57:25 +0000115 if (CurPPLexer || CurTokenLexer)
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000116 PushIncludeMacroStack();
117
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000118 CurLexer.reset(TheLexer);
Ted Kremenek68ef9fc2008-11-18 00:12:49 +0000119 CurPPLexer = TheLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000120 CurDirLookup = CurDir;
Craig Topperd2d442c2014-05-17 23:10:59 +0000121 CurSubmodule = nullptr;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000122 if (CurLexerKind != CLK_LexAfterModuleImport)
123 CurLexerKind = CLK_Lexer;
Yaron Kerene02bcdc2015-11-07 16:35:07 +0000124
Chris Lattner1eed7342008-03-09 04:10:46 +0000125 // Notify the client, if desired, that we are in a new source file.
126 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000127 SrcMgr::CharacteristicKind FileType =
Chris Lattnerb03dc762008-09-26 21:18:42 +0000128 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Mike Stump11289f42009-09-09 15:08:12 +0000129
Chris Lattner1eed7342008-03-09 04:10:46 +0000130 Callbacks->FileChanged(CurLexer->getFileLoc(),
131 PPCallbacks::EnterFile, FileType);
132 }
133}
134
Ted Kremenekaf058b52008-12-02 19:46:31 +0000135/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
136/// and start getting tokens from it using the PTH cache.
Mike Stump11289f42009-09-09 15:08:12 +0000137void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
Richard Smith67294e22014-01-31 20:47:44 +0000138 const DirectoryLookup *CurDir) {
Mike Stump11289f42009-09-09 15:08:12 +0000139
Ted Kremenekaf058b52008-12-02 19:46:31 +0000140 if (CurPPLexer || CurTokenLexer)
141 PushIncludeMacroStack();
Chris Lattner1eed7342008-03-09 04:10:46 +0000142
Ted Kremenekaf058b52008-12-02 19:46:31 +0000143 CurDirLookup = CurDir;
144 CurPTHLexer.reset(PL);
145 CurPPLexer = CurPTHLexer.get();
Craig Topperd2d442c2014-05-17 23:10:59 +0000146 CurSubmodule = nullptr;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000147 if (CurLexerKind != CLK_LexAfterModuleImport)
148 CurLexerKind = CLK_PTHLexer;
149
Ted Kremenekaf058b52008-12-02 19:46:31 +0000150 // Notify the client, if desired, that we are in a new source file.
151 if (Callbacks) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000152 FileID FID = CurPPLexer->getFileID();
Chris Lattner4fd8b952009-01-19 08:01:53 +0000153 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
154 SrcMgr::CharacteristicKind FileType =
155 SourceMgr.getFileCharacteristic(EnterLoc);
156 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
Ted Kremenekaf058b52008-12-02 19:46:31 +0000157 }
158}
Chris Lattner1eed7342008-03-09 04:10:46 +0000159
160/// EnterMacro - Add a Macro to the top of the include stack and start lexing
161/// tokens from it instead of the current buffer.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000162void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
Richard Smith5edd5832012-08-30 13:38:46 +0000163 MacroInfo *Macro, MacroArgs *Args) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000164 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000165 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000166 TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000167 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000168 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000169 TokLexer->Init(Tok, ILEnd, Macro, Args);
170 }
171
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000172 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000173 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000174 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000175 if (CurLexerKind != CLK_LexAfterModuleImport)
176 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000177}
178
179/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner3e468322008-03-10 06:06:04 +0000180/// which will cause the lexer to start returning the specified tokens.
181///
182/// If DisableMacroExpansion is true, tokens lexed from the token stream will
183/// not be subject to further macro expansion. Otherwise, these tokens will
184/// be re-macro-expanded when/if expansion is enabled.
185///
186/// If OwnsTokens is false, this method assumes that the specified stream of
187/// tokens has a permanent owner somewhere, so they do not need to be copied.
188/// If it is true, it assumes the array of tokens is allocated with new[] and
189/// must be freed.
190///
191void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
192 bool DisableMacroExpansion,
193 bool OwnsTokens) {
Richard Smithbdf54a212014-09-23 21:05:52 +0000194 if (CurLexerKind == CLK_CachingLexer) {
195 if (CachedLexPos < CachedTokens.size()) {
196 // We're entering tokens into the middle of our cached token stream. We
197 // can't represent that, so just insert the tokens into the buffer.
198 CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
199 Toks, Toks + NumToks);
200 if (OwnsTokens)
201 delete [] Toks;
202 return;
203 }
204
205 // New tokens are at the end of the cached token sequnece; insert the
206 // token stream underneath the caching lexer.
207 ExitCachingLexMode();
208 EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
209 EnterCachingLexMode();
210 return;
211 }
212
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000213 // Create a macro expander to expand from the specified token stream.
David Blaikie6d5038c2014-08-29 19:36:52 +0000214 std::unique_ptr<TokenLexer> TokLexer;
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000215 if (NumCachedTokenLexers == 0) {
David Blaikie6d5038c2014-08-29 19:36:52 +0000216 TokLexer = llvm::make_unique<TokenLexer>(
217 Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000218 } else {
David Blaikie6d5038c2014-08-29 19:36:52 +0000219 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000220 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
221 }
222
Chris Lattner1eed7342008-03-09 04:10:46 +0000223 // Save our current state.
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000224 PushIncludeMacroStack();
Craig Topperd2d442c2014-05-17 23:10:59 +0000225 CurDirLookup = nullptr;
David Blaikie6d5038c2014-08-29 19:36:52 +0000226 CurTokenLexer = std::move(TokLexer);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000227 if (CurLexerKind != CLK_LexAfterModuleImport)
228 CurLexerKind = CLK_TokenLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000229}
230
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000231/// \brief Compute the relative path that names the given file relative to
232/// the given directory.
233static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
234 const FileEntry *File,
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000235 SmallString<128> &Result) {
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000236 Result.clear();
237
238 StringRef FilePath = File->getDir()->getName();
239 StringRef Path = FilePath;
240 while (!Path.empty()) {
241 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
242 if (CurDir == Dir) {
243 Result = FilePath.substr(Path.size());
244 llvm::sys::path::append(Result,
245 llvm::sys::path::filename(File->getName()));
246 return;
247 }
248 }
249
250 Path = llvm::sys::path::parent_path(Path);
251 }
252
253 Result = File->getName();
254}
255
Eli Friedman0834a4b2013-09-19 00:41:32 +0000256void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
257 if (CurTokenLexer) {
258 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
259 return;
260 }
261 if (CurLexer) {
262 CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
263 return;
264 }
265 // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
266 // but it might if they're empty?
267}
268
Richard Smith34f30512013-11-23 04:06:09 +0000269/// \brief Determine the location to use as the end of the buffer for a lexer.
270///
271/// If the file ends with a newline, form the EOF token on the newline itself,
272/// rather than "on the line following it", which doesn't exist. This makes
273/// diagnostics relating to the end of file include the last file that the user
274/// actually typed, which is goodness.
275const char *Preprocessor::getCurLexerEndPos() {
276 const char *EndPos = CurLexer->BufferEnd;
277 if (EndPos != CurLexer->BufferStart &&
278 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
279 --EndPos;
280
281 // Handle \n\r and \r\n:
282 if (EndPos != CurLexer->BufferStart &&
283 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
284 EndPos[-1] != EndPos[0])
285 --EndPos;
286 }
287
288 return EndPos;
289}
290
291
Chris Lattner1eed7342008-03-09 04:10:46 +0000292/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
293/// the current file. This either returns the EOF token or pops a level off
294/// the include stack and keeps going.
295bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
296 assert(!CurTokenLexer &&
297 "Ending a file when currently in a macro!");
Mike Stump11289f42009-09-09 15:08:12 +0000298
Chris Lattner1eed7342008-03-09 04:10:46 +0000299 // See if this file had a controlling macro.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000300 if (CurPPLexer) { // Not ending a macro, ignore it.
Mike Stump11289f42009-09-09 15:08:12 +0000301 if (const IdentifierInfo *ControllingMacro =
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000302 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Steve Naroff3fa455a2009-04-24 20:03:17 +0000303 // Okay, this has a controlling macro, remember in HeaderFileInfo.
Yaron Keren65224612015-12-18 10:30:12 +0000304 if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000305 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +0000306 if (MacroInfo *MI =
307 getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro))) {
308 MI->UsedForHeaderGuard = true;
309 }
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000310 if (const IdentifierInfo *DefinedMacro =
311 CurPPLexer->MIOpt.GetDefinedMacro()) {
Richard Smith20e883e2015-04-29 23:20:19 +0000312 if (!isMacroDefined(ControllingMacro) &&
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000313 DefinedMacro != ControllingMacro &&
314 HeaderInfo.FirstTimeLexingFile(FE)) {
Ismail Pazarbasi8d0f2f32013-10-12 23:17:37 +0000315
316 // If the edit distance between the two macros is more than 50%,
317 // DefinedMacro may not be header guard, or can be header guard of
318 // another header file. Therefore, it maybe defining something
319 // completely different. This can be observed in the wild when
320 // handling feature macros or header guards in different files.
321
322 const StringRef ControllingMacroName = ControllingMacro->getName();
323 const StringRef DefinedMacroName = DefinedMacro->getName();
324 const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
325 DefinedMacroName.size()) / 2;
326 const unsigned ED = ControllingMacroName.edit_distance(
327 DefinedMacroName, true, MaxHalfLength);
328 if (ED <= MaxHalfLength) {
329 // Emit a warning for a bad header guard.
330 Diag(CurPPLexer->MIOpt.GetMacroLocation(),
331 diag::warn_header_guard)
332 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
333 Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
334 diag::note_header_guard)
335 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
336 << ControllingMacro
337 << FixItHint::CreateReplacement(
338 CurPPLexer->MIOpt.GetDefinedLocation(),
339 ControllingMacro->getName());
340 }
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000341 }
342 }
343 }
Chris Lattner1eed7342008-03-09 04:10:46 +0000344 }
345 }
Mike Stump11289f42009-09-09 15:08:12 +0000346
John McCall95ff2702011-10-18 00:44:04 +0000347 // Complain about reaching a true EOF within arc_cf_code_audited.
348 // We don't want to complain about reaching the end of a macro
349 // instantiation or a _Pragma.
350 if (PragmaARCCFCodeAuditedLoc.isValid() &&
John McCall43d4dd42011-10-18 01:36:41 +0000351 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
John McCall32f5fe12011-09-30 05:12:12 +0000352 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
353
354 // Recover by leaving immediately.
355 PragmaARCCFCodeAuditedLoc = SourceLocation();
356 }
357
Douglas Gregor2a20bd12015-06-19 18:25:57 +0000358 // Complain about reaching a true EOF within assume_nonnull.
359 // We don't want to complain about reaching the end of a macro
360 // instantiation or a _Pragma.
361 if (PragmaAssumeNonNullLoc.isValid() &&
362 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
363 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
364
365 // Recover by leaving immediately.
366 PragmaAssumeNonNullLoc = SourceLocation();
367 }
368
Chris Lattner1eed7342008-03-09 04:10:46 +0000369 // If this is a #include'd file, pop it off the include stack and continue
370 // lexing the #includer file.
371 if (!IncludeMacroStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000372
373 // If we lexed the code-completion file, act as if we reached EOF.
374 if (isCodeCompletionEnabled() && CurPPLexer &&
375 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
376 CodeCompletionFileLoc) {
377 if (CurLexer) {
378 Result.startToken();
379 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
380 CurLexer.reset();
381 } else {
382 assert(CurPTHLexer && "Got EOF but no current lexer set!");
383 CurPTHLexer->getEOF(Result);
384 CurPTHLexer.reset();
385 }
386
Craig Topperd2d442c2014-05-17 23:10:59 +0000387 CurPPLexer = nullptr;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000388 return true;
389 }
390
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +0000391 if (!isEndOfMacro && CurPPLexer &&
392 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
393 // Notify SourceManager to record the number of FileIDs that were created
394 // during lexing of the #include'd file.
395 unsigned NumFIDs =
396 SourceMgr.local_sloc_entry_size() -
397 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
398 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
399 }
400
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000401 FileID ExitedFID;
402 if (Callbacks && !isEndOfMacro && CurPPLexer)
403 ExitedFID = CurPPLexer->getFileID();
Richard Smith34f30512013-11-23 04:06:09 +0000404
Richard Smith67294e22014-01-31 20:47:44 +0000405 bool LeavingSubmodule = CurSubmodule && CurLexer;
Richard Smith34f30512013-11-23 04:06:09 +0000406 if (LeavingSubmodule) {
Richard Smith67294e22014-01-31 20:47:44 +0000407 // Notify the parser that we've left the module.
Richard Smith34f30512013-11-23 04:06:09 +0000408 const char *EndPos = getCurLexerEndPos();
409 Result.startToken();
410 CurLexer->BufferPtr = EndPos;
411 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
412 Result.setAnnotationEndLoc(Result.getLocation());
Richard Smith67294e22014-01-31 20:47:44 +0000413 Result.setAnnotationValue(CurSubmodule);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000414
415 // We're done with this submodule.
416 LeaveSubmodule();
Richard Smith34f30512013-11-23 04:06:09 +0000417 }
418
Chris Lattner1eed7342008-03-09 04:10:46 +0000419 // We're done with the #included file.
420 RemoveTopOfLexerStack();
421
Eli Friedman0834a4b2013-09-19 00:41:32 +0000422 // Propagate info about start-of-line/leading white-space/etc.
423 PropagateLineStartLeadingSpaceInfo(Result);
424
Chris Lattner1eed7342008-03-09 04:10:46 +0000425 // Notify the client, if desired, that we are in a new source file.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000426 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner66a740e2008-10-27 01:19:25 +0000427 SrcMgr::CharacteristicKind FileType =
Chris Lattner4fd8b952009-01-19 08:01:53 +0000428 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
429 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Argyrios Kyrtzidis7a70d2f2011-10-11 17:29:44 +0000430 PPCallbacks::ExitFile, FileType, ExitedFID);
Chris Lattner1eed7342008-03-09 04:10:46 +0000431 }
432
Richard Smith34f30512013-11-23 04:06:09 +0000433 // Client should lex another token unless we generated an EOM.
434 return LeavingSubmodule;
Chris Lattner1eed7342008-03-09 04:10:46 +0000435 }
436
Richard Smith34f30512013-11-23 04:06:09 +0000437 // If this is the end of the main file, form an EOF token.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000438 if (CurLexer) {
Richard Smith34f30512013-11-23 04:06:09 +0000439 const char *EndPos = getCurLexerEndPos();
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000440 Result.startToken();
441 CurLexer->BufferPtr = EndPos;
442 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Mike Stump11289f42009-09-09 15:08:12 +0000443
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000444 if (isCodeCompletionEnabled()) {
445 // Inserting the code-completion point increases the source buffer by 1,
446 // but the main FileID was created before inserting the point.
447 // Compensate by reducing the EOF location by 1, otherwise the location
448 // will point to the next FileID.
449 // FIXME: This is hacky, the code-completion point should probably be
450 // inserted before the main FileID is created.
451 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
452 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
453 }
454
Axel Naumann2eb1d902012-03-16 10:40:17 +0000455 if (!isIncrementalProcessingEnabled())
456 // We're done with lexing.
457 CurLexer.reset();
Chris Lattner190f64e2009-02-13 23:06:48 +0000458 } else {
459 assert(CurPTHLexer && "Got EOF but no current lexer set!");
Ted Kremenek78cc2472008-12-23 19:24:24 +0000460 CurPTHLexer->getEOF(Result);
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000461 CurPTHLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000462 }
Axel Naumann2eb1d902012-03-16 10:40:17 +0000463
464 if (!isIncrementalProcessingEnabled())
Craig Topperd2d442c2014-05-17 23:10:59 +0000465 CurPPLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000466
Argyrios Kyrtzidis8ed74142014-03-08 21:18:26 +0000467 if (TUKind == TU_Complete) {
Argyrios Kyrtzidise1974dc2014-03-07 07:47:58 +0000468 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
469 // collected all macro locations that we need to warn because they are not
470 // used.
471 for (WarnUnusedMacroLocsTy::iterator
472 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
473 I!=E; ++I)
474 Diag(*I, diag::pp_macro_not_used);
475 }
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000476
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000477 // If we are building a module that has an umbrella header, make sure that
478 // each of the headers within the directory covered by the umbrella header
479 // was actually included by the umbrella header.
480 if (Module *Mod = getCurrentModule()) {
481 if (Mod->getUmbrellaHeader()) {
482 SourceLocation StartLoc
483 = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
484
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000485 if (!getDiagnostics().isIgnored(diag::warn_uncovered_module_header,
486 StartLoc)) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000487 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
Richard Smith2b63d152015-05-16 02:28:53 +0000488 const DirectoryEntry *Dir = Mod->getUmbrellaDir().Entry;
Ben Langmuir54cbc702014-06-25 23:53:43 +0000489 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
Rafael Espindolac0809172014-06-12 14:02:15 +0000490 std::error_code EC;
Ben Langmuir54cbc702014-06-25 23:53:43 +0000491 for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End;
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000492 Entry != End && !EC; Entry.increment(EC)) {
493 using llvm::StringSwitch;
494
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000495 // Check whether this entry has an extension typically associated with
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000496 // headers.
Ben Langmuir54cbc702014-06-25 23:53:43 +0000497 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName()))
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000498 .Cases(".h", ".H", ".hh", ".hpp", true)
499 .Default(false))
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000500 continue;
501
Ben Langmuir54cbc702014-06-25 23:53:43 +0000502 if (const FileEntry *Header =
503 getFileManager().getFile(Entry->getName()))
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000504 if (!getSourceManager().hasFileInfo(Header)) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000505 if (!ModMap.isHeaderInUnavailableModule(Header)) {
506 // Find the relative path that would access this header.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000507 SmallString<128> RelativePath;
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000508 computeRelativePath(FileMgr, Dir, Header, RelativePath);
509 Diag(StartLoc, diag::warn_uncovered_module_header)
Douglas Gregor8f1f3332013-01-04 18:58:28 +0000510 << Mod->getFullModuleName() << RelativePath;
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000511 }
Douglas Gregorfe76cfd2011-12-23 00:23:59 +0000512 }
513 }
514 }
515 }
516 }
Douglas Gregorf4e76b82013-05-20 13:49:41 +0000517
Chris Lattner1eed7342008-03-09 04:10:46 +0000518 return true;
519}
520
521/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
522/// hits the end of its token stream.
523bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000524 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000525 "Ending a macro when currently in a #include file!");
526
Argyrios Kyrtzidis8cc04592011-06-29 22:20:11 +0000527 if (!MacroExpandingLexersStack.empty() &&
528 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
529 removeCachedMacroExpandedTokensOfLastLexer();
530
Chris Lattner1eed7342008-03-09 04:10:46 +0000531 // Delete or cache the now-dead macro expander.
532 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000533 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000534 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000535 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Chris Lattner1eed7342008-03-09 04:10:46 +0000536
537 // Handle this like a #include file being popped off the stack.
Chris Lattner1eed7342008-03-09 04:10:46 +0000538 return HandleEndOfFile(Result, true);
539}
540
541/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
542/// lexer stack. This should only be used in situations where the current
543/// state of the top-of-stack lexer is unknown.
544void Preprocessor::RemoveTopOfLexerStack() {
545 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattner1eed7342008-03-09 04:10:46 +0000547 if (CurTokenLexer) {
548 // Delete or cache the now-dead macro expander.
549 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremeneka0d2a162008-11-13 17:11:24 +0000550 CurTokenLexer.reset();
Chris Lattner1eed7342008-03-09 04:10:46 +0000551 else
David Blaikie6d5038c2014-08-29 19:36:52 +0000552 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
Mike Stump11289f42009-09-09 15:08:12 +0000553 }
554
Ted Kremenek7c1e61d2008-11-13 16:51:03 +0000555 PopIncludeMacroStack();
Chris Lattner1eed7342008-03-09 04:10:46 +0000556}
557
558/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
559/// comment (/##/) in microsoft mode, this method handles updating the current
560/// state, returning the token on the next source line.
561void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000562 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner1eed7342008-03-09 04:10:46 +0000563 "Pasted comment can only be formed from macro");
Chris Lattner1eed7342008-03-09 04:10:46 +0000564 // We handle this by scanning for the closest real lexer, switching it to
565 // raw mode and preprocessor mode. This will cause it to return \n as an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000566 // explicit EOD token.
Craig Topperd2d442c2014-05-17 23:10:59 +0000567 PreprocessorLexer *FoundLexer = nullptr;
Chris Lattner1eed7342008-03-09 04:10:46 +0000568 bool LexerWasInPPMode = false;
569 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
570 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
Craig Topperd2d442c2014-05-17 23:10:59 +0000571 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
Mike Stump11289f42009-09-09 15:08:12 +0000572
Chris Lattner1eed7342008-03-09 04:10:46 +0000573 // Once we find a real lexer, mark it as raw mode (disabling macro
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000574 // expansions) and preprocessor mode (return EOD). We know that the lexer
Chris Lattner1eed7342008-03-09 04:10:46 +0000575 // was *not* in raw mode before, because the macro that the comment came
576 // from was expanded. However, it could have already been in preprocessor
577 // mode (#if COMMENT) in which case we have to return it to that mode and
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000578 // return EOD.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000579 FoundLexer = ISI.ThePPLexer;
Chris Lattner1eed7342008-03-09 04:10:46 +0000580 FoundLexer->LexingRawMode = true;
581 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
582 FoundLexer->ParsingPreprocessorDirective = true;
583 break;
584 }
Mike Stump11289f42009-09-09 15:08:12 +0000585
Chris Lattner1eed7342008-03-09 04:10:46 +0000586 // Okay, we either found and switched over the lexer, or we didn't find a
587 // lexer. In either case, finish off the macro the comment came from, getting
588 // the next token.
589 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000590
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000591 // Discarding comments as long as we don't have EOF or EOD. This 'comments
Chris Lattner1eed7342008-03-09 04:10:46 +0000592 // out' the rest of the line, including any tokens that came from other macros
593 // that were active, as in:
594 // #define submacro a COMMENT b
595 // submacro c
596 // which should lex to 'a' only: 'b' and 'c' should be removed.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000597 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
Chris Lattner1eed7342008-03-09 04:10:46 +0000598 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000599
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000600 // If we got an eod token, then we successfully found the end of the line.
601 if (Tok.is(tok::eod)) {
Chris Lattner1eed7342008-03-09 04:10:46 +0000602 assert(FoundLexer && "Can't get end of line without an active lexer");
603 // Restore the lexer back to normal mode instead of raw mode.
604 FoundLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000605
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000606 // If the lexer was already in preprocessor mode, just return the EOD token
Chris Lattner1eed7342008-03-09 04:10:46 +0000607 // to finish the preprocessor line.
608 if (LexerWasInPPMode) return;
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattner1eed7342008-03-09 04:10:46 +0000610 // Otherwise, switch out of PP mode and return the next lexed token.
611 FoundLexer->ParsingPreprocessorDirective = false;
612 return Lex(Tok);
613 }
Mike Stump11289f42009-09-09 15:08:12 +0000614
Chris Lattner1eed7342008-03-09 04:10:46 +0000615 // If we got an EOF token, then we reached the end of the token stream but
616 // didn't find an explicit \n. This can only happen if there was no lexer
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000617 // active (an active lexer would return EOD at EOF if there was no \n in
Chris Lattner1eed7342008-03-09 04:10:46 +0000618 // preprocessor directive mode), so just return EOF as our token.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000619 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
Chris Lattner1eed7342008-03-09 04:10:46 +0000620}
Richard Smithb8b2ed62015-04-23 18:18:26 +0000621
Richard Smith50474bf2015-04-23 23:29:05 +0000622void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000623 if (!getLangOpts().ModulesLocalVisibility) {
624 // Just track that we entered this submodule.
625 BuildingSubmoduleStack.push_back(
626 BuildingSubmoduleInfo(M, ImportLoc, CurSubmoduleState));
627 return;
628 }
Richard Smithee977932015-05-01 21:22:17 +0000629
Richard Smith04765ae2015-05-21 01:20:10 +0000630 // Resolve as much of the module definition as we can now, before we enter
631 // one of its headers.
632 // FIXME: Can we enable Complain here?
633 // FIXME: Can we do this when local visibility is disabled?
634 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
635 ModMap.resolveExports(M, /*Complain=*/false);
636 ModMap.resolveUses(M, /*Complain=*/false);
637 ModMap.resolveConflicts(M, /*Complain=*/false);
Richard Smith42413142015-05-15 20:05:43 +0000638
Richard Smith04765ae2015-05-21 01:20:10 +0000639 // If this is the first time we've entered this module, set up its state.
Richard Smithe5202932015-05-21 01:26:53 +0000640 auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
Richard Smith04765ae2015-05-21 01:20:10 +0000641 auto &State = R.first->second;
642 bool FirstTime = R.second;
643 if (FirstTime) {
644 // Determine the set of starting macros for this submodule; take these
645 // from the "null" module (the predefines buffer).
Richard Smith4df60932015-06-30 21:29:55 +0000646 //
647 // FIXME: If we have local visibility but not modules enabled, the
648 // NullSubmoduleState is polluted by #defines in the top-level source
649 // file.
Richard Smith04765ae2015-05-21 01:20:10 +0000650 auto &StartingMacros = NullSubmoduleState.Macros;
651
652 // Restore to the starting state.
653 // FIXME: Do this lazily, when each macro name is first referenced.
654 for (auto &Macro : StartingMacros) {
Richard Smith4df60932015-06-30 21:29:55 +0000655 // Skip uninteresting macros.
656 if (!Macro.second.getLatest() &&
657 Macro.second.getOverriddenMacros().empty())
658 continue;
659
Richard Smith04765ae2015-05-21 01:20:10 +0000660 MacroState MS(Macro.second.getLatest());
661 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
662 State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
663 }
664 }
665
666 // Track that we entered this module.
667 BuildingSubmoduleStack.push_back(
668 BuildingSubmoduleInfo(M, ImportLoc, CurSubmoduleState));
669
670 // Switch to this submodule as the current submodule.
671 CurSubmoduleState = &State;
672
673 // This module is visible to itself.
674 if (FirstTime)
Richard Smith42413142015-05-15 20:05:43 +0000675 makeModuleVisible(M, ImportLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000676}
677
678void Preprocessor::LeaveSubmodule() {
679 auto &Info = BuildingSubmoduleStack.back();
680
Richard Smithdbbc5232015-05-14 02:25:44 +0000681 Module *LeavingMod = Info.M;
682 SourceLocation ImportLoc = Info.ImportLoc;
683
Richard Smithe5b53502016-02-19 22:43:58 +0000684 if ((!getLangOpts().CompilingModule ||
685 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule) &&
686 !getLangOpts().ModulesLocalVisibility) {
687 // Fast path: if we're leaving a modular header that we included textually,
688 // and we're not building the interface for that module, and we're not
689 // providing submodule visibility semantics regardless, then we don't need
690 // to create ModuleMacros. (We'd never use them.)
691 BuildingSubmoduleStack.pop_back();
692 makeModuleVisible(LeavingMod, ImportLoc);
693 return;
694 }
695
Richard Smithb8b2ed62015-04-23 18:18:26 +0000696 // Create ModuleMacros for any macros defined in this submodule.
Richard Smith04765ae2015-05-21 01:20:10 +0000697 for (auto &Macro : CurSubmoduleState->Macros) {
Richard Smithb8b2ed62015-04-23 18:18:26 +0000698 auto *II = const_cast<IdentifierInfo*>(Macro.first);
Richard Smithee977932015-05-01 21:22:17 +0000699
700 // Find the starting point for the MacroDirective chain in this submodule.
Richard Smith04765ae2015-05-21 01:20:10 +0000701 MacroDirective *OldMD = nullptr;
Richard Smithe5b53502016-02-19 22:43:58 +0000702 auto *OldState = Info.OuterSubmoduleState;
703 if (getLangOpts().ModulesLocalVisibility)
704 OldState = &NullSubmoduleState;
705 if (OldState && OldState != CurSubmoduleState) {
Richard Smith04765ae2015-05-21 01:20:10 +0000706 // FIXME: It'd be better to start at the state from when we most recently
707 // entered this submodule, but it doesn't really matter.
Richard Smithe5b53502016-02-19 22:43:58 +0000708 auto &OldMacros = OldState->Macros;
709 auto OldMacroIt = OldMacros.find(Macro.first);
710 if (OldMacroIt == OldMacros.end())
Richard Smithee977932015-05-01 21:22:17 +0000711 OldMD = nullptr;
712 else
Richard Smithe5b53502016-02-19 22:43:58 +0000713 OldMD = OldMacroIt->second.getLatest();
Richard Smithee977932015-05-01 21:22:17 +0000714 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000715
716 // This module may have exported a new macro. If so, create a ModuleMacro
717 // representing that fact.
718 bool ExplicitlyPublic = false;
Richard Smithee977932015-05-01 21:22:17 +0000719 for (auto *MD = Macro.second.getLatest(); MD != OldMD;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000720 MD = MD->getPrevious()) {
Richard Smith1e172852015-04-28 21:05:07 +0000721 assert(MD && "broken macro directive chain");
722
Richard Smith38477db2015-05-02 00:45:56 +0000723 // Stop on macros defined in other submodules we #included along the way.
Richard Smithee977932015-05-01 21:22:17 +0000724 // There's no point doing this if we're tracking local submodule
Richard Smith38477db2015-05-02 00:45:56 +0000725 // visibility, since there can be no such directives in our list.
Richard Smithee977932015-05-01 21:22:17 +0000726 if (!getLangOpts().ModulesLocalVisibility) {
727 Module *Mod = getModuleContainingLocation(MD->getLocation());
Richard Smithdbbc5232015-05-14 02:25:44 +0000728 if (Mod != LeavingMod)
Richard Smith38477db2015-05-02 00:45:56 +0000729 break;
Richard Smithee977932015-05-01 21:22:17 +0000730 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000731
732 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
733 // The latest visibility directive for a name in a submodule affects
734 // all the directives that come before it.
735 if (VisMD->isPublic())
736 ExplicitlyPublic = true;
737 else if (!ExplicitlyPublic)
738 // Private with no following public directive: not exported.
739 break;
740 } else {
741 MacroInfo *Def = nullptr;
742 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
743 Def = DefMD->getInfo();
744
745 // FIXME: Issue a warning if multiple headers for the same submodule
746 // define a macro, rather than silently ignoring all but the first.
747 bool IsNew;
Richard Smith32dbd692015-05-02 01:14:40 +0000748 // Don't bother creating a module macro if it would represent a #undef
749 // that doesn't override anything.
750 if (Def || !Macro.second.getOverriddenMacros().empty())
Richard Smithdbbc5232015-05-14 02:25:44 +0000751 addModuleMacro(LeavingMod, II, Def,
752 Macro.second.getOverriddenMacros(), IsNew);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000753 break;
754 }
755 }
Richard Smith753e0072015-04-27 23:21:38 +0000756 }
Richard Smithb8b2ed62015-04-23 18:18:26 +0000757
Richard Smith4df60932015-06-30 21:29:55 +0000758 // FIXME: Before we leave this submodule, we should parse all the other
759 // headers within it. Otherwise, we're left with an inconsistent state
760 // where we've made the module visible but don't yet have its complete
761 // contents.
762
Richard Smith04765ae2015-05-21 01:20:10 +0000763 // Put back the outer module's state, if we're tracking it.
Richard Smithee977932015-05-01 21:22:17 +0000764 if (getLangOpts().ModulesLocalVisibility)
Richard Smith04765ae2015-05-21 01:20:10 +0000765 CurSubmoduleState = Info.OuterSubmoduleState;
Richard Smithee977932015-05-01 21:22:17 +0000766
Richard Smithb8b2ed62015-04-23 18:18:26 +0000767 BuildingSubmoduleStack.pop_back();
Richard Smithdbbc5232015-05-14 02:25:44 +0000768
769 // A nested #include makes the included submodule visible.
Richard Smith4df60932015-06-30 21:29:55 +0000770 makeModuleVisible(LeavingMod, ImportLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +0000771}