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