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