150
|
1 //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
|
|
2 //
|
|
3 // 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
|
|
6 //
|
|
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"
|
|
15 #include "clang/Lex/PreprocessorOptions.h"
|
|
16 #include "clang/Basic/FileManager.h"
|
|
17 #include "clang/Basic/SourceManager.h"
|
|
18 #include "clang/Lex/HeaderSearch.h"
|
|
19 #include "clang/Lex/LexDiagnostic.h"
|
|
20 #include "clang/Lex/MacroInfo.h"
|
|
21 #include "llvm/ADT/StringSwitch.h"
|
|
22 #include "llvm/Support/FileSystem.h"
|
|
23 #include "llvm/Support/MemoryBuffer.h"
|
|
24 #include "llvm/Support/Path.h"
|
|
25 using namespace clang;
|
|
26
|
|
27 //===----------------------------------------------------------------------===//
|
|
28 // Miscellaneous Methods.
|
|
29 //===----------------------------------------------------------------------===//
|
|
30
|
|
31 /// isInPrimaryFile - Return true if we're in the top-level file, not in a
|
|
32 /// \#include. This looks through macro expansions and active _Pragma lexers.
|
|
33 bool Preprocessor::isInPrimaryFile() const {
|
|
34 if (IsFileLexer())
|
|
35 return IncludeMacroStack.empty();
|
|
36
|
|
37 // If there are any stacked lexers, we're in a #include.
|
|
38 assert(IsFileLexer(IncludeMacroStack[0]) &&
|
|
39 "Top level include stack isn't our primary lexer?");
|
|
40 return std::none_of(
|
|
41 IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
|
|
42 [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });
|
|
43 }
|
|
44
|
|
45 /// getCurrentLexer - Return the current file lexer being lexed from. Note
|
|
46 /// that this ignores any potentially active macro expansions and _Pragma
|
|
47 /// expansions going on at the time.
|
|
48 PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
|
|
49 if (IsFileLexer())
|
|
50 return CurPPLexer;
|
|
51
|
|
52 // Look for a stacked lexer.
|
|
53 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
|
|
54 if (IsFileLexer(ISI))
|
|
55 return ISI.ThePPLexer;
|
|
56 }
|
|
57 return nullptr;
|
|
58 }
|
|
59
|
|
60
|
|
61 //===----------------------------------------------------------------------===//
|
|
62 // Methods for Entering and Callbacks for leaving various contexts
|
|
63 //===----------------------------------------------------------------------===//
|
|
64
|
|
65 /// EnterSourceFile - Add a source file to the top of the include stack and
|
|
66 /// start lexing tokens from it instead of the current buffer.
|
|
67 bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
|
|
68 SourceLocation Loc) {
|
|
69 assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
|
|
70 ++NumEnteredSourceFiles;
|
|
71
|
|
72 if (MaxIncludeStackDepth < IncludeMacroStack.size())
|
|
73 MaxIncludeStackDepth = IncludeMacroStack.size();
|
|
74
|
|
75 // Get the MemoryBuffer for this FID, if it fails, we fail.
|
|
76 bool Invalid = false;
|
|
77 const llvm::MemoryBuffer *InputFile =
|
|
78 getSourceManager().getBuffer(FID, Loc, &Invalid);
|
|
79 if (Invalid) {
|
|
80 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
|
|
81 Diag(Loc, diag::err_pp_error_opening_file)
|
|
82 << std::string(SourceMgr.getBufferName(FileStart)) << "";
|
|
83 return true;
|
|
84 }
|
|
85
|
|
86 if (isCodeCompletionEnabled() &&
|
|
87 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
|
|
88 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
|
|
89 CodeCompletionLoc =
|
|
90 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
|
|
91 }
|
|
92
|
|
93 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
|
|
94 return false;
|
|
95 }
|
|
96
|
|
97 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
|
|
98 /// and start lexing tokens from it instead of the current buffer.
|
|
99 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
|
|
100 const DirectoryLookup *CurDir) {
|
|
101
|
|
102 // Add the current lexer to the include stack.
|
|
103 if (CurPPLexer || CurTokenLexer)
|
|
104 PushIncludeMacroStack();
|
|
105
|
|
106 CurLexer.reset(TheLexer);
|
|
107 CurPPLexer = TheLexer;
|
|
108 CurDirLookup = CurDir;
|
|
109 CurLexerSubmodule = nullptr;
|
|
110 if (CurLexerKind != CLK_LexAfterModuleImport)
|
|
111 CurLexerKind = CLK_Lexer;
|
|
112
|
|
113 // Notify the client, if desired, that we are in a new source file.
|
|
114 if (Callbacks && !CurLexer->Is_PragmaLexer) {
|
|
115 SrcMgr::CharacteristicKind FileType =
|
|
116 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
|
|
117
|
|
118 Callbacks->FileChanged(CurLexer->getFileLoc(),
|
|
119 PPCallbacks::EnterFile, FileType);
|
|
120 }
|
|
121 }
|
|
122
|
|
123 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
|
|
124 /// tokens from it instead of the current buffer.
|
|
125 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
|
|
126 MacroInfo *Macro, MacroArgs *Args) {
|
|
127 std::unique_ptr<TokenLexer> TokLexer;
|
|
128 if (NumCachedTokenLexers == 0) {
|
|
129 TokLexer = std::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
|
|
130 } else {
|
|
131 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
|
|
132 TokLexer->Init(Tok, ILEnd, Macro, Args);
|
|
133 }
|
|
134
|
|
135 PushIncludeMacroStack();
|
|
136 CurDirLookup = nullptr;
|
|
137 CurTokenLexer = std::move(TokLexer);
|
|
138 if (CurLexerKind != CLK_LexAfterModuleImport)
|
|
139 CurLexerKind = CLK_TokenLexer;
|
|
140 }
|
|
141
|
|
142 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
|
|
143 /// which will cause the lexer to start returning the specified tokens.
|
|
144 ///
|
|
145 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
|
|
146 /// not be subject to further macro expansion. Otherwise, these tokens will
|
|
147 /// be re-macro-expanded when/if expansion is enabled.
|
|
148 ///
|
|
149 /// If OwnsTokens is false, this method assumes that the specified stream of
|
|
150 /// tokens has a permanent owner somewhere, so they do not need to be copied.
|
|
151 /// If it is true, it assumes the array of tokens is allocated with new[] and
|
|
152 /// must be freed.
|
|
153 ///
|
|
154 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
|
|
155 bool DisableMacroExpansion, bool OwnsTokens,
|
|
156 bool IsReinject) {
|
|
157 if (CurLexerKind == CLK_CachingLexer) {
|
|
158 if (CachedLexPos < CachedTokens.size()) {
|
|
159 assert(IsReinject && "new tokens in the middle of cached stream");
|
|
160 // We're entering tokens into the middle of our cached token stream. We
|
|
161 // can't represent that, so just insert the tokens into the buffer.
|
|
162 CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
|
|
163 Toks, Toks + NumToks);
|
|
164 if (OwnsTokens)
|
|
165 delete [] Toks;
|
|
166 return;
|
|
167 }
|
|
168
|
|
169 // New tokens are at the end of the cached token sequnece; insert the
|
|
170 // token stream underneath the caching lexer.
|
|
171 ExitCachingLexMode();
|
|
172 EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
|
|
173 IsReinject);
|
|
174 EnterCachingLexMode();
|
|
175 return;
|
|
176 }
|
|
177
|
|
178 // Create a macro expander to expand from the specified token stream.
|
|
179 std::unique_ptr<TokenLexer> TokLexer;
|
|
180 if (NumCachedTokenLexers == 0) {
|
|
181 TokLexer = std::make_unique<TokenLexer>(
|
|
182 Toks, NumToks, DisableMacroExpansion, OwnsTokens, IsReinject, *this);
|
|
183 } else {
|
|
184 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
|
|
185 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
|
|
186 IsReinject);
|
|
187 }
|
|
188
|
|
189 // Save our current state.
|
|
190 PushIncludeMacroStack();
|
|
191 CurDirLookup = nullptr;
|
|
192 CurTokenLexer = std::move(TokLexer);
|
|
193 if (CurLexerKind != CLK_LexAfterModuleImport)
|
|
194 CurLexerKind = CLK_TokenLexer;
|
|
195 }
|
|
196
|
|
197 /// Compute the relative path that names the given file relative to
|
|
198 /// the given directory.
|
|
199 static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
|
|
200 const FileEntry *File,
|
|
201 SmallString<128> &Result) {
|
|
202 Result.clear();
|
|
203
|
|
204 StringRef FilePath = File->getDir()->getName();
|
|
205 StringRef Path = FilePath;
|
|
206 while (!Path.empty()) {
|
|
207 if (auto CurDir = FM.getDirectory(Path)) {
|
|
208 if (*CurDir == Dir) {
|
|
209 Result = FilePath.substr(Path.size());
|
|
210 llvm::sys::path::append(Result,
|
|
211 llvm::sys::path::filename(File->getName()));
|
|
212 return;
|
|
213 }
|
|
214 }
|
|
215
|
|
216 Path = llvm::sys::path::parent_path(Path);
|
|
217 }
|
|
218
|
|
219 Result = File->getName();
|
|
220 }
|
|
221
|
|
222 void 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
|
|
235 /// Determine the location to use as the end of the buffer for a lexer.
|
|
236 ///
|
|
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.
|
|
241 const 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
|
|
257 static 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
|
|
265 void 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;
|
|
274 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
|
|
275 std::error_code EC;
|
|
276 for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
|
|
277 End;
|
|
278 Entry != End && !EC; Entry.increment(EC)) {
|
|
279 using llvm::StringSwitch;
|
|
280
|
|
281 // Check whether this entry has an extension typically associated with
|
|
282 // headers.
|
|
283 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
|
|
284 .Cases(".h", ".H", ".hh", ".hpp", true)
|
|
285 .Default(false))
|
|
286 continue;
|
|
287
|
|
288 if (auto Header = getFileManager().getFile(Entry->path()))
|
|
289 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 }
|
|
300
|
|
301 /// 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.
|
|
304 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
|
|
305 assert(!CurTokenLexer &&
|
|
306 "Ending a file when currently in a macro!");
|
|
307
|
|
308 // If we have an unclosed module region from a pragma at the end of a
|
|
309 // module, complain and close it now.
|
|
310 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
|
|
327 // See if this file had a controlling macro.
|
|
328 if (CurPPLexer) { // Not ending a macro, ignore it.
|
|
329 if (const IdentifierInfo *ControllingMacro =
|
|
330 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
|
|
331 // Okay, this has a controlling macro, remember in HeaderFileInfo.
|
|
332 if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
|
|
333 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
|
|
334 if (MacroInfo *MI =
|
|
335 getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
|
|
336 MI->setUsedForHeaderGuard(true);
|
|
337 if (const IdentifierInfo *DefinedMacro =
|
|
338 CurPPLexer->MIOpt.GetDefinedMacro()) {
|
|
339 if (!isMacroDefined(ControllingMacro) &&
|
|
340 DefinedMacro != ControllingMacro &&
|
|
341 HeaderInfo.FirstTimeLexingFile(FE)) {
|
|
342
|
|
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 }
|
|
368 }
|
|
369 }
|
|
370 }
|
|
371 }
|
|
372 }
|
|
373
|
|
374 // 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 (PragmaARCCFCodeAuditedInfo.second.isValid() && !isEndOfMacro &&
|
|
378 !(CurLexer && CurLexer->Is_PragmaLexer)) {
|
|
379 Diag(PragmaARCCFCodeAuditedInfo.second,
|
|
380 diag::err_pp_eof_in_arc_cf_code_audited);
|
|
381
|
|
382 // Recover by leaving immediately.
|
|
383 PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
|
|
384 }
|
|
385
|
|
386 // Complain about reaching a true EOF within assume_nonnull.
|
|
387 // We don't want to complain about reaching the end of a macro
|
|
388 // instantiation or a _Pragma.
|
|
389 if (PragmaAssumeNonNullLoc.isValid() &&
|
|
390 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
|
|
391 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
|
|
392
|
|
393 // Recover by leaving immediately.
|
|
394 PragmaAssumeNonNullLoc = SourceLocation();
|
|
395 }
|
|
396
|
|
397 bool LeavingPCHThroughHeader = false;
|
|
398
|
|
399 // If this is a #include'd file, pop it off the include stack and continue
|
|
400 // lexing the #includer file.
|
|
401 if (!IncludeMacroStack.empty()) {
|
|
402
|
|
403 // If we lexed the code-completion file, act as if we reached EOF.
|
|
404 if (isCodeCompletionEnabled() && CurPPLexer &&
|
|
405 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
|
|
406 CodeCompletionFileLoc) {
|
|
407 assert(CurLexer && "Got EOF but no current lexer set!");
|
|
408 Result.startToken();
|
|
409 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
|
|
410 CurLexer.reset();
|
|
411
|
|
412 CurPPLexer = nullptr;
|
|
413 recomputeCurLexerKind();
|
|
414 return true;
|
|
415 }
|
|
416
|
|
417 if (!isEndOfMacro && CurPPLexer &&
|
173
|
418 (SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid() ||
|
|
419 // Predefines file doesn't have a valid include location.
|
|
420 (PredefinesFileID.isValid() &&
|
|
421 CurPPLexer->getFileID() == PredefinesFileID))) {
|
150
|
422 // Notify SourceManager to record the number of FileIDs that were created
|
|
423 // during lexing of the #include'd file.
|
|
424 unsigned NumFIDs =
|
|
425 SourceMgr.local_sloc_entry_size() -
|
|
426 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
|
|
427 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
|
|
428 }
|
|
429
|
|
430 bool ExitedFromPredefinesFile = false;
|
|
431 FileID ExitedFID;
|
|
432 if (!isEndOfMacro && CurPPLexer) {
|
|
433 ExitedFID = CurPPLexer->getFileID();
|
|
434
|
|
435 assert(PredefinesFileID.isValid() &&
|
|
436 "HandleEndOfFile is called before PredefinesFileId is set");
|
|
437 ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
|
|
438 }
|
|
439
|
|
440 if (LeavingSubmodule) {
|
|
441 // We're done with this submodule.
|
|
442 Module *M = LeaveSubmodule(/*ForPragma*/false);
|
|
443
|
|
444 // Notify the parser that we've left the module.
|
|
445 const char *EndPos = getCurLexerEndPos();
|
|
446 Result.startToken();
|
|
447 CurLexer->BufferPtr = EndPos;
|
|
448 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
|
|
449 Result.setAnnotationEndLoc(Result.getLocation());
|
|
450 Result.setAnnotationValue(M);
|
|
451 }
|
|
452
|
|
453 bool FoundPCHThroughHeader = false;
|
|
454 if (CurPPLexer && creatingPCHWithThroughHeader() &&
|
|
455 isPCHThroughHeader(
|
|
456 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
|
|
457 FoundPCHThroughHeader = true;
|
|
458
|
|
459 // We're done with the #included file.
|
|
460 RemoveTopOfLexerStack();
|
|
461
|
|
462 // Propagate info about start-of-line/leading white-space/etc.
|
|
463 PropagateLineStartLeadingSpaceInfo(Result);
|
|
464
|
|
465 // Notify the client, if desired, that we are in a new source file.
|
|
466 if (Callbacks && !isEndOfMacro && CurPPLexer) {
|
|
467 SrcMgr::CharacteristicKind FileType =
|
|
468 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
|
|
469 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
|
|
470 PPCallbacks::ExitFile, FileType, ExitedFID);
|
|
471 }
|
|
472
|
152
|
473 #ifndef noCbC
|
200
|
474 if (SavedTokenFlag && IncludeMacroStack.size() == SavedDepth){ // dead code?
|
152
|
475 Result = SavedToken;
|
|
476 SavedTokenFlag = false;
|
200
|
477 if (CurLexer->ParsingPreprocessorDirective) {
|
|
478 // Done parsing the "line".
|
|
479 CurLexer->ParsingPreprocessorDirective = false;
|
152
|
480
|
200
|
481 // Restore comment saving mode, in case it was disabled for directive.
|
|
482 CurLexer->resetExtendedTokenMode();
|
152
|
483
|
200
|
484 // Since we consumed a newline, we are back at the start of a line.
|
|
485 CurLexer->IsAtStartOfLine = true;
|
|
486 CurLexer->IsAtPhysicalStartOfLine = true;
|
|
487 }
|
152
|
488 return true;
|
|
489 }
|
|
490 #endif
|
|
491
|
150
|
492 // Restore conditional stack from the preamble right after exiting from the
|
|
493 // predefines file.
|
|
494 if (ExitedFromPredefinesFile)
|
|
495 replayPreambleConditionalStack();
|
|
496
|
|
497 if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
|
|
498 (isInPrimaryFile() ||
|
|
499 CurPPLexer->getFileID() == getPredefinesFileID())) {
|
|
500 // Leaving the through header. Continue directly to end of main file
|
|
501 // processing.
|
|
502 LeavingPCHThroughHeader = true;
|
|
503 } else {
|
|
504 // Client should lex another token unless we generated an EOM.
|
|
505 return LeavingSubmodule;
|
|
506 }
|
|
507 }
|
|
508
|
|
509 // If this is the end of the main file, form an EOF token.
|
|
510 assert(CurLexer && "Got EOF but no current lexer set!");
|
|
511 const char *EndPos = getCurLexerEndPos();
|
|
512 Result.startToken();
|
|
513 CurLexer->BufferPtr = EndPos;
|
|
514 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
|
|
515
|
|
516 if (isCodeCompletionEnabled()) {
|
|
517 // Inserting the code-completion point increases the source buffer by 1,
|
|
518 // but the main FileID was created before inserting the point.
|
|
519 // Compensate by reducing the EOF location by 1, otherwise the location
|
|
520 // will point to the next FileID.
|
|
521 // FIXME: This is hacky, the code-completion point should probably be
|
|
522 // inserted before the main FileID is created.
|
|
523 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
|
|
524 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
|
|
525 }
|
|
526
|
|
527 if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
|
|
528 // Reached the end of the compilation without finding the through header.
|
|
529 Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
|
|
530 << PPOpts->PCHThroughHeader << 0;
|
|
531 }
|
|
532
|
|
533 if (!isIncrementalProcessingEnabled())
|
|
534 // We're done with lexing.
|
|
535 CurLexer.reset();
|
|
536
|
|
537 if (!isIncrementalProcessingEnabled())
|
|
538 CurPPLexer = nullptr;
|
|
539
|
|
540 if (TUKind == TU_Complete) {
|
|
541 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
|
|
542 // collected all macro locations that we need to warn because they are not
|
|
543 // used.
|
|
544 for (WarnUnusedMacroLocsTy::iterator
|
|
545 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
|
|
546 I!=E; ++I)
|
|
547 Diag(*I, diag::pp_macro_not_used);
|
|
548 }
|
|
549
|
|
550 // If we are building a module that has an umbrella header, make sure that
|
|
551 // each of the headers within the directory, including all submodules, is
|
|
552 // covered by the umbrella header was actually included by the umbrella
|
|
553 // header.
|
|
554 if (Module *Mod = getCurrentModule()) {
|
|
555 llvm::SmallVector<const Module *, 4> AllMods;
|
|
556 collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
|
|
557 for (auto *M : AllMods)
|
|
558 diagnoseMissingHeaderInUmbrellaDir(*M);
|
|
559 }
|
|
560
|
|
561 return true;
|
|
562 }
|
|
563
|
|
564 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
|
|
565 /// hits the end of its token stream.
|
|
566 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
|
|
567 assert(CurTokenLexer && !CurPPLexer &&
|
|
568 "Ending a macro when currently in a #include file!");
|
|
569
|
|
570 if (!MacroExpandingLexersStack.empty() &&
|
|
571 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
|
|
572 removeCachedMacroExpandedTokensOfLastLexer();
|
|
573
|
|
574 // Delete or cache the now-dead macro expander.
|
|
575 if (NumCachedTokenLexers == TokenLexerCacheSize)
|
|
576 CurTokenLexer.reset();
|
|
577 else
|
|
578 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
|
|
579
|
|
580 // Handle this like a #include file being popped off the stack.
|
|
581 return HandleEndOfFile(Result, true);
|
|
582 }
|
|
583
|
|
584 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
|
|
585 /// lexer stack. This should only be used in situations where the current
|
|
586 /// state of the top-of-stack lexer is unknown.
|
|
587 void Preprocessor::RemoveTopOfLexerStack() {
|
|
588 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
|
|
589
|
|
590 if (CurTokenLexer) {
|
|
591 // Delete or cache the now-dead macro expander.
|
|
592 if (NumCachedTokenLexers == TokenLexerCacheSize)
|
|
593 CurTokenLexer.reset();
|
|
594 else
|
|
595 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
|
|
596 }
|
|
597
|
|
598 PopIncludeMacroStack();
|
|
599 }
|
|
600
|
|
601 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
|
|
602 /// comment (/##/) in microsoft mode, this method handles updating the current
|
|
603 /// state, returning the token on the next source line.
|
|
604 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
|
|
605 assert(CurTokenLexer && !CurPPLexer &&
|
|
606 "Pasted comment can only be formed from macro");
|
|
607 // We handle this by scanning for the closest real lexer, switching it to
|
|
608 // raw mode and preprocessor mode. This will cause it to return \n as an
|
|
609 // explicit EOD token.
|
|
610 PreprocessorLexer *FoundLexer = nullptr;
|
|
611 bool LexerWasInPPMode = false;
|
|
612 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
|
|
613 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
|
|
614
|
|
615 // Once we find a real lexer, mark it as raw mode (disabling macro
|
|
616 // expansions) and preprocessor mode (return EOD). We know that the lexer
|
|
617 // was *not* in raw mode before, because the macro that the comment came
|
|
618 // from was expanded. However, it could have already been in preprocessor
|
|
619 // mode (#if COMMENT) in which case we have to return it to that mode and
|
|
620 // return EOD.
|
|
621 FoundLexer = ISI.ThePPLexer;
|
|
622 FoundLexer->LexingRawMode = true;
|
|
623 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
|
|
624 FoundLexer->ParsingPreprocessorDirective = true;
|
|
625 break;
|
|
626 }
|
|
627
|
|
628 // Okay, we either found and switched over the lexer, or we didn't find a
|
|
629 // lexer. In either case, finish off the macro the comment came from, getting
|
|
630 // the next token.
|
|
631 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
|
|
632
|
|
633 // Discarding comments as long as we don't have EOF or EOD. This 'comments
|
|
634 // out' the rest of the line, including any tokens that came from other macros
|
|
635 // that were active, as in:
|
|
636 // #define submacro a COMMENT b
|
|
637 // submacro c
|
|
638 // which should lex to 'a' only: 'b' and 'c' should be removed.
|
|
639 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
|
|
640 Lex(Tok);
|
|
641
|
|
642 // If we got an eod token, then we successfully found the end of the line.
|
|
643 if (Tok.is(tok::eod)) {
|
|
644 assert(FoundLexer && "Can't get end of line without an active lexer");
|
|
645 // Restore the lexer back to normal mode instead of raw mode.
|
|
646 FoundLexer->LexingRawMode = false;
|
|
647
|
|
648 // If the lexer was already in preprocessor mode, just return the EOD token
|
|
649 // to finish the preprocessor line.
|
|
650 if (LexerWasInPPMode) return;
|
|
651
|
|
652 // Otherwise, switch out of PP mode and return the next lexed token.
|
|
653 FoundLexer->ParsingPreprocessorDirective = false;
|
|
654 return Lex(Tok);
|
|
655 }
|
|
656
|
|
657 // If we got an EOF token, then we reached the end of the token stream but
|
|
658 // didn't find an explicit \n. This can only happen if there was no lexer
|
|
659 // active (an active lexer would return EOD at EOF if there was no \n in
|
|
660 // preprocessor directive mode), so just return EOF as our token.
|
|
661 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
|
|
662 }
|
|
663
|
|
664 void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
|
|
665 bool ForPragma) {
|
|
666 if (!getLangOpts().ModulesLocalVisibility) {
|
|
667 // Just track that we entered this submodule.
|
|
668 BuildingSubmoduleStack.push_back(
|
|
669 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
|
|
670 PendingModuleMacroNames.size()));
|
|
671 if (Callbacks)
|
|
672 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
|
|
673 return;
|
|
674 }
|
|
675
|
|
676 // Resolve as much of the module definition as we can now, before we enter
|
|
677 // one of its headers.
|
|
678 // FIXME: Can we enable Complain here?
|
|
679 // FIXME: Can we do this when local visibility is disabled?
|
|
680 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
|
|
681 ModMap.resolveExports(M, /*Complain=*/false);
|
|
682 ModMap.resolveUses(M, /*Complain=*/false);
|
|
683 ModMap.resolveConflicts(M, /*Complain=*/false);
|
|
684
|
|
685 // If this is the first time we've entered this module, set up its state.
|
|
686 auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
|
|
687 auto &State = R.first->second;
|
|
688 bool FirstTime = R.second;
|
|
689 if (FirstTime) {
|
|
690 // Determine the set of starting macros for this submodule; take these
|
|
691 // from the "null" module (the predefines buffer).
|
|
692 //
|
|
693 // FIXME: If we have local visibility but not modules enabled, the
|
|
694 // NullSubmoduleState is polluted by #defines in the top-level source
|
|
695 // file.
|
|
696 auto &StartingMacros = NullSubmoduleState.Macros;
|
|
697
|
|
698 // Restore to the starting state.
|
|
699 // FIXME: Do this lazily, when each macro name is first referenced.
|
|
700 for (auto &Macro : StartingMacros) {
|
|
701 // Skip uninteresting macros.
|
|
702 if (!Macro.second.getLatest() &&
|
|
703 Macro.second.getOverriddenMacros().empty())
|
|
704 continue;
|
|
705
|
|
706 MacroState MS(Macro.second.getLatest());
|
|
707 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
|
|
708 State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
|
|
709 }
|
|
710 }
|
|
711
|
|
712 // Track that we entered this module.
|
|
713 BuildingSubmoduleStack.push_back(
|
|
714 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
|
|
715 PendingModuleMacroNames.size()));
|
|
716
|
|
717 if (Callbacks)
|
|
718 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
|
|
719
|
|
720 // Switch to this submodule as the current submodule.
|
|
721 CurSubmoduleState = &State;
|
|
722
|
|
723 // This module is visible to itself.
|
|
724 if (FirstTime)
|
|
725 makeModuleVisible(M, ImportLoc);
|
|
726 }
|
|
727
|
|
728 bool Preprocessor::needModuleMacros() const {
|
|
729 // If we're not within a submodule, we never need to create ModuleMacros.
|
|
730 if (BuildingSubmoduleStack.empty())
|
|
731 return false;
|
|
732 // If we are tracking module macro visibility even for textually-included
|
|
733 // headers, we need ModuleMacros.
|
|
734 if (getLangOpts().ModulesLocalVisibility)
|
|
735 return true;
|
|
736 // Otherwise, we only need module macros if we're actually compiling a module
|
|
737 // interface.
|
|
738 return getLangOpts().isCompilingModule();
|
|
739 }
|
|
740
|
|
741 Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
|
|
742 if (BuildingSubmoduleStack.empty() ||
|
|
743 BuildingSubmoduleStack.back().IsPragma != ForPragma) {
|
|
744 assert(ForPragma && "non-pragma module enter/leave mismatch");
|
|
745 return nullptr;
|
|
746 }
|
|
747
|
|
748 auto &Info = BuildingSubmoduleStack.back();
|
|
749
|
|
750 Module *LeavingMod = Info.M;
|
|
751 SourceLocation ImportLoc = Info.ImportLoc;
|
|
752
|
|
753 if (!needModuleMacros() ||
|
|
754 (!getLangOpts().ModulesLocalVisibility &&
|
|
755 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
|
|
756 // If we don't need module macros, or this is not a module for which we
|
|
757 // are tracking macro visibility, don't build any, and preserve the list
|
|
758 // of pending names for the surrounding submodule.
|
|
759 BuildingSubmoduleStack.pop_back();
|
|
760
|
|
761 if (Callbacks)
|
|
762 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
|
|
763
|
|
764 makeModuleVisible(LeavingMod, ImportLoc);
|
|
765 return LeavingMod;
|
|
766 }
|
|
767
|
|
768 // Create ModuleMacros for any macros defined in this submodule.
|
|
769 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
|
|
770 for (unsigned I = Info.OuterPendingModuleMacroNames;
|
|
771 I != PendingModuleMacroNames.size(); ++I) {
|
|
772 auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
|
|
773 if (!VisitedMacros.insert(II).second)
|
|
774 continue;
|
|
775
|
|
776 auto MacroIt = CurSubmoduleState->Macros.find(II);
|
|
777 if (MacroIt == CurSubmoduleState->Macros.end())
|
|
778 continue;
|
|
779 auto &Macro = MacroIt->second;
|
|
780
|
|
781 // Find the starting point for the MacroDirective chain in this submodule.
|
|
782 MacroDirective *OldMD = nullptr;
|
|
783 auto *OldState = Info.OuterSubmoduleState;
|
|
784 if (getLangOpts().ModulesLocalVisibility)
|
|
785 OldState = &NullSubmoduleState;
|
|
786 if (OldState && OldState != CurSubmoduleState) {
|
|
787 // FIXME: It'd be better to start at the state from when we most recently
|
|
788 // entered this submodule, but it doesn't really matter.
|
|
789 auto &OldMacros = OldState->Macros;
|
|
790 auto OldMacroIt = OldMacros.find(II);
|
|
791 if (OldMacroIt == OldMacros.end())
|
|
792 OldMD = nullptr;
|
|
793 else
|
|
794 OldMD = OldMacroIt->second.getLatest();
|
|
795 }
|
|
796
|
|
797 // This module may have exported a new macro. If so, create a ModuleMacro
|
|
798 // representing that fact.
|
|
799 bool ExplicitlyPublic = false;
|
|
800 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
|
|
801 assert(MD && "broken macro directive chain");
|
|
802
|
|
803 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
|
|
804 // The latest visibility directive for a name in a submodule affects
|
|
805 // all the directives that come before it.
|
|
806 if (VisMD->isPublic())
|
|
807 ExplicitlyPublic = true;
|
|
808 else if (!ExplicitlyPublic)
|
|
809 // Private with no following public directive: not exported.
|
|
810 break;
|
|
811 } else {
|
|
812 MacroInfo *Def = nullptr;
|
|
813 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
|
|
814 Def = DefMD->getInfo();
|
|
815
|
|
816 // FIXME: Issue a warning if multiple headers for the same submodule
|
|
817 // define a macro, rather than silently ignoring all but the first.
|
|
818 bool IsNew;
|
|
819 // Don't bother creating a module macro if it would represent a #undef
|
|
820 // that doesn't override anything.
|
|
821 if (Def || !Macro.getOverriddenMacros().empty())
|
|
822 addModuleMacro(LeavingMod, II, Def,
|
|
823 Macro.getOverriddenMacros(), IsNew);
|
|
824
|
|
825 if (!getLangOpts().ModulesLocalVisibility) {
|
|
826 // This macro is exposed to the rest of this compilation as a
|
|
827 // ModuleMacro; we don't need to track its MacroDirective any more.
|
|
828 Macro.setLatest(nullptr);
|
|
829 Macro.setOverriddenMacros(*this, {});
|
|
830 }
|
|
831 break;
|
|
832 }
|
|
833 }
|
|
834 }
|
|
835 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
|
|
836
|
|
837 // FIXME: Before we leave this submodule, we should parse all the other
|
|
838 // headers within it. Otherwise, we're left with an inconsistent state
|
|
839 // where we've made the module visible but don't yet have its complete
|
|
840 // contents.
|
|
841
|
|
842 // Put back the outer module's state, if we're tracking it.
|
|
843 if (getLangOpts().ModulesLocalVisibility)
|
|
844 CurSubmoduleState = Info.OuterSubmoduleState;
|
|
845
|
|
846 BuildingSubmoduleStack.pop_back();
|
|
847
|
|
848 if (Callbacks)
|
|
849 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
|
|
850
|
|
851 // A nested #include makes the included submodule visible.
|
|
852 makeModuleVisible(LeavingMod, ImportLoc);
|
|
853 return LeavingMod;
|
|
854 }
|