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