/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/Lex/Preprocessor.h
Line | Count | Source (jump to first uncovered line) |
1 | | //===- Preprocessor.h - C Language Family Preprocessor ----------*- C++ -*-===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | /// \file |
10 | | /// Defines the clang::Preprocessor interface. |
11 | | // |
12 | | //===----------------------------------------------------------------------===// |
13 | | |
14 | | #ifndef LLVM_CLANG_LEX_PREPROCESSOR_H |
15 | | #define LLVM_CLANG_LEX_PREPROCESSOR_H |
16 | | |
17 | | #include "clang/Basic/Diagnostic.h" |
18 | | #include "clang/Basic/DiagnosticIDs.h" |
19 | | #include "clang/Basic/IdentifierTable.h" |
20 | | #include "clang/Basic/LLVM.h" |
21 | | #include "clang/Basic/LangOptions.h" |
22 | | #include "clang/Basic/Module.h" |
23 | | #include "clang/Basic/SourceLocation.h" |
24 | | #include "clang/Basic/SourceManager.h" |
25 | | #include "clang/Basic/TokenKinds.h" |
26 | | #include "clang/Lex/HeaderSearch.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/PreprocessorExcludedConditionalDirectiveSkipMapping.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/FunctionExtras.h" |
39 | | #include "llvm/ADT/None.h" |
40 | | #include "llvm/ADT/Optional.h" |
41 | | #include "llvm/ADT/PointerUnion.h" |
42 | | #include "llvm/ADT/STLExtras.h" |
43 | | #include "llvm/ADT/SmallPtrSet.h" |
44 | | #include "llvm/ADT/SmallVector.h" |
45 | | #include "llvm/ADT/StringRef.h" |
46 | | #include "llvm/ADT/TinyPtrVector.h" |
47 | | #include "llvm/ADT/iterator_range.h" |
48 | | #include "llvm/Support/Allocator.h" |
49 | | #include "llvm/Support/Casting.h" |
50 | | #include "llvm/Support/Registry.h" |
51 | | #include <cassert> |
52 | | #include <cstddef> |
53 | | #include <cstdint> |
54 | | #include <map> |
55 | | #include <memory> |
56 | | #include <string> |
57 | | #include <utility> |
58 | | #include <vector> |
59 | | |
60 | | namespace llvm { |
61 | | |
62 | | template<unsigned InternalLen> class SmallString; |
63 | | |
64 | | } // namespace llvm |
65 | | |
66 | | namespace clang { |
67 | | |
68 | | class CodeCompletionHandler; |
69 | | class CommentHandler; |
70 | | class DirectoryEntry; |
71 | | class DirectoryLookup; |
72 | | class EmptylineHandler; |
73 | | class ExternalPreprocessorSource; |
74 | | class FileEntry; |
75 | | class FileManager; |
76 | | class HeaderSearch; |
77 | | class MacroArgs; |
78 | | class PragmaHandler; |
79 | | class PragmaNamespace; |
80 | | class PreprocessingRecord; |
81 | | class PreprocessorLexer; |
82 | | class PreprocessorOptions; |
83 | | class ScratchBuffer; |
84 | | class TargetInfo; |
85 | | |
86 | | namespace Builtin { |
87 | | class Context; |
88 | | } |
89 | | |
90 | | /// Stores token information for comparing actual tokens with |
91 | | /// predefined values. Only handles simple tokens and identifiers. |
92 | | class TokenValue { |
93 | | tok::TokenKind Kind; |
94 | | IdentifierInfo *II; |
95 | | |
96 | | public: |
97 | 1.36k | TokenValue(tok::TokenKind Kind) : Kind(Kind), II(nullptr) { |
98 | 1.36k | assert(Kind != tok::raw_identifier && "Raw identifiers are not supported."); |
99 | 0 | assert(Kind != tok::identifier && |
100 | 1.36k | "Identifiers should be created by TokenValue(IdentifierInfo *)"); |
101 | 0 | assert(!tok::isLiteral(Kind) && "Literals are not supported."); |
102 | 0 | assert(!tok::isAnnotation(Kind) && "Annotations are not supported."); |
103 | 1.36k | } |
104 | | |
105 | 385 | TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {} |
106 | | |
107 | 13.5k | bool operator==(const Token &Tok) const { |
108 | 13.5k | return Tok.getKind() == Kind && |
109 | 13.5k | (924 !II924 || II == Tok.getIdentifierInfo()221 ); |
110 | 13.5k | } |
111 | | }; |
112 | | |
113 | | /// Context in which macro name is used. |
114 | | enum MacroUse { |
115 | | // other than #define or #undef |
116 | | MU_Other = 0, |
117 | | |
118 | | // macro name specified in #define |
119 | | MU_Define = 1, |
120 | | |
121 | | // macro name specified in #undef |
122 | | MU_Undef = 2 |
123 | | }; |
124 | | |
125 | | /// Engages in a tight little dance with the lexer to efficiently |
126 | | /// preprocess tokens. |
127 | | /// |
128 | | /// Lexers know only about tokens within a single source file, and don't |
129 | | /// know anything about preprocessor-level issues like the \#include stack, |
130 | | /// token expansion, etc. |
131 | | class Preprocessor { |
132 | | friend class VAOptDefinitionContext; |
133 | | friend class VariadicMacroScopeGuard; |
134 | | |
135 | | llvm::unique_function<void(const clang::Token &)> OnToken; |
136 | | std::shared_ptr<PreprocessorOptions> PPOpts; |
137 | | DiagnosticsEngine *Diags; |
138 | | LangOptions &LangOpts; |
139 | | const TargetInfo *Target = nullptr; |
140 | | const TargetInfo *AuxTarget = nullptr; |
141 | | FileManager &FileMgr; |
142 | | SourceManager &SourceMgr; |
143 | | std::unique_ptr<ScratchBuffer> ScratchBuf; |
144 | | HeaderSearch &HeaderInfo; |
145 | | ModuleLoader &TheModuleLoader; |
146 | | |
147 | | /// External source of macros. |
148 | | ExternalPreprocessorSource *ExternalSource; |
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__FILE_NAME__; // __FILE_NAME__ |
160 | | IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__ |
161 | | IdentifierInfo *Ident__COUNTER__; // __COUNTER__ |
162 | | IdentifierInfo *Ident_Pragma, *Ident__pragma; // _Pragma, __pragma |
163 | | IdentifierInfo *Ident__identifier; // __identifier |
164 | | IdentifierInfo *Ident__VA_ARGS__; // __VA_ARGS__ |
165 | | IdentifierInfo *Ident__VA_OPT__; // __VA_OPT__ |
166 | | IdentifierInfo *Ident__has_feature; // __has_feature |
167 | | IdentifierInfo *Ident__has_extension; // __has_extension |
168 | | IdentifierInfo *Ident__has_builtin; // __has_builtin |
169 | | IdentifierInfo *Ident__has_attribute; // __has_attribute |
170 | | IdentifierInfo *Ident__has_include; // __has_include |
171 | | IdentifierInfo *Ident__has_include_next; // __has_include_next |
172 | | IdentifierInfo *Ident__has_warning; // __has_warning |
173 | | IdentifierInfo *Ident__is_identifier; // __is_identifier |
174 | | IdentifierInfo *Ident__building_module; // __building_module |
175 | | IdentifierInfo *Ident__MODULE__; // __MODULE__ |
176 | | IdentifierInfo *Ident__has_cpp_attribute; // __has_cpp_attribute |
177 | | IdentifierInfo *Ident__has_c_attribute; // __has_c_attribute |
178 | | IdentifierInfo *Ident__has_declspec; // __has_declspec_attribute |
179 | | IdentifierInfo *Ident__is_target_arch; // __is_target_arch |
180 | | IdentifierInfo *Ident__is_target_vendor; // __is_target_vendor |
181 | | IdentifierInfo *Ident__is_target_os; // __is_target_os |
182 | | IdentifierInfo *Ident__is_target_environment; // __is_target_environment |
183 | | IdentifierInfo *Ident__FLT_EVAL_METHOD__; // __FLT_EVAL_METHOD |
184 | | |
185 | | // Weak, only valid (and set) while InMacroArgs is true. |
186 | | Token* ArgMacro; |
187 | | |
188 | | SourceLocation DATELoc, TIMELoc; |
189 | | |
190 | | // FEM_UnsetOnCommandLine means that an explicit evaluation method was |
191 | | // not specified on the command line. The target is queried to set the |
192 | | // default evaluation method. |
193 | | LangOptions::FPEvalMethodKind CurrentFPEvalMethod = |
194 | | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine; |
195 | | |
196 | | // Keeps the value of the last evaluation method before a |
197 | | // `pragma float_control (precise,off) is applied. |
198 | | LangOptions::FPEvalMethodKind LastFPEvalMethod = |
199 | | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine; |
200 | | |
201 | | // The most recent pragma location where the floating point evaluation |
202 | | // method was modified. This is used to determine whether the |
203 | | // 'pragma clang fp eval_method' was used whithin the current scope. |
204 | | SourceLocation LastFPEvalPragmaLocation; |
205 | | |
206 | | LangOptions::FPEvalMethodKind TUFPEvalMethod = |
207 | | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine; |
208 | | |
209 | | // Next __COUNTER__ value, starts at 0. |
210 | | unsigned CounterValue = 0; |
211 | | |
212 | | enum { |
213 | | /// Maximum depth of \#includes. |
214 | | MaxAllowedIncludeStackDepth = 200 |
215 | | }; |
216 | | |
217 | | // State that is set before the preprocessor begins. |
218 | | bool KeepComments : 1; |
219 | | bool KeepMacroComments : 1; |
220 | | bool SuppressIncludeNotFoundError : 1; |
221 | | |
222 | | // State that changes while the preprocessor runs: |
223 | | bool InMacroArgs : 1; // True if parsing fn macro invocation args. |
224 | | |
225 | | /// Whether the preprocessor owns the header search object. |
226 | | bool OwnsHeaderSearch : 1; |
227 | | |
228 | | /// True if macro expansion is disabled. |
229 | | bool DisableMacroExpansion : 1; |
230 | | |
231 | | /// Temporarily disables DisableMacroExpansion (i.e. enables expansion) |
232 | | /// when parsing preprocessor directives. |
233 | | bool MacroExpansionInDirectivesOverride : 1; |
234 | | |
235 | | class ResetMacroExpansionHelper; |
236 | | |
237 | | /// Whether we have already loaded macros from the external source. |
238 | | mutable bool ReadMacrosFromExternalSource : 1; |
239 | | |
240 | | /// True if pragmas are enabled. |
241 | | bool PragmasEnabled : 1; |
242 | | |
243 | | /// True if the current build action is a preprocessing action. |
244 | | bool PreprocessedOutput : 1; |
245 | | |
246 | | /// True if we are currently preprocessing a #if or #elif directive |
247 | | bool ParsingIfOrElifDirective; |
248 | | |
249 | | /// True if we are pre-expanding macro arguments. |
250 | | bool InMacroArgPreExpansion; |
251 | | |
252 | | /// Mapping/lookup information for all identifiers in |
253 | | /// the program, including program keywords. |
254 | | mutable IdentifierTable Identifiers; |
255 | | |
256 | | /// This table contains all the selectors in the program. |
257 | | /// |
258 | | /// Unlike IdentifierTable above, this table *isn't* populated by the |
259 | | /// preprocessor. It is declared/expanded here because its role/lifetime is |
260 | | /// conceptually similar to the IdentifierTable. In addition, the current |
261 | | /// control flow (in clang::ParseAST()), make it convenient to put here. |
262 | | /// |
263 | | /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to |
264 | | /// the lifetime of the preprocessor. |
265 | | SelectorTable Selectors; |
266 | | |
267 | | /// Information about builtins. |
268 | | std::unique_ptr<Builtin::Context> BuiltinInfo; |
269 | | |
270 | | /// Tracks all of the pragmas that the client registered |
271 | | /// with this preprocessor. |
272 | | std::unique_ptr<PragmaNamespace> PragmaHandlers; |
273 | | |
274 | | /// Pragma handlers of the original source is stored here during the |
275 | | /// parsing of a model file. |
276 | | std::unique_ptr<PragmaNamespace> PragmaHandlersBackup; |
277 | | |
278 | | /// Tracks all of the comment handlers that the client registered |
279 | | /// with this preprocessor. |
280 | | std::vector<CommentHandler *> CommentHandlers; |
281 | | |
282 | | /// Empty line handler. |
283 | | EmptylineHandler *Emptyline = nullptr; |
284 | | |
285 | | /// True if we want to ignore EOF token and continue later on (thus |
286 | | /// avoid tearing the Lexer and etc. down). |
287 | | bool IncrementalProcessing = false; |
288 | | |
289 | | public: |
290 | | /// The kind of translation unit we are processing. |
291 | | const TranslationUnitKind TUKind; |
292 | | |
293 | | private: |
294 | | /// The code-completion handler. |
295 | | CodeCompletionHandler *CodeComplete = nullptr; |
296 | | |
297 | | /// The file that we're performing code-completion for, if any. |
298 | | const FileEntry *CodeCompletionFile = nullptr; |
299 | | |
300 | | /// The offset in file for the code-completion point. |
301 | | unsigned CodeCompletionOffset = 0; |
302 | | |
303 | | /// The location for the code-completion point. This gets instantiated |
304 | | /// when the CodeCompletionFile gets \#include'ed for preprocessing. |
305 | | SourceLocation CodeCompletionLoc; |
306 | | |
307 | | /// The start location for the file of the code-completion point. |
308 | | /// |
309 | | /// This gets instantiated when the CodeCompletionFile gets \#include'ed |
310 | | /// for preprocessing. |
311 | | SourceLocation CodeCompletionFileLoc; |
312 | | |
313 | | /// The source location of the \c import contextual keyword we just |
314 | | /// lexed, if any. |
315 | | SourceLocation ModuleImportLoc; |
316 | | |
317 | | /// The module import path that we're currently processing. |
318 | | SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> ModuleImportPath; |
319 | | |
320 | | /// Whether the last token we lexed was an '@'. |
321 | | bool LastTokenWasAt = false; |
322 | | |
323 | | /// A position within a C++20 import-seq. |
324 | | class ImportSeq { |
325 | | public: |
326 | | enum State : int { |
327 | | // Positive values represent a number of unclosed brackets. |
328 | | AtTopLevel = 0, |
329 | | AfterTopLevelTokenSeq = -1, |
330 | | AfterExport = -2, |
331 | | AfterImportSeq = -3, |
332 | | }; |
333 | | |
334 | 89.3k | ImportSeq(State S) : S(S) {} |
335 | | |
336 | | /// Saw any kind of open bracket. |
337 | 118k | void handleOpenBracket() { |
338 | 118k | S = static_cast<State>(std::max<int>(S, 0) + 1); |
339 | 118k | } |
340 | | /// Saw any kind of close bracket other than '}'. |
341 | 118k | void handleCloseBracket() { |
342 | 118k | S = static_cast<State>(std::max<int>(S, 1) - 1); |
343 | 118k | } |
344 | | /// Saw a close brace. |
345 | 27.5k | void handleCloseBrace() { |
346 | 27.5k | handleCloseBracket(); |
347 | 27.5k | if (S == AtTopLevel && !AfterHeaderName10.3k ) |
348 | 10.3k | S = AfterTopLevelTokenSeq; |
349 | 27.5k | } |
350 | | /// Saw a semicolon. |
351 | 62.6k | void handleSemi() { |
352 | 62.6k | if (atTopLevel()) { |
353 | 9.19k | S = AfterTopLevelTokenSeq; |
354 | 9.19k | AfterHeaderName = false; |
355 | 9.19k | } |
356 | 62.6k | } |
357 | | |
358 | | /// Saw an 'export' identifier. |
359 | 306 | void handleExport() { |
360 | 306 | if (S == AfterTopLevelTokenSeq) |
361 | 272 | S = AfterExport; |
362 | 34 | else if (S <= 0) |
363 | 3 | S = AtTopLevel; |
364 | 306 | } |
365 | | /// Saw an 'import' identifier. |
366 | 131 | void handleImport() { |
367 | 131 | if (S == AfterTopLevelTokenSeq || S == AfterExport36 ) |
368 | 113 | S = AfterImportSeq; |
369 | 18 | else if (S <= 0) |
370 | 13 | S = AtTopLevel; |
371 | 131 | } |
372 | | |
373 | | /// Saw a 'header-name' token; do not recognize any more 'import' tokens |
374 | | /// until we reach a top-level semicolon. |
375 | 42 | void handleHeaderName() { |
376 | 42 | if (S == AfterImportSeq) |
377 | 42 | AfterHeaderName = true; |
378 | 42 | handleMisc(); |
379 | 42 | } |
380 | | |
381 | | /// Saw any other token. |
382 | 485k | void handleMisc() { |
383 | 485k | if (S <= 0) |
384 | 60.2k | S = AtTopLevel; |
385 | 485k | } |
386 | | |
387 | 62.6k | bool atTopLevel() { return S <= 0; } |
388 | 131 | bool afterImportSeq() { return S == AfterImportSeq; } |
389 | | |
390 | | private: |
391 | | State S; |
392 | | /// Whether we're in the pp-import-suffix following the header-name in a |
393 | | /// pp-import. If so, a close-brace is not sufficient to end the |
394 | | /// top-level-token-seq of an import-seq. |
395 | | bool AfterHeaderName = false; |
396 | | }; |
397 | | |
398 | | /// Our current position within a C++20 import-seq. |
399 | | ImportSeq ImportSeqState = ImportSeq::AfterTopLevelTokenSeq; |
400 | | |
401 | | /// Whether the module import expects an identifier next. Otherwise, |
402 | | /// it expects a '.' or ';'. |
403 | | bool ModuleImportExpectsIdentifier = false; |
404 | | |
405 | | /// The identifier and source location of the currently-active |
406 | | /// \#pragma clang arc_cf_code_audited begin. |
407 | | std::pair<IdentifierInfo *, SourceLocation> PragmaARCCFCodeAuditedInfo; |
408 | | |
409 | | /// The source location of the currently-active |
410 | | /// \#pragma clang assume_nonnull begin. |
411 | | SourceLocation PragmaAssumeNonNullLoc; |
412 | | |
413 | | /// Set only for preambles which end with an active |
414 | | /// \#pragma clang assume_nonnull begin. |
415 | | /// |
416 | | /// When the preamble is loaded into the main file, |
417 | | /// `PragmaAssumeNonNullLoc` will be set to this to |
418 | | /// replay the unterminated assume_nonnull. |
419 | | SourceLocation PreambleRecordedPragmaAssumeNonNullLoc; |
420 | | |
421 | | /// True if we hit the code-completion point. |
422 | | bool CodeCompletionReached = false; |
423 | | |
424 | | /// The code completion token containing the information |
425 | | /// on the stem that is to be code completed. |
426 | | IdentifierInfo *CodeCompletionII = nullptr; |
427 | | |
428 | | /// Range for the code completion token. |
429 | | SourceRange CodeCompletionTokenRange; |
430 | | |
431 | | /// The directory that the main file should be considered to occupy, |
432 | | /// if it does not correspond to a real file (as happens when building a |
433 | | /// module). |
434 | | const DirectoryEntry *MainFileDir = nullptr; |
435 | | |
436 | | /// The number of bytes that we will initially skip when entering the |
437 | | /// main file, along with a flag that indicates whether skipping this number |
438 | | /// of bytes will place the lexer at the start of a line. |
439 | | /// |
440 | | /// This is used when loading a precompiled preamble. |
441 | | std::pair<int, bool> SkipMainFilePreamble; |
442 | | |
443 | | /// Whether we hit an error due to reaching max allowed include depth. Allows |
444 | | /// to avoid hitting the same error over and over again. |
445 | | bool HasReachedMaxIncludeDepth = false; |
446 | | |
447 | | /// The number of currently-active calls to Lex. |
448 | | /// |
449 | | /// Lex is reentrant, and asking for an (end-of-phase-4) token can often |
450 | | /// require asking for multiple additional tokens. This counter makes it |
451 | | /// possible for Lex to detect whether it's producing a token for the end |
452 | | /// of phase 4 of translation or for some other situation. |
453 | | unsigned LexLevel = 0; |
454 | | |
455 | | /// The number of (LexLevel 0) preprocessor tokens. |
456 | | unsigned TokenCount = 0; |
457 | | |
458 | | /// Preprocess every token regardless of LexLevel. |
459 | | bool PreprocessToken = false; |
460 | | |
461 | | /// The maximum number of (LexLevel 0) tokens before issuing a -Wmax-tokens |
462 | | /// warning, or zero for unlimited. |
463 | | unsigned MaxTokens = 0; |
464 | | SourceLocation MaxTokensOverrideLoc; |
465 | | |
466 | | public: |
467 | | struct PreambleSkipInfo { |
468 | | SourceLocation HashTokenLoc; |
469 | | SourceLocation IfTokenLoc; |
470 | | bool FoundNonSkipPortion; |
471 | | bool FoundElse; |
472 | | SourceLocation ElseLoc; |
473 | | |
474 | | PreambleSkipInfo(SourceLocation HashTokenLoc, SourceLocation IfTokenLoc, |
475 | | bool FoundNonSkipPortion, bool FoundElse, |
476 | | SourceLocation ElseLoc) |
477 | | : HashTokenLoc(HashTokenLoc), IfTokenLoc(IfTokenLoc), |
478 | | FoundNonSkipPortion(FoundNonSkipPortion), FoundElse(FoundElse), |
479 | 23 | ElseLoc(ElseLoc) {} |
480 | | }; |
481 | | |
482 | | using IncludedFilesSet = llvm::DenseSet<const FileEntry *>; |
483 | | |
484 | | private: |
485 | | friend class ASTReader; |
486 | | friend class MacroArgs; |
487 | | |
488 | | class PreambleConditionalStackStore { |
489 | | enum State { |
490 | | Off = 0, |
491 | | Recording = 1, |
492 | | Replaying = 2, |
493 | | }; |
494 | | |
495 | | public: |
496 | 89.3k | PreambleConditionalStackStore() = default; |
497 | | |
498 | 92 | void startRecording() { ConditionalStackState = Recording; } |
499 | 28 | void startReplaying() { ConditionalStackState = Replaying; } |
500 | 1.78M | bool isRecording() const { return ConditionalStackState == Recording; } |
501 | 89.0k | bool isReplaying() const { return ConditionalStackState == Replaying; } |
502 | | |
503 | 35 | ArrayRef<PPConditionalInfo> getStack() const { |
504 | 35 | return ConditionalStack; |
505 | 35 | } |
506 | | |
507 | 28 | void doneReplaying() { |
508 | 28 | ConditionalStack.clear(); |
509 | 28 | ConditionalStackState = Off; |
510 | 28 | } |
511 | | |
512 | 120 | void setStack(ArrayRef<PPConditionalInfo> s) { |
513 | 120 | if (!isRecording() && !isReplaying()28 ) |
514 | 0 | return; |
515 | 120 | ConditionalStack.clear(); |
516 | 120 | ConditionalStack.append(s.begin(), s.end()); |
517 | 120 | } |
518 | | |
519 | 92 | bool hasRecordedPreamble() const { return !ConditionalStack.empty(); } |
520 | | |
521 | 2.81M | bool reachedEOFWhileSkipping() const { return SkipInfo.hasValue(); } |
522 | | |
523 | 18 | void clearSkipInfo() { SkipInfo.reset(); } |
524 | | |
525 | | llvm::Optional<PreambleSkipInfo> SkipInfo; |
526 | | |
527 | | private: |
528 | | SmallVector<PPConditionalInfo, 4> ConditionalStack; |
529 | | State ConditionalStackState = Off; |
530 | | } PreambleConditionalStack; |
531 | | |
532 | | /// The current top of the stack that we're lexing from if |
533 | | /// not expanding a macro and we are lexing directly from source code. |
534 | | /// |
535 | | /// Only one of CurLexer, or CurTokenLexer will be non-null. |
536 | | std::unique_ptr<Lexer> CurLexer; |
537 | | |
538 | | /// The current top of the stack what we're lexing from |
539 | | /// if not expanding a macro. |
540 | | /// |
541 | | /// This is an alias for CurLexer. |
542 | | PreprocessorLexer *CurPPLexer = nullptr; |
543 | | |
544 | | /// Used to find the current FileEntry, if CurLexer is non-null |
545 | | /// and if applicable. |
546 | | /// |
547 | | /// This allows us to implement \#include_next and find directory-specific |
548 | | /// properties. |
549 | | ConstSearchDirIterator CurDirLookup = nullptr; |
550 | | |
551 | | /// The current macro we are expanding, if we are expanding a macro. |
552 | | /// |
553 | | /// One of CurLexer and CurTokenLexer must be null. |
554 | | std::unique_ptr<TokenLexer> CurTokenLexer; |
555 | | |
556 | | /// The kind of lexer we're currently working with. |
557 | | enum CurLexerKind { |
558 | | CLK_Lexer, |
559 | | CLK_TokenLexer, |
560 | | CLK_CachingLexer, |
561 | | CLK_LexAfterModuleImport |
562 | | } CurLexerKind = CLK_Lexer; |
563 | | |
564 | | /// If the current lexer is for a submodule that is being built, this |
565 | | /// is that submodule. |
566 | | Module *CurLexerSubmodule = nullptr; |
567 | | |
568 | | /// Keeps track of the stack of files currently |
569 | | /// \#included, and macros currently being expanded from, not counting |
570 | | /// CurLexer/CurTokenLexer. |
571 | | struct IncludeStackInfo { |
572 | | enum CurLexerKind CurLexerKind; |
573 | | Module *TheSubmodule; |
574 | | std::unique_ptr<Lexer> TheLexer; |
575 | | PreprocessorLexer *ThePPLexer; |
576 | | std::unique_ptr<TokenLexer> TheTokenLexer; |
577 | | ConstSearchDirIterator TheDirLookup; |
578 | | |
579 | | // The following constructors are completely useless copies of the default |
580 | | // versions, only needed to pacify MSVC. |
581 | | IncludeStackInfo(enum CurLexerKind CurLexerKind, Module *TheSubmodule, |
582 | | std::unique_ptr<Lexer> &&TheLexer, |
583 | | PreprocessorLexer *ThePPLexer, |
584 | | std::unique_ptr<TokenLexer> &&TheTokenLexer, |
585 | | ConstSearchDirIterator TheDirLookup) |
586 | | : CurLexerKind(std::move(CurLexerKind)), |
587 | | TheSubmodule(std::move(TheSubmodule)), TheLexer(std::move(TheLexer)), |
588 | | ThePPLexer(std::move(ThePPLexer)), |
589 | | TheTokenLexer(std::move(TheTokenLexer)), |
590 | 174M | TheDirLookup(std::move(TheDirLookup)) {} |
591 | | }; |
592 | | std::vector<IncludeStackInfo> IncludeMacroStack; |
593 | | |
594 | | /// Actions invoked when some preprocessor activity is |
595 | | /// encountered (e.g. a file is \#included, etc). |
596 | | std::unique_ptr<PPCallbacks> Callbacks; |
597 | | |
598 | | struct MacroExpandsInfo { |
599 | | Token Tok; |
600 | | MacroDefinition MD; |
601 | | SourceRange Range; |
602 | | |
603 | | MacroExpandsInfo(Token Tok, MacroDefinition MD, SourceRange Range) |
604 | 6 | : Tok(Tok), MD(MD), Range(Range) {} |
605 | | }; |
606 | | SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks; |
607 | | |
608 | | /// Information about a name that has been used to define a module macro. |
609 | | struct ModuleMacroInfo { |
610 | | /// The most recent macro directive for this identifier. |
611 | | MacroDirective *MD; |
612 | | |
613 | | /// The active module macros for this identifier. |
614 | | llvm::TinyPtrVector<ModuleMacro *> ActiveModuleMacros; |
615 | | |
616 | | /// The generation number at which we last updated ActiveModuleMacros. |
617 | | /// \see Preprocessor::VisibleModules. |
618 | | unsigned ActiveModuleMacrosGeneration = 0; |
619 | | |
620 | | /// Whether this macro name is ambiguous. |
621 | | bool IsAmbiguous = false; |
622 | | |
623 | | /// The module macros that are overridden by this macro. |
624 | | llvm::TinyPtrVector<ModuleMacro *> OverriddenMacros; |
625 | | |
626 | 102k | ModuleMacroInfo(MacroDirective *MD) : MD(MD) {} |
627 | | }; |
628 | | |
629 | | /// The state of a macro for an identifier. |
630 | | class MacroState { |
631 | | mutable llvm::PointerUnion<MacroDirective *, ModuleMacroInfo *> State; |
632 | | |
633 | | ModuleMacroInfo *getModuleInfo(Preprocessor &PP, |
634 | 336M | const IdentifierInfo *II) const { |
635 | 336M | if (II->isOutOfDate()) |
636 | 1.06k | PP.updateOutOfDateIdentifier(const_cast<IdentifierInfo&>(*II)); |
637 | | // FIXME: Find a spare bit on IdentifierInfo and store a |
638 | | // HasModuleMacros flag. |
639 | 336M | if (!II->hasMacroDefinition() || |
640 | 336M | (291M !PP.getLangOpts().Modules291M && |
641 | 291M | !PP.getLangOpts().ModulesLocalVisibility283M ) || |
642 | 336M | !PP.CurSubmoduleState->VisibleModules.getGeneration()8.13M ) |
643 | 328M | return nullptr; |
644 | | |
645 | 8.02M | auto *Info = State.dyn_cast<ModuleMacroInfo*>(); |
646 | 8.02M | if (!Info) { |
647 | 102k | Info = new (PP.getPreprocessorAllocator()) |
648 | 102k | ModuleMacroInfo(State.get<MacroDirective *>()); |
649 | 102k | State = Info; |
650 | 102k | } |
651 | | |
652 | 8.02M | if (PP.CurSubmoduleState->VisibleModules.getGeneration() != |
653 | 8.02M | Info->ActiveModuleMacrosGeneration) |
654 | 359k | PP.updateModuleMacroInfo(II, *Info); |
655 | 8.02M | return Info; |
656 | 336M | } |
657 | | |
658 | | public: |
659 | 50.1M | MacroState() : MacroState(nullptr) {} Unexecuted instantiation: clang::Preprocessor::MacroState::MacroState() clang::Preprocessor::MacroState::MacroState() Line | Count | Source | 659 | 50.1M | MacroState() : MacroState(nullptr) {} |
|
660 | 50.3M | MacroState(MacroDirective *MD) : State(MD) {} |
661 | | |
662 | 81.3M | MacroState(MacroState &&O) noexcept : State(O.State) { |
663 | 81.3M | O.State = (MacroDirective *)nullptr; |
664 | 81.3M | } |
665 | | |
666 | 45.5k | MacroState &operator=(MacroState &&O) noexcept { |
667 | 45.5k | auto S = O.State; |
668 | 45.5k | O.State = (MacroDirective *)nullptr; |
669 | 45.5k | State = S; |
670 | 45.5k | return *this; |
671 | 45.5k | } |
672 | | |
673 | 124M | ~MacroState() { |
674 | 124M | if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) |
675 | 100k | Info->~ModuleMacroInfo(); |
676 | 124M | } |
677 | | |
678 | 195M | MacroDirective *getLatest() const { |
679 | 195M | if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) |
680 | 4.07M | return Info->MD; |
681 | 190M | return State.get<MacroDirective*>(); |
682 | 195M | } |
683 | | |
684 | 46.0M | void setLatest(MacroDirective *MD) { |
685 | 46.0M | if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) |
686 | 83.3k | Info->MD = MD; |
687 | 45.9M | else |
688 | 45.9M | State = MD; |
689 | 46.0M | } |
690 | | |
691 | 145M | bool isAmbiguous(Preprocessor &PP, const IdentifierInfo *II) const { |
692 | 145M | auto *Info = getModuleInfo(PP, II); |
693 | 145M | return Info ? Info->IsAmbiguous4.00M : false141M ; |
694 | 145M | } |
695 | | |
696 | | ArrayRef<ModuleMacro *> |
697 | 145M | getActiveModuleMacros(Preprocessor &PP, const IdentifierInfo *II) const { |
698 | 145M | if (auto *Info = getModuleInfo(PP, II)) |
699 | 4.00M | return Info->ActiveModuleMacros; |
700 | 141M | return None; |
701 | 145M | } |
702 | | |
703 | | MacroDirective::DefInfo findDirectiveAtLoc(SourceLocation Loc, |
704 | 123k | SourceManager &SourceMgr) const { |
705 | | // FIXME: Incorporate module macros into the result of this. |
706 | 123k | if (auto *Latest = getLatest()) |
707 | 123k | return Latest->findDirectiveAtLoc(Loc, SourceMgr); |
708 | 1 | return {}; |
709 | 123k | } |
710 | | |
711 | 45.7M | void overrideActiveModuleMacros(Preprocessor &PP, IdentifierInfo *II) { |
712 | 45.7M | if (auto *Info = getModuleInfo(PP, II)) { |
713 | 10.7k | Info->OverriddenMacros.insert(Info->OverriddenMacros.end(), |
714 | 10.7k | Info->ActiveModuleMacros.begin(), |
715 | 10.7k | Info->ActiveModuleMacros.end()); |
716 | 10.7k | Info->ActiveModuleMacros.clear(); |
717 | 10.7k | Info->IsAmbiguous = false; |
718 | 10.7k | } |
719 | 45.7M | } |
720 | | |
721 | 446k | ArrayRef<ModuleMacro*> getOverriddenMacros() const { |
722 | 446k | if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) |
723 | 70.1k | return Info->OverriddenMacros; |
724 | 376k | return None; |
725 | 446k | } |
726 | | |
727 | | void setOverriddenMacros(Preprocessor &PP, |
728 | 446k | ArrayRef<ModuleMacro *> Overrides) { |
729 | 446k | auto *Info = State.dyn_cast<ModuleMacroInfo*>(); |
730 | 446k | if (!Info) { |
731 | 376k | if (Overrides.empty()) |
732 | 376k | return; |
733 | 0 | Info = new (PP.getPreprocessorAllocator()) |
734 | 0 | ModuleMacroInfo(State.get<MacroDirective *>()); |
735 | 0 | State = Info; |
736 | 0 | } |
737 | 69.7k | Info->OverriddenMacros.clear(); |
738 | 69.7k | Info->OverriddenMacros.insert(Info->OverriddenMacros.end(), |
739 | 69.7k | Overrides.begin(), Overrides.end()); |
740 | 69.7k | Info->ActiveModuleMacrosGeneration = 0; |
741 | 69.7k | } |
742 | | }; |
743 | | |
744 | | /// For each IdentifierInfo that was associated with a macro, we |
745 | | /// keep a mapping to the history of all macro definitions and #undefs in |
746 | | /// the reverse order (the latest one is in the head of the list). |
747 | | /// |
748 | | /// This mapping lives within the \p CurSubmoduleState. |
749 | | using MacroMap = llvm::DenseMap<const IdentifierInfo *, MacroState>; |
750 | | |
751 | | struct SubmoduleState; |
752 | | |
753 | | /// Information about a submodule that we're currently building. |
754 | | struct BuildingSubmoduleInfo { |
755 | | /// The module that we are building. |
756 | | Module *M; |
757 | | |
758 | | /// The location at which the module was included. |
759 | | SourceLocation ImportLoc; |
760 | | |
761 | | /// Whether we entered this submodule via a pragma. |
762 | | bool IsPragma; |
763 | | |
764 | | /// The previous SubmoduleState. |
765 | | SubmoduleState *OuterSubmoduleState; |
766 | | |
767 | | /// The number of pending module macro names when we started building this. |
768 | | unsigned OuterPendingModuleMacroNames; |
769 | | |
770 | | BuildingSubmoduleInfo(Module *M, SourceLocation ImportLoc, bool IsPragma, |
771 | | SubmoduleState *OuterSubmoduleState, |
772 | | unsigned OuterPendingModuleMacroNames) |
773 | | : M(M), ImportLoc(ImportLoc), IsPragma(IsPragma), |
774 | | OuterSubmoduleState(OuterSubmoduleState), |
775 | 96.2k | OuterPendingModuleMacroNames(OuterPendingModuleMacroNames) {} |
776 | | }; |
777 | | SmallVector<BuildingSubmoduleInfo, 8> BuildingSubmoduleStack; |
778 | | |
779 | | /// Information about a submodule's preprocessor state. |
780 | | struct SubmoduleState { |
781 | | /// The macros for the submodule. |
782 | | MacroMap Macros; |
783 | | |
784 | | /// The set of modules that are visible within the submodule. |
785 | | VisibleModuleSet VisibleModules; |
786 | | |
787 | | // FIXME: CounterValue? |
788 | | // FIXME: PragmaPushMacroInfo? |
789 | | }; |
790 | | std::map<Module *, SubmoduleState> Submodules; |
791 | | |
792 | | /// The preprocessor state for preprocessing outside of any submodule. |
793 | | SubmoduleState NullSubmoduleState; |
794 | | |
795 | | /// The current submodule state. Will be \p NullSubmoduleState if we're not |
796 | | /// in a submodule. |
797 | | SubmoduleState *CurSubmoduleState; |
798 | | |
799 | | /// The files that have been included. |
800 | | IncludedFilesSet IncludedFiles; |
801 | | |
802 | | /// The set of known macros exported from modules. |
803 | | llvm::FoldingSet<ModuleMacro> ModuleMacros; |
804 | | |
805 | | /// The names of potential module macros that we've not yet processed. |
806 | | llvm::SmallVector<const IdentifierInfo *, 32> PendingModuleMacroNames; |
807 | | |
808 | | /// The list of module macros, for each identifier, that are not overridden by |
809 | | /// any other module macro. |
810 | | llvm::DenseMap<const IdentifierInfo *, llvm::TinyPtrVector<ModuleMacro *>> |
811 | | LeafModuleMacros; |
812 | | |
813 | | /// Macros that we want to warn because they are not used at the end |
814 | | /// of the translation unit. |
815 | | /// |
816 | | /// We store just their SourceLocations instead of |
817 | | /// something like MacroInfo*. The benefit of this is that when we are |
818 | | /// deserializing from PCH, we don't need to deserialize identifier & macros |
819 | | /// just so that we can report that they are unused, we just warn using |
820 | | /// the SourceLocations of this set (that will be filled by the ASTReader). |
821 | | using WarnUnusedMacroLocsTy = llvm::SmallDenseSet<SourceLocation, 32>; |
822 | | WarnUnusedMacroLocsTy WarnUnusedMacroLocs; |
823 | | |
824 | | /// This is a pair of an optional message and source location used for pragmas |
825 | | /// that annotate macros like pragma clang restrict_expansion and pragma clang |
826 | | /// deprecated. This pair stores the optional message and the location of the |
827 | | /// annotation pragma for use producing diagnostics and notes. |
828 | | using MsgLocationPair = std::pair<std::string, SourceLocation>; |
829 | | |
830 | | struct MacroAnnotationInfo { |
831 | | SourceLocation Location; |
832 | | std::string Message; |
833 | | }; |
834 | | |
835 | | struct MacroAnnotations { |
836 | | llvm::Optional<MacroAnnotationInfo> DeprecationInfo; |
837 | | llvm::Optional<MacroAnnotationInfo> RestrictExpansionInfo; |
838 | | llvm::Optional<SourceLocation> FinalAnnotationLoc; |
839 | | |
840 | | static MacroAnnotations makeDeprecation(SourceLocation Loc, |
841 | 22 | std::string Msg) { |
842 | 22 | return MacroAnnotations{MacroAnnotationInfo{Loc, std::move(Msg)}, |
843 | 22 | llvm::None, llvm::None}; |
844 | 22 | } |
845 | | |
846 | | static MacroAnnotations makeRestrictExpansion(SourceLocation Loc, |
847 | 3 | std::string Msg) { |
848 | 3 | return MacroAnnotations{ |
849 | 3 | llvm::None, MacroAnnotationInfo{Loc, std::move(Msg)}, llvm::None}; |
850 | 3 | } |
851 | | |
852 | 3 | static MacroAnnotations makeFinal(SourceLocation Loc) { |
853 | 3 | return MacroAnnotations{llvm::None, llvm::None, Loc}; |
854 | 3 | } |
855 | | }; |
856 | | |
857 | | /// Warning information for macro annotations. |
858 | | llvm::DenseMap<const IdentifierInfo *, MacroAnnotations> AnnotationInfos; |
859 | | |
860 | | /// A "freelist" of MacroArg objects that can be |
861 | | /// reused for quick allocation. |
862 | | MacroArgs *MacroArgCache = nullptr; |
863 | | |
864 | | /// For each IdentifierInfo used in a \#pragma push_macro directive, |
865 | | /// we keep a MacroInfo stack used to restore the previous macro value. |
866 | | llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>> |
867 | | PragmaPushMacroInfo; |
868 | | |
869 | | // Various statistics we track for performance analysis. |
870 | | unsigned NumDirectives = 0; |
871 | | unsigned NumDefined = 0; |
872 | | unsigned NumUndefined = 0; |
873 | | unsigned NumPragma = 0; |
874 | | unsigned NumIf = 0; |
875 | | unsigned NumElse = 0; |
876 | | unsigned NumEndif = 0; |
877 | | unsigned NumEnteredSourceFiles = 0; |
878 | | unsigned MaxIncludeStackDepth = 0; |
879 | | unsigned NumMacroExpanded = 0; |
880 | | unsigned NumFnMacroExpanded = 0; |
881 | | unsigned NumBuiltinMacroExpanded = 0; |
882 | | unsigned NumFastMacroExpanded = 0; |
883 | | unsigned NumTokenPaste = 0; |
884 | | unsigned NumFastTokenPaste = 0; |
885 | | unsigned NumSkipped = 0; |
886 | | |
887 | | /// The predefined macros that preprocessor should use from the |
888 | | /// command line etc. |
889 | | std::string Predefines; |
890 | | |
891 | | /// The file ID for the preprocessor predefines. |
892 | | FileID PredefinesFileID; |
893 | | |
894 | | /// The file ID for the PCH through header. |
895 | | FileID PCHThroughHeaderFileID; |
896 | | |
897 | | /// Whether tokens are being skipped until a #pragma hdrstop is seen. |
898 | | bool SkippingUntilPragmaHdrStop = false; |
899 | | |
900 | | /// Whether tokens are being skipped until the through header is seen. |
901 | | bool SkippingUntilPCHThroughHeader = false; |
902 | | |
903 | | /// \{ |
904 | | /// Cache of macro expanders to reduce malloc traffic. |
905 | | enum { TokenLexerCacheSize = 8 }; |
906 | | unsigned NumCachedTokenLexers; |
907 | | std::unique_ptr<TokenLexer> TokenLexerCache[TokenLexerCacheSize]; |
908 | | /// \} |
909 | | |
910 | | /// Keeps macro expanded tokens for TokenLexers. |
911 | | // |
912 | | /// Works like a stack; a TokenLexer adds the macro expanded tokens that is |
913 | | /// going to lex in the cache and when it finishes the tokens are removed |
914 | | /// from the end of the cache. |
915 | | SmallVector<Token, 16> MacroExpandedTokens; |
916 | | std::vector<std::pair<TokenLexer *, size_t>> MacroExpandingLexersStack; |
917 | | |
918 | | /// A record of the macro definitions and expansions that |
919 | | /// occurred during preprocessing. |
920 | | /// |
921 | | /// This is an optional side structure that can be enabled with |
922 | | /// \c createPreprocessingRecord() prior to preprocessing. |
923 | | PreprocessingRecord *Record = nullptr; |
924 | | |
925 | | /// Cached tokens state. |
926 | | using CachedTokensTy = SmallVector<Token, 1>; |
927 | | |
928 | | /// Cached tokens are stored here when we do backtracking or |
929 | | /// lookahead. They are "lexed" by the CachingLex() method. |
930 | | CachedTokensTy CachedTokens; |
931 | | |
932 | | /// The position of the cached token that CachingLex() should |
933 | | /// "lex" next. |
934 | | /// |
935 | | /// If it points beyond the CachedTokens vector, it means that a normal |
936 | | /// Lex() should be invoked. |
937 | | CachedTokensTy::size_type CachedLexPos = 0; |
938 | | |
939 | | /// Stack of backtrack positions, allowing nested backtracks. |
940 | | /// |
941 | | /// The EnableBacktrackAtThisPos() method pushes a position to |
942 | | /// indicate where CachedLexPos should be set when the BackTrack() method is |
943 | | /// invoked (at which point the last position is popped). |
944 | | std::vector<CachedTokensTy::size_type> BacktrackPositions; |
945 | | |
946 | | struct MacroInfoChain { |
947 | | MacroInfo MI; |
948 | | MacroInfoChain *Next; |
949 | | }; |
950 | | |
951 | | /// MacroInfos are managed as a chain for easy disposal. This is the head |
952 | | /// of that list. |
953 | | MacroInfoChain *MIChainHead = nullptr; |
954 | | |
955 | | void updateOutOfDateIdentifier(IdentifierInfo &II) const; |
956 | | |
957 | | public: |
958 | | Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts, |
959 | | DiagnosticsEngine &diags, LangOptions &opts, SourceManager &SM, |
960 | | HeaderSearch &Headers, ModuleLoader &TheModuleLoader, |
961 | | IdentifierInfoLookup *IILookup = nullptr, |
962 | | bool OwnsHeaderSearch = false, |
963 | | TranslationUnitKind TUKind = TU_Complete); |
964 | | |
965 | | ~Preprocessor(); |
966 | | |
967 | | /// Initialize the preprocessor using information about the target. |
968 | | /// |
969 | | /// \param Target is owned by the caller and must remain valid for the |
970 | | /// lifetime of the preprocessor. |
971 | | /// \param AuxTarget is owned by the caller and must remain valid for |
972 | | /// the lifetime of the preprocessor. |
973 | | void Initialize(const TargetInfo &Target, |
974 | | const TargetInfo *AuxTarget = nullptr); |
975 | | |
976 | | /// Initialize the preprocessor to parse a model file |
977 | | /// |
978 | | /// To parse model files the preprocessor of the original source is reused to |
979 | | /// preserver the identifier table. However to avoid some duplicate |
980 | | /// information in the preprocessor some cleanup is needed before it is used |
981 | | /// to parse model files. This method does that cleanup. |
982 | | void InitializeForModelFile(); |
983 | | |
984 | | /// Cleanup after model file parsing |
985 | | void FinalizeForModelFile(); |
986 | | |
987 | | /// Retrieve the preprocessor options used to initialize this |
988 | | /// preprocessor. |
989 | 142k | PreprocessorOptions &getPreprocessorOpts() const { return *PPOpts; } |
990 | | |
991 | 33.9M | DiagnosticsEngine &getDiagnostics() const { return *Diags; } |
992 | 234 | void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; } |
993 | | |
994 | 5.45G | const LangOptions &getLangOpts() const { return LangOpts; } |
995 | 21.8M | const TargetInfo &getTargetInfo() const { return *Target; } |
996 | 1.29k | const TargetInfo *getAuxTargetInfo() const { return AuxTarget; } |
997 | 1.78M | FileManager &getFileManager() const { return FileMgr; } |
998 | 1.21G | SourceManager &getSourceManager() const { return SourceMgr; } |
999 | 2.72M | HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; } |
1000 | | |
1001 | 25.8M | IdentifierTable &getIdentifierTable() { return Identifiers; } |
1002 | 5.56k | const IdentifierTable &getIdentifierTable() const { return Identifiers; } |
1003 | 1.48M | SelectorTable &getSelectorTable() { return Selectors; } |
1004 | 172k | Builtin::Context &getBuiltinInfo() { return *BuiltinInfo; } |
1005 | 4.71M | llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; } |
1006 | | |
1007 | 7.41k | void setExternalSource(ExternalPreprocessorSource *Source) { |
1008 | 7.41k | ExternalSource = Source; |
1009 | 7.41k | } |
1010 | | |
1011 | 1.57M | ExternalPreprocessorSource *getExternalSource() const { |
1012 | 1.57M | return ExternalSource; |
1013 | 1.57M | } |
1014 | | |
1015 | | /// Retrieve the module loader associated with this preprocessor. |
1016 | 129k | ModuleLoader &getModuleLoader() const { return TheModuleLoader; } |
1017 | | |
1018 | 61.4M | bool hadModuleLoaderFatalFailure() const { |
1019 | 61.4M | return TheModuleLoader.HadFatalFailure; |
1020 | 61.4M | } |
1021 | | |
1022 | | /// Retrieve the number of Directives that have been processed by the |
1023 | | /// Preprocessor. |
1024 | 644k | unsigned getNumDirectives() const { |
1025 | 644k | return NumDirectives; |
1026 | 644k | } |
1027 | | |
1028 | | /// True if we are currently preprocessing a #if or #elif directive |
1029 | 15.1k | bool isParsingIfOrElifDirective() const { |
1030 | 15.1k | return ParsingIfOrElifDirective; |
1031 | 15.1k | } |
1032 | | |
1033 | | /// Control whether the preprocessor retains comments in output. |
1034 | 694 | void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) { |
1035 | 694 | this->KeepComments = KeepComments | KeepMacroComments; |
1036 | 694 | this->KeepMacroComments = KeepMacroComments; |
1037 | 694 | } |
1038 | | |
1039 | 88.0M | bool getCommentRetentionState() const { return KeepComments; } |
1040 | | |
1041 | 234 | void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; } |
1042 | 117 | bool getPragmasEnabled() const { return PragmasEnabled; } |
1043 | | |
1044 | 4 | void SetSuppressIncludeNotFoundError(bool Suppress) { |
1045 | 4 | SuppressIncludeNotFoundError = Suppress; |
1046 | 4 | } |
1047 | | |
1048 | 0 | bool GetSuppressIncludeNotFoundError() { |
1049 | 0 | return SuppressIncludeNotFoundError; |
1050 | 0 | } |
1051 | | |
1052 | | /// Sets whether the preprocessor is responsible for producing output or if |
1053 | | /// it is producing tokens to be consumed by Parse and Sema. |
1054 | 89.1k | void setPreprocessedOutput(bool IsPreprocessedOutput) { |
1055 | 89.1k | PreprocessedOutput = IsPreprocessedOutput; |
1056 | 89.1k | } |
1057 | | |
1058 | | /// Returns true if the preprocessor is responsible for generating output, |
1059 | | /// false if it is producing tokens to be consumed by Parse and Sema. |
1060 | 5.20k | bool isPreprocessedOutput() const { return PreprocessedOutput; } |
1061 | | |
1062 | | /// Return true if we are lexing directly from the specified lexer. |
1063 | 0 | bool isCurrentLexer(const PreprocessorLexer *L) const { |
1064 | 0 | return CurPPLexer == L; |
1065 | 0 | } |
1066 | | |
1067 | | /// Return the current lexer being lexed from. |
1068 | | /// |
1069 | | /// Note that this ignores any potentially active macro expansions and _Pragma |
1070 | | /// expansions going on at the time. |
1071 | 85.2k | PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; } |
1072 | | |
1073 | | /// Return the current file lexer being lexed from. |
1074 | | /// |
1075 | | /// Note that this ignores any potentially active macro expansions and _Pragma |
1076 | | /// expansions going on at the time. |
1077 | | PreprocessorLexer *getCurrentFileLexer() const; |
1078 | | |
1079 | | /// Return the submodule owning the file being lexed. This may not be |
1080 | | /// the current module if we have changed modules since entering the file. |
1081 | 0 | Module *getCurrentLexerSubmodule() const { return CurLexerSubmodule; } |
1082 | | |
1083 | | /// Returns the FileID for the preprocessor predefines. |
1084 | 786k | FileID getPredefinesFileID() const { return PredefinesFileID; } |
1085 | | |
1086 | | /// \{ |
1087 | | /// Accessors for preprocessor callbacks. |
1088 | | /// |
1089 | | /// Note that this class takes ownership of any PPCallbacks object given to |
1090 | | /// it. |
1091 | 1.78M | PPCallbacks *getPPCallbacks() const { return Callbacks.get(); } |
1092 | 138k | void addPPCallbacks(std::unique_ptr<PPCallbacks> C) { |
1093 | 138k | if (Callbacks) |
1094 | 50.5k | C = std::make_unique<PPChainedCallbacks>(std::move(C), |
1095 | 50.5k | std::move(Callbacks)); |
1096 | 138k | Callbacks = std::move(C); |
1097 | 138k | } |
1098 | | /// \} |
1099 | | |
1100 | | /// Get the number of tokens processed so far. |
1101 | 10 | unsigned getTokenCount() const { return TokenCount; } |
1102 | | |
1103 | | /// Get the max number of tokens before issuing a -Wmax-tokens warning. |
1104 | 86.6k | unsigned getMaxTokens() const { return MaxTokens; } |
1105 | | |
1106 | 1 | void overrideMaxTokens(unsigned Value, SourceLocation Loc) { |
1107 | 1 | MaxTokens = Value; |
1108 | 1 | MaxTokensOverrideLoc = Loc; |
1109 | 1 | }; |
1110 | | |
1111 | 2 | SourceLocation getMaxTokensOverrideLoc() const { return MaxTokensOverrideLoc; } |
1112 | | |
1113 | | /// Register a function that would be called on each token in the final |
1114 | | /// expanded token stream. |
1115 | | /// This also reports annotation tokens produced by the parser. |
1116 | 4.45k | void setTokenWatcher(llvm::unique_function<void(const clang::Token &)> F) { |
1117 | 4.45k | OnToken = std::move(F); |
1118 | 4.45k | } |
1119 | | |
1120 | 24 | void setPreprocessToken(bool Preprocess) { PreprocessToken = Preprocess; } |
1121 | | |
1122 | 141k | bool isMacroDefined(StringRef Id) { |
1123 | 141k | return isMacroDefined(&Identifiers.get(Id)); |
1124 | 141k | } |
1125 | 1.35M | bool isMacroDefined(const IdentifierInfo *II) { |
1126 | 1.35M | return II->hasMacroDefinition() && |
1127 | 1.35M | (1.33M !getLangOpts().Modules1.33M || (bool)getMacroDefinition(II)21.3k ); |
1128 | 1.35M | } |
1129 | | |
1130 | | /// Determine whether II is defined as a macro within the module M, |
1131 | | /// if that is a module that we've already preprocessed. Does not check for |
1132 | | /// macros imported into M. |
1133 | 69.2k | bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M) { |
1134 | 69.2k | if (!II->hasMacroDefinition()) |
1135 | 99 | return false; |
1136 | 69.1k | auto I = Submodules.find(M); |
1137 | 69.1k | if (I == Submodules.end()) |
1138 | 69.0k | return false; |
1139 | 18 | auto J = I->second.Macros.find(II); |
1140 | 18 | if (J == I->second.Macros.end()) |
1141 | 0 | return false; |
1142 | 18 | auto *MD = J->second.getLatest(); |
1143 | 18 | return MD && MD->isDefined(); |
1144 | 18 | } |
1145 | | |
1146 | 151M | MacroDefinition getMacroDefinition(const IdentifierInfo *II) { |
1147 | 151M | if (!II->hasMacroDefinition()) |
1148 | 6.18M | return {}; |
1149 | | |
1150 | 145M | MacroState &S = CurSubmoduleState->Macros[II]; |
1151 | 145M | auto *MD = S.getLatest(); |
1152 | 145M | while (MD && isa<VisibilityMacroDirective>(MD)141M ) |
1153 | 133 | MD = MD->getPrevious(); |
1154 | 145M | return MacroDefinition(dyn_cast_or_null<DefMacroDirective>(MD), |
1155 | 145M | S.getActiveModuleMacros(*this, II), |
1156 | 145M | S.isAmbiguous(*this, II)); |
1157 | 151M | } |
1158 | | |
1159 | | MacroDefinition getMacroDefinitionAtLoc(const IdentifierInfo *II, |
1160 | 29 | SourceLocation Loc) { |
1161 | 29 | if (!II->hadMacroDefinition()) |
1162 | 10 | return {}; |
1163 | | |
1164 | 19 | MacroState &S = CurSubmoduleState->Macros[II]; |
1165 | 19 | MacroDirective::DefInfo DI; |
1166 | 19 | if (auto *MD = S.getLatest()) |
1167 | 19 | DI = MD->findDirectiveAtLoc(Loc, getSourceManager()); |
1168 | | // FIXME: Compute the set of active module macros at the specified location. |
1169 | 19 | return MacroDefinition(DI.getDirective(), |
1170 | 19 | S.getActiveModuleMacros(*this, II), |
1171 | 19 | S.isAmbiguous(*this, II)); |
1172 | 29 | } |
1173 | | |
1174 | | /// Given an identifier, return its latest non-imported MacroDirective |
1175 | | /// if it is \#define'd and not \#undef'd, or null if it isn't \#define'd. |
1176 | 197 | MacroDirective *getLocalMacroDirective(const IdentifierInfo *II) const { |
1177 | 197 | if (!II->hasMacroDefinition()) |
1178 | 9 | return nullptr; |
1179 | | |
1180 | 188 | auto *MD = getLocalMacroDirectiveHistory(II); |
1181 | 188 | if (!MD || MD->getDefinition().isUndefined()) |
1182 | 0 | return nullptr; |
1183 | | |
1184 | 188 | return MD; |
1185 | 188 | } |
1186 | | |
1187 | 62.5M | const MacroInfo *getMacroInfo(const IdentifierInfo *II) const { |
1188 | 62.5M | return const_cast<Preprocessor*>(this)->getMacroInfo(II); |
1189 | 62.5M | } |
1190 | | |
1191 | 157M | MacroInfo *getMacroInfo(const IdentifierInfo *II) { |
1192 | 157M | if (!II->hasMacroDefinition()) |
1193 | 91.4M | return nullptr; |
1194 | 65.8M | if (auto MD = getMacroDefinition(II)) |
1195 | 65.7M | return MD.getMacroInfo(); |
1196 | 17.3k | return nullptr; |
1197 | 65.8M | } |
1198 | | |
1199 | | /// Given an identifier, return the latest non-imported macro |
1200 | | /// directive for that identifier. |
1201 | | /// |
1202 | | /// One can iterate over all previous macro directives from the most recent |
1203 | | /// one. |
1204 | | MacroDirective *getLocalMacroDirectiveHistory(const IdentifierInfo *II) const; |
1205 | | |
1206 | | /// Add a directive to the macro directive history for this identifier. |
1207 | | void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD); |
1208 | | DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI, |
1209 | 45.6M | SourceLocation Loc) { |
1210 | 45.6M | DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc); |
1211 | 45.6M | appendMacroDirective(II, MD); |
1212 | 45.6M | return MD; |
1213 | 45.6M | } |
1214 | | DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, |
1215 | 45.6M | MacroInfo *MI) { |
1216 | 45.6M | return appendDefMacroDirective(II, MI, MI->getDefinitionLoc()); |
1217 | 45.6M | } |
1218 | | |
1219 | | /// Set a MacroDirective that was loaded from a PCH file. |
1220 | | void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, |
1221 | | MacroDirective *MD); |
1222 | | |
1223 | | /// Register an exported macro for a module and identifier. |
1224 | | ModuleMacro *addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, |
1225 | | ArrayRef<ModuleMacro *> Overrides, bool &IsNew); |
1226 | | ModuleMacro *getModuleMacro(Module *Mod, const IdentifierInfo *II); |
1227 | | |
1228 | | /// Get the list of leaf (non-overridden) module macros for a name. |
1229 | 7.55M | ArrayRef<ModuleMacro*> getLeafModuleMacros(const IdentifierInfo *II) const { |
1230 | 7.55M | if (II->isOutOfDate()) |
1231 | 81 | updateOutOfDateIdentifier(const_cast<IdentifierInfo&>(*II)); |
1232 | 7.55M | auto I = LeafModuleMacros.find(II); |
1233 | 7.55M | if (I != LeafModuleMacros.end()) |
1234 | 5.27M | return I->second; |
1235 | 2.28M | return None; |
1236 | 7.55M | } |
1237 | | |
1238 | | /// Get the list of submodules that we're currently building. |
1239 | 0 | ArrayRef<BuildingSubmoduleInfo> getBuildingSubmodules() const { |
1240 | 0 | return BuildingSubmoduleStack; |
1241 | 0 | } |
1242 | | |
1243 | | /// \{ |
1244 | | /// Iterators for the macro history table. Currently defined macros have |
1245 | | /// IdentifierInfo::hasMacroDefinition() set and an empty |
1246 | | /// MacroInfo::getUndefLoc() at the head of the list. |
1247 | | using macro_iterator = MacroMap::const_iterator; |
1248 | | |
1249 | | macro_iterator macro_begin(bool IncludeExternalMacros = true) const; |
1250 | | macro_iterator macro_end(bool IncludeExternalMacros = true) const; |
1251 | | |
1252 | | llvm::iterator_range<macro_iterator> |
1253 | 8 | macros(bool IncludeExternalMacros = true) const { |
1254 | 8 | macro_iterator begin = macro_begin(IncludeExternalMacros); |
1255 | 8 | macro_iterator end = macro_end(IncludeExternalMacros); |
1256 | 8 | return llvm::make_range(begin, end); |
1257 | 8 | } |
1258 | | |
1259 | | /// \} |
1260 | | |
1261 | | /// Mark the file as included. |
1262 | | /// Returns true if this is the first time the file was included. |
1263 | 656k | bool markIncluded(const FileEntry *File) { |
1264 | 656k | HeaderInfo.getFileInfo(File); |
1265 | 656k | return IncludedFiles.insert(File).second; |
1266 | 656k | } |
1267 | | |
1268 | | /// Return true if this header has already been included. |
1269 | 125k | bool alreadyIncluded(const FileEntry *File) const { |
1270 | 125k | return IncludedFiles.count(File); |
1271 | 125k | } |
1272 | | |
1273 | | /// Get the set of included files. |
1274 | 1.57M | IncludedFilesSet &getIncludedFiles() { return IncludedFiles; } |
1275 | 5.56k | const IncludedFilesSet &getIncludedFiles() const { return IncludedFiles; } |
1276 | | |
1277 | | /// Return the name of the macro defined before \p Loc that has |
1278 | | /// spelling \p Tokens. If there are multiple macros with same spelling, |
1279 | | /// return the last one defined. |
1280 | | StringRef getLastMacroWithSpelling(SourceLocation Loc, |
1281 | | ArrayRef<TokenValue> Tokens) const; |
1282 | | |
1283 | | /// Set the predefines for this Preprocessor. |
1284 | | /// |
1285 | | /// These predefines are automatically injected when parsing the main file. |
1286 | 92.8k | void setPredefines(std::string P) { Predefines = std::move(P); } |
1287 | | |
1288 | | /// Return information about the specified preprocessor |
1289 | | /// identifier token. |
1290 | 473M | IdentifierInfo *getIdentifierInfo(StringRef Name) const { |
1291 | 473M | return &Identifiers.get(Name); |
1292 | 473M | } |
1293 | | |
1294 | | /// Add the specified pragma handler to this preprocessor. |
1295 | | /// |
1296 | | /// If \p Namespace is non-null, then it is a token required to exist on the |
1297 | | /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". |
1298 | | void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler); |
1299 | 2.00M | void AddPragmaHandler(PragmaHandler *Handler) { |
1300 | 2.00M | AddPragmaHandler(StringRef(), Handler); |
1301 | 2.00M | } |
1302 | | |
1303 | | /// Remove the specific pragma handler from this preprocessor. |
1304 | | /// |
1305 | | /// If \p Namespace is non-null, then it should be the namespace that |
1306 | | /// \p Handler was added to. It is an error to remove a handler that |
1307 | | /// has not been registered. |
1308 | | void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler); |
1309 | 1.31M | void RemovePragmaHandler(PragmaHandler *Handler) { |
1310 | 1.31M | RemovePragmaHandler(StringRef(), Handler); |
1311 | 1.31M | } |
1312 | | |
1313 | | /// Install empty handlers for all pragmas (making them ignored). |
1314 | | void IgnorePragmas(); |
1315 | | |
1316 | | /// Set empty line handler. |
1317 | 24 | void setEmptylineHandler(EmptylineHandler *Handler) { Emptyline = Handler; } |
1318 | | |
1319 | 20.2M | EmptylineHandler *getEmptylineHandler() const { return Emptyline; } |
1320 | | |
1321 | | /// Add the specified comment handler to the preprocessor. |
1322 | | void addCommentHandler(CommentHandler *Handler); |
1323 | | |
1324 | | /// Remove the specified comment handler. |
1325 | | /// |
1326 | | /// It is an error to remove a handler that has not been registered. |
1327 | | void removeCommentHandler(CommentHandler *Handler); |
1328 | | |
1329 | | /// Set the code completion handler to the given object. |
1330 | 86.6k | void setCodeCompletionHandler(CodeCompletionHandler &Handler) { |
1331 | 86.6k | CodeComplete = &Handler; |
1332 | 86.6k | } |
1333 | | |
1334 | | /// Retrieve the current code-completion handler. |
1335 | 20 | CodeCompletionHandler *getCodeCompletionHandler() const { |
1336 | 20 | return CodeComplete; |
1337 | 20 | } |
1338 | | |
1339 | | /// Clear out the code completion handler. |
1340 | 86.6k | void clearCodeCompletionHandler() { |
1341 | 86.6k | CodeComplete = nullptr; |
1342 | 86.6k | } |
1343 | | |
1344 | | /// Hook used by the lexer to invoke the "included file" code |
1345 | | /// completion point. |
1346 | | void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); |
1347 | | |
1348 | | /// Hook used by the lexer to invoke the "natural language" code |
1349 | | /// completion point. |
1350 | | void CodeCompleteNaturalLanguage(); |
1351 | | |
1352 | | /// Set the code completion token for filtering purposes. |
1353 | 99 | void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter) { |
1354 | 99 | CodeCompletionII = Filter; |
1355 | 99 | } |
1356 | | |
1357 | | /// Set the code completion token range for detecting replacement range later |
1358 | | /// on. |
1359 | | void setCodeCompletionTokenRange(const SourceLocation Start, |
1360 | 99 | const SourceLocation End) { |
1361 | 99 | CodeCompletionTokenRange = {Start, End}; |
1362 | 99 | } |
1363 | 0 | SourceRange getCodeCompletionTokenRange() const { |
1364 | 0 | return CodeCompletionTokenRange; |
1365 | 0 | } |
1366 | | |
1367 | | /// Get the code completion token for filtering purposes. |
1368 | 390 | StringRef getCodeCompletionFilter() { |
1369 | 390 | if (CodeCompletionII) |
1370 | 77 | return CodeCompletionII->getName(); |
1371 | 313 | return {}; |
1372 | 390 | } |
1373 | | |
1374 | | /// Retrieve the preprocessing record, or NULL if there is no |
1375 | | /// preprocessing record. |
1376 | 224k | PreprocessingRecord *getPreprocessingRecord() const { return Record; } |
1377 | | |
1378 | | /// Create a new preprocessing record, which will keep track of |
1379 | | /// all macro expansions, macro definitions, etc. |
1380 | | void createPreprocessingRecord(); |
1381 | | |
1382 | | /// Returns true if the FileEntry is the PCH through header. |
1383 | | bool isPCHThroughHeader(const FileEntry *FE); |
1384 | | |
1385 | | /// True if creating a PCH with a through header. |
1386 | | bool creatingPCHWithThroughHeader(); |
1387 | | |
1388 | | /// True if using a PCH with a through header. |
1389 | | bool usingPCHWithThroughHeader(); |
1390 | | |
1391 | | /// True if creating a PCH with a #pragma hdrstop. |
1392 | | bool creatingPCHWithPragmaHdrStop(); |
1393 | | |
1394 | | /// True if using a PCH with a #pragma hdrstop. |
1395 | | bool usingPCHWithPragmaHdrStop(); |
1396 | | |
1397 | | /// Skip tokens until after the #include of the through header or |
1398 | | /// until after a #pragma hdrstop. |
1399 | | void SkipTokensWhileUsingPCH(); |
1400 | | |
1401 | | /// Process directives while skipping until the through header or |
1402 | | /// #pragma hdrstop is found. |
1403 | | void HandleSkippedDirectiveWhileUsingPCH(Token &Result, |
1404 | | SourceLocation HashLoc); |
1405 | | |
1406 | | /// Enter the specified FileID as the main source file, |
1407 | | /// which implicitly adds the builtin defines etc. |
1408 | | void EnterMainSourceFile(); |
1409 | | |
1410 | | /// Inform the preprocessor callbacks that processing is complete. |
1411 | | void EndSourceFile(); |
1412 | | |
1413 | | /// Add a source file to the top of the include stack and |
1414 | | /// start lexing tokens from it instead of the current buffer. |
1415 | | /// |
1416 | | /// Emits a diagnostic, doesn't enter the file, and returns true on error. |
1417 | | bool EnterSourceFile(FileID FID, ConstSearchDirIterator Dir, |
1418 | | SourceLocation Loc, bool IsFirstIncludeOfFile = true); |
1419 | | |
1420 | | /// Add a Macro to the top of the include stack and start lexing |
1421 | | /// tokens from it instead of the current buffer. |
1422 | | /// |
1423 | | /// \param Args specifies the tokens input to a function-like macro. |
1424 | | /// \param ILEnd specifies the location of the ')' for a function-like macro |
1425 | | /// or the identifier for an object-like macro. |
1426 | | void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, |
1427 | | MacroArgs *Args); |
1428 | | |
1429 | | private: |
1430 | | /// Add a "macro" context to the top of the include stack, |
1431 | | /// which will cause the lexer to start returning the specified tokens. |
1432 | | /// |
1433 | | /// If \p DisableMacroExpansion is true, tokens lexed from the token stream |
1434 | | /// will not be subject to further macro expansion. Otherwise, these tokens |
1435 | | /// will be re-macro-expanded when/if expansion is enabled. |
1436 | | /// |
1437 | | /// If \p OwnsTokens is false, this method assumes that the specified stream |
1438 | | /// of tokens has a permanent owner somewhere, so they do not need to be |
1439 | | /// copied. If it is true, it assumes the array of tokens is allocated with |
1440 | | /// \c new[] and the Preprocessor will delete[] it. |
1441 | | /// |
1442 | | /// If \p IsReinject the resulting tokens will have Token::IsReinjected flag |
1443 | | /// set, see the flag documentation for details. |
1444 | | void EnterTokenStream(const Token *Toks, unsigned NumToks, |
1445 | | bool DisableMacroExpansion, bool OwnsTokens, |
1446 | | bool IsReinject); |
1447 | | |
1448 | | public: |
1449 | | void EnterTokenStream(std::unique_ptr<Token[]> Toks, unsigned NumToks, |
1450 | 372k | bool DisableMacroExpansion, bool IsReinject) { |
1451 | 372k | EnterTokenStream(Toks.release(), NumToks, DisableMacroExpansion, true, |
1452 | 372k | IsReinject); |
1453 | 372k | } |
1454 | | |
1455 | | void EnterTokenStream(ArrayRef<Token> Toks, bool DisableMacroExpansion, |
1456 | 1.01M | bool IsReinject) { |
1457 | 1.01M | EnterTokenStream(Toks.data(), Toks.size(), DisableMacroExpansion, false, |
1458 | 1.01M | IsReinject); |
1459 | 1.01M | } |
1460 | | |
1461 | | /// Pop the current lexer/macro exp off the top of the lexer stack. |
1462 | | /// |
1463 | | /// This should only be used in situations where the current state of the |
1464 | | /// top-of-stack lexer is known. |
1465 | | void RemoveTopOfLexerStack(); |
1466 | | |
1467 | | /// From the point that this method is called, and until |
1468 | | /// CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor |
1469 | | /// keeps track of the lexed tokens so that a subsequent Backtrack() call will |
1470 | | /// make the Preprocessor re-lex the same tokens. |
1471 | | /// |
1472 | | /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can |
1473 | | /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will |
1474 | | /// be combined with the EnableBacktrackAtThisPos calls in reverse order. |
1475 | | /// |
1476 | | /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack |
1477 | | /// at some point after EnableBacktrackAtThisPos. If you don't, caching of |
1478 | | /// tokens will continue indefinitely. |
1479 | | /// |
1480 | | void EnableBacktrackAtThisPos(); |
1481 | | |
1482 | | /// Disable the last EnableBacktrackAtThisPos call. |
1483 | | void CommitBacktrackedTokens(); |
1484 | | |
1485 | | /// Make Preprocessor re-lex the tokens that were lexed since |
1486 | | /// EnableBacktrackAtThisPos() was previously called. |
1487 | | void Backtrack(); |
1488 | | |
1489 | | /// True if EnableBacktrackAtThisPos() was called and |
1490 | | /// caching of tokens is on. |
1491 | 108M | bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); } |
1492 | | |
1493 | | /// Lex the next token for this preprocessor. |
1494 | | void Lex(Token &Result); |
1495 | | |
1496 | | /// Lex a token, forming a header-name token if possible. |
1497 | | bool LexHeaderName(Token &Result, bool AllowMacroExpansion = true); |
1498 | | |
1499 | | bool LexAfterModuleImport(Token &Result); |
1500 | | void CollectPpImportSuffix(SmallVectorImpl<Token> &Toks); |
1501 | | |
1502 | | void makeModuleVisible(Module *M, SourceLocation Loc); |
1503 | | |
1504 | 67 | SourceLocation getModuleImportLoc(Module *M) const { |
1505 | 67 | return CurSubmoduleState->VisibleModules.getImportLoc(M); |
1506 | 67 | } |
1507 | | |
1508 | | /// Lex a string literal, which may be the concatenation of multiple |
1509 | | /// string literals and may even come from macro expansion. |
1510 | | /// \returns true on success, false if a error diagnostic has been generated. |
1511 | | bool LexStringLiteral(Token &Result, std::string &String, |
1512 | 183 | const char *DiagnosticTag, bool AllowMacroExpansion) { |
1513 | 183 | if (AllowMacroExpansion) |
1514 | 90 | Lex(Result); |
1515 | 93 | else |
1516 | 93 | LexUnexpandedToken(Result); |
1517 | 183 | return FinishLexStringLiteral(Result, String, DiagnosticTag, |
1518 | 183 | AllowMacroExpansion); |
1519 | 183 | } |
1520 | | |
1521 | | /// Complete the lexing of a string literal where the first token has |
1522 | | /// already been lexed (see LexStringLiteral). |
1523 | | bool FinishLexStringLiteral(Token &Result, std::string &String, |
1524 | | const char *DiagnosticTag, |
1525 | | bool AllowMacroExpansion); |
1526 | | |
1527 | | /// Lex a token. If it's a comment, keep lexing until we get |
1528 | | /// something not a comment. |
1529 | | /// |
1530 | | /// This is useful in -E -C mode where comments would foul up preprocessor |
1531 | | /// directive handling. |
1532 | 8.30M | void LexNonComment(Token &Result) { |
1533 | 8.30M | do |
1534 | 8.30M | Lex(Result); |
1535 | 8.30M | while (Result.getKind() == tok::comment); |
1536 | 8.30M | } |
1537 | | |
1538 | | /// Just like Lex, but disables macro expansion of identifier tokens. |
1539 | 526M | void LexUnexpandedToken(Token &Result) { |
1540 | | // Disable macro expansion. |
1541 | 526M | bool OldVal = DisableMacroExpansion; |
1542 | 526M | DisableMacroExpansion = true; |
1543 | | // Lex the token. |
1544 | 526M | Lex(Result); |
1545 | | |
1546 | | // Reenable it. |
1547 | 526M | DisableMacroExpansion = OldVal; |
1548 | 526M | } |
1549 | | |
1550 | | /// Like LexNonComment, but this disables macro expansion of |
1551 | | /// identifier tokens. |
1552 | 4.18M | void LexUnexpandedNonComment(Token &Result) { |
1553 | 4.18M | do |
1554 | 4.18M | LexUnexpandedToken(Result); |
1555 | 4.18M | while (Result.getKind() == tok::comment); |
1556 | 4.18M | } |
1557 | | |
1558 | | /// Parses a simple integer literal to get its numeric value. Floating |
1559 | | /// point literals and user defined literals are rejected. Used primarily to |
1560 | | /// handle pragmas that accept integer arguments. |
1561 | | bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value); |
1562 | | |
1563 | | /// Disables macro expansion everywhere except for preprocessor directives. |
1564 | 61 | void SetMacroExpansionOnlyInDirectives() { |
1565 | 61 | DisableMacroExpansion = true; |
1566 | 61 | MacroExpansionInDirectivesOverride = true; |
1567 | 61 | } |
1568 | | |
1569 | | /// Peeks ahead N tokens and returns that token without consuming any |
1570 | | /// tokens. |
1571 | | /// |
1572 | | /// LookAhead(0) returns the next token that would be returned by Lex(), |
1573 | | /// LookAhead(1) returns the token after it, etc. This returns normal |
1574 | | /// tokens after phase 5. As such, it is equivalent to using |
1575 | | /// 'Lex', not 'LexUnexpandedToken'. |
1576 | 220M | const Token &LookAhead(unsigned N) { |
1577 | 220M | assert(LexLevel == 0 && "cannot use lookahead while lexing"); |
1578 | 220M | if (CachedLexPos + N < CachedTokens.size()) |
1579 | 108M | return CachedTokens[CachedLexPos+N]; |
1580 | 111M | else |
1581 | 111M | return PeekAhead(N+1); |
1582 | 220M | } |
1583 | | |
1584 | | /// When backtracking is enabled and tokens are cached, |
1585 | | /// this allows to revert a specific number of tokens. |
1586 | | /// |
1587 | | /// Note that the number of tokens being reverted should be up to the last |
1588 | | /// backtrack position, not more. |
1589 | 26.6k | void RevertCachedTokens(unsigned N) { |
1590 | 26.6k | assert(isBacktrackEnabled() && |
1591 | 26.6k | "Should only be called when tokens are cached for backtracking"); |
1592 | 0 | assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back()) |
1593 | 26.6k | && "Should revert tokens up to the last backtrack position, not more"); |
1594 | 0 | assert(signed(CachedLexPos) - signed(N) >= 0 && |
1595 | 26.6k | "Corrupted backtrack positions ?"); |
1596 | 0 | CachedLexPos -= N; |
1597 | 26.6k | } |
1598 | | |
1599 | | /// Enters a token in the token stream to be lexed next. |
1600 | | /// |
1601 | | /// If BackTrack() is called afterwards, the token will remain at the |
1602 | | /// insertion point. |
1603 | | /// If \p IsReinject is true, resulting token will have Token::IsReinjected |
1604 | | /// flag set. See the flag documentation for details. |
1605 | 2.76M | void EnterToken(const Token &Tok, bool IsReinject) { |
1606 | 2.76M | if (LexLevel) { |
1607 | | // It's not correct in general to enter caching lex mode while in the |
1608 | | // middle of a nested lexing action. |
1609 | 264 | auto TokCopy = std::make_unique<Token[]>(1); |
1610 | 264 | TokCopy[0] = Tok; |
1611 | 264 | EnterTokenStream(std::move(TokCopy), 1, true, IsReinject); |
1612 | 2.76M | } else { |
1613 | 2.76M | EnterCachingLexMode(); |
1614 | 2.76M | assert(IsReinject && "new tokens in the middle of cached stream"); |
1615 | 0 | CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok); |
1616 | 2.76M | } |
1617 | 2.76M | } |
1618 | | |
1619 | | /// We notify the Preprocessor that if it is caching tokens (because |
1620 | | /// backtrack is enabled) it should replace the most recent cached tokens |
1621 | | /// with the given annotation token. This function has no effect if |
1622 | | /// backtracking is not enabled. |
1623 | | /// |
1624 | | /// Note that the use of this function is just for optimization, so that the |
1625 | | /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is |
1626 | | /// invoked. |
1627 | 38.7M | void AnnotateCachedTokens(const Token &Tok) { |
1628 | 38.7M | assert(Tok.isAnnotation() && "Expected annotation token"); |
1629 | 38.7M | if (CachedLexPos != 0 && isBacktrackEnabled()12.6M ) |
1630 | 8.50M | AnnotatePreviousCachedTokens(Tok); |
1631 | 38.7M | } |
1632 | | |
1633 | | /// Get the location of the last cached token, suitable for setting the end |
1634 | | /// location of an annotation token. |
1635 | 12.8k | SourceLocation getLastCachedTokenLocation() const { |
1636 | 12.8k | assert(CachedLexPos != 0); |
1637 | 0 | return CachedTokens[CachedLexPos-1].getLastLoc(); |
1638 | 12.8k | } |
1639 | | |
1640 | | /// Whether \p Tok is the most recent token (`CachedLexPos - 1`) in |
1641 | | /// CachedTokens. |
1642 | | bool IsPreviousCachedToken(const Token &Tok) const; |
1643 | | |
1644 | | /// Replace token in `CachedLexPos - 1` in CachedTokens by the tokens |
1645 | | /// in \p NewToks. |
1646 | | /// |
1647 | | /// Useful when a token needs to be split in smaller ones and CachedTokens |
1648 | | /// most recent token must to be updated to reflect that. |
1649 | | void ReplacePreviousCachedToken(ArrayRef<Token> NewToks); |
1650 | | |
1651 | | /// Replace the last token with an annotation token. |
1652 | | /// |
1653 | | /// Like AnnotateCachedTokens(), this routine replaces an |
1654 | | /// already-parsed (and resolved) token with an annotation |
1655 | | /// token. However, this routine only replaces the last token with |
1656 | | /// the annotation token; it does not affect any other cached |
1657 | | /// tokens. This function has no effect if backtracking is not |
1658 | | /// enabled. |
1659 | 0 | void ReplaceLastTokenWithAnnotation(const Token &Tok) { |
1660 | 0 | assert(Tok.isAnnotation() && "Expected annotation token"); |
1661 | 0 | if (CachedLexPos != 0 && isBacktrackEnabled()) |
1662 | 0 | CachedTokens[CachedLexPos-1] = Tok; |
1663 | 0 | } |
1664 | | |
1665 | | /// Enter an annotation token into the token stream. |
1666 | | void EnterAnnotationToken(SourceRange Range, tok::TokenKind Kind, |
1667 | | void *AnnotationVal); |
1668 | | |
1669 | | /// Determine whether it's possible for a future call to Lex to produce an |
1670 | | /// annotation token created by a previous call to EnterAnnotationToken. |
1671 | 1.91M | bool mightHavePendingAnnotationTokens() { |
1672 | 1.91M | return CurLexerKind != CLK_Lexer; |
1673 | 1.91M | } |
1674 | | |
1675 | | /// Update the current token to represent the provided |
1676 | | /// identifier, in order to cache an action performed by typo correction. |
1677 | 20 | void TypoCorrectToken(const Token &Tok) { |
1678 | 20 | assert(Tok.getIdentifierInfo() && "Expected identifier token"); |
1679 | 20 | if (CachedLexPos != 0 && isBacktrackEnabled()10 ) |
1680 | 10 | CachedTokens[CachedLexPos-1] = Tok; |
1681 | 20 | } |
1682 | | |
1683 | | /// Recompute the current lexer kind based on the CurLexer/ |
1684 | | /// CurTokenLexer pointers. |
1685 | | void recomputeCurLexerKind(); |
1686 | | |
1687 | | /// Returns true if incremental processing is enabled |
1688 | 18.4M | bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; } |
1689 | | |
1690 | | /// Enables the incremental processing |
1691 | 1.40k | void enableIncrementalProcessing(bool value = true) { |
1692 | 1.40k | IncrementalProcessing = value; |
1693 | 1.40k | } |
1694 | | |
1695 | | /// Specify the point at which code-completion will be performed. |
1696 | | /// |
1697 | | /// \param File the file in which code completion should occur. If |
1698 | | /// this file is included multiple times, code-completion will |
1699 | | /// perform completion the first time it is included. If NULL, this |
1700 | | /// function clears out the code-completion point. |
1701 | | /// |
1702 | | /// \param Line the line at which code completion should occur |
1703 | | /// (1-based). |
1704 | | /// |
1705 | | /// \param Column the column at which code completion should occur |
1706 | | /// (1-based). |
1707 | | /// |
1708 | | /// \returns true if an error occurred, false otherwise. |
1709 | | bool SetCodeCompletionPoint(const FileEntry *File, |
1710 | | unsigned Line, unsigned Column); |
1711 | | |
1712 | | /// Determine if we are performing code completion. |
1713 | 505M | bool isCodeCompletionEnabled() const { return CodeCompletionFile != nullptr; } |
1714 | | |
1715 | | /// Returns the location of the code-completion point. |
1716 | | /// |
1717 | | /// Returns an invalid location if code-completion is not enabled or the file |
1718 | | /// containing the code-completion point has not been lexed yet. |
1719 | 1.11M | SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; } |
1720 | | |
1721 | | /// Returns the start location of the file of code-completion point. |
1722 | | /// |
1723 | | /// Returns an invalid location if code-completion is not enabled or the file |
1724 | | /// containing the code-completion point has not been lexed yet. |
1725 | 37.8M | SourceLocation getCodeCompletionFileLoc() const { |
1726 | 37.8M | return CodeCompletionFileLoc; |
1727 | 37.8M | } |
1728 | | |
1729 | | /// Returns true if code-completion is enabled and we have hit the |
1730 | | /// code-completion point. |
1731 | 28.3M | bool isCodeCompletionReached() const { return CodeCompletionReached; } |
1732 | | |
1733 | | /// Note that we hit the code-completion point. |
1734 | 1.41k | void setCodeCompletionReached() { |
1735 | 1.41k | assert(isCodeCompletionEnabled() && "Code-completion not enabled!"); |
1736 | 0 | CodeCompletionReached = true; |
1737 | | // Silence any diagnostics that occur after we hit the code-completion. |
1738 | 1.41k | getDiagnostics().setSuppressAllDiagnostics(true); |
1739 | 1.41k | } |
1740 | | |
1741 | | /// The location of the currently-active \#pragma clang |
1742 | | /// arc_cf_code_audited begin. |
1743 | | /// |
1744 | | /// Returns an invalid location if there is no such pragma active. |
1745 | | std::pair<IdentifierInfo *, SourceLocation> |
1746 | 24.4M | getPragmaARCCFCodeAuditedInfo() const { |
1747 | 24.4M | return PragmaARCCFCodeAuditedInfo; |
1748 | 24.4M | } |
1749 | | |
1750 | | /// Set the location of the currently-active \#pragma clang |
1751 | | /// arc_cf_code_audited begin. An invalid location ends the pragma. |
1752 | | void setPragmaARCCFCodeAuditedInfo(IdentifierInfo *Ident, |
1753 | 65.0k | SourceLocation Loc) { |
1754 | 65.0k | PragmaARCCFCodeAuditedInfo = {Ident, Loc}; |
1755 | 65.0k | } |
1756 | | |
1757 | | /// The location of the currently-active \#pragma clang |
1758 | | /// assume_nonnull begin. |
1759 | | /// |
1760 | | /// Returns an invalid location if there is no such pragma active. |
1761 | 108M | SourceLocation getPragmaAssumeNonNullLoc() const { |
1762 | 108M | return PragmaAssumeNonNullLoc; |
1763 | 108M | } |
1764 | | |
1765 | | /// Set the location of the currently-active \#pragma clang |
1766 | | /// assume_nonnull begin. An invalid location ends the pragma. |
1767 | 146k | void setPragmaAssumeNonNullLoc(SourceLocation Loc) { |
1768 | 146k | PragmaAssumeNonNullLoc = Loc; |
1769 | 146k | } |
1770 | | |
1771 | | /// Get the location of the recorded unterminated \#pragma clang |
1772 | | /// assume_nonnull begin in the preamble, if one exists. |
1773 | | /// |
1774 | | /// Returns an invalid location if the premable did not end with |
1775 | | /// such a pragma active or if there is no recorded preamble. |
1776 | 5.56k | SourceLocation getPreambleRecordedPragmaAssumeNonNullLoc() const { |
1777 | 5.56k | return PreambleRecordedPragmaAssumeNonNullLoc; |
1778 | 5.56k | } |
1779 | | |
1780 | | /// Record the location of the unterminated \#pragma clang |
1781 | | /// assume_nonnull begin in the preamble. |
1782 | 5 | void setPreambleRecordedPragmaAssumeNonNullLoc(SourceLocation Loc) { |
1783 | 5 | PreambleRecordedPragmaAssumeNonNullLoc = Loc; |
1784 | 5 | } |
1785 | | |
1786 | | /// Set the directory in which the main file should be considered |
1787 | | /// to have been found, if it is not a real file. |
1788 | 2.05k | void setMainFileDir(const DirectoryEntry *Dir) { |
1789 | 2.05k | MainFileDir = Dir; |
1790 | 2.05k | } |
1791 | | |
1792 | | /// Instruct the preprocessor to skip part of the main source file. |
1793 | | /// |
1794 | | /// \param Bytes The number of bytes in the preamble to skip. |
1795 | | /// |
1796 | | /// \param StartOfLine Whether skipping these bytes puts the lexer at the |
1797 | | /// start of a line. |
1798 | 89.1k | void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) { |
1799 | 89.1k | SkipMainFilePreamble.first = Bytes; |
1800 | 89.1k | SkipMainFilePreamble.second = StartOfLine; |
1801 | 89.1k | } |
1802 | | |
1803 | | /// Forwarding function for diagnostics. This emits a diagnostic at |
1804 | | /// the specified Token's location, translating the token's start |
1805 | | /// position in the current buffer into a SourcePosition object for rendering. |
1806 | 784k | DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const { |
1807 | 784k | return Diags->Report(Loc, DiagID); |
1808 | 784k | } |
1809 | | |
1810 | 1.20M | DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const { |
1811 | 1.20M | return Diags->Report(Tok.getLocation(), DiagID); |
1812 | 1.20M | } |
1813 | | |
1814 | | /// Return the 'spelling' of the token at the given |
1815 | | /// location; does not go up to the spelling location or down to the |
1816 | | /// expansion location. |
1817 | | /// |
1818 | | /// \param buffer A buffer which will be used only if the token requires |
1819 | | /// "cleaning", e.g. if it contains trigraphs or escaped newlines |
1820 | | /// \param invalid If non-null, will be set \c true if an error occurs. |
1821 | | StringRef getSpelling(SourceLocation loc, |
1822 | | SmallVectorImpl<char> &buffer, |
1823 | 194 | bool *invalid = nullptr) const { |
1824 | 194 | return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid); |
1825 | 194 | } |
1826 | | |
1827 | | /// Return the 'spelling' of the Tok token. |
1828 | | /// |
1829 | | /// The spelling of a token is the characters used to represent the token in |
1830 | | /// the source file after trigraph expansion and escaped-newline folding. In |
1831 | | /// particular, this wants to get the true, uncanonicalized, spelling of |
1832 | | /// things like digraphs, UCNs, etc. |
1833 | | /// |
1834 | | /// \param Invalid If non-null, will be set \c true if an error occurs. |
1835 | 2.67M | std::string getSpelling(const Token &Tok, bool *Invalid = nullptr) const { |
1836 | 2.67M | return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid); |
1837 | 2.67M | } |
1838 | | |
1839 | | /// Get the spelling of a token into a preallocated buffer, instead |
1840 | | /// of as an std::string. |
1841 | | /// |
1842 | | /// The caller is required to allocate enough space for the token, which is |
1843 | | /// guaranteed to be at least Tok.getLength() bytes long. The length of the |
1844 | | /// actual result is returned. |
1845 | | /// |
1846 | | /// Note that this method may do two possible things: it may either fill in |
1847 | | /// the buffer specified with characters, or it may *change the input pointer* |
1848 | | /// to point to a constant buffer with the data already in it (avoiding a |
1849 | | /// copy). The caller is not allowed to modify the returned buffer pointer |
1850 | | /// if an internal buffer is returned. |
1851 | | unsigned getSpelling(const Token &Tok, const char *&Buffer, |
1852 | 29.3M | bool *Invalid = nullptr) const { |
1853 | 29.3M | return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid); |
1854 | 29.3M | } |
1855 | | |
1856 | | /// Get the spelling of a token into a SmallVector. |
1857 | | /// |
1858 | | /// Note that the returned StringRef may not point to the |
1859 | | /// supplied buffer if a copy can be avoided. |
1860 | | StringRef getSpelling(const Token &Tok, |
1861 | | SmallVectorImpl<char> &Buffer, |
1862 | | bool *Invalid = nullptr) const; |
1863 | | |
1864 | | /// Relex the token at the specified location. |
1865 | | /// \returns true if there was a failure, false on success. |
1866 | | bool getRawToken(SourceLocation Loc, Token &Result, |
1867 | 117 | bool IgnoreWhiteSpace = false) { |
1868 | 117 | return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts, IgnoreWhiteSpace); |
1869 | 117 | } |
1870 | | |
1871 | | /// Given a Token \p Tok that is a numeric constant with length 1, |
1872 | | /// return the character. |
1873 | | char |
1874 | | getSpellingOfSingleCharacterNumericConstant(const Token &Tok, |
1875 | 3.66M | bool *Invalid = nullptr) const { |
1876 | 3.66M | assert(Tok.is(tok::numeric_constant) && |
1877 | 3.66M | Tok.getLength() == 1 && "Called on unsupported token"); |
1878 | 0 | assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1"); |
1879 | | |
1880 | | // If the token is carrying a literal data pointer, just use it. |
1881 | 3.66M | if (const char *D = Tok.getLiteralData()) |
1882 | 3.66M | return *D; |
1883 | | |
1884 | | // Otherwise, fall back on getCharacterData, which is slower, but always |
1885 | | // works. |
1886 | 2.03k | return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid); |
1887 | 3.66M | } |
1888 | | |
1889 | | /// Retrieve the name of the immediate macro expansion. |
1890 | | /// |
1891 | | /// This routine starts from a source location, and finds the name of the |
1892 | | /// macro responsible for its immediate expansion. It looks through any |
1893 | | /// intervening macro argument expansions to compute this. It returns a |
1894 | | /// StringRef that refers to the SourceManager-owned buffer of the source |
1895 | | /// where that macro name is spelled. Thus, the result shouldn't out-live |
1896 | | /// the SourceManager. |
1897 | 32 | StringRef getImmediateMacroName(SourceLocation Loc) { |
1898 | 32 | return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts()); |
1899 | 32 | } |
1900 | | |
1901 | | /// Plop the specified string into a scratch buffer and set the |
1902 | | /// specified token's location and length to it. |
1903 | | /// |
1904 | | /// If specified, the source location provides a location of the expansion |
1905 | | /// point of the token. |
1906 | | void CreateString(StringRef Str, Token &Tok, |
1907 | | SourceLocation ExpansionLocStart = SourceLocation(), |
1908 | | SourceLocation ExpansionLocEnd = SourceLocation()); |
1909 | | |
1910 | | /// Split the first Length characters out of the token starting at TokLoc |
1911 | | /// and return a location pointing to the split token. Re-lexing from the |
1912 | | /// split token will return the split token rather than the original. |
1913 | | SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length); |
1914 | | |
1915 | | /// Computes the source location just past the end of the |
1916 | | /// token at this source location. |
1917 | | /// |
1918 | | /// This routine can be used to produce a source location that |
1919 | | /// points just past the end of the token referenced by \p Loc, and |
1920 | | /// is generally used when a diagnostic needs to point just after a |
1921 | | /// token where it expected something different that it received. If |
1922 | | /// the returned source location would not be meaningful (e.g., if |
1923 | | /// it points into a macro), this routine returns an invalid |
1924 | | /// source location. |
1925 | | /// |
1926 | | /// \param Offset an offset from the end of the token, where the source |
1927 | | /// location should refer to. The default offset (0) produces a source |
1928 | | /// location pointing just past the end of the token; an offset of 1 produces |
1929 | | /// a source location pointing to the last character in the token, etc. |
1930 | 8.57k | SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0) { |
1931 | 8.57k | return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts); |
1932 | 8.57k | } |
1933 | | |
1934 | | /// Returns true if the given MacroID location points at the first |
1935 | | /// token of the macro expansion. |
1936 | | /// |
1937 | | /// \param MacroBegin If non-null and function returns true, it is set to |
1938 | | /// begin location of the macro. |
1939 | | bool isAtStartOfMacroExpansion(SourceLocation loc, |
1940 | 29 | SourceLocation *MacroBegin = nullptr) const { |
1941 | 29 | return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts, |
1942 | 29 | MacroBegin); |
1943 | 29 | } |
1944 | | |
1945 | | /// Returns true if the given MacroID location points at the last |
1946 | | /// token of the macro expansion. |
1947 | | /// |
1948 | | /// \param MacroEnd If non-null and function returns true, it is set to |
1949 | | /// end location of the macro. |
1950 | | bool isAtEndOfMacroExpansion(SourceLocation loc, |
1951 | 30 | SourceLocation *MacroEnd = nullptr) const { |
1952 | 30 | return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd); |
1953 | 30 | } |
1954 | | |
1955 | | /// Print the token to stderr, used for debugging. |
1956 | | void DumpToken(const Token &Tok, bool DumpFlags = false) const; |
1957 | | void DumpLocation(SourceLocation Loc) const; |
1958 | | void DumpMacro(const MacroInfo &MI) const; |
1959 | | void dumpMacroInfo(const IdentifierInfo *II); |
1960 | | |
1961 | | /// Given a location that specifies the start of a |
1962 | | /// token, return a new location that specifies a character within the token. |
1963 | | SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, |
1964 | 2.96k | unsigned Char) const { |
1965 | 2.96k | return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts); |
1966 | 2.96k | } |
1967 | | |
1968 | | /// Increment the counters for the number of token paste operations |
1969 | | /// performed. |
1970 | | /// |
1971 | | /// If fast was specified, this is a 'fast paste' case we handled. |
1972 | 6.74M | void IncrementPasteCounter(bool isFast) { |
1973 | 6.74M | if (isFast) |
1974 | 6.70M | ++NumFastTokenPaste; |
1975 | 43.7k | else |
1976 | 43.7k | ++NumTokenPaste; |
1977 | 6.74M | } |
1978 | | |
1979 | | void PrintStats(); |
1980 | | |
1981 | | size_t getTotalMemory() const; |
1982 | | |
1983 | | /// When the macro expander pastes together a comment (/##/) in Microsoft |
1984 | | /// mode, this method handles updating the current state, returning the |
1985 | | /// token on the next source line. |
1986 | | void HandleMicrosoftCommentPaste(Token &Tok); |
1987 | | |
1988 | | //===--------------------------------------------------------------------===// |
1989 | | // Preprocessor callback methods. These are invoked by a lexer as various |
1990 | | // directives and events are found. |
1991 | | |
1992 | | /// Given a tok::raw_identifier token, look up the |
1993 | | /// identifier information for the token and install it into the token, |
1994 | | /// updating the token kind accordingly. |
1995 | | IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const; |
1996 | | |
1997 | | private: |
1998 | | llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons; |
1999 | | |
2000 | | public: |
2001 | | /// Specifies the reason for poisoning an identifier. |
2002 | | /// |
2003 | | /// If that identifier is accessed while poisoned, then this reason will be |
2004 | | /// used instead of the default "poisoned" diagnostic. |
2005 | | void SetPoisonReason(IdentifierInfo *II, unsigned DiagID); |
2006 | | |
2007 | | /// Display reason for poisoned identifier. |
2008 | | void HandlePoisonedIdentifier(Token & Identifier); |
2009 | | |
2010 | 0 | void MaybeHandlePoisonedIdentifier(Token & Identifier) { |
2011 | 0 | if(IdentifierInfo * II = Identifier.getIdentifierInfo()) { |
2012 | 0 | if(II->isPoisoned()) { |
2013 | 0 | HandlePoisonedIdentifier(Identifier); |
2014 | 0 | } |
2015 | 0 | } |
2016 | 0 | } |
2017 | | |
2018 | | private: |
2019 | | /// Identifiers used for SEH handling in Borland. These are only |
2020 | | /// allowed in particular circumstances |
2021 | | // __except block |
2022 | | IdentifierInfo *Ident__exception_code, |
2023 | | *Ident___exception_code, |
2024 | | *Ident_GetExceptionCode; |
2025 | | // __except filter expression |
2026 | | IdentifierInfo *Ident__exception_info, |
2027 | | *Ident___exception_info, |
2028 | | *Ident_GetExceptionInfo; |
2029 | | // __finally |
2030 | | IdentifierInfo *Ident__abnormal_termination, |
2031 | | *Ident___abnormal_termination, |
2032 | | *Ident_AbnormalTermination; |
2033 | | |
2034 | | const char *getCurLexerEndPos(); |
2035 | | void diagnoseMissingHeaderInUmbrellaDir(const Module &Mod); |
2036 | | |
2037 | | public: |
2038 | | void PoisonSEHIdentifiers(bool Poison = true); // Borland |
2039 | | |
2040 | | /// Callback invoked when the lexer reads an identifier and has |
2041 | | /// filled in the tokens IdentifierInfo member. |
2042 | | /// |
2043 | | /// This callback potentially macro expands it or turns it into a named |
2044 | | /// token (like 'for'). |
2045 | | /// |
2046 | | /// \returns true if we actually computed a token, false if we need to |
2047 | | /// lex again. |
2048 | | bool HandleIdentifier(Token &Identifier); |
2049 | | |
2050 | | /// Callback invoked when the lexer hits the end of the current file. |
2051 | | /// |
2052 | | /// This either returns the EOF token and returns true, or |
2053 | | /// pops a level off the include stack and returns false, at which point the |
2054 | | /// client should call lex again. |
2055 | | bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); |
2056 | | |
2057 | | /// Callback invoked when the current TokenLexer hits the end of its |
2058 | | /// token stream. |
2059 | | bool HandleEndOfTokenLexer(Token &Result); |
2060 | | |
2061 | | /// Callback invoked when the lexer sees a # token at the start of a |
2062 | | /// line. |
2063 | | /// |
2064 | | /// This consumes the directive, modifies the lexer/preprocessor state, and |
2065 | | /// advances the lexer(s) so that the next token read is the correct one. |
2066 | | void HandleDirective(Token &Result); |
2067 | | |
2068 | | /// Ensure that the next token is a tok::eod token. |
2069 | | /// |
2070 | | /// If not, emit a diagnostic and consume up until the eod. |
2071 | | /// If \p EnableMacros is true, then we consider macros that expand to zero |
2072 | | /// tokens as being ok. |
2073 | | /// |
2074 | | /// \return The location of the end of the directive (the terminating |
2075 | | /// newline). |
2076 | | SourceLocation CheckEndOfDirective(const char *DirType, |
2077 | | bool EnableMacros = false); |
2078 | | |
2079 | | /// Read and discard all tokens remaining on the current line until |
2080 | | /// the tok::eod token is found. Returns the range of the skipped tokens. |
2081 | | SourceRange DiscardUntilEndOfDirective(); |
2082 | | |
2083 | | /// Returns true if the preprocessor has seen a use of |
2084 | | /// __DATE__ or __TIME__ in the file so far. |
2085 | 5.56k | bool SawDateOrTime() const { |
2086 | 5.56k | return DATELoc != SourceLocation() || TIMELoc != SourceLocation()5.56k ; |
2087 | 5.56k | } |
2088 | 5.56k | unsigned getCounterValue() const { return CounterValue; } |
2089 | 172 | void setCounterValue(unsigned V) { CounterValue = V; } |
2090 | | |
2091 | 5.34M | LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const { |
2092 | 5.34M | assert(CurrentFPEvalMethod != LangOptions::FEM_UnsetOnCommandLine && |
2093 | 5.34M | "FPEvalMethod should be set either from command line or from the " |
2094 | 5.34M | "target info"); |
2095 | 0 | return CurrentFPEvalMethod; |
2096 | 5.34M | } |
2097 | | |
2098 | 1.65k | LangOptions::FPEvalMethodKind getTUFPEvalMethod() const { |
2099 | 1.65k | return TUFPEvalMethod; |
2100 | 1.65k | } |
2101 | | |
2102 | 5.25M | SourceLocation getLastFPEvalPragmaLocation() const { |
2103 | 5.25M | return LastFPEvalPragmaLocation; |
2104 | 5.25M | } |
2105 | | |
2106 | 16 | LangOptions::FPEvalMethodKind getLastFPEvalMethod() const { |
2107 | 16 | return LastFPEvalMethod; |
2108 | 16 | } |
2109 | | |
2110 | 118 | void setLastFPEvalMethod(LangOptions::FPEvalMethodKind Val) { |
2111 | 118 | LastFPEvalMethod = Val; |
2112 | 118 | } |
2113 | | |
2114 | | void setCurrentFPEvalMethod(SourceLocation PragmaLoc, |
2115 | 5.12M | LangOptions::FPEvalMethodKind Val) { |
2116 | 5.12M | assert(Val != LangOptions::FEM_UnsetOnCommandLine && |
2117 | 5.12M | "FPEvalMethod should never be set to FEM_UnsetOnCommandLine"); |
2118 | | // This is the location of the '#pragma float_control" where the |
2119 | | // execution state is modifed. |
2120 | 0 | LastFPEvalPragmaLocation = PragmaLoc; |
2121 | 5.12M | CurrentFPEvalMethod = Val; |
2122 | 5.12M | TUFPEvalMethod = Val; |
2123 | 5.12M | } |
2124 | | |
2125 | 89.3k | void setTUFPEvalMethod(LangOptions::FPEvalMethodKind Val) { |
2126 | 89.3k | assert(Val != LangOptions::FEM_UnsetOnCommandLine && |
2127 | 89.3k | "TUPEvalMethod should never be set to FEM_UnsetOnCommandLine"); |
2128 | 0 | TUFPEvalMethod = Val; |
2129 | 89.3k | } |
2130 | | |
2131 | | /// Retrieves the module that we're currently building, if any. |
2132 | | Module *getCurrentModule(); |
2133 | | |
2134 | | /// Allocate a new MacroInfo object with the provided SourceLocation. |
2135 | | MacroInfo *AllocateMacroInfo(SourceLocation L); |
2136 | | |
2137 | | /// Turn the specified lexer token into a fully checked and spelled |
2138 | | /// filename, e.g. as an operand of \#include. |
2139 | | /// |
2140 | | /// The caller is expected to provide a buffer that is large enough to hold |
2141 | | /// the spelling of the filename, but is also expected to handle the case |
2142 | | /// when this method decides to use a different buffer. |
2143 | | /// |
2144 | | /// \returns true if the input filename was in <>'s or false if it was |
2145 | | /// in ""'s. |
2146 | | bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Buffer); |
2147 | | |
2148 | | /// Given a "foo" or \<foo> reference, look up the indicated file. |
2149 | | /// |
2150 | | /// Returns None on failure. \p isAngled indicates whether the file |
2151 | | /// reference is for system \#include's or not (i.e. using <> instead of ""). |
2152 | | Optional<FileEntryRef> |
2153 | | LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, |
2154 | | ConstSearchDirIterator FromDir, const FileEntry *FromFile, |
2155 | | ConstSearchDirIterator *CurDir, SmallVectorImpl<char> *SearchPath, |
2156 | | SmallVectorImpl<char> *RelativePath, |
2157 | | ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, |
2158 | | bool *IsFrameworkFound, bool SkipCache = false); |
2159 | | |
2160 | | /// Return true if we're in the top-level file, not in a \#include. |
2161 | | bool isInPrimaryFile() const; |
2162 | | |
2163 | | /// Lex an on-off-switch (C99 6.10.6p2) and verify that it is |
2164 | | /// followed by EOD. Return true if the token is not a valid on-off-switch. |
2165 | | bool LexOnOffSwitch(tok::OnOffSwitch &Result); |
2166 | | |
2167 | | bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, |
2168 | | bool *ShadowFlag = nullptr); |
2169 | | |
2170 | | void EnterSubmodule(Module *M, SourceLocation ImportLoc, bool ForPragma); |
2171 | | Module *LeaveSubmodule(bool ForPragma); |
2172 | | |
2173 | | private: |
2174 | | friend void TokenLexer::ExpandFunctionArguments(); |
2175 | | |
2176 | 174M | void PushIncludeMacroStack() { |
2177 | 174M | assert(CurLexerKind != CLK_CachingLexer && "cannot push a caching lexer"); |
2178 | 0 | IncludeMacroStack.emplace_back(CurLexerKind, CurLexerSubmodule, |
2179 | 174M | std::move(CurLexer), CurPPLexer, |
2180 | 174M | std::move(CurTokenLexer), CurDirLookup); |
2181 | 174M | CurPPLexer = nullptr; |
2182 | 174M | } |
2183 | | |
2184 | 174M | void PopIncludeMacroStack() { |
2185 | 174M | CurLexer = std::move(IncludeMacroStack.back().TheLexer); |
2186 | 174M | CurPPLexer = IncludeMacroStack.back().ThePPLexer; |
2187 | 174M | CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer); |
2188 | 174M | CurDirLookup = IncludeMacroStack.back().TheDirLookup; |
2189 | 174M | CurLexerSubmodule = IncludeMacroStack.back().TheSubmodule; |
2190 | 174M | CurLexerKind = IncludeMacroStack.back().CurLexerKind; |
2191 | 174M | IncludeMacroStack.pop_back(); |
2192 | 174M | } |
2193 | | |
2194 | | void PropagateLineStartLeadingSpaceInfo(Token &Result); |
2195 | | |
2196 | | /// Determine whether we need to create module macros for #defines in the |
2197 | | /// current context. |
2198 | | bool needModuleMacros() const; |
2199 | | |
2200 | | /// Update the set of active module macros and ambiguity flag for a module |
2201 | | /// macro name. |
2202 | | void updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info); |
2203 | | |
2204 | | DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI, |
2205 | | SourceLocation Loc); |
2206 | | UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc); |
2207 | | VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc, |
2208 | | bool isPublic); |
2209 | | |
2210 | | /// Lex and validate a macro name, which occurs after a |
2211 | | /// \#define or \#undef. |
2212 | | /// |
2213 | | /// \param MacroNameTok Token that represents the name defined or undefined. |
2214 | | /// \param IsDefineUndef Kind if preprocessor directive. |
2215 | | /// \param ShadowFlag Points to flag that is set if macro name shadows |
2216 | | /// a keyword. |
2217 | | /// |
2218 | | /// This emits a diagnostic, sets the token kind to eod, |
2219 | | /// and discards the rest of the macro line if the macro name is invalid. |
2220 | | void ReadMacroName(Token &MacroNameTok, MacroUse IsDefineUndef = MU_Other, |
2221 | | bool *ShadowFlag = nullptr); |
2222 | | |
2223 | | /// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the |
2224 | | /// entire line) of the macro's tokens and adds them to MacroInfo, and while |
2225 | | /// doing so performs certain validity checks including (but not limited to): |
2226 | | /// - # (stringization) is followed by a macro parameter |
2227 | | /// \param MacroNameTok - Token that represents the macro name |
2228 | | /// \param ImmediatelyAfterHeaderGuard - Macro follows an #ifdef header guard |
2229 | | /// |
2230 | | /// Either returns a pointer to a MacroInfo object OR emits a diagnostic and |
2231 | | /// returns a nullptr if an invalid sequence of tokens is encountered. |
2232 | | MacroInfo *ReadOptionalMacroParameterListAndBody( |
2233 | | const Token &MacroNameTok, bool ImmediatelyAfterHeaderGuard); |
2234 | | |
2235 | | /// The ( starting an argument list of a macro definition has just been read. |
2236 | | /// Lex the rest of the parameters and the closing ), updating \p MI with |
2237 | | /// what we learn and saving in \p LastTok the last token read. |
2238 | | /// Return true if an error occurs parsing the arg list. |
2239 | | bool ReadMacroParameterList(MacroInfo *MI, Token& LastTok); |
2240 | | |
2241 | | /// Provide a suggestion for a typoed directive. If there is no typo, then |
2242 | | /// just skip suggesting. |
2243 | | /// |
2244 | | /// \param Tok - Token that represents the directive |
2245 | | /// \param Directive - String reference for the directive name |
2246 | | /// \param EndLoc - End location for fixit |
2247 | | void SuggestTypoedDirective(const Token &Tok, |
2248 | | StringRef Directive, |
2249 | | const SourceLocation &EndLoc) const; |
2250 | | |
2251 | | /// We just read a \#if or related directive and decided that the |
2252 | | /// subsequent tokens are in the \#if'd out portion of the |
2253 | | /// file. Lex the rest of the file, until we see an \#endif. If \p |
2254 | | /// FoundNonSkipPortion is true, then we have already emitted code for part of |
2255 | | /// this \#if directive, so \#else/\#elif blocks should never be entered. If |
2256 | | /// \p FoundElse is false, then \#else directives are ok, if not, then we have |
2257 | | /// already seen one so a \#else directive is a duplicate. When this returns, |
2258 | | /// the caller can lex the first valid token. |
2259 | | void SkipExcludedConditionalBlock(SourceLocation HashTokenLoc, |
2260 | | SourceLocation IfTokenLoc, |
2261 | | bool FoundNonSkipPortion, bool FoundElse, |
2262 | | SourceLocation ElseLoc = SourceLocation()); |
2263 | | |
2264 | | /// Information about the result for evaluating an expression for a |
2265 | | /// preprocessor directive. |
2266 | | struct DirectiveEvalResult { |
2267 | | /// Whether the expression was evaluated as true or not. |
2268 | | bool Conditional; |
2269 | | |
2270 | | /// True if the expression contained identifiers that were undefined. |
2271 | | bool IncludedUndefinedIds; |
2272 | | |
2273 | | /// The source range for the expression. |
2274 | | SourceRange ExprRange; |
2275 | | }; |
2276 | | |
2277 | | /// Evaluate an integer constant expression that may occur after a |
2278 | | /// \#if or \#elif directive and return a \p DirectiveEvalResult object. |
2279 | | /// |
2280 | | /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro. |
2281 | | DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); |
2282 | | |
2283 | | /// Process a '__has_include("path")' expression. |
2284 | | /// |
2285 | | /// Returns true if successful. |
2286 | | bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II); |
2287 | | |
2288 | | /// Process '__has_include_next("path")' expression. |
2289 | | /// |
2290 | | /// Returns true if successful. |
2291 | | bool EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II); |
2292 | | |
2293 | | /// Get the directory and file from which to start \#include_next lookup. |
2294 | | std::pair<ConstSearchDirIterator, const FileEntry *> |
2295 | | getIncludeNextStart(const Token &IncludeNextTok) const; |
2296 | | |
2297 | | /// Install the standard preprocessor pragmas: |
2298 | | /// \#pragma GCC poison/system_header/dependency and \#pragma once. |
2299 | | void RegisterBuiltinPragmas(); |
2300 | | |
2301 | | /// Register builtin macros such as __LINE__ with the identifier table. |
2302 | | void RegisterBuiltinMacros(); |
2303 | | |
2304 | | /// If an identifier token is read that is to be expanded as a macro, handle |
2305 | | /// it and return the next token as 'Tok'. If we lexed a token, return true; |
2306 | | /// otherwise the caller should lex again. |
2307 | | bool HandleMacroExpandedIdentifier(Token &Identifier, const MacroDefinition &MD); |
2308 | | |
2309 | | /// Cache macro expanded tokens for TokenLexers. |
2310 | | // |
2311 | | /// Works like a stack; a TokenLexer adds the macro expanded tokens that is |
2312 | | /// going to lex in the cache and when it finishes the tokens are removed |
2313 | | /// from the end of the cache. |
2314 | | Token *cacheMacroExpandedTokens(TokenLexer *tokLexer, |
2315 | | ArrayRef<Token> tokens); |
2316 | | |
2317 | | void removeCachedMacroExpandedTokensOfLastLexer(); |
2318 | | |
2319 | | /// Determine whether the next preprocessor token to be |
2320 | | /// lexed is a '('. If so, consume the token and return true, if not, this |
2321 | | /// method should have no observable side-effect on the lexed tokens. |
2322 | | bool isNextPPTokenLParen(); |
2323 | | |
2324 | | /// After reading "MACRO(", this method is invoked to read all of the formal |
2325 | | /// arguments specified for the macro invocation. Returns null on error. |
2326 | | MacroArgs *ReadMacroCallArgumentList(Token &MacroName, MacroInfo *MI, |
2327 | | SourceLocation &MacroEnd); |
2328 | | |
2329 | | /// If an identifier token is read that is to be expanded |
2330 | | /// as a builtin macro, handle it and return the next token as 'Tok'. |
2331 | | void ExpandBuiltinMacro(Token &Tok); |
2332 | | |
2333 | | /// Read a \c _Pragma directive, slice it up, process it, then |
2334 | | /// return the first token after the directive. |
2335 | | /// This assumes that the \c _Pragma token has just been read into \p Tok. |
2336 | | void Handle_Pragma(Token &Tok); |
2337 | | |
2338 | | /// Like Handle_Pragma except the pragma text is not enclosed within |
2339 | | /// a string literal. |
2340 | | void HandleMicrosoft__pragma(Token &Tok); |
2341 | | |
2342 | | /// Add a lexer to the top of the include stack and |
2343 | | /// start lexing tokens from it instead of the current buffer. |
2344 | | void EnterSourceFileWithLexer(Lexer *TheLexer, ConstSearchDirIterator Dir); |
2345 | | |
2346 | | /// Set the FileID for the preprocessor predefines. |
2347 | 89.0k | void setPredefinesFileID(FileID FID) { |
2348 | 89.0k | assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!"); |
2349 | 0 | PredefinesFileID = FID; |
2350 | 89.0k | } |
2351 | | |
2352 | | /// Set the FileID for the PCH through header. |
2353 | | void setPCHThroughHeaderFileID(FileID FID); |
2354 | | |
2355 | | /// Returns true if we are lexing from a file and not a |
2356 | | /// pragma or a macro. |
2357 | 1.89M | static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) { |
2358 | 1.89M | return L ? !L->isPragmaLexer()1.89M : P != nullptr19 ; |
2359 | 1.89M | } |
2360 | | |
2361 | 30.1k | static bool IsFileLexer(const IncludeStackInfo& I) { |
2362 | 30.1k | return IsFileLexer(I.TheLexer.get(), I.ThePPLexer); |
2363 | 30.1k | } |
2364 | | |
2365 | 1.86M | bool IsFileLexer() const { |
2366 | 1.86M | return IsFileLexer(CurLexer.get(), CurPPLexer); |
2367 | 1.86M | } |
2368 | | |
2369 | | //===--------------------------------------------------------------------===// |
2370 | | // Caching stuff. |
2371 | | void CachingLex(Token &Result); |
2372 | | |
2373 | 551M | bool InCachingLexMode() const { |
2374 | | // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means |
2375 | | // that we are past EOF, not that we are in CachingLex mode. |
2376 | 551M | return !CurPPLexer && !CurTokenLexer384M && !IncludeMacroStack.empty()354M ; |
2377 | 551M | } |
2378 | | |
2379 | | void EnterCachingLexMode(); |
2380 | | void EnterCachingLexModeUnchecked(); |
2381 | | |
2382 | 204M | void ExitCachingLexMode() { |
2383 | 204M | if (InCachingLexMode()) |
2384 | 122M | RemoveTopOfLexerStack(); |
2385 | 204M | } |
2386 | | |
2387 | | const Token &PeekAhead(unsigned N); |
2388 | | void AnnotatePreviousCachedTokens(const Token &Tok); |
2389 | | |
2390 | | //===--------------------------------------------------------------------===// |
2391 | | /// Handle*Directive - implement the various preprocessor directives. These |
2392 | | /// should side-effect the current preprocessor object so that the next call |
2393 | | /// to Lex() will return the appropriate token next. |
2394 | | void HandleLineDirective(); |
2395 | | void HandleDigitDirective(Token &Tok); |
2396 | | void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); |
2397 | | void HandleIdentSCCSDirective(Token &Tok); |
2398 | | void HandleMacroPublicDirective(Token &Tok); |
2399 | | void HandleMacroPrivateDirective(); |
2400 | | |
2401 | | /// An additional notification that can be produced by a header inclusion or |
2402 | | /// import to tell the parser what happened. |
2403 | | struct ImportAction { |
2404 | | enum ActionKind { |
2405 | | None, |
2406 | | ModuleBegin, |
2407 | | ModuleImport, |
2408 | | SkippedModuleImport, |
2409 | | Failure, |
2410 | | } Kind; |
2411 | | Module *ModuleForHeader = nullptr; |
2412 | | |
2413 | | ImportAction(ActionKind AK, Module *Mod = nullptr) |
2414 | 1.58M | : Kind(AK), ModuleForHeader(Mod) { |
2415 | 1.58M | assert((AK == None || Mod || AK == Failure) && |
2416 | 1.58M | "no module for module action"); |
2417 | 1.58M | } |
2418 | | }; |
2419 | | |
2420 | | Optional<FileEntryRef> LookupHeaderIncludeOrImport( |
2421 | | ConstSearchDirIterator *CurDir, StringRef &Filename, |
2422 | | SourceLocation FilenameLoc, CharSourceRange FilenameRange, |
2423 | | const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl, |
2424 | | bool &IsMapped, ConstSearchDirIterator LookupFrom, |
2425 | | const FileEntry *LookupFromFile, StringRef &LookupFilename, |
2426 | | SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath, |
2427 | | ModuleMap::KnownHeader &SuggestedModule, bool isAngled); |
2428 | | |
2429 | | // File inclusion. |
2430 | | void HandleIncludeDirective(SourceLocation HashLoc, Token &Tok, |
2431 | | ConstSearchDirIterator LookupFrom = nullptr, |
2432 | | const FileEntry *LookupFromFile = nullptr); |
2433 | | ImportAction |
2434 | | HandleHeaderIncludeOrImport(SourceLocation HashLoc, Token &IncludeTok, |
2435 | | Token &FilenameTok, SourceLocation EndLoc, |
2436 | | ConstSearchDirIterator LookupFrom = nullptr, |
2437 | | const FileEntry *LookupFromFile = nullptr); |
2438 | | void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok); |
2439 | | void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok); |
2440 | | void HandleImportDirective(SourceLocation HashLoc, Token &Tok); |
2441 | | void HandleMicrosoftImportDirective(Token &Tok); |
2442 | | |
2443 | | public: |
2444 | | /// Check that the given module is available, producing a diagnostic if not. |
2445 | | /// \return \c true if the check failed (because the module is not available). |
2446 | | /// \c false if the module appears to be usable. |
2447 | | static bool checkModuleIsAvailable(const LangOptions &LangOpts, |
2448 | | const TargetInfo &TargetInfo, |
2449 | | DiagnosticsEngine &Diags, Module *M); |
2450 | | |
2451 | | // Module inclusion testing. |
2452 | | /// Find the module that owns the source or header file that |
2453 | | /// \p Loc points to. If the location is in a file that was included |
2454 | | /// into a module, or is outside any module, returns nullptr. |
2455 | | Module *getModuleForLocation(SourceLocation Loc); |
2456 | | |
2457 | | /// We want to produce a diagnostic at location IncLoc concerning an |
2458 | | /// unreachable effect at location MLoc (eg, where a desired entity was |
2459 | | /// declared or defined). Determine whether the right way to make MLoc |
2460 | | /// reachable is by #include, and if so, what header should be included. |
2461 | | /// |
2462 | | /// This is not necessarily fast, and might load unexpected module maps, so |
2463 | | /// should only be called by code that intends to produce an error. |
2464 | | /// |
2465 | | /// \param IncLoc The location at which the missing effect was detected. |
2466 | | /// \param MLoc A location within an unimported module at which the desired |
2467 | | /// effect occurred. |
2468 | | /// \return A file that can be #included to provide the desired effect. Null |
2469 | | /// if no such file could be determined or if a #include is not |
2470 | | /// appropriate (eg, if a module should be imported instead). |
2471 | | const FileEntry *getHeaderToIncludeForDiagnostics(SourceLocation IncLoc, |
2472 | | SourceLocation MLoc); |
2473 | | |
2474 | 1.20M | bool isRecordingPreamble() const { |
2475 | 1.20M | return PreambleConditionalStack.isRecording(); |
2476 | 1.20M | } |
2477 | | |
2478 | 92 | bool hasRecordedPreamble() const { |
2479 | 92 | return PreambleConditionalStack.hasRecordedPreamble(); |
2480 | 92 | } |
2481 | | |
2482 | 7 | ArrayRef<PPConditionalInfo> getPreambleConditionalStack() const { |
2483 | 7 | return PreambleConditionalStack.getStack(); |
2484 | 7 | } |
2485 | | |
2486 | 92 | void setRecordedPreambleConditionalStack(ArrayRef<PPConditionalInfo> s) { |
2487 | 92 | PreambleConditionalStack.setStack(s); |
2488 | 92 | } |
2489 | | |
2490 | | void setReplayablePreambleConditionalStack(ArrayRef<PPConditionalInfo> s, |
2491 | 28 | llvm::Optional<PreambleSkipInfo> SkipInfo) { |
2492 | 28 | PreambleConditionalStack.startReplaying(); |
2493 | 28 | PreambleConditionalStack.setStack(s); |
2494 | 28 | PreambleConditionalStack.SkipInfo = SkipInfo; |
2495 | 28 | } |
2496 | | |
2497 | 7 | llvm::Optional<PreambleSkipInfo> getPreambleSkipInfo() const { |
2498 | 7 | return PreambleConditionalStack.SkipInfo; |
2499 | 7 | } |
2500 | | |
2501 | | private: |
2502 | | /// After processing predefined file, initialize the conditional stack from |
2503 | | /// the preamble. |
2504 | | void replayPreambleConditionalStack(); |
2505 | | |
2506 | | // Macro handling. |
2507 | | void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard); |
2508 | | void HandleUndefDirective(); |
2509 | | |
2510 | | // Conditional Inclusion. |
2511 | | void HandleIfdefDirective(Token &Result, const Token &HashToken, |
2512 | | bool isIfndef, bool ReadAnyTokensBeforeDirective); |
2513 | | void HandleIfDirective(Token &IfToken, const Token &HashToken, |
2514 | | bool ReadAnyTokensBeforeDirective); |
2515 | | void HandleEndifDirective(Token &EndifToken); |
2516 | | void HandleElseDirective(Token &Result, const Token &HashToken); |
2517 | | void HandleElifFamilyDirective(Token &ElifToken, const Token &HashToken, |
2518 | | tok::PPKeywordKind Kind); |
2519 | | |
2520 | | // Pragmas. |
2521 | | void HandlePragmaDirective(PragmaIntroducer Introducer); |
2522 | | |
2523 | | public: |
2524 | | void HandlePragmaOnce(Token &OnceTok); |
2525 | | void HandlePragmaMark(Token &MarkTok); |
2526 | | void HandlePragmaPoison(); |
2527 | | void HandlePragmaSystemHeader(Token &SysHeaderTok); |
2528 | | void HandlePragmaDependency(Token &DependencyTok); |
2529 | | void HandlePragmaPushMacro(Token &Tok); |
2530 | | void HandlePragmaPopMacro(Token &Tok); |
2531 | | void HandlePragmaIncludeAlias(Token &Tok); |
2532 | | void HandlePragmaModuleBuild(Token &Tok); |
2533 | | void HandlePragmaHdrstop(Token &Tok); |
2534 | | IdentifierInfo *ParsePragmaPushOrPopMacro(Token &Tok); |
2535 | | |
2536 | | // Return true and store the first token only if any CommentHandler |
2537 | | // has inserted some tokens and getCommentRetentionState() is false. |
2538 | | bool HandleComment(Token &result, SourceRange Comment); |
2539 | | |
2540 | | /// A macro is used, update information about macros that need unused |
2541 | | /// warnings. |
2542 | | void markMacroAsUsed(MacroInfo *MI); |
2543 | | |
2544 | | void addMacroDeprecationMsg(const IdentifierInfo *II, std::string Msg, |
2545 | 26 | SourceLocation AnnotationLoc) { |
2546 | 26 | auto Annotations = AnnotationInfos.find(II); |
2547 | 26 | if (Annotations == AnnotationInfos.end()) |
2548 | 22 | AnnotationInfos.insert(std::make_pair( |
2549 | 22 | II, |
2550 | 22 | MacroAnnotations::makeDeprecation(AnnotationLoc, std::move(Msg)))); |
2551 | 4 | else |
2552 | 4 | Annotations->second.DeprecationInfo = |
2553 | 4 | MacroAnnotationInfo{AnnotationLoc, std::move(Msg)}; |
2554 | 26 | } |
2555 | | |
2556 | | void addRestrictExpansionMsg(const IdentifierInfo *II, std::string Msg, |
2557 | 7 | SourceLocation AnnotationLoc) { |
2558 | 7 | auto Annotations = AnnotationInfos.find(II); |
2559 | 7 | if (Annotations == AnnotationInfos.end()) |
2560 | 3 | AnnotationInfos.insert( |
2561 | 3 | std::make_pair(II, MacroAnnotations::makeRestrictExpansion( |
2562 | 3 | AnnotationLoc, std::move(Msg)))); |
2563 | 4 | else |
2564 | 4 | Annotations->second.RestrictExpansionInfo = |
2565 | 4 | MacroAnnotationInfo{AnnotationLoc, std::move(Msg)}; |
2566 | 7 | } |
2567 | | |
2568 | 3 | void addFinalLoc(const IdentifierInfo *II, SourceLocation AnnotationLoc) { |
2569 | 3 | auto Annotations = AnnotationInfos.find(II); |
2570 | 3 | if (Annotations == AnnotationInfos.end()) |
2571 | 3 | AnnotationInfos.insert( |
2572 | 3 | std::make_pair(II, MacroAnnotations::makeFinal(AnnotationLoc))); |
2573 | 0 | else |
2574 | 0 | Annotations->second.FinalAnnotationLoc = AnnotationLoc; |
2575 | 3 | } |
2576 | | |
2577 | 30 | const MacroAnnotations &getMacroAnnotations(const IdentifierInfo *II) const { |
2578 | 30 | return AnnotationInfos.find(II)->second; |
2579 | 30 | } |
2580 | | |
2581 | 60.7M | void emitMacroExpansionWarnings(const Token &Identifier) const { |
2582 | 60.7M | if (Identifier.getIdentifierInfo()->isDeprecatedMacro()) |
2583 | 14 | emitMacroDeprecationWarning(Identifier); |
2584 | | |
2585 | 60.7M | if (Identifier.getIdentifierInfo()->isRestrictExpansion() && |
2586 | 60.7M | !SourceMgr.isInMainFile(Identifier.getLocation())12 ) |
2587 | 10 | emitRestrictExpansionWarning(Identifier); |
2588 | 60.7M | } |
2589 | | |
2590 | | static void processPathForFileMacro(SmallVectorImpl<char> &Path, |
2591 | | const LangOptions &LangOpts, |
2592 | | const TargetInfo &TI); |
2593 | | |
2594 | | private: |
2595 | | void emitMacroDeprecationWarning(const Token &Identifier) const; |
2596 | | void emitRestrictExpansionWarning(const Token &Identifier) const; |
2597 | | void emitFinalMacroWarning(const Token &Identifier, bool IsUndef) const; |
2598 | | |
2599 | | Optional<unsigned> |
2600 | | getSkippedRangeForExcludedConditionalBlock(SourceLocation HashLoc); |
2601 | | |
2602 | | /// Contains the currently active skipped range mappings for skipping excluded |
2603 | | /// conditional directives. |
2604 | | ExcludedPreprocessorDirectiveSkipMapping |
2605 | | *ExcludedConditionalDirectiveSkipMappings; |
2606 | | }; |
2607 | | |
2608 | | /// Abstract base class that describes a handler that will receive |
2609 | | /// source ranges for each of the comments encountered in the source file. |
2610 | | class CommentHandler { |
2611 | | public: |
2612 | | virtual ~CommentHandler(); |
2613 | | |
2614 | | // The handler shall return true if it has pushed any tokens |
2615 | | // to be read using e.g. EnterToken or EnterTokenStream. |
2616 | | virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0; |
2617 | | }; |
2618 | | |
2619 | | /// Abstract base class that describes a handler that will receive |
2620 | | /// source ranges for empty lines encountered in the source file. |
2621 | | class EmptylineHandler { |
2622 | | public: |
2623 | | virtual ~EmptylineHandler(); |
2624 | | |
2625 | | // The handler handles empty lines. |
2626 | | virtual void HandleEmptyline(SourceRange Range) = 0; |
2627 | | }; |
2628 | | |
2629 | | /// Registry of pragma handlers added by plugins |
2630 | | using PragmaHandlerRegistry = llvm::Registry<PragmaHandler>; |
2631 | | |
2632 | | } // namespace clang |
2633 | | |
2634 | | #endif // LLVM_CLANG_LEX_PREPROCESSOR_H |