clang 22.0.0git
Preprocessor.h
Go to the documentation of this file.
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
20#include "clang/Basic/LLVM.h"
22#include "clang/Basic/Module.h"
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/MacroInfo.h"
30#include "clang/Lex/ModuleMap.h"
33#include "clang/Lex/Token.h"
36#include "llvm/ADT/APSInt.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/FoldingSet.h"
40#include "llvm/ADT/FunctionExtras.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 <optional>
57#include <string>
58#include <utility>
59#include <vector>
60
61namespace llvm {
62
63template<unsigned InternalLen> class SmallString;
64
65} // namespace llvm
66
67namespace clang {
68
70class CommentHandler;
71class DirectoryEntry;
74class FileEntry;
75class FileManager;
76class HeaderSearch;
77class MacroArgs;
78class PragmaHandler;
79class PragmaNamespace;
83class ScratchBuffer;
84class TargetInfo;
86
87namespace Builtin {
88class Context;
89}
90
91/// Stores token information for comparing actual tokens with
92/// predefined values. Only handles simple tokens and identifiers.
94 tok::TokenKind Kind;
96
97public:
98 TokenValue(tok::TokenKind Kind) : Kind(Kind), II(nullptr) {
99 assert(Kind != tok::raw_identifier && "Raw identifiers are not supported.");
100 assert(Kind != tok::identifier &&
101 "Identifiers should be created by TokenValue(IdentifierInfo *)");
102 assert(!tok::isLiteral(Kind) && "Literals are not supported.");
103 assert(!tok::isAnnotation(Kind) && "Annotations are not supported.");
104 }
105
106 TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {}
107
108 bool operator==(const Token &Tok) const {
109 return Tok.getKind() == Kind &&
110 (!II || II == Tok.getIdentifierInfo());
111 }
112};
113
114/// Context in which macro name is used.
116 // other than #define or #undef
118
119 // macro name specified in #define
121
122 // macro name specified in #undef
124};
125
126enum class EmbedResult {
127 Invalid = -1, // Parsing error occurred.
128 NotFound = 0, // Corresponds to __STDC_EMBED_NOT_FOUND__
129 Found = 1, // Corresponds to __STDC_EMBED_FOUND__
130 Empty = 2, // Corresponds to __STDC_EMBED_EMPTY__
131};
132
138
139/// Engages in a tight little dance with the lexer to efficiently
140/// preprocess tokens.
141///
142/// Lexers know only about tokens within a single source file, and don't
143/// know anything about preprocessor-level issues like the \#include stack,
144/// token expansion, etc.
148
149 llvm::unique_function<void(const clang::Token &)> OnToken;
150 /// Functor for getting the dependency preprocessor directives of a file.
151 ///
152 /// These are directives derived from a special form of lexing where the
153 /// source input is scanned for the preprocessor directives that might have an
154 /// effect on the dependencies for a compilation unit.
155 DependencyDirectivesGetter *GetDependencyDirectives = nullptr;
156 const PreprocessorOptions &PPOpts;
157 DiagnosticsEngine *Diags;
158 const LangOptions &LangOpts;
159 const TargetInfo *Target = nullptr;
160 const TargetInfo *AuxTarget = nullptr;
161 FileManager &FileMgr;
162 SourceManager &SourceMgr;
163 std::unique_ptr<ScratchBuffer> ScratchBuf;
164 HeaderSearch &HeaderInfo;
165 ModuleLoader &TheModuleLoader;
166
167 /// External source of macros.
168 ExternalPreprocessorSource *ExternalSource;
169
170 /// A BumpPtrAllocator object used to quickly allocate and release
171 /// objects internal to the Preprocessor.
172 llvm::BumpPtrAllocator BP;
173
174 /// Identifiers for builtin macros and other builtins.
175 IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__
176 IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__
177 IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__
178 IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__
179 IdentifierInfo *Ident__FILE_NAME__; // __FILE_NAME__
180 IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__
181 IdentifierInfo *Ident__COUNTER__; // __COUNTER__
182 IdentifierInfo *Ident_Pragma, *Ident__pragma; // _Pragma, __pragma
183 IdentifierInfo *Ident__identifier; // __identifier
184 IdentifierInfo *Ident__VA_ARGS__; // __VA_ARGS__
185 IdentifierInfo *Ident__VA_OPT__; // __VA_OPT__
186 IdentifierInfo *Ident__has_feature; // __has_feature
187 IdentifierInfo *Ident__has_extension; // __has_extension
188 IdentifierInfo *Ident__has_builtin; // __has_builtin
189 IdentifierInfo *Ident__has_constexpr_builtin; // __has_constexpr_builtin
190 IdentifierInfo *Ident__has_attribute; // __has_attribute
191 IdentifierInfo *Ident__has_embed; // __has_embed
192 IdentifierInfo *Ident__has_include; // __has_include
193 IdentifierInfo *Ident__has_include_next; // __has_include_next
194 IdentifierInfo *Ident__has_warning; // __has_warning
195 IdentifierInfo *Ident__is_identifier; // __is_identifier
196 IdentifierInfo *Ident__building_module; // __building_module
197 IdentifierInfo *Ident__MODULE__; // __MODULE__
198 IdentifierInfo *Ident__has_cpp_attribute; // __has_cpp_attribute
199 IdentifierInfo *Ident__has_c_attribute; // __has_c_attribute
200 IdentifierInfo *Ident__has_declspec; // __has_declspec_attribute
201 IdentifierInfo *Ident__is_target_arch; // __is_target_arch
202 IdentifierInfo *Ident__is_target_vendor; // __is_target_vendor
203 IdentifierInfo *Ident__is_target_os; // __is_target_os
204 IdentifierInfo *Ident__is_target_environment; // __is_target_environment
205 IdentifierInfo *Ident__is_target_variant_os;
206 IdentifierInfo *Ident__is_target_variant_environment;
207 IdentifierInfo *Ident__FLT_EVAL_METHOD__; // __FLT_EVAL_METHOD
208
209 // Weak, only valid (and set) while InMacroArgs is true.
210 Token* ArgMacro;
211
212 SourceLocation DATELoc, TIMELoc;
213
214 // FEM_UnsetOnCommandLine means that an explicit evaluation method was
215 // not specified on the command line. The target is queried to set the
216 // default evaluation method.
217 LangOptions::FPEvalMethodKind CurrentFPEvalMethod =
219
220 // The most recent pragma location where the floating point evaluation
221 // method was modified. This is used to determine whether the
222 // 'pragma clang fp eval_method' was used whithin the current scope.
223 SourceLocation LastFPEvalPragmaLocation;
224
225 LangOptions::FPEvalMethodKind TUFPEvalMethod =
227
228 // Next __COUNTER__ value, starts at 0.
229 uint32_t CounterValue = 0;
230
231 enum {
232 /// Maximum depth of \#includes.
233 MaxAllowedIncludeStackDepth = 200
234 };
235
236 // State that is set before the preprocessor begins.
237 bool KeepComments : 1;
238 bool KeepMacroComments : 1;
239 bool SuppressIncludeNotFoundError : 1;
240
241 // State that changes while the preprocessor runs:
242 bool InMacroArgs : 1; // True if parsing fn macro invocation args.
243
244 /// Whether the preprocessor owns the header search object.
245 bool OwnsHeaderSearch : 1;
246
247 /// True if macro expansion is disabled.
248 bool DisableMacroExpansion : 1;
249
250 /// Temporarily disables DisableMacroExpansion (i.e. enables expansion)
251 /// when parsing preprocessor directives.
252 bool MacroExpansionInDirectivesOverride : 1;
253
254 class ResetMacroExpansionHelper;
255
256 /// Whether we have already loaded macros from the external source.
257 mutable bool ReadMacrosFromExternalSource : 1;
258
259 /// True if pragmas are enabled.
260 bool PragmasEnabled : 1;
261
262 /// True if the current build action is a preprocessing action.
263 bool PreprocessedOutput : 1;
264
265 /// True if we are currently preprocessing a #if or #elif directive
266 bool ParsingIfOrElifDirective;
267
268 /// True if we are pre-expanding macro arguments.
269 bool InMacroArgPreExpansion;
270
271 /// Mapping/lookup information for all identifiers in
272 /// the program, including program keywords.
273 mutable IdentifierTable Identifiers;
274
275 /// This table contains all the selectors in the program.
276 ///
277 /// Unlike IdentifierTable above, this table *isn't* populated by the
278 /// preprocessor. It is declared/expanded here because its role/lifetime is
279 /// conceptually similar to the IdentifierTable. In addition, the current
280 /// control flow (in clang::ParseAST()), make it convenient to put here.
281 ///
282 /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to
283 /// the lifetime of the preprocessor.
284 SelectorTable Selectors;
285
286 /// Information about builtins.
287 std::unique_ptr<Builtin::Context> BuiltinInfo;
288
289 /// Tracks all of the pragmas that the client registered
290 /// with this preprocessor.
291 std::unique_ptr<PragmaNamespace> PragmaHandlers;
292
293 /// Pragma handlers of the original source is stored here during the
294 /// parsing of a model file.
295 std::unique_ptr<PragmaNamespace> PragmaHandlersBackup;
296
297 /// Tracks all of the comment handlers that the client registered
298 /// with this preprocessor.
299 std::vector<CommentHandler *> CommentHandlers;
300
301 /// Empty line handler.
302 EmptylineHandler *Emptyline = nullptr;
303
304 /// True to avoid tearing down the lexer etc on EOF
305 bool IncrementalProcessing = false;
306
307public:
308 /// The kind of translation unit we are processing.
310
311 /// Returns a pointer into the given file's buffer that's guaranteed
312 /// to be between tokens. The returned pointer is always before \p Start.
313 /// The maximum distance betweenthe returned pointer and \p Start is
314 /// limited by a constant value, but also an implementation detail.
315 /// If no such check point exists, \c nullptr is returned.
316 const char *getCheckPoint(FileID FID, const char *Start) const;
317
318private:
319 /// The code-completion handler.
320 CodeCompletionHandler *CodeComplete = nullptr;
321
322 /// The file that we're performing code-completion for, if any.
323 const FileEntry *CodeCompletionFile = nullptr;
324
325 /// The offset in file for the code-completion point.
326 unsigned CodeCompletionOffset = 0;
327
328 /// The location for the code-completion point. This gets instantiated
329 /// when the CodeCompletionFile gets \#include'ed for preprocessing.
330 SourceLocation CodeCompletionLoc;
331
332 /// The start location for the file of the code-completion point.
333 ///
334 /// This gets instantiated when the CodeCompletionFile gets \#include'ed
335 /// for preprocessing.
336 SourceLocation CodeCompletionFileLoc;
337
338 /// The source location of the \c import contextual keyword we just
339 /// lexed, if any.
340 SourceLocation ModuleImportLoc;
341
342 /// The import path for named module that we're currently processing.
343 SmallVector<IdentifierLoc, 2> NamedModuleImportPath;
344
345 llvm::DenseMap<FileID, SmallVector<const char *>> CheckPoints;
346 unsigned CheckPointCounter = 0;
347
348 /// Whether the import is an `@import` or a standard c++ modules import.
349 bool IsAtImport = false;
350
351 /// Whether the last token we lexed was an '@'.
352 bool LastTokenWasAt = false;
353
354 /// First pp-token source location in current translation unit.
355 SourceLocation FirstPPTokenLoc;
356
357 /// A preprocessor directive tracer to trace whether the preprocessing
358 /// state changed. These changes would mean most semantically observable
359 /// preprocessor state, particularly anything that is order dependent.
360 NoTrivialPPDirectiveTracer *DirTracer = nullptr;
361
362 /// A position within a C++20 import-seq.
363 class StdCXXImportSeq {
364 public:
365 enum State : int {
366 // Positive values represent a number of unclosed brackets.
367 AtTopLevel = 0,
368 AfterTopLevelTokenSeq = -1,
369 AfterExport = -2,
370 AfterImportSeq = -3,
371 };
372
373 StdCXXImportSeq(State S) : S(S) {}
374
375 /// Saw any kind of open bracket.
376 void handleOpenBracket() {
377 S = static_cast<State>(std::max<int>(S, 0) + 1);
378 }
379 /// Saw any kind of close bracket other than '}'.
380 void handleCloseBracket() {
381 S = static_cast<State>(std::max<int>(S, 1) - 1);
382 }
383 /// Saw a close brace.
384 void handleCloseBrace() {
385 handleCloseBracket();
386 if (S == AtTopLevel && !AfterHeaderName)
387 S = AfterTopLevelTokenSeq;
388 }
389 /// Saw a semicolon.
390 void handleSemi() {
391 if (atTopLevel()) {
392 S = AfterTopLevelTokenSeq;
393 AfterHeaderName = false;
394 }
395 }
396
397 /// Saw an 'export' identifier.
398 void handleExport() {
399 if (S == AfterTopLevelTokenSeq)
400 S = AfterExport;
401 else if (S <= 0)
402 S = AtTopLevel;
403 }
404 /// Saw an 'import' identifier.
405 void handleImport() {
406 if (S == AfterTopLevelTokenSeq || S == AfterExport)
407 S = AfterImportSeq;
408 else if (S <= 0)
409 S = AtTopLevel;
410 }
411
412 /// Saw a 'header-name' token; do not recognize any more 'import' tokens
413 /// until we reach a top-level semicolon.
414 void handleHeaderName() {
415 if (S == AfterImportSeq)
416 AfterHeaderName = true;
417 handleMisc();
418 }
419
420 /// Saw any other token.
421 void handleMisc() {
422 if (S <= 0)
423 S = AtTopLevel;
424 }
425
426 bool atTopLevel() { return S <= 0; }
427 bool afterImportSeq() { return S == AfterImportSeq; }
428 bool afterTopLevelSeq() { return S == AfterTopLevelTokenSeq; }
429
430 private:
431 State S;
432 /// Whether we're in the pp-import-suffix following the header-name in a
433 /// pp-import. If so, a close-brace is not sufficient to end the
434 /// top-level-token-seq of an import-seq.
435 bool AfterHeaderName = false;
436 };
437
438 /// Our current position within a C++20 import-seq.
439 StdCXXImportSeq StdCXXImportSeqState = StdCXXImportSeq::AfterTopLevelTokenSeq;
440
441 /// Track whether we are in a Global Module Fragment
442 class TrackGMF {
443 public:
444 enum GMFState : int {
445 GMFActive = 1,
446 MaybeGMF = 0,
447 BeforeGMFIntroducer = -1,
448 GMFAbsentOrEnded = -2,
449 };
450
451 TrackGMF(GMFState S) : S(S) {}
452
453 /// Saw a semicolon.
454 void handleSemi() {
455 // If it is immediately after the first instance of the module keyword,
456 // then that introduces the GMF.
457 if (S == MaybeGMF)
458 S = GMFActive;
459 }
460
461 /// Saw an 'export' identifier.
462 void handleExport() {
463 // The presence of an 'export' keyword always ends or excludes a GMF.
464 S = GMFAbsentOrEnded;
465 }
466
467 /// Saw an 'import' identifier.
468 void handleImport(bool AfterTopLevelTokenSeq) {
469 // If we see this before any 'module' kw, then we have no GMF.
470 if (AfterTopLevelTokenSeq && S == BeforeGMFIntroducer)
471 S = GMFAbsentOrEnded;
472 }
473
474 /// Saw a 'module' identifier.
475 void handleModule(bool AfterTopLevelTokenSeq) {
476 // This was the first module identifier and not preceded by any token
477 // that would exclude a GMF. It could begin a GMF, but only if directly
478 // followed by a semicolon.
479 if (AfterTopLevelTokenSeq && S == BeforeGMFIntroducer)
480 S = MaybeGMF;
481 else
482 S = GMFAbsentOrEnded;
483 }
484
485 /// Saw any other token.
486 void handleMisc() {
487 // We saw something other than ; after the 'module' kw, so not a GMF.
488 if (S == MaybeGMF)
489 S = GMFAbsentOrEnded;
490 }
491
492 bool inGMF() { return S == GMFActive; }
493
494 private:
495 /// Track the transitions into and out of a Global Module Fragment,
496 /// if one is present.
497 GMFState S;
498 };
499
500 TrackGMF TrackGMFState = TrackGMF::BeforeGMFIntroducer;
501
502 /// Track the status of the c++20 module decl.
503 ///
504 /// module-declaration:
505 /// 'export'[opt] 'module' module-name module-partition[opt]
506 /// attribute-specifier-seq[opt] ';'
507 ///
508 /// module-name:
509 /// module-name-qualifier[opt] identifier
510 ///
511 /// module-partition:
512 /// ':' module-name-qualifier[opt] identifier
513 ///
514 /// module-name-qualifier:
515 /// identifier '.'
516 /// module-name-qualifier identifier '.'
517 ///
518 /// Transition state:
519 ///
520 /// NotAModuleDecl --- export ---> FoundExport
521 /// NotAModuleDecl --- module ---> ImplementationCandidate
522 /// FoundExport --- module ---> InterfaceCandidate
523 /// ImplementationCandidate --- Identifier ---> ImplementationCandidate
524 /// ImplementationCandidate --- period ---> ImplementationCandidate
525 /// ImplementationCandidate --- colon ---> ImplementationCandidate
526 /// InterfaceCandidate --- Identifier ---> InterfaceCandidate
527 /// InterfaceCandidate --- period ---> InterfaceCandidate
528 /// InterfaceCandidate --- colon ---> InterfaceCandidate
529 /// ImplementationCandidate --- Semi ---> NamedModuleImplementation
530 /// NamedModuleInterface --- Semi ---> NamedModuleInterface
531 /// NamedModuleImplementation --- Anything ---> NamedModuleImplementation
532 /// NamedModuleInterface --- Anything ---> NamedModuleInterface
533 ///
534 /// FIXME: We haven't handle attribute-specifier-seq here. It may not be bad
535 /// soon since we don't support any module attributes yet.
536 class ModuleDeclSeq {
537 enum ModuleDeclState : int {
538 NotAModuleDecl,
539 FoundExport,
540 InterfaceCandidate,
541 ImplementationCandidate,
542 NamedModuleInterface,
543 NamedModuleImplementation,
544 };
545
546 public:
547 ModuleDeclSeq() = default;
548
549 void handleExport() {
550 if (State == NotAModuleDecl)
551 State = FoundExport;
552 else if (!isNamedModule())
553 reset();
554 }
555
556 void handleModule() {
557 if (State == FoundExport)
558 State = InterfaceCandidate;
559 else if (State == NotAModuleDecl)
560 State = ImplementationCandidate;
561 else if (!isNamedModule())
562 reset();
563 }
564
565 void handleIdentifier(IdentifierInfo *Identifier) {
566 if (isModuleCandidate() && Identifier)
567 Name += Identifier->getName().str();
568 else if (!isNamedModule())
569 reset();
570 }
571
572 void handleColon() {
573 if (isModuleCandidate())
574 Name += ":";
575 else if (!isNamedModule())
576 reset();
577 }
578
579 void handlePeriod() {
580 if (isModuleCandidate())
581 Name += ".";
582 else if (!isNamedModule())
583 reset();
584 }
585
586 void handleSemi() {
587 if (!Name.empty() && isModuleCandidate()) {
588 if (State == InterfaceCandidate)
589 State = NamedModuleInterface;
590 else if (State == ImplementationCandidate)
591 State = NamedModuleImplementation;
592 else
593 llvm_unreachable("Unimaged ModuleDeclState.");
594 } else if (!isNamedModule())
595 reset();
596 }
597
598 void handleMisc() {
599 if (!isNamedModule())
600 reset();
601 }
602
603 bool isModuleCandidate() const {
604 return State == InterfaceCandidate || State == ImplementationCandidate;
605 }
606
607 bool isNamedModule() const {
608 return State == NamedModuleInterface ||
609 State == NamedModuleImplementation;
610 }
611
612 bool isNamedInterface() const { return State == NamedModuleInterface; }
613
614 bool isImplementationUnit() const {
615 return State == NamedModuleImplementation && !getName().contains(':');
616 }
617
618 bool isNotAModuleDecl() const { return State == NotAModuleDecl; }
619
620 StringRef getName() const {
621 assert(isNamedModule() && "Can't get name from a non named module");
622 return Name;
623 }
624
625 StringRef getPrimaryName() const {
626 assert(isNamedModule() && "Can't get name from a non named module");
627 return getName().split(':').first;
628 }
629
630 void reset() {
631 Name.clear();
632 State = NotAModuleDecl;
633 }
634
635 private:
636 ModuleDeclState State = NotAModuleDecl;
637 std::string Name;
638 };
639
640 ModuleDeclSeq ModuleDeclState;
641
642 /// Whether the module import expects an identifier next. Otherwise,
643 /// it expects a '.' or ';'.
644 bool ModuleImportExpectsIdentifier = false;
645
646 /// The identifier and source location of the currently-active
647 /// \#pragma clang arc_cf_code_audited begin.
648 IdentifierLoc PragmaARCCFCodeAuditedInfo;
649
650 /// The source location of the currently-active
651 /// \#pragma clang assume_nonnull begin.
652 SourceLocation PragmaAssumeNonNullLoc;
653
654 /// Set only for preambles which end with an active
655 /// \#pragma clang assume_nonnull begin.
656 ///
657 /// When the preamble is loaded into the main file,
658 /// `PragmaAssumeNonNullLoc` will be set to this to
659 /// replay the unterminated assume_nonnull.
660 SourceLocation PreambleRecordedPragmaAssumeNonNullLoc;
661
662 /// True if we hit the code-completion point.
663 bool CodeCompletionReached = false;
664
665 /// The code completion token containing the information
666 /// on the stem that is to be code completed.
667 IdentifierInfo *CodeCompletionII = nullptr;
668
669 /// Range for the code completion token.
670 SourceRange CodeCompletionTokenRange;
671
672 /// The directory that the main file should be considered to occupy,
673 /// if it does not correspond to a real file (as happens when building a
674 /// module).
675 OptionalDirectoryEntryRef MainFileDir;
676
677 /// The number of bytes that we will initially skip when entering the
678 /// main file, along with a flag that indicates whether skipping this number
679 /// of bytes will place the lexer at the start of a line.
680 ///
681 /// This is used when loading a precompiled preamble.
682 std::pair<int, bool> SkipMainFilePreamble;
683
684 /// Whether we hit an error due to reaching max allowed include depth. Allows
685 /// to avoid hitting the same error over and over again.
686 bool HasReachedMaxIncludeDepth = false;
687
688 /// The number of currently-active calls to Lex.
689 ///
690 /// Lex is reentrant, and asking for an (end-of-phase-4) token can often
691 /// require asking for multiple additional tokens. This counter makes it
692 /// possible for Lex to detect whether it's producing a token for the end
693 /// of phase 4 of translation or for some other situation.
694 unsigned LexLevel = 0;
695
696 /// The number of (LexLevel 0) preprocessor tokens.
697 unsigned TokenCount = 0;
698
699 /// Preprocess every token regardless of LexLevel.
700 bool PreprocessToken = false;
701
702 /// The maximum number of (LexLevel 0) tokens before issuing a -Wmax-tokens
703 /// warning, or zero for unlimited.
704 unsigned MaxTokens = 0;
705 SourceLocation MaxTokensOverrideLoc;
706
707public:
722
723 using IncludedFilesSet = llvm::DenseSet<const FileEntry *>;
724
725private:
726 friend class ASTReader;
727 friend class MacroArgs;
728
729 class PreambleConditionalStackStore {
730 enum State {
731 Off = 0,
732 Recording = 1,
733 Replaying = 2,
734 };
735
736 public:
737 PreambleConditionalStackStore() = default;
738
739 void startRecording() { ConditionalStackState = Recording; }
740 void startReplaying() { ConditionalStackState = Replaying; }
741 bool isRecording() const { return ConditionalStackState == Recording; }
742 bool isReplaying() const { return ConditionalStackState == Replaying; }
743
744 ArrayRef<PPConditionalInfo> getStack() const {
745 return ConditionalStack;
746 }
747
748 void doneReplaying() {
749 ConditionalStack.clear();
750 ConditionalStackState = Off;
751 }
752
753 void setStack(ArrayRef<PPConditionalInfo> s) {
754 if (!isRecording() && !isReplaying())
755 return;
756 ConditionalStack.clear();
757 ConditionalStack.append(s.begin(), s.end());
758 }
759
760 bool hasRecordedPreamble() const { return !ConditionalStack.empty(); }
761
762 bool reachedEOFWhileSkipping() const { return SkipInfo.has_value(); }
763
764 void clearSkipInfo() { SkipInfo.reset(); }
765
766 std::optional<PreambleSkipInfo> SkipInfo;
767
768 private:
769 SmallVector<PPConditionalInfo, 4> ConditionalStack;
770 State ConditionalStackState = Off;
771 } PreambleConditionalStack;
772
773 /// The current top of the stack that we're lexing from if
774 /// not expanding a macro and we are lexing directly from source code.
775 ///
776 /// Only one of CurLexer, or CurTokenLexer will be non-null.
777 std::unique_ptr<Lexer> CurLexer;
778
779 /// The current top of the stack that we're lexing from
780 /// if not expanding a macro.
781 ///
782 /// This is an alias for CurLexer.
783 PreprocessorLexer *CurPPLexer = nullptr;
784
785 /// Used to find the current FileEntry, if CurLexer is non-null
786 /// and if applicable.
787 ///
788 /// This allows us to implement \#include_next and find directory-specific
789 /// properties.
790 ConstSearchDirIterator CurDirLookup = nullptr;
791
792 /// The current macro we are expanding, if we are expanding a macro.
793 ///
794 /// One of CurLexer and CurTokenLexer must be null.
795 std::unique_ptr<TokenLexer> CurTokenLexer;
796
797 /// The kind of lexer we're currently working with.
798 typedef bool (*LexerCallback)(Preprocessor &, Token &);
799 LexerCallback CurLexerCallback = &CLK_Lexer;
800
801 /// If the current lexer is for a submodule that is being built, this
802 /// is that submodule.
803 Module *CurLexerSubmodule = nullptr;
804
805 /// Keeps track of the stack of files currently
806 /// \#included, and macros currently being expanded from, not counting
807 /// CurLexer/CurTokenLexer.
808 struct IncludeStackInfo {
809 LexerCallback CurLexerCallback;
810 Module *TheSubmodule;
811 std::unique_ptr<Lexer> TheLexer;
812 PreprocessorLexer *ThePPLexer;
813 std::unique_ptr<TokenLexer> TheTokenLexer;
814 ConstSearchDirIterator TheDirLookup;
815
816 // The following constructors are completely useless copies of the default
817 // versions, only needed to pacify MSVC.
818 IncludeStackInfo(LexerCallback CurLexerCallback, Module *TheSubmodule,
819 std::unique_ptr<Lexer> &&TheLexer,
820 PreprocessorLexer *ThePPLexer,
821 std::unique_ptr<TokenLexer> &&TheTokenLexer,
822 ConstSearchDirIterator TheDirLookup)
823 : CurLexerCallback(std::move(CurLexerCallback)),
824 TheSubmodule(std::move(TheSubmodule)), TheLexer(std::move(TheLexer)),
825 ThePPLexer(std::move(ThePPLexer)),
826 TheTokenLexer(std::move(TheTokenLexer)),
827 TheDirLookup(std::move(TheDirLookup)) {}
828 };
829 std::vector<IncludeStackInfo> IncludeMacroStack;
830
831 /// Actions invoked when some preprocessor activity is
832 /// encountered (e.g. a file is \#included, etc).
833 std::unique_ptr<PPCallbacks> Callbacks;
834
835 struct MacroExpandsInfo {
836 Token Tok;
837 MacroDefinition MD;
838 SourceRange Range;
839
840 MacroExpandsInfo(Token Tok, MacroDefinition MD, SourceRange Range)
841 : Tok(Tok), MD(MD), Range(Range) {}
842 };
843 SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks;
844
845 /// Information about a name that has been used to define a module macro.
846 struct ModuleMacroInfo {
847 /// The most recent macro directive for this identifier.
848 MacroDirective *MD;
849
850 /// The active module macros for this identifier.
851 llvm::TinyPtrVector<ModuleMacro *> ActiveModuleMacros;
852
853 /// The generation number at which we last updated ActiveModuleMacros.
854 /// \see Preprocessor::VisibleModules.
855 unsigned ActiveModuleMacrosGeneration = 0;
856
857 /// Whether this macro name is ambiguous.
858 bool IsAmbiguous = false;
859
860 /// The module macros that are overridden by this macro.
861 llvm::TinyPtrVector<ModuleMacro *> OverriddenMacros;
862
863 ModuleMacroInfo(MacroDirective *MD) : MD(MD) {}
864 };
865
866 /// The state of a macro for an identifier.
867 class MacroState {
868 mutable llvm::PointerUnion<MacroDirective *, ModuleMacroInfo *> State;
869
870 ModuleMacroInfo *getModuleInfo(Preprocessor &PP,
871 const IdentifierInfo *II) const {
872 if (II->isOutOfDate())
873 PP.updateOutOfDateIdentifier(*II);
874 // FIXME: Find a spare bit on IdentifierInfo and store a
875 // HasModuleMacros flag.
876 if (!II->hasMacroDefinition() ||
877 (!PP.getLangOpts().Modules &&
878 !PP.getLangOpts().ModulesLocalVisibility) ||
879 !PP.CurSubmoduleState->VisibleModules.getGeneration())
880 return nullptr;
881
882 auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State);
883 if (!Info) {
884 Info = new (PP.getPreprocessorAllocator())
885 ModuleMacroInfo(cast<MacroDirective *>(State));
886 State = Info;
887 }
888
889 if (PP.CurSubmoduleState->VisibleModules.getGeneration() !=
890 Info->ActiveModuleMacrosGeneration)
891 PP.updateModuleMacroInfo(II, *Info);
892 return Info;
893 }
894
895 public:
896 MacroState() : MacroState(nullptr) {}
897 MacroState(MacroDirective *MD) : State(MD) {}
898
899 MacroState(MacroState &&O) noexcept : State(O.State) {
900 O.State = (MacroDirective *)nullptr;
901 }
902
903 MacroState &operator=(MacroState &&O) noexcept {
904 auto S = O.State;
905 O.State = (MacroDirective *)nullptr;
906 State = S;
907 return *this;
908 }
909
910 ~MacroState() {
911 if (auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State))
912 Info->~ModuleMacroInfo();
913 }
914
915 MacroDirective *getLatest() const {
916 if (auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State))
917 return Info->MD;
918 return cast<MacroDirective *>(State);
919 }
920
921 void setLatest(MacroDirective *MD) {
922 if (auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State))
923 Info->MD = MD;
924 else
925 State = MD;
926 }
927
928 bool isAmbiguous(Preprocessor &PP, const IdentifierInfo *II) const {
929 auto *Info = getModuleInfo(PP, II);
930 return Info ? Info->IsAmbiguous : false;
931 }
932
933 ArrayRef<ModuleMacro *>
934 getActiveModuleMacros(Preprocessor &PP, const IdentifierInfo *II) const {
935 if (auto *Info = getModuleInfo(PP, II))
936 return Info->ActiveModuleMacros;
937 return {};
938 }
939
940 MacroDirective::DefInfo findDirectiveAtLoc(SourceLocation Loc,
941 SourceManager &SourceMgr) const {
942 // FIXME: Incorporate module macros into the result of this.
943 if (auto *Latest = getLatest())
944 return Latest->findDirectiveAtLoc(Loc, SourceMgr);
945 return {};
946 }
947
948 void overrideActiveModuleMacros(Preprocessor &PP, IdentifierInfo *II) {
949 if (auto *Info = getModuleInfo(PP, II)) {
950 Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
951 Info->ActiveModuleMacros.begin(),
952 Info->ActiveModuleMacros.end());
953 Info->ActiveModuleMacros.clear();
954 Info->IsAmbiguous = false;
955 }
956 }
957
958 ArrayRef<ModuleMacro*> getOverriddenMacros() const {
959 if (auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State))
960 return Info->OverriddenMacros;
961 return {};
962 }
963
964 void setOverriddenMacros(Preprocessor &PP,
965 ArrayRef<ModuleMacro *> Overrides) {
966 auto *Info = dyn_cast_if_present<ModuleMacroInfo *>(State);
967 if (!Info) {
968 if (Overrides.empty())
969 return;
970 Info = new (PP.getPreprocessorAllocator())
971 ModuleMacroInfo(cast<MacroDirective *>(State));
972 State = Info;
973 }
974 Info->OverriddenMacros.clear();
975 Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
976 Overrides.begin(), Overrides.end());
977 Info->ActiveModuleMacrosGeneration = 0;
978 }
979 };
980
981 /// For each IdentifierInfo that was associated with a macro, we
982 /// keep a mapping to the history of all macro definitions and #undefs in
983 /// the reverse order (the latest one is in the head of the list).
984 ///
985 /// This mapping lives within the \p CurSubmoduleState.
986 using MacroMap = llvm::DenseMap<const IdentifierInfo *, MacroState>;
987
988 struct SubmoduleState;
989
990 /// Information about a submodule that we're currently building.
991 struct BuildingSubmoduleInfo {
992 /// The module that we are building.
993 Module *M;
994
995 /// The location at which the module was included.
996 SourceLocation ImportLoc;
997
998 /// Whether we entered this submodule via a pragma.
999 bool IsPragma;
1000
1001 /// The previous SubmoduleState.
1002 SubmoduleState *OuterSubmoduleState;
1003
1004 /// The number of pending module macro names when we started building this.
1005 unsigned OuterPendingModuleMacroNames;
1006
1007 BuildingSubmoduleInfo(Module *M, SourceLocation ImportLoc, bool IsPragma,
1008 SubmoduleState *OuterSubmoduleState,
1009 unsigned OuterPendingModuleMacroNames)
1010 : M(M), ImportLoc(ImportLoc), IsPragma(IsPragma),
1011 OuterSubmoduleState(OuterSubmoduleState),
1012 OuterPendingModuleMacroNames(OuterPendingModuleMacroNames) {}
1013 };
1014 SmallVector<BuildingSubmoduleInfo, 8> BuildingSubmoduleStack;
1015
1016 /// Information about a submodule's preprocessor state.
1017 struct SubmoduleState {
1018 /// The macros for the submodule.
1019 MacroMap Macros;
1020
1021 /// The set of modules that are visible within the submodule.
1022 VisibleModuleSet VisibleModules;
1023
1024 // FIXME: CounterValue?
1025 // FIXME: PragmaPushMacroInfo?
1026 };
1027 std::map<Module *, SubmoduleState> Submodules;
1028
1029 /// The preprocessor state for preprocessing outside of any submodule.
1030 SubmoduleState NullSubmoduleState;
1031
1032 /// The current submodule state. Will be \p NullSubmoduleState if we're not
1033 /// in a submodule.
1034 SubmoduleState *CurSubmoduleState;
1035
1036 /// The files that have been included.
1037 IncludedFilesSet IncludedFiles;
1038
1039 /// The set of top-level modules that affected preprocessing, but were not
1040 /// imported.
1041 llvm::SmallSetVector<Module *, 2> AffectingClangModules;
1042
1043 /// The set of known macros exported from modules.
1044 llvm::FoldingSet<ModuleMacro> ModuleMacros;
1045
1046 /// The names of potential module macros that we've not yet processed.
1047 llvm::SmallVector<IdentifierInfo *, 32> PendingModuleMacroNames;
1048
1049 /// The list of module macros, for each identifier, that are not overridden by
1050 /// any other module macro.
1051 llvm::DenseMap<const IdentifierInfo *, llvm::TinyPtrVector<ModuleMacro *>>
1052 LeafModuleMacros;
1053
1054 /// Macros that we want to warn because they are not used at the end
1055 /// of the translation unit.
1056 ///
1057 /// We store just their SourceLocations instead of
1058 /// something like MacroInfo*. The benefit of this is that when we are
1059 /// deserializing from PCH, we don't need to deserialize identifier & macros
1060 /// just so that we can report that they are unused, we just warn using
1061 /// the SourceLocations of this set (that will be filled by the ASTReader).
1062 using WarnUnusedMacroLocsTy = llvm::SmallDenseSet<SourceLocation, 32>;
1063 WarnUnusedMacroLocsTy WarnUnusedMacroLocs;
1064
1065 /// This is a pair of an optional message and source location used for pragmas
1066 /// that annotate macros like pragma clang restrict_expansion and pragma clang
1067 /// deprecated. This pair stores the optional message and the location of the
1068 /// annotation pragma for use producing diagnostics and notes.
1069 using MsgLocationPair = std::pair<std::string, SourceLocation>;
1070
1071 struct MacroAnnotationInfo {
1072 SourceLocation Location;
1073 std::string Message;
1074 };
1075
1076 struct MacroAnnotations {
1077 std::optional<MacroAnnotationInfo> DeprecationInfo;
1078 std::optional<MacroAnnotationInfo> RestrictExpansionInfo;
1079 std::optional<SourceLocation> FinalAnnotationLoc;
1080 };
1081
1082 /// Warning information for macro annotations.
1083 llvm::DenseMap<const IdentifierInfo *, MacroAnnotations> AnnotationInfos;
1084
1085 /// A "freelist" of MacroArg objects that can be
1086 /// reused for quick allocation.
1087 MacroArgs *MacroArgCache = nullptr;
1088
1089 /// For each IdentifierInfo used in a \#pragma push_macro directive,
1090 /// we keep a MacroInfo stack used to restore the previous macro value.
1091 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>
1092 PragmaPushMacroInfo;
1093
1094 // Various statistics we track for performance analysis.
1095 unsigned NumDirectives = 0;
1096 unsigned NumDefined = 0;
1097 unsigned NumUndefined = 0;
1098 unsigned NumPragma = 0;
1099 unsigned NumIf = 0;
1100 unsigned NumElse = 0;
1101 unsigned NumEndif = 0;
1102 unsigned NumEnteredSourceFiles = 0;
1103 unsigned MaxIncludeStackDepth = 0;
1104 unsigned NumMacroExpanded = 0;
1105 unsigned NumFnMacroExpanded = 0;
1106 unsigned NumBuiltinMacroExpanded = 0;
1107 unsigned NumFastMacroExpanded = 0;
1108 unsigned NumTokenPaste = 0;
1109 unsigned NumFastTokenPaste = 0;
1110 unsigned NumSkipped = 0;
1111
1112 /// The predefined macros that preprocessor should use from the
1113 /// command line etc.
1114 std::string Predefines;
1115
1116 /// The file ID for the preprocessor predefines.
1117 FileID PredefinesFileID;
1118
1119 /// The file ID for the PCH through header.
1120 FileID PCHThroughHeaderFileID;
1121
1122 /// The file ID for the predefines that come from the PCH.
1123 /// This is only set when modules are in effect.
1124 FileID PCHPredefinesFileID;
1125
1126 /// Whether tokens are being skipped until a #pragma hdrstop is seen.
1127 bool SkippingUntilPragmaHdrStop = false;
1128
1129 /// Whether tokens are being skipped until the through header is seen.
1130 bool SkippingUntilPCHThroughHeader = false;
1131
1132 /// \{
1133 /// Cache of macro expanders to reduce malloc traffic.
1134 enum { TokenLexerCacheSize = 8 };
1135 unsigned NumCachedTokenLexers;
1136 std::unique_ptr<TokenLexer> TokenLexerCache[TokenLexerCacheSize];
1137 /// \}
1138
1139 /// Keeps macro expanded tokens for TokenLexers.
1140 //
1141 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1142 /// going to lex in the cache and when it finishes the tokens are removed
1143 /// from the end of the cache.
1144 SmallVector<Token, 16> MacroExpandedTokens;
1145 std::vector<std::pair<TokenLexer *, size_t>> MacroExpandingLexersStack;
1146
1147 /// A record of the macro definitions and expansions that
1148 /// occurred during preprocessing.
1149 ///
1150 /// This is an optional side structure that can be enabled with
1151 /// \c createPreprocessingRecord() prior to preprocessing.
1152 PreprocessingRecord *Record = nullptr;
1153
1154 /// Cached tokens state.
1155 using CachedTokensTy = SmallVector<Token, 1>;
1156
1157 /// Cached tokens are stored here when we do backtracking or
1158 /// lookahead. They are "lexed" by the CachingLex() method.
1159 CachedTokensTy CachedTokens;
1160
1161 /// The position of the cached token that CachingLex() should
1162 /// "lex" next.
1163 ///
1164 /// If it points beyond the CachedTokens vector, it means that a normal
1165 /// Lex() should be invoked.
1166 CachedTokensTy::size_type CachedLexPos = 0;
1167
1168 /// Stack of backtrack positions, allowing nested backtracks.
1169 ///
1170 /// The EnableBacktrackAtThisPos() method pushes a position to
1171 /// indicate where CachedLexPos should be set when the BackTrack() method is
1172 /// invoked (at which point the last position is popped).
1173 std::vector<CachedTokensTy::size_type> BacktrackPositions;
1174
1175 /// Stack of cached tokens/initial number of cached tokens pairs, allowing
1176 /// nested unannotated backtracks.
1177 std::vector<std::pair<CachedTokensTy, CachedTokensTy::size_type>>
1178 UnannotatedBacktrackTokens;
1179
1180 /// True if \p Preprocessor::SkipExcludedConditionalBlock() is running.
1181 /// This is used to guard against calling this function recursively.
1182 ///
1183 /// See comments at the use-site for more context about why it is needed.
1184 bool SkippingExcludedConditionalBlock = false;
1185
1186 /// Keeps track of skipped range mappings that were recorded while skipping
1187 /// excluded conditional directives. It maps the source buffer pointer at
1188 /// the beginning of a skipped block, to the number of bytes that should be
1189 /// skipped.
1190 llvm::DenseMap<const char *, unsigned> RecordedSkippedRanges;
1191
1192 void updateOutOfDateIdentifier(const IdentifierInfo &II) const;
1193
1194public:
1195 Preprocessor(const PreprocessorOptions &PPOpts, DiagnosticsEngine &diags,
1196 const LangOptions &LangOpts, SourceManager &SM,
1197 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
1198 IdentifierInfoLookup *IILookup = nullptr,
1199 bool OwnsHeaderSearch = false,
1201
1202 ~Preprocessor();
1203
1204 /// Initialize the preprocessor using information about the target.
1205 ///
1206 /// \param Target is owned by the caller and must remain valid for the
1207 /// lifetime of the preprocessor.
1208 /// \param AuxTarget is owned by the caller and must remain valid for
1209 /// the lifetime of the preprocessor.
1210 void Initialize(const TargetInfo &Target,
1211 const TargetInfo *AuxTarget = nullptr);
1212
1213 /// Initialize the preprocessor to parse a model file
1214 ///
1215 /// To parse model files the preprocessor of the original source is reused to
1216 /// preserver the identifier table. However to avoid some duplicate
1217 /// information in the preprocessor some cleanup is needed before it is used
1218 /// to parse model files. This method does that cleanup.
1220
1221 /// Cleanup after model file parsing
1222 void FinalizeForModelFile();
1223
1224 /// Retrieve the preprocessor options used to initialize this preprocessor.
1225 const PreprocessorOptions &getPreprocessorOpts() const { return PPOpts; }
1226
1227 DiagnosticsEngine &getDiagnostics() const { return *Diags; }
1228 void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; }
1229
1230 const LangOptions &getLangOpts() const { return LangOpts; }
1231 const TargetInfo &getTargetInfo() const { return *Target; }
1232 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
1233 FileManager &getFileManager() const { return FileMgr; }
1234 SourceManager &getSourceManager() const { return SourceMgr; }
1235 HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
1236
1237 IdentifierTable &getIdentifierTable() { return Identifiers; }
1238 const IdentifierTable &getIdentifierTable() const { return Identifiers; }
1239 SelectorTable &getSelectorTable() { return Selectors; }
1240 Builtin::Context &getBuiltinInfo() { return *BuiltinInfo; }
1241 llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
1242
1244 ExternalSource = Source;
1245 }
1246
1248 return ExternalSource;
1249 }
1250
1251 /// Retrieve the module loader associated with this preprocessor.
1252 ModuleLoader &getModuleLoader() const { return TheModuleLoader; }
1253
1255 return TheModuleLoader.HadFatalFailure;
1256 }
1257
1258 /// Retrieve the number of Directives that have been processed by the
1259 /// Preprocessor.
1260 unsigned getNumDirectives() const {
1261 return NumDirectives;
1262 }
1263
1264 /// True if we are currently preprocessing a #if or #elif directive
1266 return ParsingIfOrElifDirective;
1267 }
1268
1269 /// Control whether the preprocessor retains comments in output.
1270 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
1271 this->KeepComments = KeepComments | KeepMacroComments;
1272 this->KeepMacroComments = KeepMacroComments;
1273 }
1274
1275 bool getCommentRetentionState() const { return KeepComments; }
1276
1277 void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; }
1278 bool getPragmasEnabled() const { return PragmasEnabled; }
1279
1281 SuppressIncludeNotFoundError = Suppress;
1282 }
1283
1285 return SuppressIncludeNotFoundError;
1286 }
1287
1288 /// Sets whether the preprocessor is responsible for producing output or if
1289 /// it is producing tokens to be consumed by Parse and Sema.
1290 void setPreprocessedOutput(bool IsPreprocessedOutput) {
1291 PreprocessedOutput = IsPreprocessedOutput;
1292 }
1293
1294 /// Returns true if the preprocessor is responsible for generating output,
1295 /// false if it is producing tokens to be consumed by Parse and Sema.
1296 bool isPreprocessedOutput() const { return PreprocessedOutput; }
1297
1298 /// Return true if we are lexing directly from the specified lexer.
1299 bool isCurrentLexer(const PreprocessorLexer *L) const {
1300 return CurPPLexer == L;
1301 }
1302
1303 /// Return the current lexer being lexed from.
1304 ///
1305 /// Note that this ignores any potentially active macro expansions and _Pragma
1306 /// expansions going on at the time.
1307 PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; }
1308
1309 /// Return the current file lexer being lexed from.
1310 ///
1311 /// Note that this ignores any potentially active macro expansions and _Pragma
1312 /// expansions going on at the time.
1314
1315 /// Return the submodule owning the file being lexed. This may not be
1316 /// the current module if we have changed modules since entering the file.
1317 Module *getCurrentLexerSubmodule() const { return CurLexerSubmodule; }
1318
1319 /// Returns the FileID for the preprocessor predefines.
1320 FileID getPredefinesFileID() const { return PredefinesFileID; }
1321
1322 /// Returns the FileID for the predefines loaded from the PCH.
1324 assert(getLangOpts().Modules &&
1325 "PCHPredefinedFileID is only set when modules is in effect!");
1326 return PCHPredefinesFileID;
1327 }
1328
1329 /// \{
1330 /// Accessors for preprocessor callbacks.
1331 ///
1332 /// Note that this class takes ownership of any PPCallbacks object given to
1333 /// it.
1334 PPCallbacks *getPPCallbacks() const { return Callbacks.get(); }
1335 void addPPCallbacks(std::unique_ptr<PPCallbacks> C) {
1336 if (Callbacks)
1337 C = std::make_unique<PPChainedCallbacks>(std::move(C),
1338 std::move(Callbacks));
1339 Callbacks = std::move(C);
1340 }
1341 void removePPCallbacks() { Callbacks.reset(); }
1342 /// \}
1343
1344 /// Get the number of tokens processed so far.
1345 unsigned getTokenCount() const { return TokenCount; }
1346
1347 /// Get the max number of tokens before issuing a -Wmax-tokens warning.
1348 unsigned getMaxTokens() const { return MaxTokens; }
1349
1351 MaxTokens = Value;
1352 MaxTokensOverrideLoc = Loc;
1353 };
1354
1355 SourceLocation getMaxTokensOverrideLoc() const { return MaxTokensOverrideLoc; }
1356
1357 /// Register a function that would be called on each token in the final
1358 /// expanded token stream.
1359 /// This also reports annotation tokens produced by the parser.
1360 void setTokenWatcher(llvm::unique_function<void(const clang::Token &)> F) {
1361 OnToken = std::move(F);
1362 }
1363
1365 GetDependencyDirectives = &Get;
1366 }
1367
1368 void setPreprocessToken(bool Preprocess) { PreprocessToken = Preprocess; }
1369
1370 bool isMacroDefined(StringRef Id) {
1371 return isMacroDefined(&Identifiers.get(Id));
1372 }
1374 return II->hasMacroDefinition() &&
1375 (!getLangOpts().Modules || (bool)getMacroDefinition(II));
1376 }
1377
1378 /// Determine whether II is defined as a macro within the module M,
1379 /// if that is a module that we've already preprocessed. Does not check for
1380 /// macros imported into M.
1382 if (!II->hasMacroDefinition())
1383 return false;
1384 auto I = Submodules.find(M);
1385 if (I == Submodules.end())
1386 return false;
1387 auto J = I->second.Macros.find(II);
1388 if (J == I->second.Macros.end())
1389 return false;
1390 auto *MD = J->second.getLatest();
1391 return MD && MD->isDefined();
1392 }
1393
1395 if (!II->hasMacroDefinition())
1396 return {};
1397
1398 MacroState &S = CurSubmoduleState->Macros[II];
1399 auto *MD = S.getLatest();
1400 while (isa_and_nonnull<VisibilityMacroDirective>(MD))
1401 MD = MD->getPrevious();
1402 return MacroDefinition(dyn_cast_or_null<DefMacroDirective>(MD),
1403 S.getActiveModuleMacros(*this, II),
1404 S.isAmbiguous(*this, II));
1405 }
1406
1408 SourceLocation Loc) {
1409 if (!II->hadMacroDefinition())
1410 return {};
1411
1412 MacroState &S = CurSubmoduleState->Macros[II];
1414 if (auto *MD = S.getLatest())
1415 DI = MD->findDirectiveAtLoc(Loc, getSourceManager());
1416 // FIXME: Compute the set of active module macros at the specified location.
1417 return MacroDefinition(DI.getDirective(),
1418 S.getActiveModuleMacros(*this, II),
1419 S.isAmbiguous(*this, II));
1420 }
1421
1422 /// Given an identifier, return its latest non-imported MacroDirective
1423 /// if it is \#define'd and not \#undef'd, or null if it isn't \#define'd.
1425 if (!II->hasMacroDefinition())
1426 return nullptr;
1427
1428 auto *MD = getLocalMacroDirectiveHistory(II);
1429 if (!MD || MD->getDefinition().isUndefined())
1430 return nullptr;
1431
1432 return MD;
1433 }
1434
1435 const MacroInfo *getMacroInfo(const IdentifierInfo *II) const {
1436 return const_cast<Preprocessor*>(this)->getMacroInfo(II);
1437 }
1438
1440 if (!II->hasMacroDefinition())
1441 return nullptr;
1442 if (auto MD = getMacroDefinition(II))
1443 return MD.getMacroInfo();
1444 return nullptr;
1445 }
1446
1447 /// Given an identifier, return the latest non-imported macro
1448 /// directive for that identifier.
1449 ///
1450 /// One can iterate over all previous macro directives from the most recent
1451 /// one.
1453
1454 /// Add a directive to the macro directive history for this identifier.
1457 SourceLocation Loc) {
1458 DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc);
1459 appendMacroDirective(II, MD);
1460 return MD;
1461 }
1466
1467 /// Set a MacroDirective that was loaded from a PCH file.
1469 MacroDirective *MD);
1470
1471 /// Register an exported macro for a module and identifier.
1474 ArrayRef<ModuleMacro *> Overrides, bool &IsNew);
1476
1477 /// Get the list of leaf (non-overridden) module macros for a name.
1479 if (II->isOutOfDate())
1480 updateOutOfDateIdentifier(*II);
1481 auto I = LeafModuleMacros.find(II);
1482 if (I != LeafModuleMacros.end())
1483 return I->second;
1484 return {};
1485 }
1486
1487 /// Get the list of submodules that we're currently building.
1489 return BuildingSubmoduleStack;
1490 }
1491
1492 /// \{
1493 /// Iterators for the macro history table. Currently defined macros have
1494 /// IdentifierInfo::hasMacroDefinition() set and an empty
1495 /// MacroInfo::getUndefLoc() at the head of the list.
1496 using macro_iterator = MacroMap::const_iterator;
1497
1498 macro_iterator macro_begin(bool IncludeExternalMacros = true) const;
1499 macro_iterator macro_end(bool IncludeExternalMacros = true) const;
1500
1501 llvm::iterator_range<macro_iterator>
1502 macros(bool IncludeExternalMacros = true) const {
1503 macro_iterator begin = macro_begin(IncludeExternalMacros);
1504 macro_iterator end = macro_end(IncludeExternalMacros);
1505 return llvm::make_range(begin, end);
1506 }
1507
1508 /// \}
1509
1510 /// Mark the given clang module as affecting the current clang module or translation unit.
1512 assert(M->isModuleMapModule());
1513 if (!BuildingSubmoduleStack.empty()) {
1514 if (M != BuildingSubmoduleStack.back().M)
1515 BuildingSubmoduleStack.back().M->AffectingClangModules.insert(M);
1516 } else {
1517 AffectingClangModules.insert(M);
1518 }
1519 }
1520
1521 /// Get the set of top-level clang modules that affected preprocessing, but were not
1522 /// imported.
1524 return AffectingClangModules;
1525 }
1526
1527 /// Mark the file as included.
1528 /// Returns true if this is the first time the file was included.
1530 HeaderInfo.getFileInfo(File).IsLocallyIncluded = true;
1531 return IncludedFiles.insert(File).second;
1532 }
1533
1534 /// Return true if this header has already been included.
1536 HeaderInfo.getFileInfo(File);
1537 return IncludedFiles.count(File);
1538 }
1539
1540 /// Get the set of included files.
1541 IncludedFilesSet &getIncludedFiles() { return IncludedFiles; }
1542 const IncludedFilesSet &getIncludedFiles() const { return IncludedFiles; }
1543
1544 /// Return the name of the macro defined before \p Loc that has
1545 /// spelling \p Tokens. If there are multiple macros with same spelling,
1546 /// return the last one defined.
1548 ArrayRef<TokenValue> Tokens) const;
1549
1550 /// Get the predefines for this processor.
1551 /// Used by some third-party tools to inspect and add predefines (see
1552 /// https://github.com/llvm/llvm-project/issues/57483).
1553 const std::string &getPredefines() const { return Predefines; }
1554
1555 /// Set the predefines for this Preprocessor.
1556 ///
1557 /// These predefines are automatically injected when parsing the main file.
1558 void setPredefines(std::string P) { Predefines = std::move(P); }
1559
1560 /// Return information about the specified preprocessor
1561 /// identifier token.
1562 IdentifierInfo *getIdentifierInfo(StringRef Name) const {
1563 return &Identifiers.get(Name);
1564 }
1565
1566 /// Add the specified pragma handler to this preprocessor.
1567 ///
1568 /// If \p Namespace is non-null, then it is a token required to exist on the
1569 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
1570 void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler);
1572 AddPragmaHandler(StringRef(), Handler);
1573 }
1574
1575 /// Remove the specific pragma handler from this preprocessor.
1576 ///
1577 /// If \p Namespace is non-null, then it should be the namespace that
1578 /// \p Handler was added to. It is an error to remove a handler that
1579 /// has not been registered.
1580 void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler);
1582 RemovePragmaHandler(StringRef(), Handler);
1583 }
1584
1585 /// Install empty handlers for all pragmas (making them ignored).
1586 void IgnorePragmas();
1587
1588 /// Set empty line handler.
1589 void setEmptylineHandler(EmptylineHandler *Handler) { Emptyline = Handler; }
1590
1591 EmptylineHandler *getEmptylineHandler() const { return Emptyline; }
1592
1593 /// Add the specified comment handler to the preprocessor.
1594 void addCommentHandler(CommentHandler *Handler);
1595
1596 /// Remove the specified comment handler.
1597 ///
1598 /// It is an error to remove a handler that has not been registered.
1599 void removeCommentHandler(CommentHandler *Handler);
1600
1601 /// Set the code completion handler to the given object.
1603 CodeComplete = &Handler;
1604 }
1605
1606 /// Retrieve the current code-completion handler.
1608 return CodeComplete;
1609 }
1610
1611 /// Clear out the code completion handler.
1613 CodeComplete = nullptr;
1614 }
1615
1616 /// Hook used by the lexer to invoke the "included file" code
1617 /// completion point.
1618 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
1619
1620 /// Hook used by the lexer to invoke the "natural language" code
1621 /// completion point.
1623
1624 /// Set the code completion token for filtering purposes.
1626 CodeCompletionII = Filter;
1627 }
1628
1629 /// Set the code completion token range for detecting replacement range later
1630 /// on.
1632 const SourceLocation End) {
1633 CodeCompletionTokenRange = {Start, End};
1634 }
1636 return CodeCompletionTokenRange;
1637 }
1638
1639 /// Get the code completion token for filtering purposes.
1641 if (CodeCompletionII)
1642 return CodeCompletionII->getName();
1643 return {};
1644 }
1645
1646 /// Retrieve the preprocessing record, or NULL if there is no
1647 /// preprocessing record.
1649
1650 /// Create a new preprocessing record, which will keep track of
1651 /// all macro expansions, macro definitions, etc.
1653
1654 /// Returns true if the FileEntry is the PCH through header.
1655 bool isPCHThroughHeader(const FileEntry *FE);
1656
1657 /// True if creating a PCH with a through header.
1659
1660 /// True if using a PCH with a through header.
1662
1663 /// True if creating a PCH with a #pragma hdrstop.
1665
1666 /// True if using a PCH with a #pragma hdrstop.
1668
1669 /// Skip tokens until after the #include of the through header or
1670 /// until after a #pragma hdrstop.
1672
1673 /// Process directives while skipping until the through header or
1674 /// #pragma hdrstop is found.
1676 SourceLocation HashLoc);
1677
1678 /// Enter the specified FileID as the main source file,
1679 /// which implicitly adds the builtin defines etc.
1680 void EnterMainSourceFile();
1681
1682 /// Inform the preprocessor callbacks that processing is complete.
1683 void EndSourceFile();
1684
1685 /// Add a source file to the top of the include stack and
1686 /// start lexing tokens from it instead of the current buffer.
1687 ///
1688 /// Emits a diagnostic, doesn't enter the file, and returns true on error.
1690 SourceLocation Loc, bool IsFirstIncludeOfFile = true);
1691
1692 /// Add a Macro to the top of the include stack and start lexing
1693 /// tokens from it instead of the current buffer.
1694 ///
1695 /// \param Args specifies the tokens input to a function-like macro.
1696 /// \param ILEnd specifies the location of the ')' for a function-like macro
1697 /// or the identifier for an object-like macro.
1699 MacroArgs *Args);
1700
1701private:
1702 /// Add a "macro" context to the top of the include stack,
1703 /// which will cause the lexer to start returning the specified tokens.
1704 ///
1705 /// If \p DisableMacroExpansion is true, tokens lexed from the token stream
1706 /// will not be subject to further macro expansion. Otherwise, these tokens
1707 /// will be re-macro-expanded when/if expansion is enabled.
1708 ///
1709 /// If \p OwnsTokens is false, this method assumes that the specified stream
1710 /// of tokens has a permanent owner somewhere, so they do not need to be
1711 /// copied. If it is true, it assumes the array of tokens is allocated with
1712 /// \c new[] and the Preprocessor will delete[] it.
1713 ///
1714 /// If \p IsReinject the resulting tokens will have Token::IsReinjected flag
1715 /// set, see the flag documentation for details.
1716 void EnterTokenStream(const Token *Toks, unsigned NumToks,
1717 bool DisableMacroExpansion, bool OwnsTokens,
1718 bool IsReinject);
1719
1720public:
1721 void EnterTokenStream(std::unique_ptr<Token[]> Toks, unsigned NumToks,
1722 bool DisableMacroExpansion, bool IsReinject) {
1723 EnterTokenStream(Toks.release(), NumToks, DisableMacroExpansion, true,
1724 IsReinject);
1725 }
1726
1727 void EnterTokenStream(ArrayRef<Token> Toks, bool DisableMacroExpansion,
1728 bool IsReinject) {
1729 EnterTokenStream(Toks.data(), Toks.size(), DisableMacroExpansion, false,
1730 IsReinject);
1731 }
1732
1733 /// Pop the current lexer/macro exp off the top of the lexer stack.
1734 ///
1735 /// This should only be used in situations where the current state of the
1736 /// top-of-stack lexer is known.
1737 void RemoveTopOfLexerStack();
1738
1739 /// From the point that this method is called, and until
1740 /// CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
1741 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
1742 /// make the Preprocessor re-lex the same tokens.
1743 ///
1744 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
1745 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
1746 /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
1747 ///
1748 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
1749 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
1750 /// tokens will continue indefinitely.
1751 ///
1752 /// \param Unannotated Whether token annotations are reverted upon calling
1753 /// Backtrack().
1754 void EnableBacktrackAtThisPos(bool Unannotated = false);
1755
1756private:
1757 std::pair<CachedTokensTy::size_type, bool> LastBacktrackPos();
1758
1759 CachedTokensTy PopUnannotatedBacktrackTokens();
1760
1761public:
1762 /// Disable the last EnableBacktrackAtThisPos call.
1764
1765 /// Make Preprocessor re-lex the tokens that were lexed since
1766 /// EnableBacktrackAtThisPos() was previously called.
1767 void Backtrack();
1768
1769 /// True if EnableBacktrackAtThisPos() was called and
1770 /// caching of tokens is on.
1771 bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
1772
1773 /// True if EnableBacktrackAtThisPos() was called and
1774 /// caching of unannotated tokens is on.
1776 return !UnannotatedBacktrackTokens.empty();
1777 }
1778
1779 /// Lex the next token for this preprocessor.
1780 void Lex(Token &Result);
1781
1782 /// Lex all tokens for this preprocessor until (and excluding) end of file.
1783 void LexTokensUntilEOF(std::vector<Token> *Tokens = nullptr);
1784
1785 /// Lex a token, forming a header-name token if possible.
1786 bool LexHeaderName(Token &Result, bool AllowMacroExpansion = true);
1787
1788 /// Lex the parameters for an #embed directive, returns nullopt on error.
1789 std::optional<LexEmbedParametersResult> LexEmbedParameters(Token &Current,
1790 bool ForHasEmbed);
1791
1792 /// Get the start location of the first pp-token in main file.
1794 assert(FirstPPTokenLoc.isValid() &&
1795 "Did not see the first pp-token in the main file");
1796 return FirstPPTokenLoc;
1797 }
1798
1801
1803 bool IncludeExports = true);
1804
1806 return CurSubmoduleState->VisibleModules.getImportLoc(M);
1807 }
1808
1809 /// Lex a string literal, which may be the concatenation of multiple
1810 /// string literals and may even come from macro expansion.
1811 /// \returns true on success, false if a error diagnostic has been generated.
1812 bool LexStringLiteral(Token &Result, std::string &String,
1813 const char *DiagnosticTag, bool AllowMacroExpansion) {
1814 if (AllowMacroExpansion)
1815 Lex(Result);
1816 else
1818 return FinishLexStringLiteral(Result, String, DiagnosticTag,
1819 AllowMacroExpansion);
1820 }
1821
1822 /// Complete the lexing of a string literal where the first token has
1823 /// already been lexed (see LexStringLiteral).
1824 bool FinishLexStringLiteral(Token &Result, std::string &String,
1825 const char *DiagnosticTag,
1826 bool AllowMacroExpansion);
1827
1828 /// Lex a token. If it's a comment, keep lexing until we get
1829 /// something not a comment.
1830 ///
1831 /// This is useful in -E -C mode where comments would foul up preprocessor
1832 /// directive handling.
1834 do
1835 Lex(Result);
1836 while (Result.getKind() == tok::comment);
1837 }
1838
1839 /// Just like Lex, but disables macro expansion of identifier tokens.
1841 // Disable macro expansion.
1842 bool OldVal = DisableMacroExpansion;
1843 DisableMacroExpansion = true;
1844 // Lex the token.
1845 Lex(Result);
1846
1847 // Reenable it.
1848 DisableMacroExpansion = OldVal;
1849 }
1850
1851 /// Like LexNonComment, but this disables macro expansion of
1852 /// identifier tokens.
1854 do
1856 while (Result.getKind() == tok::comment);
1857 }
1858
1859 /// Parses a simple integer literal to get its numeric value. Floating
1860 /// point literals and user defined literals are rejected. Used primarily to
1861 /// handle pragmas that accept integer arguments.
1862 bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value);
1863
1864 /// Disables macro expansion everywhere except for preprocessor directives.
1866 DisableMacroExpansion = true;
1867 MacroExpansionInDirectivesOverride = true;
1868 }
1869
1871 DisableMacroExpansion = MacroExpansionInDirectivesOverride = false;
1872 }
1873
1874 /// Peeks ahead N tokens and returns that token without consuming any
1875 /// tokens.
1876 ///
1877 /// LookAhead(0) returns the next token that would be returned by Lex(),
1878 /// LookAhead(1) returns the token after it, etc. This returns normal
1879 /// tokens after phase 5. As such, it is equivalent to using
1880 /// 'Lex', not 'LexUnexpandedToken'.
1881 const Token &LookAhead(unsigned N) {
1882 assert(LexLevel == 0 && "cannot use lookahead while lexing");
1883 if (CachedLexPos + N < CachedTokens.size())
1884 return CachedTokens[CachedLexPos+N];
1885 else
1886 return PeekAhead(N+1);
1887 }
1888
1889 /// When backtracking is enabled and tokens are cached,
1890 /// this allows to revert a specific number of tokens.
1891 ///
1892 /// Note that the number of tokens being reverted should be up to the last
1893 /// backtrack position, not more.
1894 void RevertCachedTokens(unsigned N) {
1895 assert(isBacktrackEnabled() &&
1896 "Should only be called when tokens are cached for backtracking");
1897 assert(signed(CachedLexPos) - signed(N) >=
1898 signed(LastBacktrackPos().first) &&
1899 "Should revert tokens up to the last backtrack position, not more");
1900 assert(signed(CachedLexPos) - signed(N) >= 0 &&
1901 "Corrupted backtrack positions ?");
1902 CachedLexPos -= N;
1903 }
1904
1905 /// Enters a token in the token stream to be lexed next.
1906 ///
1907 /// If BackTrack() is called afterwards, the token will remain at the
1908 /// insertion point.
1909 /// If \p IsReinject is true, resulting token will have Token::IsReinjected
1910 /// flag set. See the flag documentation for details.
1911 void EnterToken(const Token &Tok, bool IsReinject) {
1912 if (LexLevel) {
1913 // It's not correct in general to enter caching lex mode while in the
1914 // middle of a nested lexing action.
1915 auto TokCopy = std::make_unique<Token[]>(1);
1916 TokCopy[0] = Tok;
1917 EnterTokenStream(std::move(TokCopy), 1, true, IsReinject);
1918 } else {
1919 EnterCachingLexMode();
1920 assert(IsReinject && "new tokens in the middle of cached stream");
1921 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
1922 }
1923 }
1924
1925 /// We notify the Preprocessor that if it is caching tokens (because
1926 /// backtrack is enabled) it should replace the most recent cached tokens
1927 /// with the given annotation token. This function has no effect if
1928 /// backtracking is not enabled.
1929 ///
1930 /// Note that the use of this function is just for optimization, so that the
1931 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
1932 /// invoked.
1934 assert(Tok.isAnnotation() && "Expected annotation token");
1935 if (CachedLexPos != 0 && isBacktrackEnabled())
1936 AnnotatePreviousCachedTokens(Tok);
1937 }
1938
1939 /// Get the location of the last cached token, suitable for setting the end
1940 /// location of an annotation token.
1942 assert(CachedLexPos != 0);
1943 return CachedTokens[CachedLexPos-1].getLastLoc();
1944 }
1945
1946 /// Whether \p Tok is the most recent token (`CachedLexPos - 1`) in
1947 /// CachedTokens.
1948 bool IsPreviousCachedToken(const Token &Tok) const;
1949
1950 /// Replace token in `CachedLexPos - 1` in CachedTokens by the tokens
1951 /// in \p NewToks.
1952 ///
1953 /// Useful when a token needs to be split in smaller ones and CachedTokens
1954 /// most recent token must to be updated to reflect that.
1956
1957 /// Replace the last token with an annotation token.
1958 ///
1959 /// Like AnnotateCachedTokens(), this routine replaces an
1960 /// already-parsed (and resolved) token with an annotation
1961 /// token. However, this routine only replaces the last token with
1962 /// the annotation token; it does not affect any other cached
1963 /// tokens. This function has no effect if backtracking is not
1964 /// enabled.
1966 assert(Tok.isAnnotation() && "Expected annotation token");
1967 if (CachedLexPos != 0 && isBacktrackEnabled())
1968 CachedTokens[CachedLexPos-1] = Tok;
1969 }
1970
1971 /// Enter an annotation token into the token stream.
1973 void *AnnotationVal);
1974
1975 /// Determine whether it's possible for a future call to Lex to produce an
1976 /// annotation token created by a previous call to EnterAnnotationToken.
1978 return CurLexerCallback != CLK_Lexer;
1979 }
1980
1981 /// Update the current token to represent the provided
1982 /// identifier, in order to cache an action performed by typo correction.
1984 assert(Tok.getIdentifierInfo() && "Expected identifier token");
1985 if (CachedLexPos != 0 && isBacktrackEnabled())
1986 CachedTokens[CachedLexPos-1] = Tok;
1987 }
1988
1989 /// Recompute the current lexer kind based on the CurLexer/
1990 /// CurTokenLexer pointers.
1991 void recomputeCurLexerKind();
1992
1993 /// Returns true if incremental processing is enabled
1994 bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; }
1995
1996 /// Enables the incremental processing
1997 void enableIncrementalProcessing(bool value = true) {
1998 IncrementalProcessing = value;
1999 }
2000
2001 /// Specify the point at which code-completion will be performed.
2002 ///
2003 /// \param File the file in which code completion should occur. If
2004 /// this file is included multiple times, code-completion will
2005 /// perform completion the first time it is included. If NULL, this
2006 /// function clears out the code-completion point.
2007 ///
2008 /// \param Line the line at which code completion should occur
2009 /// (1-based).
2010 ///
2011 /// \param Column the column at which code completion should occur
2012 /// (1-based).
2013 ///
2014 /// \returns true if an error occurred, false otherwise.
2016 unsigned Column);
2017
2018 /// Determine if we are performing code completion.
2019 bool isCodeCompletionEnabled() const { return CodeCompletionFile != nullptr; }
2020
2021 /// Returns the location of the code-completion point.
2022 ///
2023 /// Returns an invalid location if code-completion is not enabled or the file
2024 /// containing the code-completion point has not been lexed yet.
2025 SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; }
2026
2027 /// Returns the start location of the file of code-completion point.
2028 ///
2029 /// Returns an invalid location if code-completion is not enabled or the file
2030 /// containing the code-completion point has not been lexed yet.
2032 return CodeCompletionFileLoc;
2033 }
2034
2035 /// Returns true if code-completion is enabled and we have hit the
2036 /// code-completion point.
2037 bool isCodeCompletionReached() const { return CodeCompletionReached; }
2038
2039 /// Note that we hit the code-completion point.
2041 assert(isCodeCompletionEnabled() && "Code-completion not enabled!");
2042 CodeCompletionReached = true;
2043 // Silence any diagnostics that occur after we hit the code-completion.
2045 }
2046
2047 /// The location of the currently-active \#pragma clang
2048 /// arc_cf_code_audited begin.
2049 ///
2050 /// Returns an invalid location if there is no such pragma active.
2052 return PragmaARCCFCodeAuditedInfo;
2053 }
2054
2055 /// Set the location of the currently-active \#pragma clang
2056 /// arc_cf_code_audited begin. An invalid location ends the pragma.
2058 SourceLocation Loc) {
2059 PragmaARCCFCodeAuditedInfo = IdentifierLoc(Loc, Ident);
2060 }
2061
2062 /// The location of the currently-active \#pragma clang
2063 /// assume_nonnull begin.
2064 ///
2065 /// Returns an invalid location if there is no such pragma active.
2067 return PragmaAssumeNonNullLoc;
2068 }
2069
2070 /// Set the location of the currently-active \#pragma clang
2071 /// assume_nonnull begin. An invalid location ends the pragma.
2073 PragmaAssumeNonNullLoc = Loc;
2074 }
2075
2076 /// Get the location of the recorded unterminated \#pragma clang
2077 /// assume_nonnull begin in the preamble, if one exists.
2078 ///
2079 /// Returns an invalid location if the premable did not end with
2080 /// such a pragma active or if there is no recorded preamble.
2082 return PreambleRecordedPragmaAssumeNonNullLoc;
2083 }
2084
2085 /// Record the location of the unterminated \#pragma clang
2086 /// assume_nonnull begin in the preamble.
2088 PreambleRecordedPragmaAssumeNonNullLoc = Loc;
2089 }
2090
2091 /// Set the directory in which the main file should be considered
2092 /// to have been found, if it is not a real file.
2093 void setMainFileDir(DirectoryEntryRef Dir) { MainFileDir = Dir; }
2094
2095 /// Instruct the preprocessor to skip part of the main source file.
2096 ///
2097 /// \param Bytes The number of bytes in the preamble to skip.
2098 ///
2099 /// \param StartOfLine Whether skipping these bytes puts the lexer at the
2100 /// start of a line.
2101 void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) {
2102 SkipMainFilePreamble.first = Bytes;
2103 SkipMainFilePreamble.second = StartOfLine;
2104 }
2105
2106 /// Forwarding function for diagnostics. This emits a diagnostic at
2107 /// the specified Token's location, translating the token's start
2108 /// position in the current buffer into a SourcePosition object for rendering.
2109 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const {
2110 return Diags->Report(Loc, DiagID);
2111 }
2112
2113 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const {
2114 return Diags->Report(Tok.getLocation(), DiagID);
2115 }
2116
2117 /// Return the 'spelling' of the token at the given
2118 /// location; does not go up to the spelling location or down to the
2119 /// expansion location.
2120 ///
2121 /// \param buffer A buffer which will be used only if the token requires
2122 /// "cleaning", e.g. if it contains trigraphs or escaped newlines
2123 /// \param invalid If non-null, will be set \c true if an error occurs.
2125 SmallVectorImpl<char> &buffer,
2126 bool *invalid = nullptr) const {
2127 return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid);
2128 }
2129
2130 /// Return the 'spelling' of the Tok token.
2131 ///
2132 /// The spelling of a token is the characters used to represent the token in
2133 /// the source file after trigraph expansion and escaped-newline folding. In
2134 /// particular, this wants to get the true, uncanonicalized, spelling of
2135 /// things like digraphs, UCNs, etc.
2136 ///
2137 /// \param Invalid If non-null, will be set \c true if an error occurs.
2138 std::string getSpelling(const Token &Tok, bool *Invalid = nullptr) const {
2139 return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid);
2140 }
2141
2142 /// Get the spelling of a token into a preallocated buffer, instead
2143 /// of as an std::string.
2144 ///
2145 /// The caller is required to allocate enough space for the token, which is
2146 /// guaranteed to be at least Tok.getLength() bytes long. The length of the
2147 /// actual result is returned.
2148 ///
2149 /// Note that this method may do two possible things: it may either fill in
2150 /// the buffer specified with characters, or it may *change the input pointer*
2151 /// to point to a constant buffer with the data already in it (avoiding a
2152 /// copy). The caller is not allowed to modify the returned buffer pointer
2153 /// if an internal buffer is returned.
2154 unsigned getSpelling(const Token &Tok, const char *&Buffer,
2155 bool *Invalid = nullptr) const {
2156 return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid);
2157 }
2158
2159 /// Get the spelling of a token into a SmallVector.
2160 ///
2161 /// Note that the returned StringRef may not point to the
2162 /// supplied buffer if a copy can be avoided.
2163 StringRef getSpelling(const Token &Tok,
2164 SmallVectorImpl<char> &Buffer,
2165 bool *Invalid = nullptr) const;
2166
2167 /// Relex the token at the specified location.
2168 /// \returns true if there was a failure, false on success.
2170 bool IgnoreWhiteSpace = false) {
2171 return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts, IgnoreWhiteSpace);
2172 }
2173
2174 /// Given a Token \p Tok that is a numeric constant with length 1,
2175 /// return the value of constant as an unsigned 8-bit integer.
2176 uint8_t
2178 bool *Invalid = nullptr) const {
2179 assert((Tok.is(tok::numeric_constant) || Tok.is(tok::binary_data)) &&
2180 Tok.getLength() == 1 && "Called on unsupported token");
2181 assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
2182
2183 // If the token is carrying a literal data pointer, just use it.
2184 if (const char *D = Tok.getLiteralData())
2185 return (Tok.getKind() == tok::binary_data) ? *D : *D - '0';
2186
2187 assert(Tok.is(tok::numeric_constant) && "binary data with no data");
2188 // Otherwise, fall back on getCharacterData, which is slower, but always
2189 // works.
2190 return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid) - '0';
2191 }
2192
2193 /// Retrieve the name of the immediate macro expansion.
2194 ///
2195 /// This routine starts from a source location, and finds the name of the
2196 /// macro responsible for its immediate expansion. It looks through any
2197 /// intervening macro argument expansions to compute this. It returns a
2198 /// StringRef that refers to the SourceManager-owned buffer of the source
2199 /// where that macro name is spelled. Thus, the result shouldn't out-live
2200 /// the SourceManager.
2202 return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts());
2203 }
2204
2205 /// Plop the specified string into a scratch buffer and set the
2206 /// specified token's location and length to it.
2207 ///
2208 /// If specified, the source location provides a location of the expansion
2209 /// point of the token.
2210 void CreateString(StringRef Str, Token &Tok,
2211 SourceLocation ExpansionLocStart = SourceLocation(),
2212 SourceLocation ExpansionLocEnd = SourceLocation());
2213
2214 /// Split the first Length characters out of the token starting at TokLoc
2215 /// and return a location pointing to the split token. Re-lexing from the
2216 /// split token will return the split token rather than the original.
2217 SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length);
2218
2219 /// Computes the source location just past the end of the
2220 /// token at this source location.
2221 ///
2222 /// This routine can be used to produce a source location that
2223 /// points just past the end of the token referenced by \p Loc, and
2224 /// is generally used when a diagnostic needs to point just after a
2225 /// token where it expected something different that it received. If
2226 /// the returned source location would not be meaningful (e.g., if
2227 /// it points into a macro), this routine returns an invalid
2228 /// source location.
2229 ///
2230 /// \param Offset an offset from the end of the token, where the source
2231 /// location should refer to. The default offset (0) produces a source
2232 /// location pointing just past the end of the token; an offset of 1 produces
2233 /// a source location pointing to the last character in the token, etc.
2235 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
2236 }
2237
2238 /// Returns true if the given MacroID location points at the first
2239 /// token of the macro expansion.
2240 ///
2241 /// \param MacroBegin If non-null and function returns true, it is set to
2242 /// begin location of the macro.
2244 SourceLocation *MacroBegin = nullptr) const {
2245 return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts,
2246 MacroBegin);
2247 }
2248
2249 /// Returns true if the given MacroID location points at the last
2250 /// token of the macro expansion.
2251 ///
2252 /// \param MacroEnd If non-null and function returns true, it is set to
2253 /// end location of the macro.
2255 SourceLocation *MacroEnd = nullptr) const {
2256 return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd);
2257 }
2258
2259 /// Print the token to stderr, used for debugging.
2260 void DumpToken(const Token &Tok, bool DumpFlags = false) const;
2261 void DumpLocation(SourceLocation Loc) const;
2262 void DumpMacro(const MacroInfo &MI) const;
2263 void dumpMacroInfo(const IdentifierInfo *II);
2264
2265 /// Given a location that specifies the start of a
2266 /// token, return a new location that specifies a character within the token.
2268 unsigned Char) const {
2269 return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts);
2270 }
2271
2272 /// Increment the counters for the number of token paste operations
2273 /// performed.
2274 ///
2275 /// If fast was specified, this is a 'fast paste' case we handled.
2276 void IncrementPasteCounter(bool isFast) {
2277 if (isFast)
2278 ++NumFastTokenPaste;
2279 else
2280 ++NumTokenPaste;
2281 }
2282
2283 void PrintStats();
2284
2285 size_t getTotalMemory() const;
2286
2287 /// When the macro expander pastes together a comment (/##/) in Microsoft
2288 /// mode, this method handles updating the current state, returning the
2289 /// token on the next source line.
2291
2292 //===--------------------------------------------------------------------===//
2293 // Preprocessor callback methods. These are invoked by a lexer as various
2294 // directives and events are found.
2295
2296 /// Given a tok::raw_identifier token, look up the
2297 /// identifier information for the token and install it into the token,
2298 /// updating the token kind accordingly.
2299 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const;
2300
2301private:
2302 llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons;
2303
2304public:
2305 /// Specifies the reason for poisoning an identifier.
2306 ///
2307 /// If that identifier is accessed while poisoned, then this reason will be
2308 /// used instead of the default "poisoned" diagnostic.
2309 void SetPoisonReason(IdentifierInfo *II, unsigned DiagID);
2310
2311 /// Display reason for poisoned identifier.
2312 void HandlePoisonedIdentifier(Token & Identifier);
2313
2315 if(IdentifierInfo * II = Identifier.getIdentifierInfo()) {
2316 if(II->isPoisoned()) {
2317 HandlePoisonedIdentifier(Identifier);
2318 }
2319 }
2320 }
2321
2322 /// Check whether the next pp-token is one of the specificed token kind. this
2323 /// method should have no observable side-effect on the lexed tokens.
2324 template <typename... Ts> bool isNextPPTokenOneOf(Ts... Ks) {
2325 static_assert(sizeof...(Ts) > 0,
2326 "requires at least one tok::TokenKind specified");
2327 // Do some quick tests for rejection cases.
2328 std::optional<Token> Val;
2329 if (CurLexer)
2330 Val = CurLexer->peekNextPPToken();
2331 else
2332 Val = CurTokenLexer->peekNextPPToken();
2333
2334 if (!Val) {
2335 // We have run off the end. If it's a source file we don't
2336 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
2337 // macro stack.
2338 if (CurPPLexer)
2339 return false;
2340 for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
2341 if (Entry.TheLexer)
2342 Val = Entry.TheLexer->peekNextPPToken();
2343 else
2344 Val = Entry.TheTokenLexer->peekNextPPToken();
2345
2346 if (Val)
2347 break;
2348
2349 // Ran off the end of a source file?
2350 if (Entry.ThePPLexer)
2351 return false;
2352 }
2353 }
2354
2355 // Okay, we found the token and return. Otherwise we found the end of the
2356 // translation unit.
2357 return Val->isOneOf(Ks...);
2358 }
2359
2360private:
2361 /// Identifiers used for SEH handling in Borland. These are only
2362 /// allowed in particular circumstances
2363 // __except block
2364 IdentifierInfo *Ident__exception_code,
2365 *Ident___exception_code,
2366 *Ident_GetExceptionCode;
2367 // __except filter expression
2368 IdentifierInfo *Ident__exception_info,
2369 *Ident___exception_info,
2370 *Ident_GetExceptionInfo;
2371 // __finally
2372 IdentifierInfo *Ident__abnormal_termination,
2373 *Ident___abnormal_termination,
2374 *Ident_AbnormalTermination;
2375
2376 const char *getCurLexerEndPos();
2377 void diagnoseMissingHeaderInUmbrellaDir(const Module &Mod);
2378
2379public:
2380 void PoisonSEHIdentifiers(bool Poison = true); // Borland
2381
2382 /// Callback invoked when the lexer reads an identifier and has
2383 /// filled in the tokens IdentifierInfo member.
2384 ///
2385 /// This callback potentially macro expands it or turns it into a named
2386 /// token (like 'for').
2387 ///
2388 /// \returns true if we actually computed a token, false if we need to
2389 /// lex again.
2390 bool HandleIdentifier(Token &Identifier);
2391
2392 /// Callback invoked when the lexer hits the end of the current file.
2393 ///
2394 /// This either returns the EOF token and returns true, or
2395 /// pops a level off the include stack and returns false, at which point the
2396 /// client should call lex again.
2397 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
2398
2399 /// Callback invoked when the current TokenLexer hits the end of its
2400 /// token stream.
2402
2403 /// Callback invoked when the lexer sees a # token at the start of a
2404 /// line.
2405 ///
2406 /// This consumes the directive, modifies the lexer/preprocessor state, and
2407 /// advances the lexer(s) so that the next token read is the correct one.
2409
2410 /// Ensure that the next token is a tok::eod token.
2411 ///
2412 /// If not, emit a diagnostic and consume up until the eod.
2413 /// If \p EnableMacros is true, then we consider macros that expand to zero
2414 /// tokens as being ok.
2415 ///
2416 /// \return The location of the end of the directive (the terminating
2417 /// newline).
2418 SourceLocation CheckEndOfDirective(const char *DirType,
2419 bool EnableMacros = false);
2420
2421 /// Read and discard all tokens remaining on the current line until
2422 /// the tok::eod token is found. Returns the range of the skipped tokens.
2427
2428 /// Same as above except retains the token that was found.
2430
2431 /// Returns true if the preprocessor has seen a use of
2432 /// __DATE__ or __TIME__ in the file so far.
2433 bool SawDateOrTime() const {
2434 return DATELoc != SourceLocation() || TIMELoc != SourceLocation();
2435 }
2436 uint32_t getCounterValue() const { return CounterValue; }
2437 void setCounterValue(uint32_t V) { CounterValue = V; }
2438
2440 assert(CurrentFPEvalMethod != LangOptions::FEM_UnsetOnCommandLine &&
2441 "FPEvalMethod should be set either from command line or from the "
2442 "target info");
2443 return CurrentFPEvalMethod;
2444 }
2445
2447 return TUFPEvalMethod;
2448 }
2449
2451 return LastFPEvalPragmaLocation;
2452 }
2453
2457 "FPEvalMethod should never be set to FEM_UnsetOnCommandLine");
2458 // This is the location of the '#pragma float_control" where the
2459 // execution state is modifed.
2460 LastFPEvalPragmaLocation = PragmaLoc;
2461 CurrentFPEvalMethod = Val;
2462 TUFPEvalMethod = Val;
2463 }
2464
2467 "TUPEvalMethod should never be set to FEM_UnsetOnCommandLine");
2468 TUFPEvalMethod = Val;
2469 }
2470
2471 /// Retrieves the module that we're currently building, if any.
2473
2474 /// Retrieves the module whose implementation we're current compiling, if any.
2476
2477 /// If we are preprocessing a named module.
2478 bool isInNamedModule() const { return ModuleDeclState.isNamedModule(); }
2479
2480 /// If we are proprocessing a named interface unit.
2481 /// Note that a module implementation partition is not considered as an
2482 /// named interface unit here although it is importable
2483 /// to ease the parsing.
2485 return ModuleDeclState.isNamedInterface();
2486 }
2487
2488 /// Get the named module name we're preprocessing.
2489 /// Requires we're preprocessing a named module.
2490 StringRef getNamedModuleName() const { return ModuleDeclState.getName(); }
2491
2492 /// If we are implementing an implementation module unit.
2493 /// Note that the module implementation partition is not considered as an
2494 /// implementation unit.
2496 return ModuleDeclState.isImplementationUnit();
2497 }
2498
2499 /// If we're importing a standard C++20 Named Modules.
2501 // NamedModuleImportPath will be non-empty only if we're importing
2502 // Standard C++ named modules.
2503 return !NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules &&
2504 !IsAtImport;
2505 }
2506
2507 /// Allocate a new MacroInfo object with the provided SourceLocation.
2509
2510 /// Turn the specified lexer token into a fully checked and spelled
2511 /// filename, e.g. as an operand of \#include.
2512 ///
2513 /// The caller is expected to provide a buffer that is large enough to hold
2514 /// the spelling of the filename, but is also expected to handle the case
2515 /// when this method decides to use a different buffer.
2516 ///
2517 /// \returns true if the input filename was in <>'s or false if it was
2518 /// in ""'s.
2519 bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Buffer);
2520
2521 /// Given a "foo" or <foo> reference, look up the indicated file.
2522 ///
2523 /// Returns std::nullopt on failure. \p isAngled indicates whether the file
2524 /// reference is for system \#include's or not (i.e. using <> instead of "").
2526 LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
2527 ConstSearchDirIterator FromDir, const FileEntry *FromFile,
2528 ConstSearchDirIterator *CurDir, SmallVectorImpl<char> *SearchPath,
2529 SmallVectorImpl<char> *RelativePath,
2530 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
2531 bool *IsFrameworkFound, bool SkipCache = false,
2532 bool OpenFile = true, bool CacheFailures = true);
2533
2534 /// Given a "Filename" or <Filename> reference, look up the indicated embed
2535 /// resource. \p isAngled indicates whether the file reference is for
2536 /// system \#include's or not (i.e. using <> instead of ""). If \p OpenFile
2537 /// is true, the file looked up is opened for reading, otherwise it only
2538 /// validates that the file exists. Quoted filenames are looked up relative
2539 /// to \p LookupFromFile if it is nonnull.
2540 ///
2541 /// Returns std::nullopt on failure.
2543 LookupEmbedFile(StringRef Filename, bool isAngled, bool OpenFile,
2544 const FileEntry *LookupFromFile = nullptr);
2545
2546 /// Return true if we're in the top-level file, not in a \#include.
2547 bool isInPrimaryFile() const;
2548
2549 /// Lex an on-off-switch (C99 6.10.6p2) and verify that it is
2550 /// followed by EOD. Return true if the token is not a valid on-off-switch.
2552
2553 bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
2554 bool *ShadowFlag = nullptr);
2555
2556 void EnterSubmodule(Module *M, SourceLocation ImportLoc, bool ForPragma);
2557 Module *LeaveSubmodule(bool ForPragma);
2558
2559private:
2560 friend void TokenLexer::ExpandFunctionArguments();
2561
2562 void PushIncludeMacroStack() {
2563 assert(CurLexerCallback != CLK_CachingLexer &&
2564 "cannot push a caching lexer");
2565 IncludeMacroStack.emplace_back(CurLexerCallback, CurLexerSubmodule,
2566 std::move(CurLexer), CurPPLexer,
2567 std::move(CurTokenLexer), CurDirLookup);
2568 CurPPLexer = nullptr;
2569 }
2570
2571 void PopIncludeMacroStack() {
2572 CurLexer = std::move(IncludeMacroStack.back().TheLexer);
2573 CurPPLexer = IncludeMacroStack.back().ThePPLexer;
2574 CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer);
2575 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
2576 CurLexerSubmodule = IncludeMacroStack.back().TheSubmodule;
2577 CurLexerCallback = IncludeMacroStack.back().CurLexerCallback;
2578 IncludeMacroStack.pop_back();
2579 }
2580
2581 void PropagateLineStartLeadingSpaceInfo(Token &Result);
2582
2583 /// Determine whether we need to create module macros for #defines in the
2584 /// current context.
2585 bool needModuleMacros() const;
2586
2587 /// Update the set of active module macros and ambiguity flag for a module
2588 /// macro name.
2589 void updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info);
2590
2591 DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI,
2592 SourceLocation Loc);
2593 UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc);
2594 VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc,
2595 bool isPublic);
2596
2597 /// Lex and validate a macro name, which occurs after a
2598 /// \#define or \#undef.
2599 ///
2600 /// \param MacroNameTok Token that represents the name defined or undefined.
2601 /// \param IsDefineUndef Kind if preprocessor directive.
2602 /// \param ShadowFlag Points to flag that is set if macro name shadows
2603 /// a keyword.
2604 ///
2605 /// This emits a diagnostic, sets the token kind to eod,
2606 /// and discards the rest of the macro line if the macro name is invalid.
2607 void ReadMacroName(Token &MacroNameTok, MacroUse IsDefineUndef = MU_Other,
2608 bool *ShadowFlag = nullptr);
2609
2610 /// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2611 /// entire line) of the macro's tokens and adds them to MacroInfo, and while
2612 /// doing so performs certain validity checks including (but not limited to):
2613 /// - # (stringization) is followed by a macro parameter
2614 /// \param MacroNameTok - Token that represents the macro name
2615 /// \param ImmediatelyAfterHeaderGuard - Macro follows an #ifdef header guard
2616 ///
2617 /// Either returns a pointer to a MacroInfo object OR emits a diagnostic and
2618 /// returns a nullptr if an invalid sequence of tokens is encountered.
2619 MacroInfo *ReadOptionalMacroParameterListAndBody(
2620 const Token &MacroNameTok, bool ImmediatelyAfterHeaderGuard);
2621
2622 /// The ( starting an argument list of a macro definition has just been read.
2623 /// Lex the rest of the parameters and the closing ), updating \p MI with
2624 /// what we learn and saving in \p LastTok the last token read.
2625 /// Return true if an error occurs parsing the arg list.
2626 bool ReadMacroParameterList(MacroInfo *MI, Token& LastTok);
2627
2628 /// Provide a suggestion for a typoed directive. If there is no typo, then
2629 /// just skip suggesting.
2630 ///
2631 /// \param Tok - Token that represents the directive
2632 /// \param Directive - String reference for the directive name
2633 void SuggestTypoedDirective(const Token &Tok, StringRef Directive) const;
2634
2635 /// We just read a \#if or related directive and decided that the
2636 /// subsequent tokens are in the \#if'd out portion of the
2637 /// file. Lex the rest of the file, until we see an \#endif. If \p
2638 /// FoundNonSkipPortion is true, then we have already emitted code for part of
2639 /// this \#if directive, so \#else/\#elif blocks should never be entered. If
2640 /// \p FoundElse is false, then \#else directives are ok, if not, then we have
2641 /// already seen one so a \#else directive is a duplicate. When this returns,
2642 /// the caller can lex the first valid token.
2643 void SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
2644 SourceLocation IfTokenLoc,
2645 bool FoundNonSkipPortion, bool FoundElse,
2646 SourceLocation ElseLoc = SourceLocation());
2647
2648 /// Information about the result for evaluating an expression for a
2649 /// preprocessor directive.
2650 struct DirectiveEvalResult {
2651 /// The integral value of the expression.
2652 std::optional<llvm::APSInt> Value;
2653
2654 /// Whether the expression was evaluated as true or not.
2655 bool Conditional;
2656
2657 /// True if the expression contained identifiers that were undefined.
2658 bool IncludedUndefinedIds;
2659
2660 /// The source range for the expression.
2661 SourceRange ExprRange;
2662 };
2663
2664 /// Evaluate an integer constant expression that may occur after a
2665 /// \#if or \#elif directive and return a \p DirectiveEvalResult object.
2666 ///
2667 /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro.
2668 DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
2669 bool CheckForEoD = true);
2670
2671 /// Evaluate an integer constant expression that may occur after a
2672 /// \#if or \#elif directive and return a \p DirectiveEvalResult object.
2673 ///
2674 /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro.
2675 /// \p EvaluatedDefined will contain the result of whether "defined" appeared
2676 /// in the evaluated expression or not.
2677 DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
2678 Token &Tok,
2679 bool &EvaluatedDefined,
2680 bool CheckForEoD = true);
2681
2682 /// Process a '__has_embed("path" [, ...])' expression.
2683 ///
2684 /// Returns predefined `__STDC_EMBED_*` macro values if
2685 /// successful.
2686 EmbedResult EvaluateHasEmbed(Token &Tok, IdentifierInfo *II);
2687
2688 /// Process a '__has_include("path")' expression.
2689 ///
2690 /// Returns true if successful.
2691 bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II);
2692
2693 /// Process '__has_include_next("path")' expression.
2694 ///
2695 /// Returns true if successful.
2696 bool EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II);
2697
2698 /// Get the directory and file from which to start \#include_next lookup.
2699 std::pair<ConstSearchDirIterator, const FileEntry *>
2700 getIncludeNextStart(const Token &IncludeNextTok) const;
2701
2702 /// Install the standard preprocessor pragmas:
2703 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
2704 void RegisterBuiltinPragmas();
2705
2706 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
2707 /// table and mark it as a builtin macro to be expanded.
2708 IdentifierInfo *RegisterBuiltinMacro(const char *Name) {
2709 // Get the identifier.
2710 IdentifierInfo *Id = getIdentifierInfo(Name);
2711
2712 // Mark it as being a macro that is builtin.
2713 MacroInfo *MI = AllocateMacroInfo(SourceLocation());
2714 MI->setIsBuiltinMacro();
2716 return Id;
2717 }
2718
2719 /// Register builtin macros such as __LINE__ with the identifier table.
2720 void RegisterBuiltinMacros();
2721
2722 /// If an identifier token is read that is to be expanded as a macro, handle
2723 /// it and return the next token as 'Tok'. If we lexed a token, return true;
2724 /// otherwise the caller should lex again.
2725 bool HandleMacroExpandedIdentifier(Token &Identifier, const MacroDefinition &MD);
2726
2727 /// Cache macro expanded tokens for TokenLexers.
2728 //
2729 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
2730 /// going to lex in the cache and when it finishes the tokens are removed
2731 /// from the end of the cache.
2732 Token *cacheMacroExpandedTokens(TokenLexer *tokLexer,
2733 ArrayRef<Token> tokens);
2734
2735 void removeCachedMacroExpandedTokensOfLastLexer();
2736
2737 /// After reading "MACRO(", this method is invoked to read all of the formal
2738 /// arguments specified for the macro invocation. Returns null on error.
2739 MacroArgs *ReadMacroCallArgumentList(Token &MacroName, MacroInfo *MI,
2740 SourceLocation &MacroEnd);
2741
2742 /// If an identifier token is read that is to be expanded
2743 /// as a builtin macro, handle it and return the next token as 'Tok'.
2744 void ExpandBuiltinMacro(Token &Tok);
2745
2746 /// Read a \c _Pragma directive, slice it up, process it, then
2747 /// return the first token after the directive.
2748 /// This assumes that the \c _Pragma token has just been read into \p Tok.
2749 void Handle_Pragma(Token &Tok);
2750
2751 /// Like Handle_Pragma except the pragma text is not enclosed within
2752 /// a string literal.
2753 void HandleMicrosoft__pragma(Token &Tok);
2754
2755 /// Add a lexer to the top of the include stack and
2756 /// start lexing tokens from it instead of the current buffer.
2757 void EnterSourceFileWithLexer(Lexer *TheLexer, ConstSearchDirIterator Dir);
2758
2759 /// Set the FileID for the preprocessor predefines.
2760 void setPredefinesFileID(FileID FID) {
2761 assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!");
2762 PredefinesFileID = FID;
2763 }
2764
2765 /// Set the FileID for the PCH through header.
2766 void setPCHThroughHeaderFileID(FileID FID);
2767
2768 /// Returns true if we are lexing from a file and not a
2769 /// pragma or a macro.
2770 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
2771 return L ? !L->isPragmaLexer() : P != nullptr;
2772 }
2773
2774 static bool IsFileLexer(const IncludeStackInfo& I) {
2775 return IsFileLexer(I.TheLexer.get(), I.ThePPLexer);
2776 }
2777
2778 bool IsFileLexer() const {
2779 return IsFileLexer(CurLexer.get(), CurPPLexer);
2780 }
2781
2782 //===--------------------------------------------------------------------===//
2783 // Standard Library Identification
2784 std::optional<CXXStandardLibraryVersionInfo> CXXStandardLibraryVersion;
2785
2786public:
2787 std::optional<std::uint64_t> getStdLibCxxVersion();
2788 bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion);
2789
2790private:
2791 //===--------------------------------------------------------------------===//
2792 // Caching stuff.
2793 void CachingLex(Token &Result);
2794
2795 bool InCachingLexMode() const {
2796 // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means
2797 // that we are past EOF, not that we are in CachingLex mode.
2798 return !CurPPLexer && !CurTokenLexer && !IncludeMacroStack.empty();
2799 }
2800
2801 void EnterCachingLexMode();
2802 void EnterCachingLexModeUnchecked();
2803
2804 void ExitCachingLexMode() {
2805 if (InCachingLexMode())
2807 }
2808
2809 const Token &PeekAhead(unsigned N);
2810 void AnnotatePreviousCachedTokens(const Token &Tok);
2811
2812 //===--------------------------------------------------------------------===//
2813 /// Handle*Directive - implement the various preprocessor directives. These
2814 /// should side-effect the current preprocessor object so that the next call
2815 /// to Lex() will return the appropriate token next.
2816 void HandleLineDirective();
2817 void HandleDigitDirective(Token &Tok);
2818 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
2819 void HandleIdentSCCSDirective(Token &Tok);
2820 void HandleMacroPublicDirective(Token &Tok);
2821 void HandleMacroPrivateDirective();
2822
2823 /// An additional notification that can be produced by a header inclusion or
2824 /// import to tell the parser what happened.
2825 struct ImportAction {
2826 enum ActionKind {
2827 None,
2828 ModuleBegin,
2829 ModuleImport,
2830 HeaderUnitImport,
2831 SkippedModuleImport,
2832 Failure,
2833 } Kind;
2834 Module *ModuleForHeader = nullptr;
2835
2836 ImportAction(ActionKind AK, Module *Mod = nullptr)
2837 : Kind(AK), ModuleForHeader(Mod) {
2838 assert((AK == None || Mod || AK == Failure) &&
2839 "no module for module action");
2840 }
2841 };
2842
2843 OptionalFileEntryRef LookupHeaderIncludeOrImport(
2844 ConstSearchDirIterator *CurDir, StringRef &Filename,
2845 SourceLocation FilenameLoc, CharSourceRange FilenameRange,
2846 const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
2847 bool &IsMapped, ConstSearchDirIterator LookupFrom,
2848 const FileEntry *LookupFromFile, StringRef &LookupFilename,
2849 SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
2850 ModuleMap::KnownHeader &SuggestedModule, bool isAngled);
2851 // Binary data inclusion
2852 void HandleEmbedDirective(SourceLocation HashLoc, Token &Tok,
2853 const FileEntry *LookupFromFile = nullptr);
2854 void HandleEmbedDirectiveImpl(SourceLocation HashLoc,
2855 const LexEmbedParametersResult &Params,
2856 StringRef BinaryContents, StringRef FileName);
2857
2858 // File inclusion.
2859 void HandleIncludeDirective(SourceLocation HashLoc, Token &Tok,
2860 ConstSearchDirIterator LookupFrom = nullptr,
2861 const FileEntry *LookupFromFile = nullptr);
2862 ImportAction
2863 HandleHeaderIncludeOrImport(SourceLocation HashLoc, Token &IncludeTok,
2864 Token &FilenameTok, SourceLocation EndLoc,
2865 ConstSearchDirIterator LookupFrom = nullptr,
2866 const FileEntry *LookupFromFile = nullptr);
2867 void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok);
2868 void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok);
2869 void HandleImportDirective(SourceLocation HashLoc, Token &Tok);
2870 void HandleMicrosoftImportDirective(Token &Tok);
2871
2872public:
2873 /// Check that the given module is available, producing a diagnostic if not.
2874 /// \return \c true if the check failed (because the module is not available).
2875 /// \c false if the module appears to be usable.
2876 static bool checkModuleIsAvailable(const LangOptions &LangOpts,
2877 const TargetInfo &TargetInfo,
2878 const Module &M, DiagnosticsEngine &Diags);
2879
2880 // Module inclusion testing.
2881 /// Find the module that owns the source or header file that
2882 /// \p Loc points to. If the location is in a file that was included
2883 /// into a module, or is outside any module, returns nullptr.
2884 Module *getModuleForLocation(SourceLocation Loc, bool AllowTextual);
2885
2886 /// We want to produce a diagnostic at location IncLoc concerning an
2887 /// unreachable effect at location MLoc (eg, where a desired entity was
2888 /// declared or defined). Determine whether the right way to make MLoc
2889 /// reachable is by #include, and if so, what header should be included.
2890 ///
2891 /// This is not necessarily fast, and might load unexpected module maps, so
2892 /// should only be called by code that intends to produce an error.
2893 ///
2894 /// \param IncLoc The location at which the missing effect was detected.
2895 /// \param MLoc A location within an unimported module at which the desired
2896 /// effect occurred.
2897 /// \return A file that can be #included to provide the desired effect. Null
2898 /// if no such file could be determined or if a #include is not
2899 /// appropriate (eg, if a module should be imported instead).
2901 SourceLocation MLoc);
2902
2903 bool isRecordingPreamble() const {
2904 return PreambleConditionalStack.isRecording();
2905 }
2906
2907 bool hasRecordedPreamble() const {
2908 return PreambleConditionalStack.hasRecordedPreamble();
2909 }
2910
2912 return PreambleConditionalStack.getStack();
2913 }
2914
2916 PreambleConditionalStack.setStack(s);
2917 }
2918
2920 ArrayRef<PPConditionalInfo> s, std::optional<PreambleSkipInfo> SkipInfo) {
2921 PreambleConditionalStack.startReplaying();
2922 PreambleConditionalStack.setStack(s);
2923 PreambleConditionalStack.SkipInfo = SkipInfo;
2924 }
2925
2926 std::optional<PreambleSkipInfo> getPreambleSkipInfo() const {
2927 return PreambleConditionalStack.SkipInfo;
2928 }
2929
2930private:
2931 /// After processing predefined file, initialize the conditional stack from
2932 /// the preamble.
2933 void replayPreambleConditionalStack();
2934
2935 // Macro handling.
2936 void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard);
2937 void HandleUndefDirective();
2938
2939 // Conditional Inclusion.
2940 void HandleIfdefDirective(Token &Result, const Token &HashToken,
2941 bool isIfndef, bool ReadAnyTokensBeforeDirective);
2942 void HandleIfDirective(Token &IfToken, const Token &HashToken,
2943 bool ReadAnyTokensBeforeDirective);
2944 void HandleEndifDirective(Token &EndifToken);
2945 void HandleElseDirective(Token &Result, const Token &HashToken);
2946 void HandleElifFamilyDirective(Token &ElifToken, const Token &HashToken,
2947 tok::PPKeywordKind Kind);
2948
2949 // Pragmas.
2950 void HandlePragmaDirective(PragmaIntroducer Introducer);
2951
2952public:
2953 void HandlePragmaOnce(Token &OnceTok);
2954 void HandlePragmaMark(Token &MarkTok);
2955 void HandlePragmaPoison();
2956 void HandlePragmaSystemHeader(Token &SysHeaderTok);
2957 void HandlePragmaDependency(Token &DependencyTok);
2964
2965 // Return true and store the first token only if any CommentHandler
2966 // has inserted some tokens and getCommentRetentionState() is false.
2967 bool HandleComment(Token &result, SourceRange Comment);
2968
2969 /// A macro is used, update information about macros that need unused
2970 /// warnings.
2971 void markMacroAsUsed(MacroInfo *MI);
2972
2973 void addMacroDeprecationMsg(const IdentifierInfo *II, std::string Msg,
2974 SourceLocation AnnotationLoc) {
2975 AnnotationInfos[II].DeprecationInfo =
2976 MacroAnnotationInfo{AnnotationLoc, std::move(Msg)};
2977 }
2978
2979 void addRestrictExpansionMsg(const IdentifierInfo *II, std::string Msg,
2980 SourceLocation AnnotationLoc) {
2981 AnnotationInfos[II].RestrictExpansionInfo =
2982 MacroAnnotationInfo{AnnotationLoc, std::move(Msg)};
2983 }
2984
2985 void addFinalLoc(const IdentifierInfo *II, SourceLocation AnnotationLoc) {
2986 AnnotationInfos[II].FinalAnnotationLoc = AnnotationLoc;
2987 }
2988
2989 const MacroAnnotations &getMacroAnnotations(const IdentifierInfo *II) const {
2990 return AnnotationInfos.find(II)->second;
2991 }
2992
2993 void emitMacroExpansionWarnings(const Token &Identifier,
2994 bool IsIfnDef = false) const {
2995 IdentifierInfo *Info = Identifier.getIdentifierInfo();
2996 if (Info->isDeprecatedMacro())
2997 emitMacroDeprecationWarning(Identifier);
2998
2999 if (Info->isRestrictExpansion() &&
3000 !SourceMgr.isInMainFile(Identifier.getLocation()))
3001 emitRestrictExpansionWarning(Identifier);
3002
3003 if (!IsIfnDef) {
3004 if (Info->getName() == "INFINITY" && getLangOpts().NoHonorInfs)
3005 emitRestrictInfNaNWarning(Identifier, 0);
3006 if (Info->getName() == "NAN" && getLangOpts().NoHonorNaNs)
3007 emitRestrictInfNaNWarning(Identifier, 1);
3008 }
3009 }
3010
3012 const LangOptions &LangOpts,
3013 const TargetInfo &TI);
3014
3016 const PresumedLoc &PLoc,
3017 const LangOptions &LangOpts,
3018 const TargetInfo &TI);
3019
3020private:
3021 void emitMacroDeprecationWarning(const Token &Identifier) const;
3022 void emitRestrictExpansionWarning(const Token &Identifier) const;
3023 void emitFinalMacroWarning(const Token &Identifier, bool IsUndef) const;
3024 void emitRestrictInfNaNWarning(const Token &Identifier,
3025 unsigned DiagSelection) const;
3026
3027 /// This boolean state keeps track if the current scanned token (by this PP)
3028 /// is in an "-Wunsafe-buffer-usage" opt-out region. Assuming PP scans a
3029 /// translation unit in a linear order.
3030 bool InSafeBufferOptOutRegion = false;
3031
3032 /// Hold the start location of the current "-Wunsafe-buffer-usage" opt-out
3033 /// region if PP is currently in such a region. Hold undefined value
3034 /// otherwise.
3035 SourceLocation CurrentSafeBufferOptOutStart; // It is used to report the start location of an never-closed region.
3036
3037 using SafeBufferOptOutRegionsTy =
3039 // An ordered sequence of "-Wunsafe-buffer-usage" opt-out regions in this
3040 // translation unit. Each region is represented by a pair of start and
3041 // end locations.
3042 SafeBufferOptOutRegionsTy SafeBufferOptOutMap;
3043
3044 // The "-Wunsafe-buffer-usage" opt-out regions in loaded ASTs. We use the
3045 // following structure to manage them by their ASTs.
3046 struct {
3047 // A map from unique IDs to region maps of loaded ASTs. The ID identifies a
3048 // loaded AST. See `SourceManager::getUniqueLoadedASTID`.
3049 llvm::DenseMap<FileID, SafeBufferOptOutRegionsTy> LoadedRegions;
3050
3051 // Returns a reference to the safe buffer opt-out regions of the loaded
3052 // AST where `Loc` belongs to. (Construct if absent)
3053 SafeBufferOptOutRegionsTy &
3054 findAndConsLoadedOptOutMap(SourceLocation Loc, SourceManager &SrcMgr) {
3055 return LoadedRegions[SrcMgr.getUniqueLoadedASTFileID(Loc)];
3056 }
3057
3058 // Returns a reference to the safe buffer opt-out regions of the loaded
3059 // AST where `Loc` belongs to. (This const function returns nullptr if
3060 // absent.)
3061 const SafeBufferOptOutRegionsTy *
3062 lookupLoadedOptOutMap(SourceLocation Loc,
3063 const SourceManager &SrcMgr) const {
3064 FileID FID = SrcMgr.getUniqueLoadedASTFileID(Loc);
3065 auto Iter = LoadedRegions.find(FID);
3066
3067 if (Iter == LoadedRegions.end())
3068 return nullptr;
3069 return &Iter->getSecond();
3070 }
3071 } LoadedSafeBufferOptOutMap;
3072
3073public:
3074 /// \return true iff the given `Loc` is in a "-Wunsafe-buffer-usage" opt-out
3075 /// region. This `Loc` must be a source location that has been pre-processed.
3076 bool isSafeBufferOptOut(const SourceManager&SourceMgr, const SourceLocation &Loc) const;
3077
3078 /// Alter the state of whether this PP currently is in a
3079 /// "-Wunsafe-buffer-usage" opt-out region.
3080 ///
3081 /// \param isEnter true if this PP is entering a region; otherwise, this PP
3082 /// is exiting a region
3083 /// \param Loc the location of the entry or exit of a
3084 /// region
3085 /// \return true iff it is INVALID to enter or exit a region, i.e.,
3086 /// attempt to enter a region before exiting a previous region, or exiting a
3087 /// region that PP is not currently in.
3088 bool enterOrExitSafeBufferOptOutRegion(bool isEnter,
3089 const SourceLocation &Loc);
3090
3091 /// \return true iff this PP is currently in a "-Wunsafe-buffer-usage"
3092 /// opt-out region
3094
3095 /// \param StartLoc output argument. It will be set to the start location of
3096 /// the current "-Wunsafe-buffer-usage" opt-out region iff this function
3097 /// returns true.
3098 /// \return true iff this PP is currently in a "-Wunsafe-buffer-usage"
3099 /// opt-out region
3100 bool isPPInSafeBufferOptOutRegion(SourceLocation &StartLoc);
3101
3102 /// \return a sequence of SourceLocations representing ordered opt-out regions
3103 /// specified by
3104 /// `\#pragma clang unsafe_buffer_usage begin/end`s of this translation unit.
3105 SmallVector<SourceLocation, 64> serializeSafeBufferOptOutMap() const;
3106
3107 /// \param SrcLocSeqs a sequence of SourceLocations deserialized from a
3108 /// record of code `PP_UNSAFE_BUFFER_USAGE`.
3109 /// \return true iff the `Preprocessor` has been updated; false `Preprocessor`
3110 /// is same as itself before the call.
3112 const SmallVectorImpl<SourceLocation> &SrcLocSeqs);
3113
3114 /// Whether we've seen pp-directives which may have changed the preprocessing
3115 /// state.
3116 bool hasSeenNoTrivialPPDirective() const;
3117
3118private:
3119 /// Helper functions to forward lexing to the actual lexer. They all share the
3120 /// same signature.
3121 static bool CLK_Lexer(Preprocessor &P, Token &Result) {
3122 return P.CurLexer->Lex(Result);
3123 }
3124 static bool CLK_TokenLexer(Preprocessor &P, Token &Result) {
3125 return P.CurTokenLexer->Lex(Result);
3126 }
3127 static bool CLK_CachingLexer(Preprocessor &P, Token &Result) {
3128 P.CachingLex(Result);
3129 return true;
3130 }
3131 static bool CLK_DependencyDirectivesLexer(Preprocessor &P, Token &Result) {
3132 return P.CurLexer->LexDependencyDirectiveToken(Result);
3133 }
3134 static bool CLK_LexAfterModuleImport(Preprocessor &P, Token &Result) {
3135 return P.LexAfterModuleImport(Result);
3136 }
3137};
3138
3139/// Abstract base class that describes a handler that will receive
3140/// source ranges for each of the comments encountered in the source file.
3142public:
3144
3145 // The handler shall return true if it has pushed any tokens
3146 // to be read using e.g. EnterToken or EnterTokenStream.
3147 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
3148};
3149
3150/// Abstract base class that describes a handler that will receive
3151/// source ranges for empty lines encountered in the source file.
3153public:
3155
3156 // The handler handles empty lines.
3157 virtual void HandleEmptyline(SourceRange Range) = 0;
3158};
3159
3160/// Helper class to shuttle information about #embed directives from the
3161/// preprocessor to the parser through an annotation token.
3163 StringRef BinaryData;
3164 StringRef FileName;
3165};
3166
3167/// Registry of pragma handlers added by plugins
3168using PragmaHandlerRegistry = llvm::Registry<PragmaHandler>;
3169
3170} // namespace clang
3171
3172namespace llvm {
3173extern template class CLANG_TEMPLATE_ABI Registry<clang::PragmaHandler>;
3174} // namespace llvm
3175
3176#endif // LLVM_CLANG_LEX_PREPROCESSOR_H
#define V(N, I)
Defines the Diagnostic-related interfaces.
Defines the Diagnostic IDs-related interfaces.
Token Tok
The Token.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
#define SM(sm)
Defines the PPCallbacks interface.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the clang::TokenKind enum and support functions.
VerifyDiagnosticConsumer::Directive Directive
__device__ __2f16 float __ockl_bool s
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:235
Callback handler that receives notifications when performing code completion within the preprocessor.
Abstract base class that describes a handler that will receive source ranges for each of the comments...
virtual bool HandleComment(Preprocessor &PP, SourceRange Comment)=0
A directive for a defined macro or a macro imported from a module.
Definition MacroInfo.h:432
Functor that returns the dependency directives for a given file.
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
void setSuppressAllDiagnostics(bool Val)
Suppress all diagnostics, to silence the front end when we know that we don't want any more diagnosti...
Definition Diagnostic.h:730
A reference to a DirectoryEntry that includes the name of the directory as it was accessed by the Fil...
Cached information about one directory (either on disk or in the virtual file system).
Abstract base class that describes a handler that will receive source ranges for empty lines encounte...
virtual void HandleEmptyline(SourceRange Range)=0
Abstract interface for external sources of preprocessor information.
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:302
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:53
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
One of these records is kept for each identifier that is lexed.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
bool hasMacroDefinition() const
Return true if this identifier is #defined to some other value.
bool isDeprecatedMacro() const
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
StringRef getName() const
Return the actual identifier string.
bool isRestrictExpansion() const
A simple pair of identifier info and location.
Implements an efficient mapping from strings to IdentifierInfo nodes.
FPEvalMethodKind
Possible float expression evaluation method choices.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1056
static bool isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin=nullptr)
Returns true if the given MacroID location points at the first token of the macro expansion.
Definition Lexer.cpp:870
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition Lexer.h:399
static bool isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd=nullptr)
Returns true if the given MacroID location points at the last token of the macro expansion.
Definition Lexer.cpp:892
static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid=nullptr)
getSpelling - This method is used to get the spelling of a token into a preallocated buffer,...
Definition Lexer.cpp:451
static bool getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, const LangOptions &LangOpts, bool IgnoreWhiteSpace=false)
Relex the token at the specified location.
Definition Lexer.cpp:509
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:848
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition MacroArgs.h:30
A description of the current definition of a macro.
Definition MacroInfo.h:590
const DefMacroDirective * getDirective() const
Definition MacroInfo.h:375
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition MacroInfo.h:313
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition MacroInfo.h:125
Abstract interface for a module loader.
Represents a macro directive exported by a module.
Definition MacroInfo.h:514
A header that is known to reside within a given module, whether it was included or excluded.
Definition ModuleMap.h:158
Describes a module or submodule.
Definition Module.h:144
bool isModuleMapModule() const
Definition Module.h:251
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
PragmaHandler - Instances of this interface defined to handle the various pragmas that the language f...
Definition Pragma.h:65
PragmaNamespace - This PragmaHandler subdivides the namespace of pragmas, allowing hierarchical pragm...
Definition Pragma.h:96
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
SourceLocation getLastFPEvalPragmaLocation() const
bool isMacroDefined(const IdentifierInfo *II)
MacroDirective * getLocalMacroDirective(const IdentifierInfo *II) const
Given an identifier, return its latest non-imported MacroDirective if it is #define'd and not #undef'...
bool markIncluded(FileEntryRef File)
Mark the file as included.
void HandlePragmaPushMacro(Token &Tok)
Handle #pragma push_macro.
Definition Pragma.cpp:633
void FinalizeForModelFile()
Cleanup after model file parsing.
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
void HandlePragmaPoison()
HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
Definition Pragma.cpp:438
void setCodeCompletionHandler(CodeCompletionHandler &Handler)
Set the code completion handler to the given object.
void dumpMacroInfo(const IdentifierInfo *II)
void HandlePragmaSystemHeader(Token &SysHeaderTok)
HandlePragmaSystemHeader - Implement #pragma GCC system_header.
Definition Pragma.cpp:480
bool creatingPCHWithThroughHeader()
True if creating a PCH with a through header.
void DumpToken(const Token &Tok, bool DumpFlags=false) const
Print the token to stderr, used for debugging.
void MaybeHandlePoisonedIdentifier(Token &Identifier)
ModuleMacro * addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides, bool &IsNew)
Register an exported macro for a module and identifier.
void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, MacroDirective *MD)
Set a MacroDirective that was loaded from a PCH file.
MacroDefinition getMacroDefinitionAtLoc(const IdentifierInfo *II, SourceLocation Loc)
void markClangModuleAsAffecting(Module *M)
Mark the given clang module as affecting the current clang module or translation unit.
void setPragmaARCCFCodeAuditedInfo(IdentifierInfo *Ident, SourceLocation Loc)
Set the location of the currently-active #pragma clang arc_cf_code_audited begin.
void HandlePragmaModuleBuild(Token &Tok)
Definition Pragma.cpp:810
void InitializeForModelFile()
Initialize the preprocessor to parse a model file.
OptionalFileEntryRef LookupEmbedFile(StringRef Filename, bool isAngled, bool OpenFile, const FileEntry *LookupFromFile=nullptr)
Given a "Filename" or <Filename> reference, look up the indicated embed resource.
SourceLocation getCodeCompletionLoc() const
Returns the location of the code-completion point.
ArrayRef< ModuleMacro * > getLeafModuleMacros(const IdentifierInfo *II) const
Get the list of leaf (non-overridden) module macros for a name.
void CollectPpImportSuffix(SmallVectorImpl< Token > &Toks)
Collect the tokens of a C++20 pp-import-suffix.
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
void IgnorePragmas()
Install empty handlers for all pragmas (making them ignored).
Definition Pragma.cpp:2216
DefMacroDirective * appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI)
PPCallbacks * getPPCallbacks() const
bool isInNamedInterfaceUnit() const
If we are proprocessing a named interface unit.
ArrayRef< PPConditionalInfo > getPreambleConditionalStack() const
void setPreambleRecordedPragmaAssumeNonNullLoc(SourceLocation Loc)
Record the location of the unterminated #pragma clang assume_nonnull begin in the preamble.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
ArrayRef< BuildingSubmoduleInfo > getBuildingSubmodules() const
Get the list of submodules that we're currently building.
SourceLocation getCodeCompletionFileLoc() const
Returns the start location of the file of code-completion point.
DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const
SourceRange getCodeCompletionTokenRange() const
SourceLocation getModuleImportLoc(Module *M) const
void overrideMaxTokens(unsigned Value, SourceLocation Loc)
void setCodeCompletionTokenRange(const SourceLocation Start, const SourceLocation End)
Set the code completion token range for detecting replacement range later on.
bool isRecordingPreamble() const
void HandleSkippedDirectiveWhileUsingPCH(Token &Result, SourceLocation HashLoc)
Process directives while skipping until the through header or pragma hdrstop is found.
void setRecordedPreambleConditionalStack(ArrayRef< PPConditionalInfo > s)
void enableIncrementalProcessing(bool value=true)
Enables the incremental processing.
bool LexAfterModuleImport(Token &Result)
Lex a token following the 'import' contextual keyword.
void TypoCorrectToken(const Token &Tok)
Update the current token to represent the provided identifier, in order to cache an action performed ...
bool GetSuppressIncludeNotFoundError()
bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M)
Determine whether II is defined as a macro within the module M, if that is a module that we've alread...
void setPragmaAssumeNonNullLoc(SourceLocation Loc)
Set the location of the currently-active #pragma clang assume_nonnull begin.
bool isInPrimaryFile() const
Return true if we're in the top-level file, not in a #include.
macro_iterator macro_begin(bool IncludeExternalMacros=true) const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
void markMacroAsUsed(MacroInfo *MI)
A macro is used, update information about macros that need unused warnings.
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
void EnterSubmodule(Module *M, SourceLocation ImportLoc, bool ForPragma)
bool isSafeBufferOptOut(const SourceManager &SourceMgr, const SourceLocation &Loc) const
void addMacroDeprecationMsg(const IdentifierInfo *II, std::string Msg, SourceLocation AnnotationLoc)
const char * getCheckPoint(FileID FID, const char *Start) const
Returns a pointer into the given file's buffer that's guaranteed to be between tokens.
void addRestrictExpansionMsg(const IdentifierInfo *II, std::string Msg, SourceLocation AnnotationLoc)
IdentifierInfo * LookUpIdentifierInfo(Token &Identifier) const
Given a tok::raw_identifier token, look up the identifier information for the token and install it in...
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
void setPreprocessedOutput(bool IsPreprocessedOutput)
Sets whether the preprocessor is responsible for producing output or if it is producing tokens to be ...
void addFinalLoc(const IdentifierInfo *II, SourceLocation AnnotationLoc)
bool IsPreviousCachedToken(const Token &Tok) const
Whether Tok is the most recent token (CachedLexPos - 1) in CachedTokens.
bool SawDateOrTime() const
Returns true if the preprocessor has seen a use of DATE or TIME in the file so far.
const TargetInfo * getAuxTargetInfo() const
void CommitBacktrackedTokens()
Disable the last EnableBacktrackAtThisPos call.
Definition PPCaching.cpp:56
friend class MacroArgs
void DumpMacro(const MacroInfo &MI) const
bool HandleEndOfTokenLexer(Token &Result)
Callback invoked when the current TokenLexer hits the end of its token stream.
void setDiagnostics(DiagnosticsEngine &D)
IncludedFilesSet & getIncludedFiles()
Get the set of included files.
void setCodeCompletionReached()
Note that we hit the code-completion point.
bool SetCodeCompletionPoint(FileEntryRef File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
void AnnotateCachedTokens(const Token &Tok)
We notify the Preprocessor that if it is caching tokens (because backtrack is enabled) it should repl...
bool isPreprocessedOutput() const
Returns true if the preprocessor is responsible for generating output, false if it is producing token...
StringRef getNamedModuleName() const
Get the named module name we're preprocessing.
bool mightHavePendingAnnotationTokens()
Determine whether it's possible for a future call to Lex to produce an annotation token created by a ...
bool isInImportingCXXNamedModules() const
If we're importing a standard C++20 Named Modules.
void Lex(Token &Result)
Lex the next token for this preprocessor.
void EnterTokenStream(ArrayRef< Token > Toks, bool DisableMacroExpansion, bool IsReinject)
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
bool EnterSourceFile(FileID FID, ConstSearchDirIterator Dir, SourceLocation Loc, bool IsFirstIncludeOfFile=true)
Add a source file to the top of the include stack and start lexing tokens from it instead of the curr...
bool isParsingIfOrElifDirective() const
True if we are currently preprocessing a if or elif directive.
unsigned getNumDirectives() const
Retrieve the number of Directives that have been processed by the Preprocessor.
bool isInImplementationUnit() const
If we are implementing an implementation module unit.
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with this preprocessor.
void LexNonComment(Token &Result)
Lex a token.
void removeCommentHandler(CommentHandler *Handler)
Remove the specified comment handler.
PreprocessorLexer * getCurrentLexer() const
Return the current lexer being lexed from.
SourceRange DiscardUntilEndOfDirective()
Read and discard all tokens remaining on the current line until the tok::eod token is found.
bool LexOnOffSwitch(tok::OnOffSwitch &Result)
Lex an on-off-switch (C99 6.10.6p2) and verify that it is followed by EOD.
Definition Pragma.cpp:971
StringRef getCodeCompletionFilter()
Get the code completion token for filtering purposes.
void setMainFileDir(DirectoryEntryRef Dir)
Set the directory in which the main file should be considered to have been found, if it is not a real...
const IdentifierTable & getIdentifierTable() const
void HandlePragmaDependency(Token &DependencyTok)
HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
Definition Pragma.cpp:512
SourceLocation CheckEndOfDirective(const char *DirType, bool EnableMacros=false)
Ensure that the next token is a tok::eod token.
void HandlePoisonedIdentifier(Token &Identifier)
Display reason for poisoned identifier.
friend class ASTReader
void Backtrack()
Make Preprocessor re-lex the tokens that were lexed since EnableBacktrackAtThisPos() was previously c...
Definition PPCaching.cpp:66
bool isCurrentLexer(const PreprocessorLexer *L) const
Return true if we are lexing directly from the specified lexer.
bool HandleIdentifier(Token &Identifier)
Callback invoked when the lexer reads an identifier and has filled in the tokens IdentifierInfo membe...
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
bool enterOrExitSafeBufferOptOutRegion(bool isEnter, const SourceLocation &Loc)
Alter the state of whether this PP currently is in a "-Wunsafe-buffer-usage" opt-out region.
void IncrementPasteCounter(bool isFast)
Increment the counters for the number of token paste operations performed.
IdentifierLoc getPragmaARCCFCodeAuditedInfo() const
The location of the currently-active #pragma clang arc_cf_code_audited begin.
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc.
void setReplayablePreambleConditionalStack(ArrayRef< PPConditionalInfo > s, std::optional< PreambleSkipInfo > SkipInfo)
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
friend class VAOptDefinitionContext
const MacroAnnotations & getMacroAnnotations(const IdentifierInfo *II) const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
uint8_t getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the value of constant as an unsign...
macro_iterator macro_end(bool IncludeExternalMacros=true) const
SourceManager & getSourceManager() const
bool isBacktrackEnabled() const
True if EnableBacktrackAtThisPos() was called and caching of tokens is on.
MacroDefinition getMacroDefinition(const IdentifierInfo *II)
bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag=nullptr)
std::optional< PreambleSkipInfo > getPreambleSkipInfo() const
void setPreprocessToken(bool Preprocess)
void SetPoisonReason(IdentifierInfo *II, unsigned DiagID)
Specifies the reason for poisoning an identifier.
void HandlePragmaOnce(Token &OnceTok)
HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
Definition Pragma.cpp:413
EmptylineHandler * getEmptylineHandler() const
bool getCommentRetentionState() const
bool isMacroDefined(StringRef Id)
static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, const Module &M, DiagnosticsEngine &Diags)
Check that the given module is available, producing a diagnostic if not.
Module * getCurrentModuleImplementation()
Retrieves the module whose implementation we're current compiling, if any.
void SetMacroExpansionOnlyInDirectives()
Disables macro expansion everywhere except for preprocessor directives.
bool hasRecordedPreamble() const
SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Char) const
Given a location that specifies the start of a token, return a new location that specifies a characte...
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
bool isNextPPTokenOneOf(Ts... Ks)
Check whether the next pp-token is one of the specificed token kind.
MacroMap::const_iterator macro_iterator
void createPreprocessingRecord()
Create a new preprocessing record, which will keep track of all macro expansions, macro definitions,...
SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length)
Split the first Length characters out of the token starting at TokLoc and return a location pointing ...
bool isUnannotatedBacktrackEnabled() const
True if EnableBacktrackAtThisPos() was called and caching of unannotated tokens is on.
void EnterTokenStream(std::unique_ptr< Token[]> Toks, unsigned NumToks, bool DisableMacroExpansion, bool IsReinject)
void RevertCachedTokens(unsigned N)
When backtracking is enabled and tokens are cached, this allows to revert a specific number of tokens...
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
FileID getPCHPredefinesFileID() const
Returns the FileID for the predefines loaded from the PCH.
std::optional< std::uint64_t > getStdLibCxxVersion()
void RemovePragmaHandler(PragmaHandler *Handler)
unsigned getTokenCount() const
Get the number of tokens processed so far.
unsigned getMaxTokens() const
Get the max number of tokens before issuing a -Wmax-tokens warning.
SourceLocation getMaxTokensOverrideLoc() const
void makeModuleVisible(Module *M, SourceLocation Loc, bool IncludeExports=true)
bool hadModuleLoaderFatalFailure() const
static void processPathToFileName(SmallVectorImpl< char > &FileName, const PresumedLoc &PLoc, const LangOptions &LangOpts, const TargetInfo &TI)
void setCurrentFPEvalMethod(SourceLocation PragmaLoc, LangOptions::FPEvalMethodKind Val)
const TargetInfo & getTargetInfo() const
FileManager & getFileManager() const
bool LexHeaderName(Token &Result, bool AllowMacroExpansion=true)
Lex a token, forming a header-name token if possible.
std::string getSpelling(const Token &Tok, bool *Invalid=nullptr) const
Return the 'spelling' of the Tok token.
bool isPCHThroughHeader(const FileEntry *FE)
Returns true if the FileEntry is the PCH through header.
void DumpLocation(SourceLocation Loc) const
friend class VariadicMacroScopeGuard
Module * getCurrentLexerSubmodule() const
Return the submodule owning the file being lexed.
bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value)
Parses a simple integer literal to get its numeric value.
MacroInfo * AllocateMacroInfo(SourceLocation L)
Allocate a new MacroInfo object with the provided SourceLocation.
void setDependencyDirectivesGetter(DependencyDirectivesGetter &Get)
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool creatingPCHWithPragmaHdrStop()
True if creating a PCH with a pragma hdrstop.
bool alreadyIncluded(FileEntryRef File) const
Return true if this header has already been included.
llvm::iterator_range< macro_iterator > macros(bool IncludeExternalMacros=true) const
void Initialize(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize the preprocessor using information about the target.
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
void LexUnexpandedNonComment(Token &Result)
Like LexNonComment, but this disables macro expansion of identifier tokens.
void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler)
Add the specified pragma handler to this preprocessor.
Definition Pragma.cpp:918
llvm::BumpPtrAllocator & getPreprocessorAllocator()
ModuleMacro * getModuleMacro(Module *Mod, const IdentifierInfo *II)
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool HandleComment(Token &result, SourceRange Comment)
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
bool GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer)
Turn the specified lexer token into a fully checked and spelled filename, e.g.
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
HeaderSearch & getHeaderSearchInfo() const
void emitMacroExpansionWarnings(const Token &Identifier, bool IsIfnDef=false) const
bool setDeserializedSafeBufferOptOutMap(const SmallVectorImpl< SourceLocation > &SrcLocSeqs)
void HandlePragmaPopMacro(Token &Tok)
Handle #pragma pop_macro.
Definition Pragma.cpp:656
void ReplaceLastTokenWithAnnotation(const Token &Tok)
Replace the last token with an annotation token.
ExternalPreprocessorSource * getExternalSource() const
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
Module * LeaveSubmodule(bool ForPragma)
const std::string & getPredefines() const
Get the predefines for this processor.
void HandleDirective(Token &Result)
Callback invoked when the lexer sees a # token at the start of a line.
SmallVector< SourceLocation, 64 > serializeSafeBufferOptOutMap() const
CodeCompletionHandler * getCodeCompletionHandler() const
Retrieve the current code-completion handler.
void recomputeCurLexerKind()
Recompute the current lexer kind based on the CurLexer/ CurTokenLexer pointers.
void EnterAnnotationToken(SourceRange Range, tok::TokenKind Kind, void *AnnotationVal)
Enter an annotation token into the token stream.
void setTokenWatcher(llvm::unique_function< void(const clang::Token &)> F)
Register a function that would be called on each token in the final expanded token stream.
MacroInfo * getMacroInfo(const IdentifierInfo *II)
void setPredefines(std::string P)
Set the predefines for this Preprocessor.
OptionalFileEntryRef LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, ConstSearchDirIterator FromDir, const FileEntry *FromFile, ConstSearchDirIterator *CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool OpenFile=true, bool CacheFailures=true)
Given a "foo" or <foo> reference, look up the indicated file.
IdentifierTable & getIdentifierTable()
Builtin::Context & getBuiltinInfo()
void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine)
Instruct the preprocessor to skip part of the main source file.
const PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
void ReplacePreviousCachedToken(ArrayRef< Token > NewToks)
Replace token in CachedLexPos - 1 in CachedTokens by the tokens in NewToks.
LangOptions::FPEvalMethodKind getTUFPEvalMethod() const
const LangOptions & getLangOpts() const
void setTUFPEvalMethod(LangOptions::FPEvalMethodKind Val)
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled)
Hook used by the lexer to invoke the "included file" code completion point.
void SetSuppressIncludeNotFoundError(bool Suppress)
static void processPathForFileMacro(SmallVectorImpl< char > &Path, const LangOptions &LangOpts, const TargetInfo &TI)
llvm::DenseMap< FileID, SafeBufferOptOutRegionsTy > LoadedRegions
bool isInNamedModule() const
If we are preprocessing a named module.
void EnableBacktrackAtThisPos(bool Unannotated=false)
From the point that this method is called, and until CommitBacktrackedTokens() or Backtrack() is call...
Definition PPCaching.cpp:34
void RemoveTopOfLexerStack()
Pop the current lexer/macro exp off the top of the lexer stack.
void PoisonSEHIdentifiers(bool Poison=true)
bool isAtStartOfMacroExpansion(SourceLocation loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the first token of the macro expansion.
size_t getTotalMemory() const
void setCounterValue(uint32_t V)
void setExternalSource(ExternalPreprocessorSource *Source)
void clearCodeCompletionHandler()
Clear out the code completion handler.
void AddPragmaHandler(PragmaHandler *Handler)
OptionalFileEntryRef getHeaderToIncludeForDiagnostics(SourceLocation IncLoc, SourceLocation MLoc)
We want to produce a diagnostic at location IncLoc concerning an unreachable effect at location MLoc ...
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
IdentifierInfo * ParsePragmaPushOrPopMacro(Token &Tok)
ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Definition Pragma.cpp:568
void LexTokensUntilEOF(std::vector< Token > *Tokens=nullptr)
Lex all tokens for this preprocessor until (and excluding) end of file.
bool getRawToken(SourceLocation Loc, Token &Result, bool IgnoreWhiteSpace=false)
Relex the token at the specified location.
bool usingPCHWithPragmaHdrStop()
True if using a PCH with a pragma hdrstop.
void CodeCompleteNaturalLanguage()
Hook used by the lexer to invoke the "natural language" code completion point.
void EndSourceFile()
Inform the preprocessor callbacks that processing is complete.
bool HandleEndOfFile(Token &Result, bool isEndOfMacro=false)
Callback invoked when the lexer hits the end of the current file.
void setPragmasEnabled(bool Enabled)
DefMacroDirective * appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI, SourceLocation Loc)
void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments)
Control whether the preprocessor retains comments in output.
bool isAtEndOfMacroExpansion(SourceLocation loc, SourceLocation *MacroEnd=nullptr) const
Returns true if the given MacroID location points at the last token of the macro expansion.
SourceLocation getMainFileFirstPPTokenLoc() const
Get the start location of the first pp-token in main file.
void HandlePragmaMark(Token &MarkTok)
Definition Pragma.cpp:428
bool getPragmasEnabled() const
void HandlePragmaHdrstop(Token &Tok)
Definition Pragma.cpp:884
PreprocessingRecord * getPreprocessingRecord() const
Retrieve the preprocessing record, or NULL if there is no preprocessing record.
void setEmptylineHandler(EmptylineHandler *Handler)
Set empty line handler.
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLastCachedTokenLocation() const
Get the location of the last cached token, suitable for setting the end location of an annotation tok...
bool hasSeenNoTrivialPPDirective() const
Whether we've seen pp-directives which may have changed the preprocessing state.
llvm::DenseSet< const FileEntry * > IncludedFilesSet
unsigned getSpelling(const Token &Tok, const char *&Buffer, bool *Invalid=nullptr) const
Get the spelling of a token into a preallocated buffer, instead of as an std::string.
SelectorTable & getSelectorTable()
void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler)
Remove the specific pragma handler from this preprocessor.
Definition Pragma.cpp:949
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
const llvm::SmallSetVector< Module *, 2 > & getAffectingClangModules() const
Get the set of top-level clang modules that affected preprocessing, but were not imported.
std::optional< LexEmbedParametersResult > LexEmbedParameters(Token &Current, bool ForHasEmbed)
Lex the parameters for an embed directive, returns nullopt on error.
const IncludedFilesSet & getIncludedFiles() const
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
void HandlePragmaIncludeAlias(Token &Tok)
Definition Pragma.cpp:691
Module * getModuleForLocation(SourceLocation Loc, bool AllowTextual)
Find the module that owns the source or header file that Loc points to.
uint32_t getCounterValue() const
void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter)
Set the code completion token for filtering purposes.
SourceLocation getPreambleRecordedPragmaAssumeNonNullLoc() const
Get the location of the recorded unterminated #pragma clang assume_nonnull begin in the preamble,...
void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args)
Add a Macro to the top of the include stack and start lexing tokens from it instead of the current bu...
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
void SkipTokensWhileUsingPCH()
Skip tokens until after the include of the through header or until after a pragma hdrstop.
bool usingPCHWithThroughHeader()
True if using a PCH with a through header.
bool LexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Lex a string literal, which may be the concatenation of multiple string literals and may even come fr...
void HandleMicrosoftCommentPaste(Token &Tok)
When the macro expander pastes together a comment (/##/) in Microsoft mode, this method handles updat...
Preprocessor(const PreprocessorOptions &PPOpts, DiagnosticsEngine &diags, const LangOptions &LangOpts, SourceManager &SM, HeaderSearch &Headers, ModuleLoader &TheModuleLoader, IdentifierInfoLookup *IILookup=nullptr, bool OwnsHeaderSearch=false, TranslationUnitKind TUKind=TU_Complete)
void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD)
Add a directive to the macro directive history for this identifier.
Represents an unpacked "presumed" location which can be presented to the user.
ScratchBuffer - This class exposes a simple interface for the dynamic construction of tokens.
This table allows us to fully hide how we implement multi-keyword caching.
Encodes a location in the source.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Exposes information about the current target.
Definition TargetInfo.h:226
TokenValue(IdentifierInfo *II)
TokenValue(tok::TokenKind Kind)
bool operator==(const Token &Tok) const
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:195
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:140
#define bool
Definition gpuintrin.h:32
Public enums and private classes that are part of the SourceManager implementation.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
OnOffSwitch
Defines the possible values of an on-off-switch (C99 6.10.6p2).
Definition TokenKinds.h:56
bool isLiteral(TokenKind K)
Return true if this is a "literal" kind, like a numeric constant, string, etc.
Definition TokenKinds.h:97
PPKeywordKind
Provides a namespace for preprocessor keywords which start with a '#' at the beginning of the line.
Definition TokenKinds.h:33
bool isAnnotation(TokenKind K)
Return true if this is any of tok::annot_* kinds.
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
llvm::Registry< PragmaHandler > PragmaHandlerRegistry
Registry of pragma handlers added by plugins.
@ Conditional
A conditional (?:) operator.
Definition Sema.h:668
detail::SearchDirIteratorImpl< true > ConstSearchDirIterator
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
MacroUse
Context in which macro name is used.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
@ Result
The result type of a method or function.
Definition TypeBase.h:905
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Complete
The translation unit is a complete translation unit.
CustomizableOptional< DirectoryEntryRef > OptionalDirectoryEntryRef
U cast(CodeGen::Address addr)
Definition Address.h:327
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
Helper class to shuttle information about embed directives from the preprocessor to the parser throug...
Describes how and where the pragma was introduced.
Definition Pragma.h:51
PreambleSkipInfo(SourceLocation HashTokenLoc, SourceLocation IfTokenLoc, bool FoundNonSkipPortion, bool FoundElse, SourceLocation ElseLoc)