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 /// Whether tokens are being skipped until a #pragma hdrstop is seen.
1123 bool SkippingUntilPragmaHdrStop = false;
1124
1125 /// Whether tokens are being skipped until the through header is seen.
1126 bool SkippingUntilPCHThroughHeader = false;
1127
1128 /// \{
1129 /// Cache of macro expanders to reduce malloc traffic.
1130 enum { TokenLexerCacheSize = 8 };
1131 unsigned NumCachedTokenLexers;
1132 std::unique_ptr<TokenLexer> TokenLexerCache[TokenLexerCacheSize];
1133 /// \}
1134
1135 /// Keeps macro expanded tokens for TokenLexers.
1136 //
1137 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1138 /// going to lex in the cache and when it finishes the tokens are removed
1139 /// from the end of the cache.
1140 SmallVector<Token, 16> MacroExpandedTokens;
1141 std::vector<std::pair<TokenLexer *, size_t>> MacroExpandingLexersStack;
1142
1143 /// A record of the macro definitions and expansions that
1144 /// occurred during preprocessing.
1145 ///
1146 /// This is an optional side structure that can be enabled with
1147 /// \c createPreprocessingRecord() prior to preprocessing.
1148 PreprocessingRecord *Record = nullptr;
1149
1150 /// Cached tokens state.
1151 using CachedTokensTy = SmallVector<Token, 1>;
1152
1153 /// Cached tokens are stored here when we do backtracking or
1154 /// lookahead. They are "lexed" by the CachingLex() method.
1155 CachedTokensTy CachedTokens;
1156
1157 /// The position of the cached token that CachingLex() should
1158 /// "lex" next.
1159 ///
1160 /// If it points beyond the CachedTokens vector, it means that a normal
1161 /// Lex() should be invoked.
1162 CachedTokensTy::size_type CachedLexPos = 0;
1163
1164 /// Stack of backtrack positions, allowing nested backtracks.
1165 ///
1166 /// The EnableBacktrackAtThisPos() method pushes a position to
1167 /// indicate where CachedLexPos should be set when the BackTrack() method is
1168 /// invoked (at which point the last position is popped).
1169 std::vector<CachedTokensTy::size_type> BacktrackPositions;
1170
1171 /// Stack of cached tokens/initial number of cached tokens pairs, allowing
1172 /// nested unannotated backtracks.
1173 std::vector<std::pair<CachedTokensTy, CachedTokensTy::size_type>>
1174 UnannotatedBacktrackTokens;
1175
1176 /// True if \p Preprocessor::SkipExcludedConditionalBlock() is running.
1177 /// This is used to guard against calling this function recursively.
1178 ///
1179 /// See comments at the use-site for more context about why it is needed.
1180 bool SkippingExcludedConditionalBlock = false;
1181
1182 /// Keeps track of skipped range mappings that were recorded while skipping
1183 /// excluded conditional directives. It maps the source buffer pointer at
1184 /// the beginning of a skipped block, to the number of bytes that should be
1185 /// skipped.
1186 llvm::DenseMap<const char *, unsigned> RecordedSkippedRanges;
1187
1188 void updateOutOfDateIdentifier(const IdentifierInfo &II) const;
1189
1190public:
1191 Preprocessor(const PreprocessorOptions &PPOpts, DiagnosticsEngine &diags,
1192 const LangOptions &LangOpts, SourceManager &SM,
1193 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
1194 IdentifierInfoLookup *IILookup = nullptr,
1195 bool OwnsHeaderSearch = false,
1197
1198 ~Preprocessor();
1199
1200 /// Initialize the preprocessor using information about the target.
1201 ///
1202 /// \param Target is owned by the caller and must remain valid for the
1203 /// lifetime of the preprocessor.
1204 /// \param AuxTarget is owned by the caller and must remain valid for
1205 /// the lifetime of the preprocessor.
1206 void Initialize(const TargetInfo &Target,
1207 const TargetInfo *AuxTarget = nullptr);
1208
1209 /// Initialize the preprocessor to parse a model file
1210 ///
1211 /// To parse model files the preprocessor of the original source is reused to
1212 /// preserver the identifier table. However to avoid some duplicate
1213 /// information in the preprocessor some cleanup is needed before it is used
1214 /// to parse model files. This method does that cleanup.
1216
1217 /// Cleanup after model file parsing
1218 void FinalizeForModelFile();
1219
1220 /// Retrieve the preprocessor options used to initialize this preprocessor.
1221 const PreprocessorOptions &getPreprocessorOpts() const { return PPOpts; }
1222
1223 DiagnosticsEngine &getDiagnostics() const { return *Diags; }
1224 void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; }
1225
1226 const LangOptions &getLangOpts() const { return LangOpts; }
1227 const TargetInfo &getTargetInfo() const { return *Target; }
1228 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
1229 FileManager &getFileManager() const { return FileMgr; }
1230 SourceManager &getSourceManager() const { return SourceMgr; }
1231 HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
1232
1233 IdentifierTable &getIdentifierTable() { return Identifiers; }
1234 const IdentifierTable &getIdentifierTable() const { return Identifiers; }
1235 SelectorTable &getSelectorTable() { return Selectors; }
1236 Builtin::Context &getBuiltinInfo() { return *BuiltinInfo; }
1237 llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
1238
1240 ExternalSource = Source;
1241 }
1242
1244 return ExternalSource;
1245 }
1246
1247 /// Retrieve the module loader associated with this preprocessor.
1248 ModuleLoader &getModuleLoader() const { return TheModuleLoader; }
1249
1251 return TheModuleLoader.HadFatalFailure;
1252 }
1253
1254 /// Retrieve the number of Directives that have been processed by the
1255 /// Preprocessor.
1256 unsigned getNumDirectives() const {
1257 return NumDirectives;
1258 }
1259
1260 /// True if we are currently preprocessing a #if or #elif directive
1262 return ParsingIfOrElifDirective;
1263 }
1264
1265 /// Control whether the preprocessor retains comments in output.
1266 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
1267 this->KeepComments = KeepComments | KeepMacroComments;
1268 this->KeepMacroComments = KeepMacroComments;
1269 }
1270
1271 bool getCommentRetentionState() const { return KeepComments; }
1272
1273 void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; }
1274 bool getPragmasEnabled() const { return PragmasEnabled; }
1275
1277 SuppressIncludeNotFoundError = Suppress;
1278 }
1279
1281 return SuppressIncludeNotFoundError;
1282 }
1283
1284 /// Sets whether the preprocessor is responsible for producing output or if
1285 /// it is producing tokens to be consumed by Parse and Sema.
1286 void setPreprocessedOutput(bool IsPreprocessedOutput) {
1287 PreprocessedOutput = IsPreprocessedOutput;
1288 }
1289
1290 /// Returns true if the preprocessor is responsible for generating output,
1291 /// false if it is producing tokens to be consumed by Parse and Sema.
1292 bool isPreprocessedOutput() const { return PreprocessedOutput; }
1293
1294 /// Return true if we are lexing directly from the specified lexer.
1295 bool isCurrentLexer(const PreprocessorLexer *L) const {
1296 return CurPPLexer == L;
1297 }
1298
1299 /// Return the current lexer being lexed from.
1300 ///
1301 /// Note that this ignores any potentially active macro expansions and _Pragma
1302 /// expansions going on at the time.
1303 PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; }
1304
1305 /// Return the current file lexer being lexed from.
1306 ///
1307 /// Note that this ignores any potentially active macro expansions and _Pragma
1308 /// expansions going on at the time.
1310
1311 /// Return the submodule owning the file being lexed. This may not be
1312 /// the current module if we have changed modules since entering the file.
1313 Module *getCurrentLexerSubmodule() const { return CurLexerSubmodule; }
1314
1315 /// Returns the FileID for the preprocessor predefines.
1316 FileID getPredefinesFileID() const { return PredefinesFileID; }
1317
1318 /// \{
1319 /// Accessors for preprocessor callbacks.
1320 ///
1321 /// Note that this class takes ownership of any PPCallbacks object given to
1322 /// it.
1323 PPCallbacks *getPPCallbacks() const { return Callbacks.get(); }
1324 void addPPCallbacks(std::unique_ptr<PPCallbacks> C) {
1325 if (Callbacks)
1326 C = std::make_unique<PPChainedCallbacks>(std::move(C),
1327 std::move(Callbacks));
1328 Callbacks = std::move(C);
1329 }
1330 void removePPCallbacks() { Callbacks.reset(); }
1331 /// \}
1332
1333 /// Get the number of tokens processed so far.
1334 unsigned getTokenCount() const { return TokenCount; }
1335
1336 /// Get the max number of tokens before issuing a -Wmax-tokens warning.
1337 unsigned getMaxTokens() const { return MaxTokens; }
1338
1340 MaxTokens = Value;
1341 MaxTokensOverrideLoc = Loc;
1342 };
1343
1344 SourceLocation getMaxTokensOverrideLoc() const { return MaxTokensOverrideLoc; }
1345
1346 /// Register a function that would be called on each token in the final
1347 /// expanded token stream.
1348 /// This also reports annotation tokens produced by the parser.
1349 void setTokenWatcher(llvm::unique_function<void(const clang::Token &)> F) {
1350 OnToken = std::move(F);
1351 }
1352
1354 GetDependencyDirectives = &Get;
1355 }
1356
1357 void setPreprocessToken(bool Preprocess) { PreprocessToken = Preprocess; }
1358
1359 bool isMacroDefined(StringRef Id) {
1360 return isMacroDefined(&Identifiers.get(Id));
1361 }
1363 return II->hasMacroDefinition() &&
1364 (!getLangOpts().Modules || (bool)getMacroDefinition(II));
1365 }
1366
1367 /// Determine whether II is defined as a macro within the module M,
1368 /// if that is a module that we've already preprocessed. Does not check for
1369 /// macros imported into M.
1371 if (!II->hasMacroDefinition())
1372 return false;
1373 auto I = Submodules.find(M);
1374 if (I == Submodules.end())
1375 return false;
1376 auto J = I->second.Macros.find(II);
1377 if (J == I->second.Macros.end())
1378 return false;
1379 auto *MD = J->second.getLatest();
1380 return MD && MD->isDefined();
1381 }
1382
1384 if (!II->hasMacroDefinition())
1385 return {};
1386
1387 MacroState &S = CurSubmoduleState->Macros[II];
1388 auto *MD = S.getLatest();
1389 while (isa_and_nonnull<VisibilityMacroDirective>(MD))
1390 MD = MD->getPrevious();
1391 return MacroDefinition(dyn_cast_or_null<DefMacroDirective>(MD),
1392 S.getActiveModuleMacros(*this, II),
1393 S.isAmbiguous(*this, II));
1394 }
1395
1397 SourceLocation Loc) {
1398 if (!II->hadMacroDefinition())
1399 return {};
1400
1401 MacroState &S = CurSubmoduleState->Macros[II];
1403 if (auto *MD = S.getLatest())
1404 DI = MD->findDirectiveAtLoc(Loc, getSourceManager());
1405 // FIXME: Compute the set of active module macros at the specified location.
1406 return MacroDefinition(DI.getDirective(),
1407 S.getActiveModuleMacros(*this, II),
1408 S.isAmbiguous(*this, II));
1409 }
1410
1411 /// Given an identifier, return its latest non-imported MacroDirective
1412 /// if it is \#define'd and not \#undef'd, or null if it isn't \#define'd.
1414 if (!II->hasMacroDefinition())
1415 return nullptr;
1416
1417 auto *MD = getLocalMacroDirectiveHistory(II);
1418 if (!MD || MD->getDefinition().isUndefined())
1419 return nullptr;
1420
1421 return MD;
1422 }
1423
1424 const MacroInfo *getMacroInfo(const IdentifierInfo *II) const {
1425 return const_cast<Preprocessor*>(this)->getMacroInfo(II);
1426 }
1427
1429 if (!II->hasMacroDefinition())
1430 return nullptr;
1431 if (auto MD = getMacroDefinition(II))
1432 return MD.getMacroInfo();
1433 return nullptr;
1434 }
1435
1436 /// Given an identifier, return the latest non-imported macro
1437 /// directive for that identifier.
1438 ///
1439 /// One can iterate over all previous macro directives from the most recent
1440 /// one.
1442
1443 /// Add a directive to the macro directive history for this identifier.
1446 SourceLocation Loc) {
1447 DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc);
1448 appendMacroDirective(II, MD);
1449 return MD;
1450 }
1455
1456 /// Set a MacroDirective that was loaded from a PCH file.
1458 MacroDirective *MD);
1459
1460 /// Register an exported macro for a module and identifier.
1463 ArrayRef<ModuleMacro *> Overrides, bool &IsNew);
1465
1466 /// Get the list of leaf (non-overridden) module macros for a name.
1468 if (II->isOutOfDate())
1469 updateOutOfDateIdentifier(*II);
1470 auto I = LeafModuleMacros.find(II);
1471 if (I != LeafModuleMacros.end())
1472 return I->second;
1473 return {};
1474 }
1475
1476 /// Get the list of submodules that we're currently building.
1478 return BuildingSubmoduleStack;
1479 }
1480
1481 /// \{
1482 /// Iterators for the macro history table. Currently defined macros have
1483 /// IdentifierInfo::hasMacroDefinition() set and an empty
1484 /// MacroInfo::getUndefLoc() at the head of the list.
1485 using macro_iterator = MacroMap::const_iterator;
1486
1487 macro_iterator macro_begin(bool IncludeExternalMacros = true) const;
1488 macro_iterator macro_end(bool IncludeExternalMacros = true) const;
1489
1490 llvm::iterator_range<macro_iterator>
1491 macros(bool IncludeExternalMacros = true) const {
1492 macro_iterator begin = macro_begin(IncludeExternalMacros);
1493 macro_iterator end = macro_end(IncludeExternalMacros);
1494 return llvm::make_range(begin, end);
1495 }
1496
1497 /// \}
1498
1499 /// Mark the given clang module as affecting the current clang module or translation unit.
1501 assert(M->isModuleMapModule());
1502 if (!BuildingSubmoduleStack.empty()) {
1503 if (M != BuildingSubmoduleStack.back().M)
1504 BuildingSubmoduleStack.back().M->AffectingClangModules.insert(M);
1505 } else {
1506 AffectingClangModules.insert(M);
1507 }
1508 }
1509
1510 /// Get the set of top-level clang modules that affected preprocessing, but were not
1511 /// imported.
1513 return AffectingClangModules;
1514 }
1515
1516 /// Mark the file as included.
1517 /// Returns true if this is the first time the file was included.
1519 HeaderInfo.getFileInfo(File).IsLocallyIncluded = true;
1520 return IncludedFiles.insert(File).second;
1521 }
1522
1523 /// Return true if this header has already been included.
1525 HeaderInfo.getFileInfo(File);
1526 return IncludedFiles.count(File);
1527 }
1528
1529 /// Get the set of included files.
1530 IncludedFilesSet &getIncludedFiles() { return IncludedFiles; }
1531 const IncludedFilesSet &getIncludedFiles() const { return IncludedFiles; }
1532
1533 /// Return the name of the macro defined before \p Loc that has
1534 /// spelling \p Tokens. If there are multiple macros with same spelling,
1535 /// return the last one defined.
1537 ArrayRef<TokenValue> Tokens) const;
1538
1539 /// Get the predefines for this processor.
1540 /// Used by some third-party tools to inspect and add predefines (see
1541 /// https://github.com/llvm/llvm-project/issues/57483).
1542 const std::string &getPredefines() const { return Predefines; }
1543
1544 /// Set the predefines for this Preprocessor.
1545 ///
1546 /// These predefines are automatically injected when parsing the main file.
1547 void setPredefines(std::string P) { Predefines = std::move(P); }
1548
1549 /// Return information about the specified preprocessor
1550 /// identifier token.
1551 IdentifierInfo *getIdentifierInfo(StringRef Name) const {
1552 return &Identifiers.get(Name);
1553 }
1554
1555 /// Add the specified pragma handler to this preprocessor.
1556 ///
1557 /// If \p Namespace is non-null, then it is a token required to exist on the
1558 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
1559 void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler);
1561 AddPragmaHandler(StringRef(), Handler);
1562 }
1563
1564 /// Remove the specific pragma handler from this preprocessor.
1565 ///
1566 /// If \p Namespace is non-null, then it should be the namespace that
1567 /// \p Handler was added to. It is an error to remove a handler that
1568 /// has not been registered.
1569 void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler);
1571 RemovePragmaHandler(StringRef(), Handler);
1572 }
1573
1574 /// Install empty handlers for all pragmas (making them ignored).
1575 void IgnorePragmas();
1576
1577 /// Set empty line handler.
1578 void setEmptylineHandler(EmptylineHandler *Handler) { Emptyline = Handler; }
1579
1580 EmptylineHandler *getEmptylineHandler() const { return Emptyline; }
1581
1582 /// Add the specified comment handler to the preprocessor.
1583 void addCommentHandler(CommentHandler *Handler);
1584
1585 /// Remove the specified comment handler.
1586 ///
1587 /// It is an error to remove a handler that has not been registered.
1588 void removeCommentHandler(CommentHandler *Handler);
1589
1590 /// Set the code completion handler to the given object.
1592 CodeComplete = &Handler;
1593 }
1594
1595 /// Retrieve the current code-completion handler.
1597 return CodeComplete;
1598 }
1599
1600 /// Clear out the code completion handler.
1602 CodeComplete = nullptr;
1603 }
1604
1605 /// Hook used by the lexer to invoke the "included file" code
1606 /// completion point.
1607 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
1608
1609 /// Hook used by the lexer to invoke the "natural language" code
1610 /// completion point.
1612
1613 /// Set the code completion token for filtering purposes.
1615 CodeCompletionII = Filter;
1616 }
1617
1618 /// Set the code completion token range for detecting replacement range later
1619 /// on.
1621 const SourceLocation End) {
1622 CodeCompletionTokenRange = {Start, End};
1623 }
1625 return CodeCompletionTokenRange;
1626 }
1627
1628 /// Get the code completion token for filtering purposes.
1630 if (CodeCompletionII)
1631 return CodeCompletionII->getName();
1632 return {};
1633 }
1634
1635 /// Retrieve the preprocessing record, or NULL if there is no
1636 /// preprocessing record.
1638
1639 /// Create a new preprocessing record, which will keep track of
1640 /// all macro expansions, macro definitions, etc.
1642
1643 /// Returns true if the FileEntry is the PCH through header.
1644 bool isPCHThroughHeader(const FileEntry *FE);
1645
1646 /// True if creating a PCH with a through header.
1648
1649 /// True if using a PCH with a through header.
1651
1652 /// True if creating a PCH with a #pragma hdrstop.
1654
1655 /// True if using a PCH with a #pragma hdrstop.
1657
1658 /// Skip tokens until after the #include of the through header or
1659 /// until after a #pragma hdrstop.
1661
1662 /// Process directives while skipping until the through header or
1663 /// #pragma hdrstop is found.
1665 SourceLocation HashLoc);
1666
1667 /// Enter the specified FileID as the main source file,
1668 /// which implicitly adds the builtin defines etc.
1669 void EnterMainSourceFile();
1670
1671 /// Inform the preprocessor callbacks that processing is complete.
1672 void EndSourceFile();
1673
1674 /// Add a source file to the top of the include stack and
1675 /// start lexing tokens from it instead of the current buffer.
1676 ///
1677 /// Emits a diagnostic, doesn't enter the file, and returns true on error.
1679 SourceLocation Loc, bool IsFirstIncludeOfFile = true);
1680
1681 /// Add a Macro to the top of the include stack and start lexing
1682 /// tokens from it instead of the current buffer.
1683 ///
1684 /// \param Args specifies the tokens input to a function-like macro.
1685 /// \param ILEnd specifies the location of the ')' for a function-like macro
1686 /// or the identifier for an object-like macro.
1688 MacroArgs *Args);
1689
1690private:
1691 /// Add a "macro" context to the top of the include stack,
1692 /// which will cause the lexer to start returning the specified tokens.
1693 ///
1694 /// If \p DisableMacroExpansion is true, tokens lexed from the token stream
1695 /// will not be subject to further macro expansion. Otherwise, these tokens
1696 /// will be re-macro-expanded when/if expansion is enabled.
1697 ///
1698 /// If \p OwnsTokens is false, this method assumes that the specified stream
1699 /// of tokens has a permanent owner somewhere, so they do not need to be
1700 /// copied. If it is true, it assumes the array of tokens is allocated with
1701 /// \c new[] and the Preprocessor will delete[] it.
1702 ///
1703 /// If \p IsReinject the resulting tokens will have Token::IsReinjected flag
1704 /// set, see the flag documentation for details.
1705 void EnterTokenStream(const Token *Toks, unsigned NumToks,
1706 bool DisableMacroExpansion, bool OwnsTokens,
1707 bool IsReinject);
1708
1709public:
1710 void EnterTokenStream(std::unique_ptr<Token[]> Toks, unsigned NumToks,
1711 bool DisableMacroExpansion, bool IsReinject) {
1712 EnterTokenStream(Toks.release(), NumToks, DisableMacroExpansion, true,
1713 IsReinject);
1714 }
1715
1716 void EnterTokenStream(ArrayRef<Token> Toks, bool DisableMacroExpansion,
1717 bool IsReinject) {
1718 EnterTokenStream(Toks.data(), Toks.size(), DisableMacroExpansion, false,
1719 IsReinject);
1720 }
1721
1722 /// Pop the current lexer/macro exp off the top of the lexer stack.
1723 ///
1724 /// This should only be used in situations where the current state of the
1725 /// top-of-stack lexer is known.
1726 void RemoveTopOfLexerStack();
1727
1728 /// From the point that this method is called, and until
1729 /// CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
1730 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
1731 /// make the Preprocessor re-lex the same tokens.
1732 ///
1733 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
1734 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
1735 /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
1736 ///
1737 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
1738 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
1739 /// tokens will continue indefinitely.
1740 ///
1741 /// \param Unannotated Whether token annotations are reverted upon calling
1742 /// Backtrack().
1743 void EnableBacktrackAtThisPos(bool Unannotated = false);
1744
1745private:
1746 std::pair<CachedTokensTy::size_type, bool> LastBacktrackPos();
1747
1748 CachedTokensTy PopUnannotatedBacktrackTokens();
1749
1750public:
1751 /// Disable the last EnableBacktrackAtThisPos call.
1753
1754 /// Make Preprocessor re-lex the tokens that were lexed since
1755 /// EnableBacktrackAtThisPos() was previously called.
1756 void Backtrack();
1757
1758 /// True if EnableBacktrackAtThisPos() was called and
1759 /// caching of tokens is on.
1760 bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
1761
1762 /// True if EnableBacktrackAtThisPos() was called and
1763 /// caching of unannotated tokens is on.
1765 return !UnannotatedBacktrackTokens.empty();
1766 }
1767
1768 /// Lex the next token for this preprocessor.
1769 void Lex(Token &Result);
1770
1771 /// Lex all tokens for this preprocessor until (and excluding) end of file.
1772 void LexTokensUntilEOF(std::vector<Token> *Tokens = nullptr);
1773
1774 /// Lex a token, forming a header-name token if possible.
1775 bool LexHeaderName(Token &Result, bool AllowMacroExpansion = true);
1776
1777 /// Lex the parameters for an #embed directive, returns nullopt on error.
1778 std::optional<LexEmbedParametersResult> LexEmbedParameters(Token &Current,
1779 bool ForHasEmbed);
1780
1781 /// Get the start location of the first pp-token in main file.
1783 assert(FirstPPTokenLoc.isValid() &&
1784 "Did not see the first pp-token in the main file");
1785 return FirstPPTokenLoc;
1786 }
1787
1790
1792 bool IncludeExports = true);
1793
1795 return CurSubmoduleState->VisibleModules.getImportLoc(M);
1796 }
1797
1798 /// Lex a string literal, which may be the concatenation of multiple
1799 /// string literals and may even come from macro expansion.
1800 /// \returns true on success, false if a error diagnostic has been generated.
1801 bool LexStringLiteral(Token &Result, std::string &String,
1802 const char *DiagnosticTag, bool AllowMacroExpansion) {
1803 if (AllowMacroExpansion)
1804 Lex(Result);
1805 else
1807 return FinishLexStringLiteral(Result, String, DiagnosticTag,
1808 AllowMacroExpansion);
1809 }
1810
1811 /// Complete the lexing of a string literal where the first token has
1812 /// already been lexed (see LexStringLiteral).
1813 bool FinishLexStringLiteral(Token &Result, std::string &String,
1814 const char *DiagnosticTag,
1815 bool AllowMacroExpansion);
1816
1817 /// Lex a token. If it's a comment, keep lexing until we get
1818 /// something not a comment.
1819 ///
1820 /// This is useful in -E -C mode where comments would foul up preprocessor
1821 /// directive handling.
1823 do
1824 Lex(Result);
1825 while (Result.getKind() == tok::comment);
1826 }
1827
1828 /// Just like Lex, but disables macro expansion of identifier tokens.
1830 // Disable macro expansion.
1831 bool OldVal = DisableMacroExpansion;
1832 DisableMacroExpansion = true;
1833 // Lex the token.
1834 Lex(Result);
1835
1836 // Reenable it.
1837 DisableMacroExpansion = OldVal;
1838 }
1839
1840 /// Like LexNonComment, but this disables macro expansion of
1841 /// identifier tokens.
1843 do
1845 while (Result.getKind() == tok::comment);
1846 }
1847
1848 /// Parses a simple integer literal to get its numeric value. Floating
1849 /// point literals and user defined literals are rejected. Used primarily to
1850 /// handle pragmas that accept integer arguments.
1851 bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value);
1852
1853 /// Disables macro expansion everywhere except for preprocessor directives.
1855 DisableMacroExpansion = true;
1856 MacroExpansionInDirectivesOverride = true;
1857 }
1858
1860 DisableMacroExpansion = MacroExpansionInDirectivesOverride = false;
1861 }
1862
1863 /// Peeks ahead N tokens and returns that token without consuming any
1864 /// tokens.
1865 ///
1866 /// LookAhead(0) returns the next token that would be returned by Lex(),
1867 /// LookAhead(1) returns the token after it, etc. This returns normal
1868 /// tokens after phase 5. As such, it is equivalent to using
1869 /// 'Lex', not 'LexUnexpandedToken'.
1870 const Token &LookAhead(unsigned N) {
1871 assert(LexLevel == 0 && "cannot use lookahead while lexing");
1872 if (CachedLexPos + N < CachedTokens.size())
1873 return CachedTokens[CachedLexPos+N];
1874 else
1875 return PeekAhead(N+1);
1876 }
1877
1878 /// When backtracking is enabled and tokens are cached,
1879 /// this allows to revert a specific number of tokens.
1880 ///
1881 /// Note that the number of tokens being reverted should be up to the last
1882 /// backtrack position, not more.
1883 void RevertCachedTokens(unsigned N) {
1884 assert(isBacktrackEnabled() &&
1885 "Should only be called when tokens are cached for backtracking");
1886 assert(signed(CachedLexPos) - signed(N) >=
1887 signed(LastBacktrackPos().first) &&
1888 "Should revert tokens up to the last backtrack position, not more");
1889 assert(signed(CachedLexPos) - signed(N) >= 0 &&
1890 "Corrupted backtrack positions ?");
1891 CachedLexPos -= N;
1892 }
1893
1894 /// Enters a token in the token stream to be lexed next.
1895 ///
1896 /// If BackTrack() is called afterwards, the token will remain at the
1897 /// insertion point.
1898 /// If \p IsReinject is true, resulting token will have Token::IsReinjected
1899 /// flag set. See the flag documentation for details.
1900 void EnterToken(const Token &Tok, bool IsReinject) {
1901 if (LexLevel) {
1902 // It's not correct in general to enter caching lex mode while in the
1903 // middle of a nested lexing action.
1904 auto TokCopy = std::make_unique<Token[]>(1);
1905 TokCopy[0] = Tok;
1906 EnterTokenStream(std::move(TokCopy), 1, true, IsReinject);
1907 } else {
1908 EnterCachingLexMode();
1909 assert(IsReinject && "new tokens in the middle of cached stream");
1910 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
1911 }
1912 }
1913
1914 /// We notify the Preprocessor that if it is caching tokens (because
1915 /// backtrack is enabled) it should replace the most recent cached tokens
1916 /// with the given annotation token. This function has no effect if
1917 /// backtracking is not enabled.
1918 ///
1919 /// Note that the use of this function is just for optimization, so that the
1920 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
1921 /// invoked.
1923 assert(Tok.isAnnotation() && "Expected annotation token");
1924 if (CachedLexPos != 0 && isBacktrackEnabled())
1925 AnnotatePreviousCachedTokens(Tok);
1926 }
1927
1928 /// Get the location of the last cached token, suitable for setting the end
1929 /// location of an annotation token.
1931 assert(CachedLexPos != 0);
1932 return CachedTokens[CachedLexPos-1].getLastLoc();
1933 }
1934
1935 /// Whether \p Tok is the most recent token (`CachedLexPos - 1`) in
1936 /// CachedTokens.
1937 bool IsPreviousCachedToken(const Token &Tok) const;
1938
1939 /// Replace token in `CachedLexPos - 1` in CachedTokens by the tokens
1940 /// in \p NewToks.
1941 ///
1942 /// Useful when a token needs to be split in smaller ones and CachedTokens
1943 /// most recent token must to be updated to reflect that.
1945
1946 /// Replace the last token with an annotation token.
1947 ///
1948 /// Like AnnotateCachedTokens(), this routine replaces an
1949 /// already-parsed (and resolved) token with an annotation
1950 /// token. However, this routine only replaces the last token with
1951 /// the annotation token; it does not affect any other cached
1952 /// tokens. This function has no effect if backtracking is not
1953 /// enabled.
1955 assert(Tok.isAnnotation() && "Expected annotation token");
1956 if (CachedLexPos != 0 && isBacktrackEnabled())
1957 CachedTokens[CachedLexPos-1] = Tok;
1958 }
1959
1960 /// Enter an annotation token into the token stream.
1962 void *AnnotationVal);
1963
1964 /// Determine whether it's possible for a future call to Lex to produce an
1965 /// annotation token created by a previous call to EnterAnnotationToken.
1967 return CurLexerCallback != CLK_Lexer;
1968 }
1969
1970 /// Update the current token to represent the provided
1971 /// identifier, in order to cache an action performed by typo correction.
1973 assert(Tok.getIdentifierInfo() && "Expected identifier token");
1974 if (CachedLexPos != 0 && isBacktrackEnabled())
1975 CachedTokens[CachedLexPos-1] = Tok;
1976 }
1977
1978 /// Recompute the current lexer kind based on the CurLexer/
1979 /// CurTokenLexer pointers.
1980 void recomputeCurLexerKind();
1981
1982 /// Returns true if incremental processing is enabled
1983 bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; }
1984
1985 /// Enables the incremental processing
1986 void enableIncrementalProcessing(bool value = true) {
1987 IncrementalProcessing = value;
1988 }
1989
1990 /// Specify the point at which code-completion will be performed.
1991 ///
1992 /// \param File the file in which code completion should occur. If
1993 /// this file is included multiple times, code-completion will
1994 /// perform completion the first time it is included. If NULL, this
1995 /// function clears out the code-completion point.
1996 ///
1997 /// \param Line the line at which code completion should occur
1998 /// (1-based).
1999 ///
2000 /// \param Column the column at which code completion should occur
2001 /// (1-based).
2002 ///
2003 /// \returns true if an error occurred, false otherwise.
2005 unsigned Column);
2006
2007 /// Determine if we are performing code completion.
2008 bool isCodeCompletionEnabled() const { return CodeCompletionFile != nullptr; }
2009
2010 /// Returns the location of the code-completion point.
2011 ///
2012 /// Returns an invalid location if code-completion is not enabled or the file
2013 /// containing the code-completion point has not been lexed yet.
2014 SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; }
2015
2016 /// Returns the start location of the file of code-completion point.
2017 ///
2018 /// Returns an invalid location if code-completion is not enabled or the file
2019 /// containing the code-completion point has not been lexed yet.
2021 return CodeCompletionFileLoc;
2022 }
2023
2024 /// Returns true if code-completion is enabled and we have hit the
2025 /// code-completion point.
2026 bool isCodeCompletionReached() const { return CodeCompletionReached; }
2027
2028 /// Note that we hit the code-completion point.
2030 assert(isCodeCompletionEnabled() && "Code-completion not enabled!");
2031 CodeCompletionReached = true;
2032 // Silence any diagnostics that occur after we hit the code-completion.
2034 }
2035
2036 /// The location of the currently-active \#pragma clang
2037 /// arc_cf_code_audited begin.
2038 ///
2039 /// Returns an invalid location if there is no such pragma active.
2041 return PragmaARCCFCodeAuditedInfo;
2042 }
2043
2044 /// Set the location of the currently-active \#pragma clang
2045 /// arc_cf_code_audited begin. An invalid location ends the pragma.
2047 SourceLocation Loc) {
2048 PragmaARCCFCodeAuditedInfo = IdentifierLoc(Loc, Ident);
2049 }
2050
2051 /// The location of the currently-active \#pragma clang
2052 /// assume_nonnull begin.
2053 ///
2054 /// Returns an invalid location if there is no such pragma active.
2056 return PragmaAssumeNonNullLoc;
2057 }
2058
2059 /// Set the location of the currently-active \#pragma clang
2060 /// assume_nonnull begin. An invalid location ends the pragma.
2062 PragmaAssumeNonNullLoc = Loc;
2063 }
2064
2065 /// Get the location of the recorded unterminated \#pragma clang
2066 /// assume_nonnull begin in the preamble, if one exists.
2067 ///
2068 /// Returns an invalid location if the premable did not end with
2069 /// such a pragma active or if there is no recorded preamble.
2071 return PreambleRecordedPragmaAssumeNonNullLoc;
2072 }
2073
2074 /// Record the location of the unterminated \#pragma clang
2075 /// assume_nonnull begin in the preamble.
2077 PreambleRecordedPragmaAssumeNonNullLoc = Loc;
2078 }
2079
2080 /// Set the directory in which the main file should be considered
2081 /// to have been found, if it is not a real file.
2082 void setMainFileDir(DirectoryEntryRef Dir) { MainFileDir = Dir; }
2083
2084 /// Instruct the preprocessor to skip part of the main source file.
2085 ///
2086 /// \param Bytes The number of bytes in the preamble to skip.
2087 ///
2088 /// \param StartOfLine Whether skipping these bytes puts the lexer at the
2089 /// start of a line.
2090 void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) {
2091 SkipMainFilePreamble.first = Bytes;
2092 SkipMainFilePreamble.second = StartOfLine;
2093 }
2094
2095 /// Forwarding function for diagnostics. This emits a diagnostic at
2096 /// the specified Token's location, translating the token's start
2097 /// position in the current buffer into a SourcePosition object for rendering.
2098 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const {
2099 return Diags->Report(Loc, DiagID);
2100 }
2101
2102 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const {
2103 return Diags->Report(Tok.getLocation(), DiagID);
2104 }
2105
2106 /// Return the 'spelling' of the token at the given
2107 /// location; does not go up to the spelling location or down to the
2108 /// expansion location.
2109 ///
2110 /// \param buffer A buffer which will be used only if the token requires
2111 /// "cleaning", e.g. if it contains trigraphs or escaped newlines
2112 /// \param invalid If non-null, will be set \c true if an error occurs.
2114 SmallVectorImpl<char> &buffer,
2115 bool *invalid = nullptr) const {
2116 return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid);
2117 }
2118
2119 /// Return the 'spelling' of the Tok token.
2120 ///
2121 /// The spelling of a token is the characters used to represent the token in
2122 /// the source file after trigraph expansion and escaped-newline folding. In
2123 /// particular, this wants to get the true, uncanonicalized, spelling of
2124 /// things like digraphs, UCNs, etc.
2125 ///
2126 /// \param Invalid If non-null, will be set \c true if an error occurs.
2127 std::string getSpelling(const Token &Tok, bool *Invalid = nullptr) const {
2128 return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid);
2129 }
2130
2131 /// Get the spelling of a token into a preallocated buffer, instead
2132 /// of as an std::string.
2133 ///
2134 /// The caller is required to allocate enough space for the token, which is
2135 /// guaranteed to be at least Tok.getLength() bytes long. The length of the
2136 /// actual result is returned.
2137 ///
2138 /// Note that this method may do two possible things: it may either fill in
2139 /// the buffer specified with characters, or it may *change the input pointer*
2140 /// to point to a constant buffer with the data already in it (avoiding a
2141 /// copy). The caller is not allowed to modify the returned buffer pointer
2142 /// if an internal buffer is returned.
2143 unsigned getSpelling(const Token &Tok, const char *&Buffer,
2144 bool *Invalid = nullptr) const {
2145 return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid);
2146 }
2147
2148 /// Get the spelling of a token into a SmallVector.
2149 ///
2150 /// Note that the returned StringRef may not point to the
2151 /// supplied buffer if a copy can be avoided.
2152 StringRef getSpelling(const Token &Tok,
2153 SmallVectorImpl<char> &Buffer,
2154 bool *Invalid = nullptr) const;
2155
2156 /// Relex the token at the specified location.
2157 /// \returns true if there was a failure, false on success.
2159 bool IgnoreWhiteSpace = false) {
2160 return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts, IgnoreWhiteSpace);
2161 }
2162
2163 /// Given a Token \p Tok that is a numeric constant with length 1,
2164 /// return the value of constant as an unsigned 8-bit integer.
2165 uint8_t
2167 bool *Invalid = nullptr) const {
2168 assert((Tok.is(tok::numeric_constant) || Tok.is(tok::binary_data)) &&
2169 Tok.getLength() == 1 && "Called on unsupported token");
2170 assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
2171
2172 // If the token is carrying a literal data pointer, just use it.
2173 if (const char *D = Tok.getLiteralData())
2174 return (Tok.getKind() == tok::binary_data) ? *D : *D - '0';
2175
2176 assert(Tok.is(tok::numeric_constant) && "binary data with no data");
2177 // Otherwise, fall back on getCharacterData, which is slower, but always
2178 // works.
2179 return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid) - '0';
2180 }
2181
2182 /// Retrieve the name of the immediate macro expansion.
2183 ///
2184 /// This routine starts from a source location, and finds the name of the
2185 /// macro responsible for its immediate expansion. It looks through any
2186 /// intervening macro argument expansions to compute this. It returns a
2187 /// StringRef that refers to the SourceManager-owned buffer of the source
2188 /// where that macro name is spelled. Thus, the result shouldn't out-live
2189 /// the SourceManager.
2191 return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts());
2192 }
2193
2194 /// Plop the specified string into a scratch buffer and set the
2195 /// specified token's location and length to it.
2196 ///
2197 /// If specified, the source location provides a location of the expansion
2198 /// point of the token.
2199 void CreateString(StringRef Str, Token &Tok,
2200 SourceLocation ExpansionLocStart = SourceLocation(),
2201 SourceLocation ExpansionLocEnd = SourceLocation());
2202
2203 /// Split the first Length characters out of the token starting at TokLoc
2204 /// and return a location pointing to the split token. Re-lexing from the
2205 /// split token will return the split token rather than the original.
2206 SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length);
2207
2208 /// Computes the source location just past the end of the
2209 /// token at this source location.
2210 ///
2211 /// This routine can be used to produce a source location that
2212 /// points just past the end of the token referenced by \p Loc, and
2213 /// is generally used when a diagnostic needs to point just after a
2214 /// token where it expected something different that it received. If
2215 /// the returned source location would not be meaningful (e.g., if
2216 /// it points into a macro), this routine returns an invalid
2217 /// source location.
2218 ///
2219 /// \param Offset an offset from the end of the token, where the source
2220 /// location should refer to. The default offset (0) produces a source
2221 /// location pointing just past the end of the token; an offset of 1 produces
2222 /// a source location pointing to the last character in the token, etc.
2224 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
2225 }
2226
2227 /// Returns true if the given MacroID location points at the first
2228 /// token of the macro expansion.
2229 ///
2230 /// \param MacroBegin If non-null and function returns true, it is set to
2231 /// begin location of the macro.
2233 SourceLocation *MacroBegin = nullptr) const {
2234 return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts,
2235 MacroBegin);
2236 }
2237
2238 /// Returns true if the given MacroID location points at the last
2239 /// token of the macro expansion.
2240 ///
2241 /// \param MacroEnd If non-null and function returns true, it is set to
2242 /// end location of the macro.
2244 SourceLocation *MacroEnd = nullptr) const {
2245 return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd);
2246 }
2247
2248 /// Print the token to stderr, used for debugging.
2249 void DumpToken(const Token &Tok, bool DumpFlags = false) const;
2250 void DumpLocation(SourceLocation Loc) const;
2251 void DumpMacro(const MacroInfo &MI) const;
2252 void dumpMacroInfo(const IdentifierInfo *II);
2253
2254 /// Given a location that specifies the start of a
2255 /// token, return a new location that specifies a character within the token.
2257 unsigned Char) const {
2258 return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts);
2259 }
2260
2261 /// Increment the counters for the number of token paste operations
2262 /// performed.
2263 ///
2264 /// If fast was specified, this is a 'fast paste' case we handled.
2265 void IncrementPasteCounter(bool isFast) {
2266 if (isFast)
2267 ++NumFastTokenPaste;
2268 else
2269 ++NumTokenPaste;
2270 }
2271
2272 void PrintStats();
2273
2274 size_t getTotalMemory() const;
2275
2276 /// When the macro expander pastes together a comment (/##/) in Microsoft
2277 /// mode, this method handles updating the current state, returning the
2278 /// token on the next source line.
2280
2281 //===--------------------------------------------------------------------===//
2282 // Preprocessor callback methods. These are invoked by a lexer as various
2283 // directives and events are found.
2284
2285 /// Given a tok::raw_identifier token, look up the
2286 /// identifier information for the token and install it into the token,
2287 /// updating the token kind accordingly.
2288 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const;
2289
2290private:
2291 llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons;
2292
2293public:
2294 /// Specifies the reason for poisoning an identifier.
2295 ///
2296 /// If that identifier is accessed while poisoned, then this reason will be
2297 /// used instead of the default "poisoned" diagnostic.
2298 void SetPoisonReason(IdentifierInfo *II, unsigned DiagID);
2299
2300 /// Display reason for poisoned identifier.
2301 void HandlePoisonedIdentifier(Token & Identifier);
2302
2304 if(IdentifierInfo * II = Identifier.getIdentifierInfo()) {
2305 if(II->isPoisoned()) {
2306 HandlePoisonedIdentifier(Identifier);
2307 }
2308 }
2309 }
2310
2311 /// Check whether the next pp-token is one of the specificed token kind. this
2312 /// method should have no observable side-effect on the lexed tokens.
2313 template <typename... Ts> bool isNextPPTokenOneOf(Ts... Ks) {
2314 static_assert(sizeof...(Ts) > 0,
2315 "requires at least one tok::TokenKind specified");
2316 // Do some quick tests for rejection cases.
2317 std::optional<Token> Val;
2318 if (CurLexer)
2319 Val = CurLexer->peekNextPPToken();
2320 else
2321 Val = CurTokenLexer->peekNextPPToken();
2322
2323 if (!Val) {
2324 // We have run off the end. If it's a source file we don't
2325 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
2326 // macro stack.
2327 if (CurPPLexer)
2328 return false;
2329 for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
2330 if (Entry.TheLexer)
2331 Val = Entry.TheLexer->peekNextPPToken();
2332 else
2333 Val = Entry.TheTokenLexer->peekNextPPToken();
2334
2335 if (Val)
2336 break;
2337
2338 // Ran off the end of a source file?
2339 if (Entry.ThePPLexer)
2340 return false;
2341 }
2342 }
2343
2344 // Okay, we found the token and return. Otherwise we found the end of the
2345 // translation unit.
2346 return Val->isOneOf(Ks...);
2347 }
2348
2349private:
2350 /// Identifiers used for SEH handling in Borland. These are only
2351 /// allowed in particular circumstances
2352 // __except block
2353 IdentifierInfo *Ident__exception_code,
2354 *Ident___exception_code,
2355 *Ident_GetExceptionCode;
2356 // __except filter expression
2357 IdentifierInfo *Ident__exception_info,
2358 *Ident___exception_info,
2359 *Ident_GetExceptionInfo;
2360 // __finally
2361 IdentifierInfo *Ident__abnormal_termination,
2362 *Ident___abnormal_termination,
2363 *Ident_AbnormalTermination;
2364
2365 const char *getCurLexerEndPos();
2366 void diagnoseMissingHeaderInUmbrellaDir(const Module &Mod);
2367
2368public:
2369 void PoisonSEHIdentifiers(bool Poison = true); // Borland
2370
2371 /// Callback invoked when the lexer reads an identifier and has
2372 /// filled in the tokens IdentifierInfo member.
2373 ///
2374 /// This callback potentially macro expands it or turns it into a named
2375 /// token (like 'for').
2376 ///
2377 /// \returns true if we actually computed a token, false if we need to
2378 /// lex again.
2379 bool HandleIdentifier(Token &Identifier);
2380
2381 /// Callback invoked when the lexer hits the end of the current file.
2382 ///
2383 /// This either returns the EOF token and returns true, or
2384 /// pops a level off the include stack and returns false, at which point the
2385 /// client should call lex again.
2386 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
2387
2388 /// Callback invoked when the current TokenLexer hits the end of its
2389 /// token stream.
2391
2392 /// Callback invoked when the lexer sees a # token at the start of a
2393 /// line.
2394 ///
2395 /// This consumes the directive, modifies the lexer/preprocessor state, and
2396 /// advances the lexer(s) so that the next token read is the correct one.
2398
2399 /// Ensure that the next token is a tok::eod token.
2400 ///
2401 /// If not, emit a diagnostic and consume up until the eod.
2402 /// If \p EnableMacros is true, then we consider macros that expand to zero
2403 /// tokens as being ok.
2404 ///
2405 /// \return The location of the end of the directive (the terminating
2406 /// newline).
2407 SourceLocation CheckEndOfDirective(const char *DirType,
2408 bool EnableMacros = false);
2409
2410 /// Read and discard all tokens remaining on the current line until
2411 /// the tok::eod token is found. Returns the range of the skipped tokens.
2416
2417 /// Same as above except retains the token that was found.
2419
2420 /// Returns true if the preprocessor has seen a use of
2421 /// __DATE__ or __TIME__ in the file so far.
2422 bool SawDateOrTime() const {
2423 return DATELoc != SourceLocation() || TIMELoc != SourceLocation();
2424 }
2425 uint32_t getCounterValue() const { return CounterValue; }
2426 void setCounterValue(uint32_t V) { CounterValue = V; }
2427
2429 assert(CurrentFPEvalMethod != LangOptions::FEM_UnsetOnCommandLine &&
2430 "FPEvalMethod should be set either from command line or from the "
2431 "target info");
2432 return CurrentFPEvalMethod;
2433 }
2434
2436 return TUFPEvalMethod;
2437 }
2438
2440 return LastFPEvalPragmaLocation;
2441 }
2442
2446 "FPEvalMethod should never be set to FEM_UnsetOnCommandLine");
2447 // This is the location of the '#pragma float_control" where the
2448 // execution state is modifed.
2449 LastFPEvalPragmaLocation = PragmaLoc;
2450 CurrentFPEvalMethod = Val;
2451 TUFPEvalMethod = Val;
2452 }
2453
2456 "TUPEvalMethod should never be set to FEM_UnsetOnCommandLine");
2457 TUFPEvalMethod = Val;
2458 }
2459
2460 /// Retrieves the module that we're currently building, if any.
2462
2463 /// Retrieves the module whose implementation we're current compiling, if any.
2465
2466 /// If we are preprocessing a named module.
2467 bool isInNamedModule() const { return ModuleDeclState.isNamedModule(); }
2468
2469 /// If we are proprocessing a named interface unit.
2470 /// Note that a module implementation partition is not considered as an
2471 /// named interface unit here although it is importable
2472 /// to ease the parsing.
2474 return ModuleDeclState.isNamedInterface();
2475 }
2476
2477 /// Get the named module name we're preprocessing.
2478 /// Requires we're preprocessing a named module.
2479 StringRef getNamedModuleName() const { return ModuleDeclState.getName(); }
2480
2481 /// If we are implementing an implementation module unit.
2482 /// Note that the module implementation partition is not considered as an
2483 /// implementation unit.
2485 return ModuleDeclState.isImplementationUnit();
2486 }
2487
2488 /// If we're importing a standard C++20 Named Modules.
2490 // NamedModuleImportPath will be non-empty only if we're importing
2491 // Standard C++ named modules.
2492 return !NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules &&
2493 !IsAtImport;
2494 }
2495
2496 /// Allocate a new MacroInfo object with the provided SourceLocation.
2498
2499 /// Turn the specified lexer token into a fully checked and spelled
2500 /// filename, e.g. as an operand of \#include.
2501 ///
2502 /// The caller is expected to provide a buffer that is large enough to hold
2503 /// the spelling of the filename, but is also expected to handle the case
2504 /// when this method decides to use a different buffer.
2505 ///
2506 /// \returns true if the input filename was in <>'s or false if it was
2507 /// in ""'s.
2508 bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Buffer);
2509
2510 /// Given a "foo" or <foo> reference, look up the indicated file.
2511 ///
2512 /// Returns std::nullopt on failure. \p isAngled indicates whether the file
2513 /// reference is for system \#include's or not (i.e. using <> instead of "").
2515 LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
2516 ConstSearchDirIterator FromDir, const FileEntry *FromFile,
2517 ConstSearchDirIterator *CurDir, SmallVectorImpl<char> *SearchPath,
2518 SmallVectorImpl<char> *RelativePath,
2519 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
2520 bool *IsFrameworkFound, bool SkipCache = false,
2521 bool OpenFile = true, bool CacheFailures = true);
2522
2523 /// Given a "Filename" or <Filename> reference, look up the indicated embed
2524 /// resource. \p isAngled indicates whether the file reference is for
2525 /// system \#include's or not (i.e. using <> instead of ""). If \p OpenFile
2526 /// is true, the file looked up is opened for reading, otherwise it only
2527 /// validates that the file exists. Quoted filenames are looked up relative
2528 /// to \p LookupFromFile if it is nonnull.
2529 ///
2530 /// Returns std::nullopt on failure.
2532 LookupEmbedFile(StringRef Filename, bool isAngled, bool OpenFile,
2533 const FileEntry *LookupFromFile = nullptr);
2534
2535 /// Return true if we're in the top-level file, not in a \#include.
2536 bool isInPrimaryFile() const;
2537
2538 /// Lex an on-off-switch (C99 6.10.6p2) and verify that it is
2539 /// followed by EOD. Return true if the token is not a valid on-off-switch.
2541
2542 bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
2543 bool *ShadowFlag = nullptr);
2544
2545 void EnterSubmodule(Module *M, SourceLocation ImportLoc, bool ForPragma);
2546 Module *LeaveSubmodule(bool ForPragma);
2547
2548private:
2549 friend void TokenLexer::ExpandFunctionArguments();
2550
2551 void PushIncludeMacroStack() {
2552 assert(CurLexerCallback != CLK_CachingLexer &&
2553 "cannot push a caching lexer");
2554 IncludeMacroStack.emplace_back(CurLexerCallback, CurLexerSubmodule,
2555 std::move(CurLexer), CurPPLexer,
2556 std::move(CurTokenLexer), CurDirLookup);
2557 CurPPLexer = nullptr;
2558 }
2559
2560 void PopIncludeMacroStack() {
2561 CurLexer = std::move(IncludeMacroStack.back().TheLexer);
2562 CurPPLexer = IncludeMacroStack.back().ThePPLexer;
2563 CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer);
2564 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
2565 CurLexerSubmodule = IncludeMacroStack.back().TheSubmodule;
2566 CurLexerCallback = IncludeMacroStack.back().CurLexerCallback;
2567 IncludeMacroStack.pop_back();
2568 }
2569
2570 void PropagateLineStartLeadingSpaceInfo(Token &Result);
2571
2572 /// Determine whether we need to create module macros for #defines in the
2573 /// current context.
2574 bool needModuleMacros() const;
2575
2576 /// Update the set of active module macros and ambiguity flag for a module
2577 /// macro name.
2578 void updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info);
2579
2580 DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI,
2581 SourceLocation Loc);
2582 UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc);
2583 VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc,
2584 bool isPublic);
2585
2586 /// Lex and validate a macro name, which occurs after a
2587 /// \#define or \#undef.
2588 ///
2589 /// \param MacroNameTok Token that represents the name defined or undefined.
2590 /// \param IsDefineUndef Kind if preprocessor directive.
2591 /// \param ShadowFlag Points to flag that is set if macro name shadows
2592 /// a keyword.
2593 ///
2594 /// This emits a diagnostic, sets the token kind to eod,
2595 /// and discards the rest of the macro line if the macro name is invalid.
2596 void ReadMacroName(Token &MacroNameTok, MacroUse IsDefineUndef = MU_Other,
2597 bool *ShadowFlag = nullptr);
2598
2599 /// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2600 /// entire line) of the macro's tokens and adds them to MacroInfo, and while
2601 /// doing so performs certain validity checks including (but not limited to):
2602 /// - # (stringization) is followed by a macro parameter
2603 /// \param MacroNameTok - Token that represents the macro name
2604 /// \param ImmediatelyAfterHeaderGuard - Macro follows an #ifdef header guard
2605 ///
2606 /// Either returns a pointer to a MacroInfo object OR emits a diagnostic and
2607 /// returns a nullptr if an invalid sequence of tokens is encountered.
2608 MacroInfo *ReadOptionalMacroParameterListAndBody(
2609 const Token &MacroNameTok, bool ImmediatelyAfterHeaderGuard);
2610
2611 /// The ( starting an argument list of a macro definition has just been read.
2612 /// Lex the rest of the parameters and the closing ), updating \p MI with
2613 /// what we learn and saving in \p LastTok the last token read.
2614 /// Return true if an error occurs parsing the arg list.
2615 bool ReadMacroParameterList(MacroInfo *MI, Token& LastTok);
2616
2617 /// Provide a suggestion for a typoed directive. If there is no typo, then
2618 /// just skip suggesting.
2619 ///
2620 /// \param Tok - Token that represents the directive
2621 /// \param Directive - String reference for the directive name
2622 void SuggestTypoedDirective(const Token &Tok, StringRef Directive) const;
2623
2624 /// We just read a \#if or related directive and decided that the
2625 /// subsequent tokens are in the \#if'd out portion of the
2626 /// file. Lex the rest of the file, until we see an \#endif. If \p
2627 /// FoundNonSkipPortion is true, then we have already emitted code for part of
2628 /// this \#if directive, so \#else/\#elif blocks should never be entered. If
2629 /// \p FoundElse is false, then \#else directives are ok, if not, then we have
2630 /// already seen one so a \#else directive is a duplicate. When this returns,
2631 /// the caller can lex the first valid token.
2632 void SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
2633 SourceLocation IfTokenLoc,
2634 bool FoundNonSkipPortion, bool FoundElse,
2635 SourceLocation ElseLoc = SourceLocation());
2636
2637 /// Information about the result for evaluating an expression for a
2638 /// preprocessor directive.
2639 struct DirectiveEvalResult {
2640 /// The integral value of the expression.
2641 std::optional<llvm::APSInt> Value;
2642
2643 /// Whether the expression was evaluated as true or not.
2644 bool Conditional;
2645
2646 /// True if the expression contained identifiers that were undefined.
2647 bool IncludedUndefinedIds;
2648
2649 /// The source range for the expression.
2650 SourceRange ExprRange;
2651 };
2652
2653 /// Evaluate an integer constant expression that may occur after a
2654 /// \#if or \#elif directive and return a \p DirectiveEvalResult object.
2655 ///
2656 /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro.
2657 DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
2658 bool CheckForEoD = true);
2659
2660 /// Evaluate an integer constant expression that may occur after a
2661 /// \#if or \#elif directive and return a \p DirectiveEvalResult object.
2662 ///
2663 /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro.
2664 /// \p EvaluatedDefined will contain the result of whether "defined" appeared
2665 /// in the evaluated expression or not.
2666 DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
2667 Token &Tok,
2668 bool &EvaluatedDefined,
2669 bool CheckForEoD = true);
2670
2671 /// Process a '__has_embed("path" [, ...])' expression.
2672 ///
2673 /// Returns predefined `__STDC_EMBED_*` macro values if
2674 /// successful.
2675 EmbedResult EvaluateHasEmbed(Token &Tok, IdentifierInfo *II);
2676
2677 /// Process a '__has_include("path")' expression.
2678 ///
2679 /// Returns true if successful.
2680 bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II);
2681
2682 /// Process '__has_include_next("path")' expression.
2683 ///
2684 /// Returns true if successful.
2685 bool EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II);
2686
2687 /// Get the directory and file from which to start \#include_next lookup.
2688 std::pair<ConstSearchDirIterator, const FileEntry *>
2689 getIncludeNextStart(const Token &IncludeNextTok) const;
2690
2691 /// Install the standard preprocessor pragmas:
2692 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
2693 void RegisterBuiltinPragmas();
2694
2695 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
2696 /// table and mark it as a builtin macro to be expanded.
2697 IdentifierInfo *RegisterBuiltinMacro(const char *Name) {
2698 // Get the identifier.
2699 IdentifierInfo *Id = getIdentifierInfo(Name);
2700
2701 // Mark it as being a macro that is builtin.
2702 MacroInfo *MI = AllocateMacroInfo(SourceLocation());
2703 MI->setIsBuiltinMacro();
2705 return Id;
2706 }
2707
2708 /// Register builtin macros such as __LINE__ with the identifier table.
2709 void RegisterBuiltinMacros();
2710
2711 /// If an identifier token is read that is to be expanded as a macro, handle
2712 /// it and return the next token as 'Tok'. If we lexed a token, return true;
2713 /// otherwise the caller should lex again.
2714 bool HandleMacroExpandedIdentifier(Token &Identifier, const MacroDefinition &MD);
2715
2716 /// Cache macro expanded tokens for TokenLexers.
2717 //
2718 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
2719 /// going to lex in the cache and when it finishes the tokens are removed
2720 /// from the end of the cache.
2721 Token *cacheMacroExpandedTokens(TokenLexer *tokLexer,
2722 ArrayRef<Token> tokens);
2723
2724 void removeCachedMacroExpandedTokensOfLastLexer();
2725
2726 /// After reading "MACRO(", this method is invoked to read all of the formal
2727 /// arguments specified for the macro invocation. Returns null on error.
2728 MacroArgs *ReadMacroCallArgumentList(Token &MacroName, MacroInfo *MI,
2729 SourceLocation &MacroEnd);
2730
2731 /// If an identifier token is read that is to be expanded
2732 /// as a builtin macro, handle it and return the next token as 'Tok'.
2733 void ExpandBuiltinMacro(Token &Tok);
2734
2735 /// Read a \c _Pragma directive, slice it up, process it, then
2736 /// return the first token after the directive.
2737 /// This assumes that the \c _Pragma token has just been read into \p Tok.
2738 void Handle_Pragma(Token &Tok);
2739
2740 /// Like Handle_Pragma except the pragma text is not enclosed within
2741 /// a string literal.
2742 void HandleMicrosoft__pragma(Token &Tok);
2743
2744 /// Add a lexer to the top of the include stack and
2745 /// start lexing tokens from it instead of the current buffer.
2746 void EnterSourceFileWithLexer(Lexer *TheLexer, ConstSearchDirIterator Dir);
2747
2748 /// Set the FileID for the preprocessor predefines.
2749 void setPredefinesFileID(FileID FID) {
2750 assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!");
2751 PredefinesFileID = FID;
2752 }
2753
2754 /// Set the FileID for the PCH through header.
2755 void setPCHThroughHeaderFileID(FileID FID);
2756
2757 /// Returns true if we are lexing from a file and not a
2758 /// pragma or a macro.
2759 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
2760 return L ? !L->isPragmaLexer() : P != nullptr;
2761 }
2762
2763 static bool IsFileLexer(const IncludeStackInfo& I) {
2764 return IsFileLexer(I.TheLexer.get(), I.ThePPLexer);
2765 }
2766
2767 bool IsFileLexer() const {
2768 return IsFileLexer(CurLexer.get(), CurPPLexer);
2769 }
2770
2771 //===--------------------------------------------------------------------===//
2772 // Standard Library Identification
2773 std::optional<CXXStandardLibraryVersionInfo> CXXStandardLibraryVersion;
2774
2775public:
2776 std::optional<std::uint64_t> getStdLibCxxVersion();
2777 bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion);
2778
2779private:
2780 //===--------------------------------------------------------------------===//
2781 // Caching stuff.
2782 void CachingLex(Token &Result);
2783
2784 bool InCachingLexMode() const {
2785 // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means
2786 // that we are past EOF, not that we are in CachingLex mode.
2787 return !CurPPLexer && !CurTokenLexer && !IncludeMacroStack.empty();
2788 }
2789
2790 void EnterCachingLexMode();
2791 void EnterCachingLexModeUnchecked();
2792
2793 void ExitCachingLexMode() {
2794 if (InCachingLexMode())
2796 }
2797
2798 const Token &PeekAhead(unsigned N);
2799 void AnnotatePreviousCachedTokens(const Token &Tok);
2800
2801 //===--------------------------------------------------------------------===//
2802 /// Handle*Directive - implement the various preprocessor directives. These
2803 /// should side-effect the current preprocessor object so that the next call
2804 /// to Lex() will return the appropriate token next.
2805 void HandleLineDirective();
2806 void HandleDigitDirective(Token &Tok);
2807 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
2808 void HandleIdentSCCSDirective(Token &Tok);
2809 void HandleMacroPublicDirective(Token &Tok);
2810 void HandleMacroPrivateDirective();
2811
2812 /// An additional notification that can be produced by a header inclusion or
2813 /// import to tell the parser what happened.
2814 struct ImportAction {
2815 enum ActionKind {
2816 None,
2817 ModuleBegin,
2818 ModuleImport,
2819 HeaderUnitImport,
2820 SkippedModuleImport,
2821 Failure,
2822 } Kind;
2823 Module *ModuleForHeader = nullptr;
2824
2825 ImportAction(ActionKind AK, Module *Mod = nullptr)
2826 : Kind(AK), ModuleForHeader(Mod) {
2827 assert((AK == None || Mod || AK == Failure) &&
2828 "no module for module action");
2829 }
2830 };
2831
2832 OptionalFileEntryRef LookupHeaderIncludeOrImport(
2833 ConstSearchDirIterator *CurDir, StringRef &Filename,
2834 SourceLocation FilenameLoc, CharSourceRange FilenameRange,
2835 const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
2836 bool &IsMapped, ConstSearchDirIterator LookupFrom,
2837 const FileEntry *LookupFromFile, StringRef &LookupFilename,
2838 SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
2839 ModuleMap::KnownHeader &SuggestedModule, bool isAngled);
2840 // Binary data inclusion
2841 void HandleEmbedDirective(SourceLocation HashLoc, Token &Tok,
2842 const FileEntry *LookupFromFile = nullptr);
2843 void HandleEmbedDirectiveImpl(SourceLocation HashLoc,
2844 const LexEmbedParametersResult &Params,
2845 StringRef BinaryContents, StringRef FileName);
2846
2847 // File inclusion.
2848 void HandleIncludeDirective(SourceLocation HashLoc, Token &Tok,
2849 ConstSearchDirIterator LookupFrom = nullptr,
2850 const FileEntry *LookupFromFile = nullptr);
2851 ImportAction
2852 HandleHeaderIncludeOrImport(SourceLocation HashLoc, Token &IncludeTok,
2853 Token &FilenameTok, SourceLocation EndLoc,
2854 ConstSearchDirIterator LookupFrom = nullptr,
2855 const FileEntry *LookupFromFile = nullptr);
2856 void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok);
2857 void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok);
2858 void HandleImportDirective(SourceLocation HashLoc, Token &Tok);
2859 void HandleMicrosoftImportDirective(Token &Tok);
2860
2861public:
2862 /// Check that the given module is available, producing a diagnostic if not.
2863 /// \return \c true if the check failed (because the module is not available).
2864 /// \c false if the module appears to be usable.
2865 static bool checkModuleIsAvailable(const LangOptions &LangOpts,
2866 const TargetInfo &TargetInfo,
2867 const Module &M, DiagnosticsEngine &Diags);
2868
2869 // Module inclusion testing.
2870 /// Find the module that owns the source or header file that
2871 /// \p Loc points to. If the location is in a file that was included
2872 /// into a module, or is outside any module, returns nullptr.
2873 Module *getModuleForLocation(SourceLocation Loc, bool AllowTextual);
2874
2875 /// We want to produce a diagnostic at location IncLoc concerning an
2876 /// unreachable effect at location MLoc (eg, where a desired entity was
2877 /// declared or defined). Determine whether the right way to make MLoc
2878 /// reachable is by #include, and if so, what header should be included.
2879 ///
2880 /// This is not necessarily fast, and might load unexpected module maps, so
2881 /// should only be called by code that intends to produce an error.
2882 ///
2883 /// \param IncLoc The location at which the missing effect was detected.
2884 /// \param MLoc A location within an unimported module at which the desired
2885 /// effect occurred.
2886 /// \return A file that can be #included to provide the desired effect. Null
2887 /// if no such file could be determined or if a #include is not
2888 /// appropriate (eg, if a module should be imported instead).
2890 SourceLocation MLoc);
2891
2892 bool isRecordingPreamble() const {
2893 return PreambleConditionalStack.isRecording();
2894 }
2895
2896 bool hasRecordedPreamble() const {
2897 return PreambleConditionalStack.hasRecordedPreamble();
2898 }
2899
2901 return PreambleConditionalStack.getStack();
2902 }
2903
2905 PreambleConditionalStack.setStack(s);
2906 }
2907
2909 ArrayRef<PPConditionalInfo> s, std::optional<PreambleSkipInfo> SkipInfo) {
2910 PreambleConditionalStack.startReplaying();
2911 PreambleConditionalStack.setStack(s);
2912 PreambleConditionalStack.SkipInfo = SkipInfo;
2913 }
2914
2915 std::optional<PreambleSkipInfo> getPreambleSkipInfo() const {
2916 return PreambleConditionalStack.SkipInfo;
2917 }
2918
2919private:
2920 /// After processing predefined file, initialize the conditional stack from
2921 /// the preamble.
2922 void replayPreambleConditionalStack();
2923
2924 // Macro handling.
2925 void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard);
2926 void HandleUndefDirective();
2927
2928 // Conditional Inclusion.
2929 void HandleIfdefDirective(Token &Result, const Token &HashToken,
2930 bool isIfndef, bool ReadAnyTokensBeforeDirective);
2931 void HandleIfDirective(Token &IfToken, const Token &HashToken,
2932 bool ReadAnyTokensBeforeDirective);
2933 void HandleEndifDirective(Token &EndifToken);
2934 void HandleElseDirective(Token &Result, const Token &HashToken);
2935 void HandleElifFamilyDirective(Token &ElifToken, const Token &HashToken,
2936 tok::PPKeywordKind Kind);
2937
2938 // Pragmas.
2939 void HandlePragmaDirective(PragmaIntroducer Introducer);
2940
2941public:
2942 void HandlePragmaOnce(Token &OnceTok);
2943 void HandlePragmaMark(Token &MarkTok);
2944 void HandlePragmaPoison();
2945 void HandlePragmaSystemHeader(Token &SysHeaderTok);
2946 void HandlePragmaDependency(Token &DependencyTok);
2953
2954 // Return true and store the first token only if any CommentHandler
2955 // has inserted some tokens and getCommentRetentionState() is false.
2956 bool HandleComment(Token &result, SourceRange Comment);
2957
2958 /// A macro is used, update information about macros that need unused
2959 /// warnings.
2960 void markMacroAsUsed(MacroInfo *MI);
2961
2962 void addMacroDeprecationMsg(const IdentifierInfo *II, std::string Msg,
2963 SourceLocation AnnotationLoc) {
2964 AnnotationInfos[II].DeprecationInfo =
2965 MacroAnnotationInfo{AnnotationLoc, std::move(Msg)};
2966 }
2967
2968 void addRestrictExpansionMsg(const IdentifierInfo *II, std::string Msg,
2969 SourceLocation AnnotationLoc) {
2970 AnnotationInfos[II].RestrictExpansionInfo =
2971 MacroAnnotationInfo{AnnotationLoc, std::move(Msg)};
2972 }
2973
2974 void addFinalLoc(const IdentifierInfo *II, SourceLocation AnnotationLoc) {
2975 AnnotationInfos[II].FinalAnnotationLoc = AnnotationLoc;
2976 }
2977
2978 const MacroAnnotations &getMacroAnnotations(const IdentifierInfo *II) const {
2979 return AnnotationInfos.find(II)->second;
2980 }
2981
2982 void emitMacroExpansionWarnings(const Token &Identifier,
2983 bool IsIfnDef = false) const {
2984 IdentifierInfo *Info = Identifier.getIdentifierInfo();
2985 if (Info->isDeprecatedMacro())
2986 emitMacroDeprecationWarning(Identifier);
2987
2988 if (Info->isRestrictExpansion() &&
2989 !SourceMgr.isInMainFile(Identifier.getLocation()))
2990 emitRestrictExpansionWarning(Identifier);
2991
2992 if (!IsIfnDef) {
2993 if (Info->getName() == "INFINITY" && getLangOpts().NoHonorInfs)
2994 emitRestrictInfNaNWarning(Identifier, 0);
2995 if (Info->getName() == "NAN" && getLangOpts().NoHonorNaNs)
2996 emitRestrictInfNaNWarning(Identifier, 1);
2997 }
2998 }
2999
3001 const LangOptions &LangOpts,
3002 const TargetInfo &TI);
3003
3005 const PresumedLoc &PLoc,
3006 const LangOptions &LangOpts,
3007 const TargetInfo &TI);
3008
3009private:
3010 void emitMacroDeprecationWarning(const Token &Identifier) const;
3011 void emitRestrictExpansionWarning(const Token &Identifier) const;
3012 void emitFinalMacroWarning(const Token &Identifier, bool IsUndef) const;
3013 void emitRestrictInfNaNWarning(const Token &Identifier,
3014 unsigned DiagSelection) const;
3015
3016 /// This boolean state keeps track if the current scanned token (by this PP)
3017 /// is in an "-Wunsafe-buffer-usage" opt-out region. Assuming PP scans a
3018 /// translation unit in a linear order.
3019 bool InSafeBufferOptOutRegion = false;
3020
3021 /// Hold the start location of the current "-Wunsafe-buffer-usage" opt-out
3022 /// region if PP is currently in such a region. Hold undefined value
3023 /// otherwise.
3024 SourceLocation CurrentSafeBufferOptOutStart; // It is used to report the start location of an never-closed region.
3025
3026 using SafeBufferOptOutRegionsTy =
3028 // An ordered sequence of "-Wunsafe-buffer-usage" opt-out regions in this
3029 // translation unit. Each region is represented by a pair of start and
3030 // end locations.
3031 SafeBufferOptOutRegionsTy SafeBufferOptOutMap;
3032
3033 // The "-Wunsafe-buffer-usage" opt-out regions in loaded ASTs. We use the
3034 // following structure to manage them by their ASTs.
3035 struct {
3036 // A map from unique IDs to region maps of loaded ASTs. The ID identifies a
3037 // loaded AST. See `SourceManager::getUniqueLoadedASTID`.
3038 llvm::DenseMap<FileID, SafeBufferOptOutRegionsTy> LoadedRegions;
3039
3040 // Returns a reference to the safe buffer opt-out regions of the loaded
3041 // AST where `Loc` belongs to. (Construct if absent)
3042 SafeBufferOptOutRegionsTy &
3043 findAndConsLoadedOptOutMap(SourceLocation Loc, SourceManager &SrcMgr) {
3044 return LoadedRegions[SrcMgr.getUniqueLoadedASTFileID(Loc)];
3045 }
3046
3047 // Returns a reference to the safe buffer opt-out regions of the loaded
3048 // AST where `Loc` belongs to. (This const function returns nullptr if
3049 // absent.)
3050 const SafeBufferOptOutRegionsTy *
3051 lookupLoadedOptOutMap(SourceLocation Loc,
3052 const SourceManager &SrcMgr) const {
3053 FileID FID = SrcMgr.getUniqueLoadedASTFileID(Loc);
3054 auto Iter = LoadedRegions.find(FID);
3055
3056 if (Iter == LoadedRegions.end())
3057 return nullptr;
3058 return &Iter->getSecond();
3059 }
3060 } LoadedSafeBufferOptOutMap;
3061
3062public:
3063 /// \return true iff the given `Loc` is in a "-Wunsafe-buffer-usage" opt-out
3064 /// region. This `Loc` must be a source location that has been pre-processed.
3065 bool isSafeBufferOptOut(const SourceManager&SourceMgr, const SourceLocation &Loc) const;
3066
3067 /// Alter the state of whether this PP currently is in a
3068 /// "-Wunsafe-buffer-usage" opt-out region.
3069 ///
3070 /// \param isEnter true if this PP is entering a region; otherwise, this PP
3071 /// is exiting a region
3072 /// \param Loc the location of the entry or exit of a
3073 /// region
3074 /// \return true iff it is INVALID to enter or exit a region, i.e.,
3075 /// attempt to enter a region before exiting a previous region, or exiting a
3076 /// region that PP is not currently in.
3077 bool enterOrExitSafeBufferOptOutRegion(bool isEnter,
3078 const SourceLocation &Loc);
3079
3080 /// \return true iff this PP is currently in a "-Wunsafe-buffer-usage"
3081 /// opt-out region
3083
3084 /// \param StartLoc output argument. It will be set to the start location of
3085 /// the current "-Wunsafe-buffer-usage" opt-out region iff this function
3086 /// returns true.
3087 /// \return true iff this PP is currently in a "-Wunsafe-buffer-usage"
3088 /// opt-out region
3089 bool isPPInSafeBufferOptOutRegion(SourceLocation &StartLoc);
3090
3091 /// \return a sequence of SourceLocations representing ordered opt-out regions
3092 /// specified by
3093 /// `\#pragma clang unsafe_buffer_usage begin/end`s of this translation unit.
3094 SmallVector<SourceLocation, 64> serializeSafeBufferOptOutMap() const;
3095
3096 /// \param SrcLocSeqs a sequence of SourceLocations deserialized from a
3097 /// record of code `PP_UNSAFE_BUFFER_USAGE`.
3098 /// \return true iff the `Preprocessor` has been updated; false `Preprocessor`
3099 /// is same as itself before the call.
3101 const SmallVectorImpl<SourceLocation> &SrcLocSeqs);
3102
3103 /// Whether we've seen pp-directives which may have changed the preprocessing
3104 /// state.
3105 bool hasSeenNoTrivialPPDirective() const;
3106
3107private:
3108 /// Helper functions to forward lexing to the actual lexer. They all share the
3109 /// same signature.
3110 static bool CLK_Lexer(Preprocessor &P, Token &Result) {
3111 return P.CurLexer->Lex(Result);
3112 }
3113 static bool CLK_TokenLexer(Preprocessor &P, Token &Result) {
3114 return P.CurTokenLexer->Lex(Result);
3115 }
3116 static bool CLK_CachingLexer(Preprocessor &P, Token &Result) {
3117 P.CachingLex(Result);
3118 return true;
3119 }
3120 static bool CLK_DependencyDirectivesLexer(Preprocessor &P, Token &Result) {
3121 return P.CurLexer->LexDependencyDirectiveToken(Result);
3122 }
3123 static bool CLK_LexAfterModuleImport(Preprocessor &P, Token &Result) {
3124 return P.LexAfterModuleImport(Result);
3125 }
3126};
3127
3128/// Abstract base class that describes a handler that will receive
3129/// source ranges for each of the comments encountered in the source file.
3131public:
3133
3134 // The handler shall return true if it has pushed any tokens
3135 // to be read using e.g. EnterToken or EnterTokenStream.
3136 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
3137};
3138
3139/// Abstract base class that describes a handler that will receive
3140/// source ranges for empty lines encountered in the source file.
3142public:
3144
3145 // The handler handles empty lines.
3146 virtual void HandleEmptyline(SourceRange Range) = 0;
3147};
3148
3149/// Helper class to shuttle information about #embed directives from the
3150/// preprocessor to the parser through an annotation token.
3152 StringRef BinaryData;
3153 StringRef FileName;
3154};
3155
3156/// Registry of pragma handlers added by plugins
3157using PragmaHandlerRegistry = llvm::Registry<PragmaHandler>;
3158
3159} // namespace clang
3160
3161namespace llvm {
3162extern template class CLANG_TEMPLATE_ABI Registry<clang::PragmaHandler>;
3163} // namespace llvm
3164
3165#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:229
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.
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:189
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:134
#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:667
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)