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