Bug Summary

File:tools/clang/lib/Lex/PPLexerChange.cpp
Warning:line 604, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name PPLexerChange.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Lex -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Lex -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Lex -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Lex/PPLexerChange.cpp

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Lex/PPLexerChange.cpp

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

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h

1//===- Preprocessor.h - C Language Family Preprocessor ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// \brief Defines the clang::Preprocessor interface.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_LEX_PREPROCESSOR_H
16#define LLVM_CLANG_LEX_PREPROCESSOR_H
17
18#include "clang/Basic/Builtins.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/LLVM.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/Module.h"
24#include "clang/Basic/SourceLocation.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/TokenKinds.h"
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/MacroInfo.h"
29#include "clang/Lex/ModuleLoader.h"
30#include "clang/Lex/ModuleMap.h"
31#include "clang/Lex/PPCallbacks.h"
32#include "clang/Lex/PTHLexer.h"
33#include "clang/Lex/Token.h"
34#include "clang/Lex/TokenLexer.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/FoldingSet.h"
38#include "llvm/ADT/None.h"
39#include "llvm/ADT/Optional.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include "llvm/ADT/StringRef.h"
45#include "llvm/ADT/TinyPtrVector.h"
46#include "llvm/ADT/iterator_range.h"
47#include "llvm/Support/Allocator.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/Registry.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <memory>
54#include <map>
55#include <string>
56#include <utility>
57#include <vector>
58
59namespace llvm {
60
61template<unsigned InternalLen> class SmallString;
62
63} // namespace llvm
64
65namespace clang {
66
67class CodeCompletionHandler;
68class CommentHandler;
69class DirectoryEntry;
70class DirectoryLookup;
71class ExternalPreprocessorSource;
72class FileEntry;
73class FileManager;
74class HeaderSearch;
75class MacroArgs;
76class MemoryBufferCache;
77class PragmaHandler;
78class PragmaNamespace;
79class PreprocessingRecord;
80class PreprocessorLexer;
81class PreprocessorOptions;
82class PTHManager;
83class ScratchBuffer;
84class TargetInfo;
85
86/// \brief Stores token information for comparing actual tokens with
87/// predefined values. Only handles simple tokens and identifiers.
88class TokenValue {
89 tok::TokenKind Kind;
90 IdentifierInfo *II;
91
92public:
93 TokenValue(tok::TokenKind Kind) : Kind(Kind), II(nullptr) {
94 assert(Kind != tok::raw_identifier && "Raw identifiers are not supported.")(static_cast <bool> (Kind != tok::raw_identifier &&
"Raw identifiers are not supported.") ? void (0) : __assert_fail
("Kind != tok::raw_identifier && \"Raw identifiers are not supported.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 94, __extension__ __PRETTY_FUNCTION__))
;
95 assert(Kind != tok::identifier &&(static_cast <bool> (Kind != tok::identifier &&
"Identifiers should be created by TokenValue(IdentifierInfo *)"
) ? void (0) : __assert_fail ("Kind != tok::identifier && \"Identifiers should be created by TokenValue(IdentifierInfo *)\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 96, __extension__ __PRETTY_FUNCTION__))
96 "Identifiers should be created by TokenValue(IdentifierInfo *)")(static_cast <bool> (Kind != tok::identifier &&
"Identifiers should be created by TokenValue(IdentifierInfo *)"
) ? void (0) : __assert_fail ("Kind != tok::identifier && \"Identifiers should be created by TokenValue(IdentifierInfo *)\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 96, __extension__ __PRETTY_FUNCTION__))
;
97 assert(!tok::isLiteral(Kind) && "Literals are not supported.")(static_cast <bool> (!tok::isLiteral(Kind) && "Literals are not supported."
) ? void (0) : __assert_fail ("!tok::isLiteral(Kind) && \"Literals are not supported.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 97, __extension__ __PRETTY_FUNCTION__))
;
98 assert(!tok::isAnnotation(Kind) && "Annotations are not supported.")(static_cast <bool> (!tok::isAnnotation(Kind) &&
"Annotations are not supported.") ? void (0) : __assert_fail
("!tok::isAnnotation(Kind) && \"Annotations are not supported.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 98, __extension__ __PRETTY_FUNCTION__))
;
99 }
100
101 TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {}
102
103 bool operator==(const Token &Tok) const {
104 return Tok.getKind() == Kind &&
105 (!II || II == Tok.getIdentifierInfo());
106 }
107};
108
109/// \brief Context in which macro name is used.
110enum MacroUse {
111 // other than #define or #undef
112 MU_Other = 0,
113
114 // macro name specified in #define
115 MU_Define = 1,
116
117 // macro name specified in #undef
118 MU_Undef = 2
119};
120
121/// \brief Engages in a tight little dance with the lexer to efficiently
122/// preprocess tokens.
123///
124/// Lexers know only about tokens within a single source file, and don't
125/// know anything about preprocessor-level issues like the \#include stack,
126/// token expansion, etc.
127class Preprocessor {
128 friend class VAOptDefinitionContext;
129 friend class VariadicMacroScopeGuard;
130
131 std::shared_ptr<PreprocessorOptions> PPOpts;
132 DiagnosticsEngine *Diags;
133 LangOptions &LangOpts;
134 const TargetInfo *Target = nullptr;
135 const TargetInfo *AuxTarget = nullptr;
136 FileManager &FileMgr;
137 SourceManager &SourceMgr;
138 MemoryBufferCache &PCMCache;
139 std::unique_ptr<ScratchBuffer> ScratchBuf;
140 HeaderSearch &HeaderInfo;
141 ModuleLoader &TheModuleLoader;
142
143 /// \brief External source of macros.
144 ExternalPreprocessorSource *ExternalSource;
145
146 /// An optional PTHManager object used for getting tokens from
147 /// a token cache rather than lexing the original source file.
148 std::unique_ptr<PTHManager> PTH;
149
150 /// A BumpPtrAllocator object used to quickly allocate and release
151 /// objects internal to the Preprocessor.
152 llvm::BumpPtrAllocator BP;
153
154 /// Identifiers for builtin macros and other builtins.
155 IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__
156 IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__
157 IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__
158 IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__
159 IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__
160 IdentifierInfo *Ident__COUNTER__; // __COUNTER__
161 IdentifierInfo *Ident_Pragma, *Ident__pragma; // _Pragma, __pragma
162 IdentifierInfo *Ident__identifier; // __identifier
163 IdentifierInfo *Ident__VA_ARGS__; // __VA_ARGS__
164 IdentifierInfo *Ident__VA_OPT__; // __VA_OPT__
165 IdentifierInfo *Ident__has_feature; // __has_feature
166 IdentifierInfo *Ident__has_extension; // __has_extension
167 IdentifierInfo *Ident__has_builtin; // __has_builtin
168 IdentifierInfo *Ident__has_attribute; // __has_attribute
169 IdentifierInfo *Ident__has_include; // __has_include
170 IdentifierInfo *Ident__has_include_next; // __has_include_next
171 IdentifierInfo *Ident__has_warning; // __has_warning
172 IdentifierInfo *Ident__is_identifier; // __is_identifier
173 IdentifierInfo *Ident__building_module; // __building_module
174 IdentifierInfo *Ident__MODULE__; // __MODULE__
175 IdentifierInfo *Ident__has_cpp_attribute; // __has_cpp_attribute
176 IdentifierInfo *Ident__has_c_attribute; // __has_c_attribute
177 IdentifierInfo *Ident__has_declspec; // __has_declspec_attribute
178 IdentifierInfo *Ident__is_target_arch; // __is_target_arch
179 IdentifierInfo *Ident__is_target_vendor; // __is_target_vendor
180 IdentifierInfo *Ident__is_target_os; // __is_target_os
181 IdentifierInfo *Ident__is_target_environment; // __is_target_environment
182
183 SourceLocation DATELoc, TIMELoc;
184
185 // Next __COUNTER__ value, starts at 0.
186 unsigned CounterValue = 0;
187
188 enum {
189 /// \brief Maximum depth of \#includes.
190 MaxAllowedIncludeStackDepth = 200
191 };
192
193 // State that is set before the preprocessor begins.
194 bool KeepComments : 1;
195 bool KeepMacroComments : 1;
196 bool SuppressIncludeNotFoundError : 1;
197
198 // State that changes while the preprocessor runs:
199 bool InMacroArgs : 1; // True if parsing fn macro invocation args.
200
201 /// Whether the preprocessor owns the header search object.
202 bool OwnsHeaderSearch : 1;
203
204 /// True if macro expansion is disabled.
205 bool DisableMacroExpansion : 1;
206
207 /// Temporarily disables DisableMacroExpansion (i.e. enables expansion)
208 /// when parsing preprocessor directives.
209 bool MacroExpansionInDirectivesOverride : 1;
210
211 class ResetMacroExpansionHelper;
212
213 /// \brief Whether we have already loaded macros from the external source.
214 mutable bool ReadMacrosFromExternalSource : 1;
215
216 /// \brief True if pragmas are enabled.
217 bool PragmasEnabled : 1;
218
219 /// \brief True if the current build action is a preprocessing action.
220 bool PreprocessedOutput : 1;
221
222 /// \brief True if we are currently preprocessing a #if or #elif directive
223 bool ParsingIfOrElifDirective;
224
225 /// \brief True if we are pre-expanding macro arguments.
226 bool InMacroArgPreExpansion;
227
228 /// \brief Mapping/lookup information for all identifiers in
229 /// the program, including program keywords.
230 mutable IdentifierTable Identifiers;
231
232 /// \brief This table contains all the selectors in the program.
233 ///
234 /// Unlike IdentifierTable above, this table *isn't* populated by the
235 /// preprocessor. It is declared/expanded here because its role/lifetime is
236 /// conceptually similar to the IdentifierTable. In addition, the current
237 /// control flow (in clang::ParseAST()), make it convenient to put here.
238 ///
239 /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to
240 /// the lifetime of the preprocessor.
241 SelectorTable Selectors;
242
243 /// \brief Information about builtins.
244 Builtin::Context BuiltinInfo;
245
246 /// \brief Tracks all of the pragmas that the client registered
247 /// with this preprocessor.
248 std::unique_ptr<PragmaNamespace> PragmaHandlers;
249
250 /// \brief Pragma handlers of the original source is stored here during the
251 /// parsing of a model file.
252 std::unique_ptr<PragmaNamespace> PragmaHandlersBackup;
253
254 /// \brief Tracks all of the comment handlers that the client registered
255 /// with this preprocessor.
256 std::vector<CommentHandler *> CommentHandlers;
257
258 /// \brief True if we want to ignore EOF token and continue later on (thus
259 /// avoid tearing the Lexer and etc. down).
260 bool IncrementalProcessing = false;
261
262 /// The kind of translation unit we are processing.
263 TranslationUnitKind TUKind;
264
265 /// \brief The code-completion handler.
266 CodeCompletionHandler *CodeComplete = nullptr;
267
268 /// \brief The file that we're performing code-completion for, if any.
269 const FileEntry *CodeCompletionFile = nullptr;
270
271 /// \brief The offset in file for the code-completion point.
272 unsigned CodeCompletionOffset = 0;
273
274 /// \brief The location for the code-completion point. This gets instantiated
275 /// when the CodeCompletionFile gets \#include'ed for preprocessing.
276 SourceLocation CodeCompletionLoc;
277
278 /// \brief The start location for the file of the code-completion point.
279 ///
280 /// This gets instantiated when the CodeCompletionFile gets \#include'ed
281 /// for preprocessing.
282 SourceLocation CodeCompletionFileLoc;
283
284 /// \brief The source location of the \c import contextual keyword we just
285 /// lexed, if any.
286 SourceLocation ModuleImportLoc;
287
288 /// \brief The module import path that we're currently processing.
289 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> ModuleImportPath;
290
291 /// \brief Whether the last token we lexed was an '@'.
292 bool LastTokenWasAt = false;
293
294 /// \brief Whether the module import expects an identifier next. Otherwise,
295 /// it expects a '.' or ';'.
296 bool ModuleImportExpectsIdentifier = false;
297
298 /// \brief The source location of the currently-active
299 /// \#pragma clang arc_cf_code_audited begin.
300 SourceLocation PragmaARCCFCodeAuditedLoc;
301
302 /// \brief The source location of the currently-active
303 /// \#pragma clang assume_nonnull begin.
304 SourceLocation PragmaAssumeNonNullLoc;
305
306 /// \brief True if we hit the code-completion point.
307 bool CodeCompletionReached = false;
308
309 /// \brief The code completion token containing the information
310 /// on the stem that is to be code completed.
311 IdentifierInfo *CodeCompletionII = nullptr;
312
313 /// \brief The directory that the main file should be considered to occupy,
314 /// if it does not correspond to a real file (as happens when building a
315 /// module).
316 const DirectoryEntry *MainFileDir = nullptr;
317
318 /// \brief The number of bytes that we will initially skip when entering the
319 /// main file, along with a flag that indicates whether skipping this number
320 /// of bytes will place the lexer at the start of a line.
321 ///
322 /// This is used when loading a precompiled preamble.
323 std::pair<int, bool> SkipMainFilePreamble;
324
325public:
326 struct PreambleSkipInfo {
327 SourceLocation HashTokenLoc;
328 SourceLocation IfTokenLoc;
329 bool FoundNonSkipPortion;
330 bool FoundElse;
331 SourceLocation ElseLoc;
332
333 PreambleSkipInfo(SourceLocation HashTokenLoc, SourceLocation IfTokenLoc,
334 bool FoundNonSkipPortion, bool FoundElse,
335 SourceLocation ElseLoc)
336 : HashTokenLoc(HashTokenLoc), IfTokenLoc(IfTokenLoc),
337 FoundNonSkipPortion(FoundNonSkipPortion), FoundElse(FoundElse),
338 ElseLoc(ElseLoc) {}
339 };
340
341private:
342 friend class ASTReader;
343 friend class MacroArgs;
344
345 class PreambleConditionalStackStore {
346 enum State {
347 Off = 0,
348 Recording = 1,
349 Replaying = 2,
350 };
351
352 public:
353 PreambleConditionalStackStore() = default;
354
355 void startRecording() { ConditionalStackState = Recording; }
356 void startReplaying() { ConditionalStackState = Replaying; }
357 bool isRecording() const { return ConditionalStackState == Recording; }
358 bool isReplaying() const { return ConditionalStackState == Replaying; }
359
360 ArrayRef<PPConditionalInfo> getStack() const {
361 return ConditionalStack;
362 }
363
364 void doneReplaying() {
365 ConditionalStack.clear();
366 ConditionalStackState = Off;
367 }
368
369 void setStack(ArrayRef<PPConditionalInfo> s) {
370 if (!isRecording() && !isReplaying())
371 return;
372 ConditionalStack.clear();
373 ConditionalStack.append(s.begin(), s.end());
374 }
375
376 bool hasRecordedPreamble() const { return !ConditionalStack.empty(); }
377
378 bool reachedEOFWhileSkipping() const { return SkipInfo.hasValue(); }
379
380 void clearSkipInfo() { SkipInfo.reset(); }
381
382 llvm::Optional<PreambleSkipInfo> SkipInfo;
383
384 private:
385 SmallVector<PPConditionalInfo, 4> ConditionalStack;
386 State ConditionalStackState = Off;
387 } PreambleConditionalStack;
388
389 /// \brief The current top of the stack that we're lexing from if
390 /// not expanding a macro and we are lexing directly from source code.
391 ///
392 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
393 std::unique_ptr<Lexer> CurLexer;
394
395 /// \brief The current top of stack that we're lexing from if
396 /// not expanding from a macro and we are lexing from a PTH cache.
397 ///
398 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
399 std::unique_ptr<PTHLexer> CurPTHLexer;
400
401 /// \brief The current top of the stack what we're lexing from
402 /// if not expanding a macro.
403 ///
404 /// This is an alias for either CurLexer or CurPTHLexer.
405 PreprocessorLexer *CurPPLexer = nullptr;
406
407 /// \brief Used to find the current FileEntry, if CurLexer is non-null
408 /// and if applicable.
409 ///
410 /// This allows us to implement \#include_next and find directory-specific
411 /// properties.
412 const DirectoryLookup *CurDirLookup = nullptr;
413
414 /// \brief The current macro we are expanding, if we are expanding a macro.
415 ///
416 /// One of CurLexer and CurTokenLexer must be null.
417 std::unique_ptr<TokenLexer> CurTokenLexer;
418
419 /// \brief The kind of lexer we're currently working with.
420 enum CurLexerKind {
421 CLK_Lexer,
422 CLK_PTHLexer,
423 CLK_TokenLexer,
424 CLK_CachingLexer,
425 CLK_LexAfterModuleImport
426 } CurLexerKind = CLK_Lexer;
427
428 /// \brief If the current lexer is for a submodule that is being built, this
429 /// is that submodule.
430 Module *CurLexerSubmodule = nullptr;
431
432 /// \brief Keeps track of the stack of files currently
433 /// \#included, and macros currently being expanded from, not counting
434 /// CurLexer/CurTokenLexer.
435 struct IncludeStackInfo {
436 enum CurLexerKind CurLexerKind;
437 Module *TheSubmodule;
438 std::unique_ptr<Lexer> TheLexer;
439 std::unique_ptr<PTHLexer> ThePTHLexer;
440 PreprocessorLexer *ThePPLexer;
441 std::unique_ptr<TokenLexer> TheTokenLexer;
442 const DirectoryLookup *TheDirLookup;
443
444 // The following constructors are completely useless copies of the default
445 // versions, only needed to pacify MSVC.
446 IncludeStackInfo(enum CurLexerKind CurLexerKind, Module *TheSubmodule,
447 std::unique_ptr<Lexer> &&TheLexer,
448 std::unique_ptr<PTHLexer> &&ThePTHLexer,
449 PreprocessorLexer *ThePPLexer,
450 std::unique_ptr<TokenLexer> &&TheTokenLexer,
451 const DirectoryLookup *TheDirLookup)
452 : CurLexerKind(std::move(CurLexerKind)),
453 TheSubmodule(std::move(TheSubmodule)), TheLexer(std::move(TheLexer)),
454 ThePTHLexer(std::move(ThePTHLexer)),
455 ThePPLexer(std::move(ThePPLexer)),
456 TheTokenLexer(std::move(TheTokenLexer)),
457 TheDirLookup(std::move(TheDirLookup)) {}
458 };
459 std::vector<IncludeStackInfo> IncludeMacroStack;
460
461 /// \brief Actions invoked when some preprocessor activity is
462 /// encountered (e.g. a file is \#included, etc).
463 std::unique_ptr<PPCallbacks> Callbacks;
464
465 struct MacroExpandsInfo {
466 Token Tok;
467 MacroDefinition MD;
468 SourceRange Range;
469
470 MacroExpandsInfo(Token Tok, MacroDefinition MD, SourceRange Range)
471 : Tok(Tok), MD(MD), Range(Range) {}
472 };
473 SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks;
474
475 /// Information about a name that has been used to define a module macro.
476 struct ModuleMacroInfo {
477 /// The most recent macro directive for this identifier.
478 MacroDirective *MD;
479
480 /// The active module macros for this identifier.
481 llvm::TinyPtrVector<ModuleMacro *> ActiveModuleMacros;
482
483 /// The generation number at which we last updated ActiveModuleMacros.
484 /// \see Preprocessor::VisibleModules.
485 unsigned ActiveModuleMacrosGeneration = 0;
486
487 /// Whether this macro name is ambiguous.
488 bool IsAmbiguous = false;
489
490 /// The module macros that are overridden by this macro.
491 llvm::TinyPtrVector<ModuleMacro *> OverriddenMacros;
492
493 ModuleMacroInfo(MacroDirective *MD) : MD(MD) {}
494 };
495
496 /// The state of a macro for an identifier.
497 class MacroState {
498 mutable llvm::PointerUnion<MacroDirective *, ModuleMacroInfo *> State;
499
500 ModuleMacroInfo *getModuleInfo(Preprocessor &PP,
501 const IdentifierInfo *II) const {
502 if (II->isOutOfDate())
503 PP.updateOutOfDateIdentifier(const_cast<IdentifierInfo&>(*II));
504 // FIXME: Find a spare bit on IdentifierInfo and store a
505 // HasModuleMacros flag.
506 if (!II->hasMacroDefinition() ||
507 (!PP.getLangOpts().Modules &&
508 !PP.getLangOpts().ModulesLocalVisibility) ||
509 !PP.CurSubmoduleState->VisibleModules.getGeneration())
510 return nullptr;
511
512 auto *Info = State.dyn_cast<ModuleMacroInfo*>();
513 if (!Info) {
514 Info = new (PP.getPreprocessorAllocator())
515 ModuleMacroInfo(State.get<MacroDirective *>());
516 State = Info;
517 }
518
519 if (PP.CurSubmoduleState->VisibleModules.getGeneration() !=
520 Info->ActiveModuleMacrosGeneration)
521 PP.updateModuleMacroInfo(II, *Info);
522 return Info;
523 }
524
525 public:
526 MacroState() : MacroState(nullptr) {}
527 MacroState(MacroDirective *MD) : State(MD) {}
528
529 MacroState(MacroState &&O) noexcept : State(O.State) {
530 O.State = (MacroDirective *)nullptr;
531 }
532
533 MacroState &operator=(MacroState &&O) noexcept {
534 auto S = O.State;
535 O.State = (MacroDirective *)nullptr;
536 State = S;
537 return *this;
538 }
539
540 ~MacroState() {
541 if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
542 Info->~ModuleMacroInfo();
543 }
544
545 MacroDirective *getLatest() const {
546 if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
547 return Info->MD;
548 return State.get<MacroDirective*>();
549 }
550
551 void setLatest(MacroDirective *MD) {
552 if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
553 Info->MD = MD;
554 else
555 State = MD;
556 }
557
558 bool isAmbiguous(Preprocessor &PP, const IdentifierInfo *II) const {
559 auto *Info = getModuleInfo(PP, II);
560 return Info ? Info->IsAmbiguous : false;
561 }
562
563 ArrayRef<ModuleMacro *>
564 getActiveModuleMacros(Preprocessor &PP, const IdentifierInfo *II) const {
565 if (auto *Info = getModuleInfo(PP, II))
566 return Info->ActiveModuleMacros;
567 return None;
568 }
569
570 MacroDirective::DefInfo findDirectiveAtLoc(SourceLocation Loc,
571 SourceManager &SourceMgr) const {
572 // FIXME: Incorporate module macros into the result of this.
573 if (auto *Latest = getLatest())
574 return Latest->findDirectiveAtLoc(Loc, SourceMgr);
575 return {};
576 }
577
578 void overrideActiveModuleMacros(Preprocessor &PP, IdentifierInfo *II) {
579 if (auto *Info = getModuleInfo(PP, II)) {
580 Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
581 Info->ActiveModuleMacros.begin(),
582 Info->ActiveModuleMacros.end());
583 Info->ActiveModuleMacros.clear();
584 Info->IsAmbiguous = false;
585 }
586 }
587
588 ArrayRef<ModuleMacro*> getOverriddenMacros() const {
589 if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
590 return Info->OverriddenMacros;
591 return None;
592 }
593
594 void setOverriddenMacros(Preprocessor &PP,
595 ArrayRef<ModuleMacro *> Overrides) {
596 auto *Info = State.dyn_cast<ModuleMacroInfo*>();
597 if (!Info) {
8
Taking true branch
598 if (Overrides.empty())
9
Assuming the condition is false
10
Taking false branch
599 return;
600 Info = new (PP.getPreprocessorAllocator())
11
Null pointer value stored to 'Info'
601 ModuleMacroInfo(State.get<MacroDirective *>());
602 State = Info;
603 }
604 Info->OverriddenMacros.clear();
12
Called C++ object pointer is null
605 Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
606 Overrides.begin(), Overrides.end());
607 Info->ActiveModuleMacrosGeneration = 0;
608 }
609 };
610
611 /// For each IdentifierInfo that was associated with a macro, we
612 /// keep a mapping to the history of all macro definitions and #undefs in
613 /// the reverse order (the latest one is in the head of the list).
614 ///
615 /// This mapping lives within the \p CurSubmoduleState.
616 using MacroMap = llvm::DenseMap<const IdentifierInfo *, MacroState>;
617
618 struct SubmoduleState;
619
620 /// \brief Information about a submodule that we're currently building.
621 struct BuildingSubmoduleInfo {
622 /// The module that we are building.
623 Module *M;
624
625 /// The location at which the module was included.
626 SourceLocation ImportLoc;
627
628 /// Whether we entered this submodule via a pragma.
629 bool IsPragma;
630
631 /// The previous SubmoduleState.
632 SubmoduleState *OuterSubmoduleState;
633
634 /// The number of pending module macro names when we started building this.
635 unsigned OuterPendingModuleMacroNames;
636
637 BuildingSubmoduleInfo(Module *M, SourceLocation ImportLoc, bool IsPragma,
638 SubmoduleState *OuterSubmoduleState,
639 unsigned OuterPendingModuleMacroNames)
640 : M(M), ImportLoc(ImportLoc), IsPragma(IsPragma),
641 OuterSubmoduleState(OuterSubmoduleState),
642 OuterPendingModuleMacroNames(OuterPendingModuleMacroNames) {}
643 };
644 SmallVector<BuildingSubmoduleInfo, 8> BuildingSubmoduleStack;
645
646 /// \brief Information about a submodule's preprocessor state.
647 struct SubmoduleState {
648 /// The macros for the submodule.
649 MacroMap Macros;
650
651 /// The set of modules that are visible within the submodule.
652 VisibleModuleSet VisibleModules;
653
654 // FIXME: CounterValue?
655 // FIXME: PragmaPushMacroInfo?
656 };
657 std::map<Module *, SubmoduleState> Submodules;
658
659 /// The preprocessor state for preprocessing outside of any submodule.
660 SubmoduleState NullSubmoduleState;
661
662 /// The current submodule state. Will be \p NullSubmoduleState if we're not
663 /// in a submodule.
664 SubmoduleState *CurSubmoduleState;
665
666 /// The set of known macros exported from modules.
667 llvm::FoldingSet<ModuleMacro> ModuleMacros;
668
669 /// The names of potential module macros that we've not yet processed.
670 llvm::SmallVector<const IdentifierInfo *, 32> PendingModuleMacroNames;
671
672 /// The list of module macros, for each identifier, that are not overridden by
673 /// any other module macro.
674 llvm::DenseMap<const IdentifierInfo *, llvm::TinyPtrVector<ModuleMacro *>>
675 LeafModuleMacros;
676
677 /// \brief Macros that we want to warn because they are not used at the end
678 /// of the translation unit.
679 ///
680 /// We store just their SourceLocations instead of
681 /// something like MacroInfo*. The benefit of this is that when we are
682 /// deserializing from PCH, we don't need to deserialize identifier & macros
683 /// just so that we can report that they are unused, we just warn using
684 /// the SourceLocations of this set (that will be filled by the ASTReader).
685 /// We are using SmallPtrSet instead of a vector for faster removal.
686 using WarnUnusedMacroLocsTy = llvm::SmallPtrSet<SourceLocation, 32>;
687 WarnUnusedMacroLocsTy WarnUnusedMacroLocs;
688
689 /// \brief A "freelist" of MacroArg objects that can be
690 /// reused for quick allocation.
691 MacroArgs *MacroArgCache = nullptr;
692
693 /// For each IdentifierInfo used in a \#pragma push_macro directive,
694 /// we keep a MacroInfo stack used to restore the previous macro value.
695 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>
696 PragmaPushMacroInfo;
697
698 // Various statistics we track for performance analysis.
699 unsigned NumDirectives = 0;
700 unsigned NumDefined = 0;
701 unsigned NumUndefined = 0;
702 unsigned NumPragma = 0;
703 unsigned NumIf = 0;
704 unsigned NumElse = 0;
705 unsigned NumEndif = 0;
706 unsigned NumEnteredSourceFiles = 0;
707 unsigned MaxIncludeStackDepth = 0;
708 unsigned NumMacroExpanded = 0;
709 unsigned NumFnMacroExpanded = 0;
710 unsigned NumBuiltinMacroExpanded = 0;
711 unsigned NumFastMacroExpanded = 0;
712 unsigned NumTokenPaste = 0;
713 unsigned NumFastTokenPaste = 0;
714 unsigned NumSkipped = 0;
715
716 /// \brief The predefined macros that preprocessor should use from the
717 /// command line etc.
718 std::string Predefines;
719
720 /// \brief The file ID for the preprocessor predefines.
721 FileID PredefinesFileID;
722
723 /// \{
724 /// \brief Cache of macro expanders to reduce malloc traffic.
725 enum { TokenLexerCacheSize = 8 };
726 unsigned NumCachedTokenLexers;
727 std::unique_ptr<TokenLexer> TokenLexerCache[TokenLexerCacheSize];
728 /// \}
729
730 /// \brief Keeps macro expanded tokens for TokenLexers.
731 //
732 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
733 /// going to lex in the cache and when it finishes the tokens are removed
734 /// from the end of the cache.
735 SmallVector<Token, 16> MacroExpandedTokens;
736 std::vector<std::pair<TokenLexer *, size_t>> MacroExpandingLexersStack;
737
738 /// \brief A record of the macro definitions and expansions that
739 /// occurred during preprocessing.
740 ///
741 /// This is an optional side structure that can be enabled with
742 /// \c createPreprocessingRecord() prior to preprocessing.
743 PreprocessingRecord *Record = nullptr;
744
745 /// Cached tokens state.
746 using CachedTokensTy = SmallVector<Token, 1>;
747
748 /// \brief Cached tokens are stored here when we do backtracking or
749 /// lookahead. They are "lexed" by the CachingLex() method.
750 CachedTokensTy CachedTokens;
751
752 /// \brief The position of the cached token that CachingLex() should
753 /// "lex" next.
754 ///
755 /// If it points beyond the CachedTokens vector, it means that a normal
756 /// Lex() should be invoked.
757 CachedTokensTy::size_type CachedLexPos = 0;
758
759 /// \brief Stack of backtrack positions, allowing nested backtracks.
760 ///
761 /// The EnableBacktrackAtThisPos() method pushes a position to
762 /// indicate where CachedLexPos should be set when the BackTrack() method is
763 /// invoked (at which point the last position is popped).
764 std::vector<CachedTokensTy::size_type> BacktrackPositions;
765
766 struct MacroInfoChain {
767 MacroInfo MI;
768 MacroInfoChain *Next;
769 };
770
771 /// MacroInfos are managed as a chain for easy disposal. This is the head
772 /// of that list.
773 MacroInfoChain *MIChainHead = nullptr;
774
775 void updateOutOfDateIdentifier(IdentifierInfo &II) const;
776
777public:
778 Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
779 DiagnosticsEngine &diags, LangOptions &opts, SourceManager &SM,
780 MemoryBufferCache &PCMCache,
781 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
782 IdentifierInfoLookup *IILookup = nullptr,
783 bool OwnsHeaderSearch = false,
784 TranslationUnitKind TUKind = TU_Complete);
785
786 ~Preprocessor();
787
788 /// \brief Initialize the preprocessor using information about the target.
789 ///
790 /// \param Target is owned by the caller and must remain valid for the
791 /// lifetime of the preprocessor.
792 /// \param AuxTarget is owned by the caller and must remain valid for
793 /// the lifetime of the preprocessor.
794 void Initialize(const TargetInfo &Target,
795 const TargetInfo *AuxTarget = nullptr);
796
797 /// \brief Initialize the preprocessor to parse a model file
798 ///
799 /// To parse model files the preprocessor of the original source is reused to
800 /// preserver the identifier table. However to avoid some duplicate
801 /// information in the preprocessor some cleanup is needed before it is used
802 /// to parse model files. This method does that cleanup.
803 void InitializeForModelFile();
804
805 /// \brief Cleanup after model file parsing
806 void FinalizeForModelFile();
807
808 /// \brief Retrieve the preprocessor options used to initialize this
809 /// preprocessor.
810 PreprocessorOptions &getPreprocessorOpts() const { return *PPOpts; }
811
812 DiagnosticsEngine &getDiagnostics() const { return *Diags; }
813 void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; }
814
815 const LangOptions &getLangOpts() const { return LangOpts; }
816 const TargetInfo &getTargetInfo() const { return *Target; }
817 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
818 FileManager &getFileManager() const { return FileMgr; }
819 SourceManager &getSourceManager() const { return SourceMgr; }
820 MemoryBufferCache &getPCMCache() const { return PCMCache; }
821 HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
822
823 IdentifierTable &getIdentifierTable() { return Identifiers; }
824 const IdentifierTable &getIdentifierTable() const { return Identifiers; }
825 SelectorTable &getSelectorTable() { return Selectors; }
826 Builtin::Context &getBuiltinInfo() { return BuiltinInfo; }
827 llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
828
829 void setPTHManager(PTHManager* pm);
830
831 PTHManager *getPTHManager() { return PTH.get(); }
832
833 void setExternalSource(ExternalPreprocessorSource *Source) {
834 ExternalSource = Source;
835 }
836
837 ExternalPreprocessorSource *getExternalSource() const {
838 return ExternalSource;
839 }
840
841 /// \brief Retrieve the module loader associated with this preprocessor.
842 ModuleLoader &getModuleLoader() const { return TheModuleLoader; }
843
844 bool hadModuleLoaderFatalFailure() const {
845 return TheModuleLoader.HadFatalFailure;
846 }
847
848 /// \brief True if we are currently preprocessing a #if or #elif directive
849 bool isParsingIfOrElifDirective() const {
850 return ParsingIfOrElifDirective;
851 }
852
853 /// \brief Control whether the preprocessor retains comments in output.
854 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
855 this->KeepComments = KeepComments | KeepMacroComments;
856 this->KeepMacroComments = KeepMacroComments;
857 }
858
859 bool getCommentRetentionState() const { return KeepComments; }
860
861 void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; }
862 bool getPragmasEnabled() const { return PragmasEnabled; }
863
864 void SetSuppressIncludeNotFoundError(bool Suppress) {
865 SuppressIncludeNotFoundError = Suppress;
866 }
867
868 bool GetSuppressIncludeNotFoundError() {
869 return SuppressIncludeNotFoundError;
870 }
871
872 /// Sets whether the preprocessor is responsible for producing output or if
873 /// it is producing tokens to be consumed by Parse and Sema.
874 void setPreprocessedOutput(bool IsPreprocessedOutput) {
875 PreprocessedOutput = IsPreprocessedOutput;
876 }
877
878 /// Returns true if the preprocessor is responsible for generating output,
879 /// false if it is producing tokens to be consumed by Parse and Sema.
880 bool isPreprocessedOutput() const { return PreprocessedOutput; }
881
882 /// \brief Return true if we are lexing directly from the specified lexer.
883 bool isCurrentLexer(const PreprocessorLexer *L) const {
884 return CurPPLexer == L;
885 }
886
887 /// \brief Return the current lexer being lexed from.
888 ///
889 /// Note that this ignores any potentially active macro expansions and _Pragma
890 /// expansions going on at the time.
891 PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; }
892
893 /// \brief Return the current file lexer being lexed from.
894 ///
895 /// Note that this ignores any potentially active macro expansions and _Pragma
896 /// expansions going on at the time.
897 PreprocessorLexer *getCurrentFileLexer() const;
898
899 /// \brief Return the submodule owning the file being lexed. This may not be
900 /// the current module if we have changed modules since entering the file.
901 Module *getCurrentLexerSubmodule() const { return CurLexerSubmodule; }
902
903 /// \brief Returns the FileID for the preprocessor predefines.
904 FileID getPredefinesFileID() const { return PredefinesFileID; }
905
906 /// \{
907 /// \brief Accessors for preprocessor callbacks.
908 ///
909 /// Note that this class takes ownership of any PPCallbacks object given to
910 /// it.
911 PPCallbacks *getPPCallbacks() const { return Callbacks.get(); }
912 void addPPCallbacks(std::unique_ptr<PPCallbacks> C) {
913 if (Callbacks)
914 C = llvm::make_unique<PPChainedCallbacks>(std::move(C),
915 std::move(Callbacks));
916 Callbacks = std::move(C);
917 }
918 /// \}
919
920 bool isMacroDefined(StringRef Id) {
921 return isMacroDefined(&Identifiers.get(Id));
922 }
923 bool isMacroDefined(const IdentifierInfo *II) {
924 return II->hasMacroDefinition() &&
925 (!getLangOpts().Modules || (bool)getMacroDefinition(II));
926 }
927
928 /// \brief Determine whether II is defined as a macro within the module M,
929 /// if that is a module that we've already preprocessed. Does not check for
930 /// macros imported into M.
931 bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M) {
932 if (!II->hasMacroDefinition())
933 return false;
934 auto I = Submodules.find(M);
935 if (I == Submodules.end())
936 return false;
937 auto J = I->second.Macros.find(II);
938 if (J == I->second.Macros.end())
939 return false;
940 auto *MD = J->second.getLatest();
941 return MD && MD->isDefined();
942 }
943
944 MacroDefinition getMacroDefinition(const IdentifierInfo *II) {
945 if (!II->hasMacroDefinition())
946 return {};
947
948 MacroState &S = CurSubmoduleState->Macros[II];
949 auto *MD = S.getLatest();
950 while (MD && isa<VisibilityMacroDirective>(MD))
951 MD = MD->getPrevious();
952 return MacroDefinition(dyn_cast_or_null<DefMacroDirective>(MD),
953 S.getActiveModuleMacros(*this, II),
954 S.isAmbiguous(*this, II));
955 }
956
957 MacroDefinition getMacroDefinitionAtLoc(const IdentifierInfo *II,
958 SourceLocation Loc) {
959 if (!II->hadMacroDefinition())
960 return {};
961
962 MacroState &S = CurSubmoduleState->Macros[II];
963 MacroDirective::DefInfo DI;
964 if (auto *MD = S.getLatest())
965 DI = MD->findDirectiveAtLoc(Loc, getSourceManager());
966 // FIXME: Compute the set of active module macros at the specified location.
967 return MacroDefinition(DI.getDirective(),
968 S.getActiveModuleMacros(*this, II),
969 S.isAmbiguous(*this, II));
970 }
971
972 /// \brief Given an identifier, return its latest non-imported MacroDirective
973 /// if it is \#define'd and not \#undef'd, or null if it isn't \#define'd.
974 MacroDirective *getLocalMacroDirective(const IdentifierInfo *II) const {
975 if (!II->hasMacroDefinition())
976 return nullptr;
977
978 auto *MD = getLocalMacroDirectiveHistory(II);
979 if (!MD || MD->getDefinition().isUndefined())
980 return nullptr;
981
982 return MD;
983 }
984
985 const MacroInfo *getMacroInfo(const IdentifierInfo *II) const {
986 return const_cast<Preprocessor*>(this)->getMacroInfo(II);
987 }
988
989 MacroInfo *getMacroInfo(const IdentifierInfo *II) {
990 if (!II->hasMacroDefinition())
991 return nullptr;
992 if (auto MD = getMacroDefinition(II))
993 return MD.getMacroInfo();
994 return nullptr;
995 }
996
997 /// \brief Given an identifier, return the latest non-imported macro
998 /// directive for that identifier.
999 ///
1000 /// One can iterate over all previous macro directives from the most recent
1001 /// one.
1002 MacroDirective *getLocalMacroDirectiveHistory(const IdentifierInfo *II) const;
1003
1004 /// \brief Add a directive to the macro directive history for this identifier.
1005 void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD);
1006 DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI,
1007 SourceLocation Loc) {
1008 DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc);
1009 appendMacroDirective(II, MD);
1010 return MD;
1011 }
1012 DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II,
1013 MacroInfo *MI) {
1014 return appendDefMacroDirective(II, MI, MI->getDefinitionLoc());
1015 }
1016
1017 /// \brief Set a MacroDirective that was loaded from a PCH file.
1018 void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED,
1019 MacroDirective *MD);
1020
1021 /// \brief Register an exported macro for a module and identifier.
1022 ModuleMacro *addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro,
1023 ArrayRef<ModuleMacro *> Overrides, bool &IsNew);
1024 ModuleMacro *getModuleMacro(Module *Mod, IdentifierInfo *II);
1025
1026 /// \brief Get the list of leaf (non-overridden) module macros for a name.
1027 ArrayRef<ModuleMacro*> getLeafModuleMacros(const IdentifierInfo *II) const {
1028 if (II->isOutOfDate())
1029 updateOutOfDateIdentifier(const_cast<IdentifierInfo&>(*II));
1030 auto I = LeafModuleMacros.find(II);
1031 if (I != LeafModuleMacros.end())
1032 return I->second;
1033 return None;
1034 }
1035
1036 /// \{
1037 /// Iterators for the macro history table. Currently defined macros have
1038 /// IdentifierInfo::hasMacroDefinition() set and an empty
1039 /// MacroInfo::getUndefLoc() at the head of the list.
1040 using macro_iterator = MacroMap::const_iterator;
1041
1042 macro_iterator macro_begin(bool IncludeExternalMacros = true) const;
1043 macro_iterator macro_end(bool IncludeExternalMacros = true) const;
1044 llvm::iterator_range<macro_iterator>
1045
1046 macros(bool IncludeExternalMacros = true) const {
1047 return llvm::make_range(macro_begin(IncludeExternalMacros),
1048 macro_end(IncludeExternalMacros));
1049 }
1050 /// \}
1051
1052 /// \brief Return the name of the macro defined before \p Loc that has
1053 /// spelling \p Tokens. If there are multiple macros with same spelling,
1054 /// return the last one defined.
1055 StringRef getLastMacroWithSpelling(SourceLocation Loc,
1056 ArrayRef<TokenValue> Tokens) const;
1057
1058 const std::string &getPredefines() const { return Predefines; }
1059
1060 /// \brief Set the predefines for this Preprocessor.
1061 ///
1062 /// These predefines are automatically injected when parsing the main file.
1063 void setPredefines(const char *P) { Predefines = P; }
1064 void setPredefines(StringRef P) { Predefines = P; }
1065
1066 /// Return information about the specified preprocessor
1067 /// identifier token.
1068 IdentifierInfo *getIdentifierInfo(StringRef Name) const {
1069 return &Identifiers.get(Name);
1070 }
1071
1072 /// \brief Add the specified pragma handler to this preprocessor.
1073 ///
1074 /// If \p Namespace is non-null, then it is a token required to exist on the
1075 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
1076 void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler);
1077 void AddPragmaHandler(PragmaHandler *Handler) {
1078 AddPragmaHandler(StringRef(), Handler);
1079 }
1080
1081 /// \brief Remove the specific pragma handler from this preprocessor.
1082 ///
1083 /// If \p Namespace is non-null, then it should be the namespace that
1084 /// \p Handler was added to. It is an error to remove a handler that
1085 /// has not been registered.
1086 void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler);
1087 void RemovePragmaHandler(PragmaHandler *Handler) {
1088 RemovePragmaHandler(StringRef(), Handler);
1089 }
1090
1091 /// Install empty handlers for all pragmas (making them ignored).
1092 void IgnorePragmas();
1093
1094 /// \brief Add the specified comment handler to the preprocessor.
1095 void addCommentHandler(CommentHandler *Handler);
1096
1097 /// \brief Remove the specified comment handler.
1098 ///
1099 /// It is an error to remove a handler that has not been registered.
1100 void removeCommentHandler(CommentHandler *Handler);
1101
1102 /// \brief Set the code completion handler to the given object.
1103 void setCodeCompletionHandler(CodeCompletionHandler &Handler) {
1104 CodeComplete = &Handler;
1105 }
1106
1107 /// \brief Retrieve the current code-completion handler.
1108 CodeCompletionHandler *getCodeCompletionHandler() const {
1109 return CodeComplete;
1110 }
1111
1112 /// \brief Clear out the code completion handler.
1113 void clearCodeCompletionHandler() {
1114 CodeComplete = nullptr;
1115 }
1116
1117 /// \brief Hook used by the lexer to invoke the "natural language" code
1118 /// completion point.
1119 void CodeCompleteNaturalLanguage();
1120
1121 /// \brief Set the code completion token for filtering purposes.
1122 void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter) {
1123 CodeCompletionII = Filter;
1124 }
1125
1126 /// \brief Get the code completion token for filtering purposes.
1127 StringRef getCodeCompletionFilter() {
1128 if (CodeCompletionII)
1129 return CodeCompletionII->getName();
1130 return {};
1131 }
1132
1133 /// \brief Retrieve the preprocessing record, or NULL if there is no
1134 /// preprocessing record.
1135 PreprocessingRecord *getPreprocessingRecord() const { return Record; }
1136
1137 /// \brief Create a new preprocessing record, which will keep track of
1138 /// all macro expansions, macro definitions, etc.
1139 void createPreprocessingRecord();
1140
1141 /// \brief Enter the specified FileID as the main source file,
1142 /// which implicitly adds the builtin defines etc.
1143 void EnterMainSourceFile();
1144
1145 /// \brief Inform the preprocessor callbacks that processing is complete.
1146 void EndSourceFile();
1147
1148 /// \brief Add a source file to the top of the include stack and
1149 /// start lexing tokens from it instead of the current buffer.
1150 ///
1151 /// Emits a diagnostic, doesn't enter the file, and returns true on error.
1152 bool EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir,
1153 SourceLocation Loc);
1154
1155 /// \brief Add a Macro to the top of the include stack and start lexing
1156 /// tokens from it instead of the current buffer.
1157 ///
1158 /// \param Args specifies the tokens input to a function-like macro.
1159 /// \param ILEnd specifies the location of the ')' for a function-like macro
1160 /// or the identifier for an object-like macro.
1161 void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroInfo *Macro,
1162 MacroArgs *Args);
1163
1164 /// \brief Add a "macro" context to the top of the include stack,
1165 /// which will cause the lexer to start returning the specified tokens.
1166 ///
1167 /// If \p DisableMacroExpansion is true, tokens lexed from the token stream
1168 /// will not be subject to further macro expansion. Otherwise, these tokens
1169 /// will be re-macro-expanded when/if expansion is enabled.
1170 ///
1171 /// If \p OwnsTokens is false, this method assumes that the specified stream
1172 /// of tokens has a permanent owner somewhere, so they do not need to be
1173 /// copied. If it is true, it assumes the array of tokens is allocated with
1174 /// \c new[] and the Preprocessor will delete[] it.
1175private:
1176 void EnterTokenStream(const Token *Toks, unsigned NumToks,
1177 bool DisableMacroExpansion, bool OwnsTokens);
1178
1179public:
1180 void EnterTokenStream(std::unique_ptr<Token[]> Toks, unsigned NumToks,
1181 bool DisableMacroExpansion) {
1182 EnterTokenStream(Toks.release(), NumToks, DisableMacroExpansion, true);
1183 }
1184
1185 void EnterTokenStream(ArrayRef<Token> Toks, bool DisableMacroExpansion) {
1186 EnterTokenStream(Toks.data(), Toks.size(), DisableMacroExpansion, false);
1187 }
1188
1189 /// \brief Pop the current lexer/macro exp off the top of the lexer stack.
1190 ///
1191 /// This should only be used in situations where the current state of the
1192 /// top-of-stack lexer is known.
1193 void RemoveTopOfLexerStack();
1194
1195 /// From the point that this method is called, and until
1196 /// CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
1197 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
1198 /// make the Preprocessor re-lex the same tokens.
1199 ///
1200 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
1201 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
1202 /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
1203 ///
1204 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
1205 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
1206 /// tokens will continue indefinitely.
1207 ///
1208 void EnableBacktrackAtThisPos();
1209
1210 /// \brief Disable the last EnableBacktrackAtThisPos call.
1211 void CommitBacktrackedTokens();
1212
1213 struct CachedTokensRange {
1214 CachedTokensTy::size_type Begin, End;
1215 };
1216
1217private:
1218 /// \brief A range of cached tokens that should be erased after lexing
1219 /// when backtracking requires the erasure of such cached tokens.
1220 Optional<CachedTokensRange> CachedTokenRangeToErase;
1221
1222public:
1223 /// \brief Returns the range of cached tokens that were lexed since
1224 /// EnableBacktrackAtThisPos() was previously called.
1225 CachedTokensRange LastCachedTokenRange();
1226
1227 /// \brief Erase the range of cached tokens that were lexed since
1228 /// EnableBacktrackAtThisPos() was previously called.
1229 void EraseCachedTokens(CachedTokensRange TokenRange);
1230
1231 /// \brief Make Preprocessor re-lex the tokens that were lexed since
1232 /// EnableBacktrackAtThisPos() was previously called.
1233 void Backtrack();
1234
1235 /// \brief True if EnableBacktrackAtThisPos() was called and
1236 /// caching of tokens is on.
1237 bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
1238
1239 /// \brief Lex the next token for this preprocessor.
1240 void Lex(Token &Result);
1241
1242 void LexAfterModuleImport(Token &Result);
1243
1244 void makeModuleVisible(Module *M, SourceLocation Loc);
1245
1246 SourceLocation getModuleImportLoc(Module *M) const {
1247 return CurSubmoduleState->VisibleModules.getImportLoc(M);
1248 }
1249
1250 /// \brief Lex a string literal, which may be the concatenation of multiple
1251 /// string literals and may even come from macro expansion.
1252 /// \returns true on success, false if a error diagnostic has been generated.
1253 bool LexStringLiteral(Token &Result, std::string &String,
1254 const char *DiagnosticTag, bool AllowMacroExpansion) {
1255 if (AllowMacroExpansion)
1256 Lex(Result);
1257 else
1258 LexUnexpandedToken(Result);
1259 return FinishLexStringLiteral(Result, String, DiagnosticTag,
1260 AllowMacroExpansion);
1261 }
1262
1263 /// \brief Complete the lexing of a string literal where the first token has
1264 /// already been lexed (see LexStringLiteral).
1265 bool FinishLexStringLiteral(Token &Result, std::string &String,
1266 const char *DiagnosticTag,
1267 bool AllowMacroExpansion);
1268
1269 /// \brief Lex a token. If it's a comment, keep lexing until we get
1270 /// something not a comment.
1271 ///
1272 /// This is useful in -E -C mode where comments would foul up preprocessor
1273 /// directive handling.
1274 void LexNonComment(Token &Result) {
1275 do
1276 Lex(Result);
1277 while (Result.getKind() == tok::comment);
1278 }
1279
1280 /// \brief Just like Lex, but disables macro expansion of identifier tokens.
1281 void LexUnexpandedToken(Token &Result) {
1282 // Disable macro expansion.
1283 bool OldVal = DisableMacroExpansion;
1284 DisableMacroExpansion = true;
1285 // Lex the token.
1286 Lex(Result);
1287
1288 // Reenable it.
1289 DisableMacroExpansion = OldVal;
1290 }
1291
1292 /// \brief Like LexNonComment, but this disables macro expansion of
1293 /// identifier tokens.
1294 void LexUnexpandedNonComment(Token &Result) {
1295 do
1296 LexUnexpandedToken(Result);
1297 while (Result.getKind() == tok::comment);
1298 }
1299
1300 /// \brief Parses a simple integer literal to get its numeric value. Floating
1301 /// point literals and user defined literals are rejected. Used primarily to
1302 /// handle pragmas that accept integer arguments.
1303 bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value);
1304
1305 /// Disables macro expansion everywhere except for preprocessor directives.
1306 void SetMacroExpansionOnlyInDirectives() {
1307 DisableMacroExpansion = true;
1308 MacroExpansionInDirectivesOverride = true;
1309 }
1310
1311 /// \brief Peeks ahead N tokens and returns that token without consuming any
1312 /// tokens.
1313 ///
1314 /// LookAhead(0) returns the next token that would be returned by Lex(),
1315 /// LookAhead(1) returns the token after it, etc. This returns normal
1316 /// tokens after phase 5. As such, it is equivalent to using
1317 /// 'Lex', not 'LexUnexpandedToken'.
1318 const Token &LookAhead(unsigned N) {
1319 if (CachedLexPos + N < CachedTokens.size())
1320 return CachedTokens[CachedLexPos+N];
1321 else
1322 return PeekAhead(N+1);
1323 }
1324
1325 /// \brief When backtracking is enabled and tokens are cached,
1326 /// this allows to revert a specific number of tokens.
1327 ///
1328 /// Note that the number of tokens being reverted should be up to the last
1329 /// backtrack position, not more.
1330 void RevertCachedTokens(unsigned N) {
1331 assert(isBacktrackEnabled() &&(static_cast <bool> (isBacktrackEnabled() && "Should only be called when tokens are cached for backtracking"
) ? void (0) : __assert_fail ("isBacktrackEnabled() && \"Should only be called when tokens are cached for backtracking\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1332, __extension__ __PRETTY_FUNCTION__))
1332 "Should only be called when tokens are cached for backtracking")(static_cast <bool> (isBacktrackEnabled() && "Should only be called when tokens are cached for backtracking"
) ? void (0) : __assert_fail ("isBacktrackEnabled() && \"Should only be called when tokens are cached for backtracking\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1332, __extension__ __PRETTY_FUNCTION__))
;
1333 assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back())(static_cast <bool> (signed(CachedLexPos) - signed(N) >=
signed(BacktrackPositions.back()) && "Should revert tokens up to the last backtrack position, not more"
) ? void (0) : __assert_fail ("signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back()) && \"Should revert tokens up to the last backtrack position, not more\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1334, __extension__ __PRETTY_FUNCTION__))
1334 && "Should revert tokens up to the last backtrack position, not more")(static_cast <bool> (signed(CachedLexPos) - signed(N) >=
signed(BacktrackPositions.back()) && "Should revert tokens up to the last backtrack position, not more"
) ? void (0) : __assert_fail ("signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back()) && \"Should revert tokens up to the last backtrack position, not more\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1334, __extension__ __PRETTY_FUNCTION__))
;
1335 assert(signed(CachedLexPos) - signed(N) >= 0 &&(static_cast <bool> (signed(CachedLexPos) - signed(N) >=
0 && "Corrupted backtrack positions ?") ? void (0) :
__assert_fail ("signed(CachedLexPos) - signed(N) >= 0 && \"Corrupted backtrack positions ?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1336, __extension__ __PRETTY_FUNCTION__))
1336 "Corrupted backtrack positions ?")(static_cast <bool> (signed(CachedLexPos) - signed(N) >=
0 && "Corrupted backtrack positions ?") ? void (0) :
__assert_fail ("signed(CachedLexPos) - signed(N) >= 0 && \"Corrupted backtrack positions ?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1336, __extension__ __PRETTY_FUNCTION__))
;
1337 CachedLexPos -= N;
1338 }
1339
1340 /// \brief Enters a token in the token stream to be lexed next.
1341 ///
1342 /// If BackTrack() is called afterwards, the token will remain at the
1343 /// insertion point.
1344 void EnterToken(const Token &Tok) {
1345 EnterCachingLexMode();
1346 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
1347 }
1348
1349 /// We notify the Preprocessor that if it is caching tokens (because
1350 /// backtrack is enabled) it should replace the most recent cached tokens
1351 /// with the given annotation token. This function has no effect if
1352 /// backtracking is not enabled.
1353 ///
1354 /// Note that the use of this function is just for optimization, so that the
1355 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
1356 /// invoked.
1357 void AnnotateCachedTokens(const Token &Tok) {
1358 assert(Tok.isAnnotation() && "Expected annotation token")(static_cast <bool> (Tok.isAnnotation() && "Expected annotation token"
) ? void (0) : __assert_fail ("Tok.isAnnotation() && \"Expected annotation token\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1358, __extension__ __PRETTY_FUNCTION__))
;
1359 if (CachedLexPos != 0 && isBacktrackEnabled())
1360 AnnotatePreviousCachedTokens(Tok);
1361 }
1362
1363 /// Get the location of the last cached token, suitable for setting the end
1364 /// location of an annotation token.
1365 SourceLocation getLastCachedTokenLocation() const {
1366 assert(CachedLexPos != 0)(static_cast <bool> (CachedLexPos != 0) ? void (0) : __assert_fail
("CachedLexPos != 0", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1366, __extension__ __PRETTY_FUNCTION__))
;
1367 return CachedTokens[CachedLexPos-1].getLastLoc();
1368 }
1369
1370 /// \brief Whether \p Tok is the most recent token (`CachedLexPos - 1`) in
1371 /// CachedTokens.
1372 bool IsPreviousCachedToken(const Token &Tok) const;
1373
1374 /// \brief Replace token in `CachedLexPos - 1` in CachedTokens by the tokens
1375 /// in \p NewToks.
1376 ///
1377 /// Useful when a token needs to be split in smaller ones and CachedTokens
1378 /// most recent token must to be updated to reflect that.
1379 void ReplacePreviousCachedToken(ArrayRef<Token> NewToks);
1380
1381 /// \brief Replace the last token with an annotation token.
1382 ///
1383 /// Like AnnotateCachedTokens(), this routine replaces an
1384 /// already-parsed (and resolved) token with an annotation
1385 /// token. However, this routine only replaces the last token with
1386 /// the annotation token; it does not affect any other cached
1387 /// tokens. This function has no effect if backtracking is not
1388 /// enabled.
1389 void ReplaceLastTokenWithAnnotation(const Token &Tok) {
1390 assert(Tok.isAnnotation() && "Expected annotation token")(static_cast <bool> (Tok.isAnnotation() && "Expected annotation token"
) ? void (0) : __assert_fail ("Tok.isAnnotation() && \"Expected annotation token\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1390, __extension__ __PRETTY_FUNCTION__))
;
1391 if (CachedLexPos != 0 && isBacktrackEnabled())
1392 CachedTokens[CachedLexPos-1] = Tok;
1393 }
1394
1395 /// Enter an annotation token into the token stream.
1396 void EnterAnnotationToken(SourceRange Range, tok::TokenKind Kind,
1397 void *AnnotationVal);
1398
1399 /// Update the current token to represent the provided
1400 /// identifier, in order to cache an action performed by typo correction.
1401 void TypoCorrectToken(const Token &Tok) {
1402 assert(Tok.getIdentifierInfo() && "Expected identifier token")(static_cast <bool> (Tok.getIdentifierInfo() &&
"Expected identifier token") ? void (0) : __assert_fail ("Tok.getIdentifierInfo() && \"Expected identifier token\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1402, __extension__ __PRETTY_FUNCTION__))
;
1403 if (CachedLexPos != 0 && isBacktrackEnabled())
1404 CachedTokens[CachedLexPos-1] = Tok;
1405 }
1406
1407 /// \brief Recompute the current lexer kind based on the CurLexer/CurPTHLexer/
1408 /// CurTokenLexer pointers.
1409 void recomputeCurLexerKind();
1410
1411 /// \brief Returns true if incremental processing is enabled
1412 bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; }
1413
1414 /// \brief Enables the incremental processing
1415 void enableIncrementalProcessing(bool value = true) {
1416 IncrementalProcessing = value;
1417 }
1418
1419 /// \brief Specify the point at which code-completion will be performed.
1420 ///
1421 /// \param File the file in which code completion should occur. If
1422 /// this file is included multiple times, code-completion will
1423 /// perform completion the first time it is included. If NULL, this
1424 /// function clears out the code-completion point.
1425 ///
1426 /// \param Line the line at which code completion should occur
1427 /// (1-based).
1428 ///
1429 /// \param Column the column at which code completion should occur
1430 /// (1-based).
1431 ///
1432 /// \returns true if an error occurred, false otherwise.
1433 bool SetCodeCompletionPoint(const FileEntry *File,
1434 unsigned Line, unsigned Column);
1435
1436 /// \brief Determine if we are performing code completion.
1437 bool isCodeCompletionEnabled() const { return CodeCompletionFile != nullptr; }
1438
1439 /// \brief Returns the location of the code-completion point.
1440 ///
1441 /// Returns an invalid location if code-completion is not enabled or the file
1442 /// containing the code-completion point has not been lexed yet.
1443 SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; }
1444
1445 /// \brief Returns the start location of the file of code-completion point.
1446 ///
1447 /// Returns an invalid location if code-completion is not enabled or the file
1448 /// containing the code-completion point has not been lexed yet.
1449 SourceLocation getCodeCompletionFileLoc() const {
1450 return CodeCompletionFileLoc;
1451 }
1452
1453 /// \brief Returns true if code-completion is enabled and we have hit the
1454 /// code-completion point.
1455 bool isCodeCompletionReached() const { return CodeCompletionReached; }
1456
1457 /// \brief Note that we hit the code-completion point.
1458 void setCodeCompletionReached() {
1459 assert(isCodeCompletionEnabled() && "Code-completion not enabled!")(static_cast <bool> (isCodeCompletionEnabled() &&
"Code-completion not enabled!") ? void (0) : __assert_fail (
"isCodeCompletionEnabled() && \"Code-completion not enabled!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1459, __extension__ __PRETTY_FUNCTION__))
;
1460 CodeCompletionReached = true;
1461 // Silence any diagnostics that occur after we hit the code-completion.
1462 getDiagnostics().setSuppressAllDiagnostics(true);
1463 }
1464
1465 /// \brief The location of the currently-active \#pragma clang
1466 /// arc_cf_code_audited begin.
1467 ///
1468 /// Returns an invalid location if there is no such pragma active.
1469 SourceLocation getPragmaARCCFCodeAuditedLoc() const {
1470 return PragmaARCCFCodeAuditedLoc;
1471 }
1472
1473 /// \brief Set the location of the currently-active \#pragma clang
1474 /// arc_cf_code_audited begin. An invalid location ends the pragma.
1475 void setPragmaARCCFCodeAuditedLoc(SourceLocation Loc) {
1476 PragmaARCCFCodeAuditedLoc = Loc;
1477 }
1478
1479 /// \brief The location of the currently-active \#pragma clang
1480 /// assume_nonnull begin.
1481 ///
1482 /// Returns an invalid location if there is no such pragma active.
1483 SourceLocation getPragmaAssumeNonNullLoc() const {
1484 return PragmaAssumeNonNullLoc;
1485 }
1486
1487 /// \brief Set the location of the currently-active \#pragma clang
1488 /// assume_nonnull begin. An invalid location ends the pragma.
1489 void setPragmaAssumeNonNullLoc(SourceLocation Loc) {
1490 PragmaAssumeNonNullLoc = Loc;
1491 }
1492
1493 /// \brief Set the directory in which the main file should be considered
1494 /// to have been found, if it is not a real file.
1495 void setMainFileDir(const DirectoryEntry *Dir) {
1496 MainFileDir = Dir;
1497 }
1498
1499 /// \brief Instruct the preprocessor to skip part of the main source file.
1500 ///
1501 /// \param Bytes The number of bytes in the preamble to skip.
1502 ///
1503 /// \param StartOfLine Whether skipping these bytes puts the lexer at the
1504 /// start of a line.
1505 void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) {
1506 SkipMainFilePreamble.first = Bytes;
1507 SkipMainFilePreamble.second = StartOfLine;
1508 }
1509
1510 /// Forwarding function for diagnostics. This emits a diagnostic at
1511 /// the specified Token's location, translating the token's start
1512 /// position in the current buffer into a SourcePosition object for rendering.
1513 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const {
1514 return Diags->Report(Loc, DiagID);
1515 }
1516
1517 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const {
1518 return Diags->Report(Tok.getLocation(), DiagID);
1519 }
1520
1521 /// Return the 'spelling' of the token at the given
1522 /// location; does not go up to the spelling location or down to the
1523 /// expansion location.
1524 ///
1525 /// \param buffer A buffer which will be used only if the token requires
1526 /// "cleaning", e.g. if it contains trigraphs or escaped newlines
1527 /// \param invalid If non-null, will be set \c true if an error occurs.
1528 StringRef getSpelling(SourceLocation loc,
1529 SmallVectorImpl<char> &buffer,
1530 bool *invalid = nullptr) const {
1531 return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid);
1532 }
1533
1534 /// \brief Return the 'spelling' of the Tok token.
1535 ///
1536 /// The spelling of a token is the characters used to represent the token in
1537 /// the source file after trigraph expansion and escaped-newline folding. In
1538 /// particular, this wants to get the true, uncanonicalized, spelling of
1539 /// things like digraphs, UCNs, etc.
1540 ///
1541 /// \param Invalid If non-null, will be set \c true if an error occurs.
1542 std::string getSpelling(const Token &Tok, bool *Invalid = nullptr) const {
1543 return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid);
1544 }
1545
1546 /// \brief Get the spelling of a token into a preallocated buffer, instead
1547 /// of as an std::string.
1548 ///
1549 /// The caller is required to allocate enough space for the token, which is
1550 /// guaranteed to be at least Tok.getLength() bytes long. The length of the
1551 /// actual result is returned.
1552 ///
1553 /// Note that this method may do two possible things: it may either fill in
1554 /// the buffer specified with characters, or it may *change the input pointer*
1555 /// to point to a constant buffer with the data already in it (avoiding a
1556 /// copy). The caller is not allowed to modify the returned buffer pointer
1557 /// if an internal buffer is returned.
1558 unsigned getSpelling(const Token &Tok, const char *&Buffer,
1559 bool *Invalid = nullptr) const {
1560 return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid);
1561 }
1562
1563 /// \brief Get the spelling of a token into a SmallVector.
1564 ///
1565 /// Note that the returned StringRef may not point to the
1566 /// supplied buffer if a copy can be avoided.
1567 StringRef getSpelling(const Token &Tok,
1568 SmallVectorImpl<char> &Buffer,
1569 bool *Invalid = nullptr) const;
1570
1571 /// \brief Relex the token at the specified location.
1572 /// \returns true if there was a failure, false on success.
1573 bool getRawToken(SourceLocation Loc, Token &Result,
1574 bool IgnoreWhiteSpace = false) {
1575 return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts, IgnoreWhiteSpace);
1576 }
1577
1578 /// \brief Given a Token \p Tok that is a numeric constant with length 1,
1579 /// return the character.
1580 char
1581 getSpellingOfSingleCharacterNumericConstant(const Token &Tok,
1582 bool *Invalid = nullptr) const {
1583 assert(Tok.is(tok::numeric_constant) &&(static_cast <bool> (Tok.is(tok::numeric_constant) &&
Tok.getLength() == 1 && "Called on unsupported token"
) ? void (0) : __assert_fail ("Tok.is(tok::numeric_constant) && Tok.getLength() == 1 && \"Called on unsupported token\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1584, __extension__ __PRETTY_FUNCTION__))
1584 Tok.getLength() == 1 && "Called on unsupported token")(static_cast <bool> (Tok.is(tok::numeric_constant) &&
Tok.getLength() == 1 && "Called on unsupported token"
) ? void (0) : __assert_fail ("Tok.is(tok::numeric_constant) && Tok.getLength() == 1 && \"Called on unsupported token\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1584, __extension__ __PRETTY_FUNCTION__))
;
1585 assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1")(static_cast <bool> (!Tok.needsCleaning() && "Token can't need cleaning with length 1"
) ? void (0) : __assert_fail ("!Tok.needsCleaning() && \"Token can't need cleaning with length 1\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1585, __extension__ __PRETTY_FUNCTION__))
;
1586
1587 // If the token is carrying a literal data pointer, just use it.
1588 if (const char *D = Tok.getLiteralData())
1589 return *D;
1590
1591 // Otherwise, fall back on getCharacterData, which is slower, but always
1592 // works.
1593 return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid);
1594 }
1595
1596 /// \brief Retrieve the name of the immediate macro expansion.
1597 ///
1598 /// This routine starts from a source location, and finds the name of the
1599 /// macro responsible for its immediate expansion. It looks through any
1600 /// intervening macro argument expansions to compute this. It returns a
1601 /// StringRef that refers to the SourceManager-owned buffer of the source
1602 /// where that macro name is spelled. Thus, the result shouldn't out-live
1603 /// the SourceManager.
1604 StringRef getImmediateMacroName(SourceLocation Loc) {
1605 return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts());
1606 }
1607
1608 /// \brief Plop the specified string into a scratch buffer and set the
1609 /// specified token's location and length to it.
1610 ///
1611 /// If specified, the source location provides a location of the expansion
1612 /// point of the token.
1613 void CreateString(StringRef Str, Token &Tok,
1614 SourceLocation ExpansionLocStart = SourceLocation(),
1615 SourceLocation ExpansionLocEnd = SourceLocation());
1616
1617 /// \brief Computes the source location just past the end of the
1618 /// token at this source location.
1619 ///
1620 /// This routine can be used to produce a source location that
1621 /// points just past the end of the token referenced by \p Loc, and
1622 /// is generally used when a diagnostic needs to point just after a
1623 /// token where it expected something different that it received. If
1624 /// the returned source location would not be meaningful (e.g., if
1625 /// it points into a macro), this routine returns an invalid
1626 /// source location.
1627 ///
1628 /// \param Offset an offset from the end of the token, where the source
1629 /// location should refer to. The default offset (0) produces a source
1630 /// location pointing just past the end of the token; an offset of 1 produces
1631 /// a source location pointing to the last character in the token, etc.
1632 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0) {
1633 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
1634 }
1635
1636 /// \brief Returns true if the given MacroID location points at the first
1637 /// token of the macro expansion.
1638 ///
1639 /// \param MacroBegin If non-null and function returns true, it is set to
1640 /// begin location of the macro.
1641 bool isAtStartOfMacroExpansion(SourceLocation loc,
1642 SourceLocation *MacroBegin = nullptr) const {
1643 return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts,
1644 MacroBegin);
1645 }
1646
1647 /// \brief Returns true if the given MacroID location points at the last
1648 /// token of the macro expansion.
1649 ///
1650 /// \param MacroEnd If non-null and function returns true, it is set to
1651 /// end location of the macro.
1652 bool isAtEndOfMacroExpansion(SourceLocation loc,
1653 SourceLocation *MacroEnd = nullptr) const {
1654 return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd);
1655 }
1656
1657 /// \brief Print the token to stderr, used for debugging.
1658 void DumpToken(const Token &Tok, bool DumpFlags = false) const;
1659 void DumpLocation(SourceLocation Loc) const;
1660 void DumpMacro(const MacroInfo &MI) const;
1661 void dumpMacroInfo(const IdentifierInfo *II);
1662
1663 /// \brief Given a location that specifies the start of a
1664 /// token, return a new location that specifies a character within the token.
1665 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
1666 unsigned Char) const {
1667 return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts);
1668 }
1669
1670 /// \brief Increment the counters for the number of token paste operations
1671 /// performed.
1672 ///
1673 /// If fast was specified, this is a 'fast paste' case we handled.
1674 void IncrementPasteCounter(bool isFast) {
1675 if (isFast)
1676 ++NumFastTokenPaste;
1677 else
1678 ++NumTokenPaste;
1679 }
1680
1681 void PrintStats();
1682
1683 size_t getTotalMemory() const;
1684
1685 /// When the macro expander pastes together a comment (/##/) in Microsoft
1686 /// mode, this method handles updating the current state, returning the
1687 /// token on the next source line.
1688 void HandleMicrosoftCommentPaste(Token &Tok);
1689
1690 //===--------------------------------------------------------------------===//
1691 // Preprocessor callback methods. These are invoked by a lexer as various
1692 // directives and events are found.
1693
1694 /// Given a tok::raw_identifier token, look up the
1695 /// identifier information for the token and install it into the token,
1696 /// updating the token kind accordingly.
1697 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const;
1698
1699private:
1700 llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons;
1701
1702public:
1703 /// \brief Specifies the reason for poisoning an identifier.
1704 ///
1705 /// If that identifier is accessed while poisoned, then this reason will be
1706 /// used instead of the default "poisoned" diagnostic.
1707 void SetPoisonReason(IdentifierInfo *II, unsigned DiagID);
1708
1709 /// \brief Display reason for poisoned identifier.
1710 void HandlePoisonedIdentifier(Token & Tok);
1711
1712 void MaybeHandlePoisonedIdentifier(Token & Identifier) {
1713 if(IdentifierInfo * II = Identifier.getIdentifierInfo()) {
1714 if(II->isPoisoned()) {
1715 HandlePoisonedIdentifier(Identifier);
1716 }
1717 }
1718 }
1719
1720private:
1721 /// Identifiers used for SEH handling in Borland. These are only
1722 /// allowed in particular circumstances
1723 // __except block
1724 IdentifierInfo *Ident__exception_code,
1725 *Ident___exception_code,
1726 *Ident_GetExceptionCode;
1727 // __except filter expression
1728 IdentifierInfo *Ident__exception_info,
1729 *Ident___exception_info,
1730 *Ident_GetExceptionInfo;
1731 // __finally
1732 IdentifierInfo *Ident__abnormal_termination,
1733 *Ident___abnormal_termination,
1734 *Ident_AbnormalTermination;
1735
1736 const char *getCurLexerEndPos();
1737 void diagnoseMissingHeaderInUmbrellaDir(const Module &Mod);
1738
1739public:
1740 void PoisonSEHIdentifiers(bool Poison = true); // Borland
1741
1742 /// \brief Callback invoked when the lexer reads an identifier and has
1743 /// filled in the tokens IdentifierInfo member.
1744 ///
1745 /// This callback potentially macro expands it or turns it into a named
1746 /// token (like 'for').
1747 ///
1748 /// \returns true if we actually computed a token, false if we need to
1749 /// lex again.
1750 bool HandleIdentifier(Token &Identifier);
1751
1752 /// \brief Callback invoked when the lexer hits the end of the current file.
1753 ///
1754 /// This either returns the EOF token and returns true, or
1755 /// pops a level off the include stack and returns false, at which point the
1756 /// client should call lex again.
1757 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
1758
1759 /// \brief Callback invoked when the current TokenLexer hits the end of its
1760 /// token stream.
1761 bool HandleEndOfTokenLexer(Token &Result);
1762
1763 /// \brief Callback invoked when the lexer sees a # token at the start of a
1764 /// line.
1765 ///
1766 /// This consumes the directive, modifies the lexer/preprocessor state, and
1767 /// advances the lexer(s) so that the next token read is the correct one.
1768 void HandleDirective(Token &Result);
1769
1770 /// \brief Ensure that the next token is a tok::eod token.
1771 ///
1772 /// If not, emit a diagnostic and consume up until the eod.
1773 /// If \p EnableMacros is true, then we consider macros that expand to zero
1774 /// tokens as being ok.
1775 void CheckEndOfDirective(const char *Directive, bool EnableMacros = false);
1776
1777 /// \brief Read and discard all tokens remaining on the current line until
1778 /// the tok::eod token is found.
1779 void DiscardUntilEndOfDirective();
1780
1781 /// \brief Returns true if the preprocessor has seen a use of
1782 /// __DATE__ or __TIME__ in the file so far.
1783 bool SawDateOrTime() const {
1784 return DATELoc != SourceLocation() || TIMELoc != SourceLocation();
1785 }
1786 unsigned getCounterValue() const { return CounterValue; }
1787 void setCounterValue(unsigned V) { CounterValue = V; }
1788
1789 /// \brief Retrieves the module that we're currently building, if any.
1790 Module *getCurrentModule();
1791
1792 /// \brief Allocate a new MacroInfo object with the provided SourceLocation.
1793 MacroInfo *AllocateMacroInfo(SourceLocation L);
1794
1795 /// \brief Turn the specified lexer token into a fully checked and spelled
1796 /// filename, e.g. as an operand of \#include.
1797 ///
1798 /// The caller is expected to provide a buffer that is large enough to hold
1799 /// the spelling of the filename, but is also expected to handle the case
1800 /// when this method decides to use a different buffer.
1801 ///
1802 /// \returns true if the input filename was in <>'s or false if it was
1803 /// in ""'s.
1804 bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Filename);
1805
1806 /// \brief Given a "foo" or \<foo> reference, look up the indicated file.
1807 ///
1808 /// Returns null on failure. \p isAngled indicates whether the file
1809 /// reference is for system \#include's or not (i.e. using <> instead of "").
1810 const FileEntry *LookupFile(SourceLocation FilenameLoc, StringRef Filename,
1811 bool isAngled, const DirectoryLookup *FromDir,
1812 const FileEntry *FromFile,
1813 const DirectoryLookup *&CurDir,
1814 SmallVectorImpl<char> *SearchPath,
1815 SmallVectorImpl<char> *RelativePath,
1816 ModuleMap::KnownHeader *SuggestedModule,
1817 bool *IsMapped, bool SkipCache = false);
1818
1819 /// \brief Get the DirectoryLookup structure used to find the current
1820 /// FileEntry, if CurLexer is non-null and if applicable.
1821 ///
1822 /// This allows us to implement \#include_next and find directory-specific
1823 /// properties.
1824 const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; }
1825
1826 /// \brief Return true if we're in the top-level file, not in a \#include.
1827 bool isInPrimaryFile() const;
1828
1829 /// \brief Handle cases where the \#include name is expanded
1830 /// from a macro as multiple tokens, which need to be glued together.
1831 ///
1832 /// This occurs for code like:
1833 /// \code
1834 /// \#define FOO <x/y.h>
1835 /// \#include FOO
1836 /// \endcode
1837 /// because in this case, "<x/y.h>" is returned as 7 tokens, not one.
1838 ///
1839 /// This code concatenates and consumes tokens up to the '>' token. It
1840 /// returns false if the > was found, otherwise it returns true if it finds
1841 /// and consumes the EOD marker.
1842 bool ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
1843 SourceLocation &End);
1844
1845 /// \brief Lex an on-off-switch (C99 6.10.6p2) and verify that it is
1846 /// followed by EOD. Return true if the token is not a valid on-off-switch.
1847 bool LexOnOffSwitch(tok::OnOffSwitch &OOS);
1848
1849 bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
1850 bool *ShadowFlag = nullptr);
1851
1852 void EnterSubmodule(Module *M, SourceLocation ImportLoc, bool ForPragma);
1853 Module *LeaveSubmodule(bool ForPragma);
1854
1855private:
1856 friend void TokenLexer::ExpandFunctionArguments();
1857
1858 void PushIncludeMacroStack() {
1859 assert(CurLexerKind != CLK_CachingLexer && "cannot push a caching lexer")(static_cast <bool> (CurLexerKind != CLK_CachingLexer &&
"cannot push a caching lexer") ? void (0) : __assert_fail ("CurLexerKind != CLK_CachingLexer && \"cannot push a caching lexer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 1859, __extension__ __PRETTY_FUNCTION__))
;
1860 IncludeMacroStack.emplace_back(CurLexerKind, CurLexerSubmodule,
1861 std::move(CurLexer), std::move(CurPTHLexer),
1862 CurPPLexer, std::move(CurTokenLexer),
1863 CurDirLookup);
1864 CurPPLexer = nullptr;
1865 }
1866
1867 void PopIncludeMacroStack() {
1868 CurLexer = std::move(IncludeMacroStack.back().TheLexer);
1869 CurPTHLexer = std::move(IncludeMacroStack.back().ThePTHLexer);
1870 CurPPLexer = IncludeMacroStack.back().ThePPLexer;
1871 CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer);
1872 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
1873 CurLexerSubmodule = IncludeMacroStack.back().TheSubmodule;
1874 CurLexerKind = IncludeMacroStack.back().CurLexerKind;
1875 IncludeMacroStack.pop_back();
1876 }
1877
1878 void PropagateLineStartLeadingSpaceInfo(Token &Result);
1879
1880 /// Determine whether we need to create module macros for #defines in the
1881 /// current context.
1882 bool needModuleMacros() const;
1883
1884 /// Update the set of active module macros and ambiguity flag for a module
1885 /// macro name.
1886 void updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info);
1887
1888 DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI,
1889 SourceLocation Loc);
1890 UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc);
1891 VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc,
1892 bool isPublic);
1893
1894 /// \brief Lex and validate a macro name, which occurs after a
1895 /// \#define or \#undef.
1896 ///
1897 /// \param MacroNameTok Token that represents the name defined or undefined.
1898 /// \param IsDefineUndef Kind if preprocessor directive.
1899 /// \param ShadowFlag Points to flag that is set if macro name shadows
1900 /// a keyword.
1901 ///
1902 /// This emits a diagnostic, sets the token kind to eod,
1903 /// and discards the rest of the macro line if the macro name is invalid.
1904 void ReadMacroName(Token &MacroNameTok, MacroUse IsDefineUndef = MU_Other,
1905 bool *ShadowFlag = nullptr);
1906
1907 /// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
1908 /// entire line) of the macro's tokens and adds them to MacroInfo, and while
1909 /// doing so performs certain validity checks including (but not limited to):
1910 /// - # (stringization) is followed by a macro parameter
1911 /// \param MacroNameTok - Token that represents the macro name
1912 /// \param ImmediatelyAfterHeaderGuard - Macro follows an #ifdef header guard
1913 ///
1914 /// Either returns a pointer to a MacroInfo object OR emits a diagnostic and
1915 /// returns a nullptr if an invalid sequence of tokens is encountered.
1916 MacroInfo *ReadOptionalMacroParameterListAndBody(
1917 const Token &MacroNameTok, bool ImmediatelyAfterHeaderGuard);
1918
1919 /// The ( starting an argument list of a macro definition has just been read.
1920 /// Lex the rest of the parameters and the closing ), updating \p MI with
1921 /// what we learn and saving in \p LastTok the last token read.
1922 /// Return true if an error occurs parsing the arg list.
1923 bool ReadMacroParameterList(MacroInfo *MI, Token& LastTok);
1924
1925 /// We just read a \#if or related directive and decided that the
1926 /// subsequent tokens are in the \#if'd out portion of the
1927 /// file. Lex the rest of the file, until we see an \#endif. If \p
1928 /// FoundNonSkipPortion is true, then we have already emitted code for part of
1929 /// this \#if directive, so \#else/\#elif blocks should never be entered. If
1930 /// \p FoundElse is false, then \#else directives are ok, if not, then we have
1931 /// already seen one so a \#else directive is a duplicate. When this returns,
1932 /// the caller can lex the first valid token.
1933 void SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
1934 SourceLocation IfTokenLoc,
1935 bool FoundNonSkipPortion, bool FoundElse,
1936 SourceLocation ElseLoc = SourceLocation());
1937
1938 /// \brief A fast PTH version of SkipExcludedConditionalBlock.
1939 void PTHSkipExcludedConditionalBlock();
1940
1941 /// Information about the result for evaluating an expression for a
1942 /// preprocessor directive.
1943 struct DirectiveEvalResult {
1944 /// Whether the expression was evaluated as true or not.
1945 bool Conditional;
1946
1947 /// True if the expression contained identifiers that were undefined.
1948 bool IncludedUndefinedIds;
1949 };
1950
1951 /// \brief Evaluate an integer constant expression that may occur after a
1952 /// \#if or \#elif directive and return a \p DirectiveEvalResult object.
1953 ///
1954 /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro.
1955 DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
1956
1957 /// \brief Install the standard preprocessor pragmas:
1958 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1959 void RegisterBuiltinPragmas();
1960
1961 /// \brief Register builtin macros such as __LINE__ with the identifier table.
1962 void RegisterBuiltinMacros();
1963
1964 /// If an identifier token is read that is to be expanded as a macro, handle
1965 /// it and return the next token as 'Tok'. If we lexed a token, return true;
1966 /// otherwise the caller should lex again.
1967 bool HandleMacroExpandedIdentifier(Token &Tok, const MacroDefinition &MD);
1968
1969 /// \brief Cache macro expanded tokens for TokenLexers.
1970 //
1971 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1972 /// going to lex in the cache and when it finishes the tokens are removed
1973 /// from the end of the cache.
1974 Token *cacheMacroExpandedTokens(TokenLexer *tokLexer,
1975 ArrayRef<Token> tokens);
1976
1977 void removeCachedMacroExpandedTokensOfLastLexer();
1978
1979 /// Determine whether the next preprocessor token to be
1980 /// lexed is a '('. If so, consume the token and return true, if not, this
1981 /// method should have no observable side-effect on the lexed tokens.
1982 bool isNextPPTokenLParen();
1983
1984 /// After reading "MACRO(", this method is invoked to read all of the formal
1985 /// arguments specified for the macro invocation. Returns null on error.
1986 MacroArgs *ReadMacroCallArgumentList(Token &MacroName, MacroInfo *MI,
1987 SourceLocation &ExpansionEnd);
1988
1989 /// \brief If an identifier token is read that is to be expanded
1990 /// as a builtin macro, handle it and return the next token as 'Tok'.
1991 void ExpandBuiltinMacro(Token &Tok);
1992
1993 /// \brief Read a \c _Pragma directive, slice it up, process it, then
1994 /// return the first token after the directive.
1995 /// This assumes that the \c _Pragma token has just been read into \p Tok.
1996 void Handle_Pragma(Token &Tok);
1997
1998 /// \brief Like Handle_Pragma except the pragma text is not enclosed within
1999 /// a string literal.
2000 void HandleMicrosoft__pragma(Token &Tok);
2001
2002 /// \brief Add a lexer to the top of the include stack and
2003 /// start lexing tokens from it instead of the current buffer.
2004 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
2005
2006 /// \brief Add a lexer to the top of the include stack and
2007 /// start getting tokens from it using the PTH cache.
2008 void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir);
2009
2010 /// \brief Set the FileID for the preprocessor predefines.
2011 void setPredefinesFileID(FileID FID) {
2012 assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!")(static_cast <bool> (PredefinesFileID.isInvalid() &&
"PredefinesFileID already set!") ? void (0) : __assert_fail (
"PredefinesFileID.isInvalid() && \"PredefinesFileID already set!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Lex/Preprocessor.h"
, 2012, __extension__ __PRETTY_FUNCTION__))
;
2013 PredefinesFileID = FID;
2014 }
2015
2016 /// \brief Returns true if we are lexing from a file and not a
2017 /// pragma or a macro.
2018 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
2019 return L ? !L->isPragmaLexer() : P != nullptr;
2020 }
2021
2022 static bool IsFileLexer(const IncludeStackInfo& I) {
2023 return IsFileLexer(I.TheLexer.get(), I.ThePPLexer);
2024 }
2025
2026 bool IsFileLexer() const {
2027 return IsFileLexer(CurLexer.get(), CurPPLexer);
2028 }
2029
2030 //===--------------------------------------------------------------------===//
2031 // Caching stuff.
2032 void CachingLex(Token &Result);
2033
2034 bool InCachingLexMode() const {
2035 // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means
2036 // that we are past EOF, not that we are in CachingLex mode.
2037 return !CurPPLexer && !CurTokenLexer && !CurPTHLexer &&
2038 !IncludeMacroStack.empty();
2039 }
2040
2041 void EnterCachingLexMode();
2042
2043 void ExitCachingLexMode() {
2044 if (InCachingLexMode())
2045 RemoveTopOfLexerStack();
2046 }
2047
2048 const Token &PeekAhead(unsigned N);
2049 void AnnotatePreviousCachedTokens(const Token &Tok);
2050
2051 //===--------------------------------------------------------------------===//
2052 /// Handle*Directive - implement the various preprocessor directives. These
2053 /// should side-effect the current preprocessor object so that the next call
2054 /// to Lex() will return the appropriate token next.
2055 void HandleLineDirective();
2056 void HandleDigitDirective(Token &Tok);
2057 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
2058 void HandleIdentSCCSDirective(Token &Tok);
2059 void HandleMacroPublicDirective(Token &Tok);
2060 void HandleMacroPrivateDirective();
2061
2062 // File inclusion.
2063 void HandleIncludeDirective(SourceLocation HashLoc,
2064 Token &Tok,
2065 const DirectoryLookup *LookupFrom = nullptr,
2066 const FileEntry *LookupFromFile = nullptr,
2067 bool isImport = false);
2068 void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok);
2069 void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok);
2070 void HandleImportDirective(SourceLocation HashLoc, Token &Tok);
2071 void HandleMicrosoftImportDirective(Token &Tok);
2072
2073public:
2074 /// Check that the given module is available, producing a diagnostic if not.
2075 /// \return \c true if the check failed (because the module is not available).
2076 /// \c false if the module appears to be usable.
2077 static bool checkModuleIsAvailable(const LangOptions &LangOpts,
2078 const TargetInfo &TargetInfo,
2079 DiagnosticsEngine &Diags, Module *M);
2080
2081 // Module inclusion testing.
2082 /// \brief Find the module that owns the source or header file that
2083 /// \p Loc points to. If the location is in a file that was included
2084 /// into a module, or is outside any module, returns nullptr.
2085 Module *getModuleForLocation(SourceLocation Loc);
2086
2087 /// \brief We want to produce a diagnostic at location IncLoc concerning a
2088 /// missing module import.
2089 ///
2090 /// \param IncLoc The location at which the missing import was detected.
2091 /// \param M The desired module.
2092 /// \param MLoc A location within the desired module at which some desired
2093 /// effect occurred (eg, where a desired entity was declared).
2094 ///
2095 /// \return A file that can be #included to import a module containing MLoc.
2096 /// Null if no such file could be determined or if a #include is not
2097 /// appropriate.
2098 const FileEntry *getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
2099 Module *M,
2100 SourceLocation MLoc);
2101
2102 bool isRecordingPreamble() const {
2103 return PreambleConditionalStack.isRecording();
2104 }
2105
2106 bool hasRecordedPreamble() const {
2107 return PreambleConditionalStack.hasRecordedPreamble();
2108 }
2109
2110 ArrayRef<PPConditionalInfo> getPreambleConditionalStack() const {
2111 return PreambleConditionalStack.getStack();
2112 }
2113
2114 void setRecordedPreambleConditionalStack(ArrayRef<PPConditionalInfo> s) {
2115 PreambleConditionalStack.setStack(s);
2116 }
2117
2118 void setReplayablePreambleConditionalStack(ArrayRef<PPConditionalInfo> s,
2119 llvm::Optional<PreambleSkipInfo> SkipInfo) {
2120 PreambleConditionalStack.startReplaying();
2121 PreambleConditionalStack.setStack(s);
2122 PreambleConditionalStack.SkipInfo = SkipInfo;
2123 }
2124
2125 llvm::Optional<PreambleSkipInfo> getPreambleSkipInfo() const {
2126 return PreambleConditionalStack.SkipInfo;
2127 }
2128
2129private:
2130 /// \brief After processing predefined file, initialize the conditional stack from
2131 /// the preamble.
2132 void replayPreambleConditionalStack();
2133
2134 // Macro handling.
2135 void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterTopLevelIfndef);
2136 void HandleUndefDirective();
2137
2138 // Conditional Inclusion.
2139 void HandleIfdefDirective(Token &Tok, const Token &HashToken,
2140 bool isIfndef, bool ReadAnyTokensBeforeDirective);
2141 void HandleIfDirective(Token &Tok, const Token &HashToken,
2142 bool ReadAnyTokensBeforeDirective);
2143 void HandleEndifDirective(Token &Tok);
2144 void HandleElseDirective(Token &Tok, const Token &HashToken);
2145 void HandleElifDirective(Token &Tok, const Token &HashToken);
2146
2147 // Pragmas.
2148 void HandlePragmaDirective(SourceLocation IntroducerLoc,
2149 PragmaIntroducerKind Introducer);
2150
2151public:
2152 void HandlePragmaOnce(Token &OnceTok);
2153 void HandlePragmaMark();
2154 void HandlePragmaPoison();
2155 void HandlePragmaSystemHeader(Token &SysHeaderTok);
2156 void HandlePragmaDependency(Token &DependencyTok);
2157 void HandlePragmaPushMacro(Token &Tok);
2158 void HandlePragmaPopMacro(Token &Tok);
2159 void HandlePragmaIncludeAlias(Token &Tok);
2160 void HandlePragmaModuleBuild(Token &Tok);
2161 IdentifierInfo *ParsePragmaPushOrPopMacro(Token &Tok);
2162
2163 // Return true and store the first token only if any CommentHandler
2164 // has inserted some tokens and getCommentRetentionState() is false.
2165 bool HandleComment(Token &Token, SourceRange Comment);
2166
2167 /// \brief A macro is used, update information about macros that need unused
2168 /// warnings.
2169 void markMacroAsUsed(MacroInfo *MI);
2170};
2171
2172/// \brief Abstract base class that describes a handler that will receive
2173/// source ranges for each of the comments encountered in the source file.
2174class CommentHandler {
2175public:
2176 virtual ~CommentHandler();
2177
2178 // The handler shall return true if it has pushed any tokens
2179 // to be read using e.g. EnterToken or EnterTokenStream.
2180 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
2181};
2182
2183/// \brief Registry of pragma handlers added by plugins
2184using PragmaHandlerRegistry = llvm::Registry<PragmaHandler>;
2185
2186} // namespace clang
2187
2188#endif // LLVM_CLANG_LEX_PREPROCESSOR_H