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