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