1 //===--- Preprocessor.h - C Language Family Preprocessor --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Preprocessor interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LEX_PREPROCESSOR_H
15 #define LLVM_CLANG_LEX_PREPROCESSOR_H
17 #include "clang/Basic/Builtins.h"
18 #include "clang/Basic/Diagnostic.h"
19 #include "clang/Basic/IdentifierTable.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Lex/MacroInfo.h"
23 #include "clang/Lex/PPCallbacks.h"
24 #include "clang/Lex/PTHLexer.h"
25 #include "clang/Lex/PTHManager.h"
26 #include "clang/Lex/TokenLexer.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/IntrusiveRefCntPtr.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/Support/Allocator.h"
37 template<unsigned InternalLen> class SmallString;
43 class ExternalPreprocessorSource;
47 class PragmaNamespace;
53 class CodeCompletionHandler;
54 class DirectoryLookup;
55 class PreprocessingRecord;
57 class PreprocessorOptions;
59 /// \brief Stores token information for comparing actual tokens with
60 /// predefined values. Only handles simple tokens and identifiers.
66 TokenValue(tok::TokenKind Kind) : Kind(Kind), II(0) {
67 assert(Kind != tok::raw_identifier && "Raw identifiers are not supported.");
68 assert(Kind != tok::identifier &&
69 "Identifiers should be created by TokenValue(IdentifierInfo *)");
70 assert(!tok::isLiteral(Kind) && "Literals are not supported.");
71 assert(!tok::isAnnotation(Kind) && "Annotations are not supported.");
73 TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {}
74 bool operator==(const Token &Tok) const {
75 return Tok.getKind() == Kind &&
76 (!II || II == Tok.getIdentifierInfo());
80 /// Preprocessor - This object engages in a tight little dance with the lexer to
81 /// efficiently preprocess tokens. Lexers know only about tokens within a
82 /// single source file, and don't know anything about preprocessor-level issues
83 /// like the \#include stack, token expansion, etc.
85 class Preprocessor : public RefCountedBase<Preprocessor> {
86 IntrusiveRefCntPtr<PreprocessorOptions> PPOpts;
87 DiagnosticsEngine *Diags;
88 LangOptions &LangOpts;
89 const TargetInfo *Target;
91 SourceManager &SourceMgr;
92 ScratchBuffer *ScratchBuf;
93 HeaderSearch &HeaderInfo;
94 ModuleLoader &TheModuleLoader;
96 /// \brief External source of macros.
97 ExternalPreprocessorSource *ExternalSource;
100 /// PTH - An optional PTHManager object used for getting tokens from
101 /// a token cache rather than lexing the original source file.
102 OwningPtr<PTHManager> PTH;
104 /// BP - A BumpPtrAllocator object used to quickly allocate and release
105 /// objects internal to the Preprocessor.
106 llvm::BumpPtrAllocator BP;
108 /// Identifiers for builtin macros and other builtins.
109 IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__
110 IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__
111 IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__
112 IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__
113 IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__
114 IdentifierInfo *Ident__COUNTER__; // __COUNTER__
115 IdentifierInfo *Ident_Pragma, *Ident__pragma; // _Pragma, __pragma
116 IdentifierInfo *Ident__VA_ARGS__; // __VA_ARGS__
117 IdentifierInfo *Ident__has_feature; // __has_feature
118 IdentifierInfo *Ident__has_extension; // __has_extension
119 IdentifierInfo *Ident__has_builtin; // __has_builtin
120 IdentifierInfo *Ident__has_attribute; // __has_attribute
121 IdentifierInfo *Ident__has_include; // __has_include
122 IdentifierInfo *Ident__has_include_next; // __has_include_next
123 IdentifierInfo *Ident__has_warning; // __has_warning
124 IdentifierInfo *Ident__building_module; // __building_module
125 IdentifierInfo *Ident__MODULE__; // __MODULE__
127 SourceLocation DATELoc, TIMELoc;
128 unsigned CounterValue; // Next __COUNTER__ value.
131 /// MaxIncludeStackDepth - Maximum depth of \#includes.
132 MaxAllowedIncludeStackDepth = 200
135 // State that is set before the preprocessor begins.
136 bool KeepComments : 1;
137 bool KeepMacroComments : 1;
138 bool SuppressIncludeNotFoundError : 1;
140 // State that changes while the preprocessor runs:
141 bool InMacroArgs : 1; // True if parsing fn macro invocation args.
143 /// Whether the preprocessor owns the header search object.
144 bool OwnsHeaderSearch : 1;
146 /// DisableMacroExpansion - True if macro expansion is disabled.
147 bool DisableMacroExpansion : 1;
149 /// MacroExpansionInDirectivesOverride - Temporarily disables
150 /// DisableMacroExpansion (i.e. enables expansion) when parsing preprocessor
152 bool MacroExpansionInDirectivesOverride : 1;
154 class ResetMacroExpansionHelper;
156 /// \brief Whether we have already loaded macros from the external source.
157 mutable bool ReadMacrosFromExternalSource : 1;
159 /// \brief True if pragmas are enabled.
160 bool PragmasEnabled : 1;
162 /// \brief True if the current build action is a preprocessing action.
163 bool PreprocessedOutput : 1;
165 /// \brief True if we are currently preprocessing a #if or #elif directive
166 bool ParsingIfOrElifDirective;
168 /// \brief True if we are pre-expanding macro arguments.
169 bool InMacroArgPreExpansion;
171 /// Identifiers - This is mapping/lookup information for all identifiers in
172 /// the program, including program keywords.
173 mutable IdentifierTable Identifiers;
175 /// Selectors - This table contains all the selectors in the program. Unlike
176 /// IdentifierTable above, this table *isn't* populated by the preprocessor.
177 /// It is declared/expanded here because it's role/lifetime is
178 /// conceptually similar the IdentifierTable. In addition, the current control
179 /// flow (in clang::ParseAST()), make it convenient to put here.
180 /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to
181 /// the lifetime of the preprocessor.
182 SelectorTable Selectors;
184 /// BuiltinInfo - Information about builtins.
185 Builtin::Context BuiltinInfo;
187 /// PragmaHandlers - This tracks all of the pragmas that the client registered
188 /// with this preprocessor.
189 PragmaNamespace *PragmaHandlers;
191 /// \brief Tracks all of the comment handlers that the client registered
192 /// with this preprocessor.
193 std::vector<CommentHandler *> CommentHandlers;
195 /// \brief True if we want to ignore EOF token and continue later on (thus
196 /// avoid tearing the Lexer and etc. down).
197 bool IncrementalProcessing;
199 /// \brief The code-completion handler.
200 CodeCompletionHandler *CodeComplete;
202 /// \brief The file that we're performing code-completion for, if any.
203 const FileEntry *CodeCompletionFile;
205 /// \brief The offset in file for the code-completion point.
206 unsigned CodeCompletionOffset;
208 /// \brief The location for the code-completion point. This gets instantiated
209 /// when the CodeCompletionFile gets \#include'ed for preprocessing.
210 SourceLocation CodeCompletionLoc;
212 /// \brief The start location for the file of the code-completion point.
214 /// This gets instantiated when the CodeCompletionFile gets \#include'ed
215 /// for preprocessing.
216 SourceLocation CodeCompletionFileLoc;
218 /// \brief The source location of the 'import' contextual keyword we just
220 SourceLocation ModuleImportLoc;
222 /// \brief The module import path that we're currently processing.
223 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> ModuleImportPath;
225 /// \brief Whether the module import expectes an identifier next. Otherwise,
226 /// it expects a '.' or ';'.
227 bool ModuleImportExpectsIdentifier;
229 /// \brief The source location of the currently-active
230 /// #pragma clang arc_cf_code_audited begin.
231 SourceLocation PragmaARCCFCodeAuditedLoc;
233 /// \brief True if we hit the code-completion point.
234 bool CodeCompletionReached;
236 /// \brief The number of bytes that we will initially skip when entering the
237 /// main file, which is used when loading a precompiled preamble, along
238 /// with a flag that indicates whether skipping this number of bytes will
239 /// place the lexer at the start of a line.
240 std::pair<unsigned, bool> SkipMainFilePreamble;
242 /// CurLexer - This is the current top of the stack that we're lexing from if
243 /// not expanding a macro and we are lexing directly from source code.
244 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
245 OwningPtr<Lexer> CurLexer;
247 /// CurPTHLexer - This is the current top of stack that we're lexing from if
248 /// not expanding from a macro and we are lexing from a PTH cache.
249 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
250 OwningPtr<PTHLexer> CurPTHLexer;
252 /// CurPPLexer - This is the current top of the stack what we're lexing from
253 /// if not expanding a macro. This is an alias for either CurLexer or
255 PreprocessorLexer *CurPPLexer;
257 /// CurLookup - The DirectoryLookup structure used to find the current
258 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to
259 /// implement \#include_next and find directory-specific properties.
260 const DirectoryLookup *CurDirLookup;
262 /// CurTokenLexer - This is the current macro we are expanding, if we are
263 /// expanding a macro. One of CurLexer and CurTokenLexer must be null.
264 OwningPtr<TokenLexer> CurTokenLexer;
266 /// \brief The kind of lexer we're currently working with.
272 CLK_LexAfterModuleImport
275 /// IncludeMacroStack - This keeps track of the stack of files currently
276 /// \#included, and macros currently being expanded from, not counting
277 /// CurLexer/CurTokenLexer.
278 struct IncludeStackInfo {
279 enum CurLexerKind CurLexerKind;
281 PTHLexer *ThePTHLexer;
282 PreprocessorLexer *ThePPLexer;
283 TokenLexer *TheTokenLexer;
284 const DirectoryLookup *TheDirLookup;
286 IncludeStackInfo(enum CurLexerKind K, Lexer *L, PTHLexer* P,
287 PreprocessorLexer* PPL,
288 TokenLexer* TL, const DirectoryLookup *D)
289 : CurLexerKind(K), TheLexer(L), ThePTHLexer(P), ThePPLexer(PPL),
290 TheTokenLexer(TL), TheDirLookup(D) {}
292 std::vector<IncludeStackInfo> IncludeMacroStack;
294 /// Callbacks - These are actions invoked when some preprocessor activity is
295 /// encountered (e.g. a file is \#included, etc).
296 PPCallbacks *Callbacks;
298 struct MacroExpandsInfo {
302 MacroExpandsInfo(Token Tok, MacroDirective *MD, SourceRange Range)
303 : Tok(Tok), MD(MD), Range(Range) { }
305 SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks;
307 /// Macros - For each IdentifierInfo that was associated with a macro, we
308 /// keep a mapping to the history of all macro definitions and #undefs in
309 /// the reverse order (the latest one is in the head of the list).
310 llvm::DenseMap<const IdentifierInfo*, MacroDirective*> Macros;
311 friend class ASTReader;
313 /// \brief Macros that we want to warn because they are not used at the end
314 /// of the translation unit; we store just their SourceLocations instead
315 /// something like MacroInfo*. The benefit of this is that when we are
316 /// deserializing from PCH, we don't need to deserialize identifier & macros
317 /// just so that we can report that they are unused, we just warn using
318 /// the SourceLocations of this set (that will be filled by the ASTReader).
319 /// We are using SmallPtrSet instead of a vector for faster removal.
320 typedef llvm::SmallPtrSet<SourceLocation, 32> WarnUnusedMacroLocsTy;
321 WarnUnusedMacroLocsTy WarnUnusedMacroLocs;
323 /// MacroArgCache - This is a "freelist" of MacroArg objects that can be
324 /// reused for quick allocation.
325 MacroArgs *MacroArgCache;
326 friend class MacroArgs;
328 /// PragmaPushMacroInfo - For each IdentifierInfo used in a #pragma
329 /// push_macro directive, we keep a MacroInfo stack used to restore
330 /// previous macro value.
331 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> > PragmaPushMacroInfo;
333 // Various statistics we track for performance analysis.
334 unsigned NumDirectives, NumIncluded, NumDefined, NumUndefined, NumPragma;
335 unsigned NumIf, NumElse, NumEndif;
336 unsigned NumEnteredSourceFiles, MaxIncludeStackDepth;
337 unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded;
338 unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste;
341 /// Predefines - This string is the predefined macros that preprocessor
342 /// should use from the command line etc.
343 std::string Predefines;
345 /// \brief The file ID for the preprocessor predefines.
346 FileID PredefinesFileID;
348 /// TokenLexerCache - Cache macro expanders to reduce malloc traffic.
349 enum { TokenLexerCacheSize = 8 };
350 unsigned NumCachedTokenLexers;
351 TokenLexer *TokenLexerCache[TokenLexerCacheSize];
353 /// \brief Keeps macro expanded tokens for TokenLexers.
355 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
356 /// going to lex in the cache and when it finishes the tokens are removed
357 /// from the end of the cache.
358 SmallVector<Token, 16> MacroExpandedTokens;
359 std::vector<std::pair<TokenLexer *, size_t> > MacroExpandingLexersStack;
361 /// \brief A record of the macro definitions and expansions that
362 /// occurred during preprocessing.
364 /// This is an optional side structure that can be enabled with
365 /// \c createPreprocessingRecord() prior to preprocessing.
366 PreprocessingRecord *Record;
368 private: // Cached tokens state.
369 typedef SmallVector<Token, 1> CachedTokensTy;
371 /// CachedTokens - Cached tokens are stored here when we do backtracking or
372 /// lookahead. They are "lexed" by the CachingLex() method.
373 CachedTokensTy CachedTokens;
375 /// CachedLexPos - The position of the cached token that CachingLex() should
376 /// "lex" next. If it points beyond the CachedTokens vector, it means that
377 /// a normal Lex() should be invoked.
378 CachedTokensTy::size_type CachedLexPos;
380 /// BacktrackPositions - Stack of backtrack positions, allowing nested
381 /// backtracks. The EnableBacktrackAtThisPos() method pushes a position to
382 /// indicate where CachedLexPos should be set when the BackTrack() method is
383 /// invoked (at which point the last position is popped).
384 std::vector<CachedTokensTy::size_type> BacktrackPositions;
386 struct MacroInfoChain {
388 MacroInfoChain *Next;
389 MacroInfoChain *Prev;
392 /// MacroInfos are managed as a chain for easy disposal. This is the head
394 MacroInfoChain *MIChainHead;
396 /// MICache - A "freelist" of MacroInfo objects that can be reused for quick
398 MacroInfoChain *MICache;
401 Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
402 DiagnosticsEngine &diags, LangOptions &opts,
403 const TargetInfo *target,
404 SourceManager &SM, HeaderSearch &Headers,
405 ModuleLoader &TheModuleLoader,
406 IdentifierInfoLookup *IILookup = 0,
407 bool OwnsHeaderSearch = false,
408 bool DelayInitialization = false,
409 bool IncrProcessing = false);
413 /// \brief Initialize the preprocessor, if the constructor did not already
414 /// perform the initialization.
416 /// \param Target Information about the target.
417 void Initialize(const TargetInfo &Target);
419 /// \brief Retrieve the preprocessor options used to initialize this
421 PreprocessorOptions &getPreprocessorOpts() const { return *PPOpts; }
423 DiagnosticsEngine &getDiagnostics() const { return *Diags; }
424 void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; }
426 const LangOptions &getLangOpts() const { return LangOpts; }
427 const TargetInfo &getTargetInfo() const { return *Target; }
428 FileManager &getFileManager() const { return FileMgr; }
429 SourceManager &getSourceManager() const { return SourceMgr; }
430 HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
432 IdentifierTable &getIdentifierTable() { return Identifiers; }
433 SelectorTable &getSelectorTable() { return Selectors; }
434 Builtin::Context &getBuiltinInfo() { return BuiltinInfo; }
435 llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
437 void setPTHManager(PTHManager* pm);
439 PTHManager *getPTHManager() { return PTH.get(); }
441 void setExternalSource(ExternalPreprocessorSource *Source) {
442 ExternalSource = Source;
445 ExternalPreprocessorSource *getExternalSource() const {
446 return ExternalSource;
449 /// \brief Retrieve the module loader associated with this preprocessor.
450 ModuleLoader &getModuleLoader() const { return TheModuleLoader; }
452 /// \brief True if we are currently preprocessing a #if or #elif directive
453 bool isParsingIfOrElifDirective() const {
454 return ParsingIfOrElifDirective;
457 /// SetCommentRetentionState - Control whether or not the preprocessor retains
458 /// comments in output.
459 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
460 this->KeepComments = KeepComments | KeepMacroComments;
461 this->KeepMacroComments = KeepMacroComments;
464 bool getCommentRetentionState() const { return KeepComments; }
466 void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; }
467 bool getPragmasEnabled() const { return PragmasEnabled; }
469 void SetSuppressIncludeNotFoundError(bool Suppress) {
470 SuppressIncludeNotFoundError = Suppress;
473 bool GetSuppressIncludeNotFoundError() {
474 return SuppressIncludeNotFoundError;
477 /// Sets whether the preprocessor is responsible for producing output or if
478 /// it is producing tokens to be consumed by Parse and Sema.
479 void setPreprocessedOutput(bool IsPreprocessedOutput) {
480 PreprocessedOutput = IsPreprocessedOutput;
483 /// Returns true if the preprocessor is responsible for generating output,
484 /// false if it is producing tokens to be consumed by Parse and Sema.
485 bool isPreprocessedOutput() const { return PreprocessedOutput; }
487 /// isCurrentLexer - Return true if we are lexing directly from the specified
489 bool isCurrentLexer(const PreprocessorLexer *L) const {
490 return CurPPLexer == L;
493 /// getCurrentLexer - Return the current lexer being lexed from. Note
494 /// that this ignores any potentially active macro expansions and _Pragma
495 /// expansions going on at the time.
496 PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; }
498 /// getCurrentFileLexer - Return the current file lexer being lexed from.
499 /// Note that this ignores any potentially active macro expansions and _Pragma
500 /// expansions going on at the time.
501 PreprocessorLexer *getCurrentFileLexer() const;
503 /// \brief Returns the file ID for the preprocessor predefines.
504 FileID getPredefinesFileID() const { return PredefinesFileID; }
506 /// getPPCallbacks/addPPCallbacks - Accessors for preprocessor callbacks.
507 /// Note that this class takes ownership of any PPCallbacks object given to
509 PPCallbacks *getPPCallbacks() const { return Callbacks; }
510 void addPPCallbacks(PPCallbacks *C) {
512 C = new PPChainedCallbacks(C, Callbacks);
516 /// \brief Given an identifier, return its latest MacroDirective if it is
517 // \#defined or null if it isn't \#define'd.
518 MacroDirective *getMacroDirective(IdentifierInfo *II) const {
519 if (!II->hasMacroDefinition())
522 MacroDirective *MD = getMacroDirectiveHistory(II);
523 assert(MD->isDefined() && "Macro is undefined!");
527 const MacroInfo *getMacroInfo(IdentifierInfo *II) const {
528 return const_cast<Preprocessor*>(this)->getMacroInfo(II);
531 MacroInfo *getMacroInfo(IdentifierInfo *II) {
532 if (MacroDirective *MD = getMacroDirective(II))
533 return MD->getMacroInfo();
537 /// \brief Given an identifier, return the (probably #undef'd) MacroInfo
538 /// representing the most recent macro definition. One can iterate over all
539 /// previous macro definitions from it. This method should only be called for
540 /// identifiers that hadMacroDefinition().
541 MacroDirective *getMacroDirectiveHistory(const IdentifierInfo *II) const;
543 /// \brief Add a directive to the macro directive history for this identifier.
544 void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD);
545 DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI,
548 DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc, isImported);
549 appendMacroDirective(II, MD);
552 DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI){
553 return appendDefMacroDirective(II, MI, MI->getDefinitionLoc(), false);
555 /// \brief Set a MacroDirective that was loaded from a PCH file.
556 void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *MD);
558 /// macro_iterator/macro_begin/macro_end - This allows you to walk the macro
559 /// history table. Currently defined macros have
560 /// IdentifierInfo::hasMacroDefinition() set and an empty
561 /// MacroInfo::getUndefLoc() at the head of the list.
562 typedef llvm::DenseMap<const IdentifierInfo *,
563 MacroDirective*>::const_iterator macro_iterator;
564 macro_iterator macro_begin(bool IncludeExternalMacros = true) const;
565 macro_iterator macro_end(bool IncludeExternalMacros = true) const;
567 /// \brief Return the name of the macro defined before \p Loc that has
568 /// spelling \p Tokens. If there are multiple macros with same spelling,
569 /// return the last one defined.
570 StringRef getLastMacroWithSpelling(SourceLocation Loc,
571 ArrayRef<TokenValue> Tokens) const;
573 const std::string &getPredefines() const { return Predefines; }
574 /// setPredefines - Set the predefines for this Preprocessor. These
575 /// predefines are automatically injected when parsing the main file.
576 void setPredefines(const char *P) { Predefines = P; }
577 void setPredefines(const std::string &P) { Predefines = P; }
579 /// Return information about the specified preprocessor
580 /// identifier token.
581 IdentifierInfo *getIdentifierInfo(StringRef Name) const {
582 return &Identifiers.get(Name);
585 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
586 /// If 'Namespace' is non-null, then it is a token required to exist on the
587 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
588 void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler);
589 void AddPragmaHandler(PragmaHandler *Handler) {
590 AddPragmaHandler(StringRef(), Handler);
593 /// RemovePragmaHandler - Remove the specific pragma handler from
594 /// the preprocessor. If \p Namespace is non-null, then it should
595 /// be the namespace that \p Handler was added to. It is an error
596 /// to remove a handler that has not been registered.
597 void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler);
598 void RemovePragmaHandler(PragmaHandler *Handler) {
599 RemovePragmaHandler(StringRef(), Handler);
602 /// \brief Add the specified comment handler to the preprocessor.
603 void addCommentHandler(CommentHandler *Handler);
605 /// \brief Remove the specified comment handler.
607 /// It is an error to remove a handler that has not been registered.
608 void removeCommentHandler(CommentHandler *Handler);
610 /// \brief Set the code completion handler to the given object.
611 void setCodeCompletionHandler(CodeCompletionHandler &Handler) {
612 CodeComplete = &Handler;
615 /// \brief Retrieve the current code-completion handler.
616 CodeCompletionHandler *getCodeCompletionHandler() const {
620 /// \brief Clear out the code completion handler.
621 void clearCodeCompletionHandler() {
625 /// \brief Hook used by the lexer to invoke the "natural language" code
626 /// completion point.
627 void CodeCompleteNaturalLanguage();
629 /// \brief Retrieve the preprocessing record, or NULL if there is no
630 /// preprocessing record.
631 PreprocessingRecord *getPreprocessingRecord() const { return Record; }
633 /// \brief Create a new preprocessing record, which will keep track of
634 /// all macro expansions, macro definitions, etc.
635 void createPreprocessingRecord();
637 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
638 /// which implicitly adds the builtin defines etc.
639 void EnterMainSourceFile();
641 /// EndSourceFile - Inform the preprocessor callbacks that processing is
643 void EndSourceFile();
645 /// EnterSourceFile - Add a source file to the top of the include stack and
646 /// start lexing tokens from it instead of the current buffer. Emit an error
647 /// and don't enter the file on error.
648 void EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir,
651 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
652 /// tokens from it instead of the current buffer. Args specifies the
653 /// tokens input to a function-like macro.
655 /// ILEnd specifies the location of the ')' for a function-like macro or the
656 /// identifier for an object-like macro.
657 void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroInfo *Macro,
660 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
661 /// which will cause the lexer to start returning the specified tokens.
663 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
664 /// not be subject to further macro expansion. Otherwise, these tokens will
665 /// be re-macro-expanded when/if expansion is enabled.
667 /// If OwnsTokens is false, this method assumes that the specified stream of
668 /// tokens has a permanent owner somewhere, so they do not need to be copied.
669 /// If it is true, it assumes the array of tokens is allocated with new[] and
672 void EnterTokenStream(const Token *Toks, unsigned NumToks,
673 bool DisableMacroExpansion, bool OwnsTokens);
675 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
676 /// lexer stack. This should only be used in situations where the current
677 /// state of the top-of-stack lexer is known.
678 void RemoveTopOfLexerStack();
680 /// EnableBacktrackAtThisPos - From the point that this method is called, and
681 /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
682 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
683 /// make the Preprocessor re-lex the same tokens.
685 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
686 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
687 /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
689 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
690 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
691 /// tokens will continue indefinitely.
693 void EnableBacktrackAtThisPos();
695 /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call.
696 void CommitBacktrackedTokens();
698 /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since
699 /// EnableBacktrackAtThisPos() was previously called.
702 /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and
703 /// caching of tokens is on.
704 bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
706 /// Lex - To lex a token from the preprocessor, just pull a token from the
707 /// current lexer or macro object.
708 void Lex(Token &Result) {
709 switch (CurLexerKind) {
710 case CLK_Lexer: CurLexer->Lex(Result); break;
711 case CLK_PTHLexer: CurPTHLexer->Lex(Result); break;
712 case CLK_TokenLexer: CurTokenLexer->Lex(Result); break;
713 case CLK_CachingLexer: CachingLex(Result); break;
714 case CLK_LexAfterModuleImport: LexAfterModuleImport(Result); break;
718 void LexAfterModuleImport(Token &Result);
720 /// \brief Lex a string literal, which may be the concatenation of multiple
721 /// string literals and may even come from macro expansion.
722 /// \returns true on success, false if a error diagnostic has been generated.
723 bool LexStringLiteral(Token &Result, std::string &String,
724 const char *DiagnosticTag, bool AllowMacroExpansion) {
725 if (AllowMacroExpansion)
728 LexUnexpandedToken(Result);
729 return FinishLexStringLiteral(Result, String, DiagnosticTag,
730 AllowMacroExpansion);
733 /// \brief Complete the lexing of a string literal where the first token has
734 /// already been lexed (see LexStringLiteral).
735 bool FinishLexStringLiteral(Token &Result, std::string &String,
736 const char *DiagnosticTag,
737 bool AllowMacroExpansion);
739 /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get
740 /// something not a comment. This is useful in -E -C mode where comments
741 /// would foul up preprocessor directive handling.
742 void LexNonComment(Token &Result) {
745 while (Result.getKind() == tok::comment);
748 /// LexUnexpandedToken - This is just like Lex, but this disables macro
749 /// expansion of identifier tokens.
750 void LexUnexpandedToken(Token &Result) {
751 // Disable macro expansion.
752 bool OldVal = DisableMacroExpansion;
753 DisableMacroExpansion = true;
758 DisableMacroExpansion = OldVal;
761 /// LexUnexpandedNonComment - Like LexNonComment, but this disables macro
762 /// expansion of identifier tokens.
763 void LexUnexpandedNonComment(Token &Result) {
765 LexUnexpandedToken(Result);
766 while (Result.getKind() == tok::comment);
769 /// Disables macro expansion everywhere except for preprocessor directives.
770 void SetMacroExpansionOnlyInDirectives() {
771 DisableMacroExpansion = true;
772 MacroExpansionInDirectivesOverride = true;
775 /// LookAhead - This peeks ahead N tokens and returns that token without
776 /// consuming any tokens. LookAhead(0) returns the next token that would be
777 /// returned by Lex(), LookAhead(1) returns the token after it, etc. This
778 /// returns normal tokens after phase 5. As such, it is equivalent to using
779 /// 'Lex', not 'LexUnexpandedToken'.
780 const Token &LookAhead(unsigned N) {
781 if (CachedLexPos + N < CachedTokens.size())
782 return CachedTokens[CachedLexPos+N];
784 return PeekAhead(N+1);
787 /// RevertCachedTokens - When backtracking is enabled and tokens are cached,
788 /// this allows to revert a specific number of tokens.
789 /// Note that the number of tokens being reverted should be up to the last
790 /// backtrack position, not more.
791 void RevertCachedTokens(unsigned N) {
792 assert(isBacktrackEnabled() &&
793 "Should only be called when tokens are cached for backtracking");
794 assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back())
795 && "Should revert tokens up to the last backtrack position, not more");
796 assert(signed(CachedLexPos) - signed(N) >= 0 &&
797 "Corrupted backtrack positions ?");
801 /// EnterToken - Enters a token in the token stream to be lexed next. If
802 /// BackTrack() is called afterwards, the token will remain at the insertion
804 void EnterToken(const Token &Tok) {
805 EnterCachingLexMode();
806 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
809 /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching
810 /// tokens (because backtrack is enabled) it should replace the most recent
811 /// cached tokens with the given annotation token. This function has no effect
812 /// if backtracking is not enabled.
814 /// Note that the use of this function is just for optimization; so that the
815 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
817 void AnnotateCachedTokens(const Token &Tok) {
818 assert(Tok.isAnnotation() && "Expected annotation token");
819 if (CachedLexPos != 0 && isBacktrackEnabled())
820 AnnotatePreviousCachedTokens(Tok);
823 /// \brief Replace the last token with an annotation token.
825 /// Like AnnotateCachedTokens(), this routine replaces an
826 /// already-parsed (and resolved) token with an annotation
827 /// token. However, this routine only replaces the last token with
828 /// the annotation token; it does not affect any other cached
829 /// tokens. This function has no effect if backtracking is not
831 void ReplaceLastTokenWithAnnotation(const Token &Tok) {
832 assert(Tok.isAnnotation() && "Expected annotation token");
833 if (CachedLexPos != 0 && isBacktrackEnabled())
834 CachedTokens[CachedLexPos-1] = Tok;
837 /// TypoCorrectToken - Update the current token to represent the provided
838 /// identifier, in order to cache an action performed by typo correction.
839 void TypoCorrectToken(const Token &Tok) {
840 assert(Tok.getIdentifierInfo() && "Expected identifier token");
841 if (CachedLexPos != 0 && isBacktrackEnabled())
842 CachedTokens[CachedLexPos-1] = Tok;
845 /// \brief Recompute the current lexer kind based on the CurLexer/CurPTHLexer/
846 /// CurTokenLexer pointers.
847 void recomputeCurLexerKind();
849 /// \brief Returns true if incremental processing is enabled
850 bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; }
852 /// \brief Enables the incremental processing
853 void enableIncrementalProcessing(bool value = true) {
854 IncrementalProcessing = value;
857 /// \brief Specify the point at which code-completion will be performed.
859 /// \param File the file in which code completion should occur. If
860 /// this file is included multiple times, code-completion will
861 /// perform completion the first time it is included. If NULL, this
862 /// function clears out the code-completion point.
864 /// \param Line the line at which code completion should occur
867 /// \param Column the column at which code completion should occur
870 /// \returns true if an error occurred, false otherwise.
871 bool SetCodeCompletionPoint(const FileEntry *File,
872 unsigned Line, unsigned Column);
874 /// \brief Determine if we are performing code completion.
875 bool isCodeCompletionEnabled() const { return CodeCompletionFile != 0; }
877 /// \brief Returns the location of the code-completion point.
878 /// Returns an invalid location if code-completion is not enabled or the file
879 /// containing the code-completion point has not been lexed yet.
880 SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; }
882 /// \brief Returns the start location of the file of code-completion point.
883 /// Returns an invalid location if code-completion is not enabled or the file
884 /// containing the code-completion point has not been lexed yet.
885 SourceLocation getCodeCompletionFileLoc() const {
886 return CodeCompletionFileLoc;
889 /// \brief Returns true if code-completion is enabled and we have hit the
890 /// code-completion point.
891 bool isCodeCompletionReached() const { return CodeCompletionReached; }
893 /// \brief Note that we hit the code-completion point.
894 void setCodeCompletionReached() {
895 assert(isCodeCompletionEnabled() && "Code-completion not enabled!");
896 CodeCompletionReached = true;
897 // Silence any diagnostics that occur after we hit the code-completion.
898 getDiagnostics().setSuppressAllDiagnostics(true);
901 /// \brief The location of the currently-active \#pragma clang
902 /// arc_cf_code_audited begin. Returns an invalid location if there
903 /// is no such pragma active.
904 SourceLocation getPragmaARCCFCodeAuditedLoc() const {
905 return PragmaARCCFCodeAuditedLoc;
908 /// \brief Set the location of the currently-active \#pragma clang
909 /// arc_cf_code_audited begin. An invalid location ends the pragma.
910 void setPragmaARCCFCodeAuditedLoc(SourceLocation Loc) {
911 PragmaARCCFCodeAuditedLoc = Loc;
914 /// \brief Instruct the preprocessor to skip part of the main source file.
916 /// \param Bytes The number of bytes in the preamble to skip.
918 /// \param StartOfLine Whether skipping these bytes puts the lexer at the
920 void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) {
921 SkipMainFilePreamble.first = Bytes;
922 SkipMainFilePreamble.second = StartOfLine;
925 /// Diag - Forwarding function for diagnostics. This emits a diagnostic at
926 /// the specified Token's location, translating the token's start
927 /// position in the current buffer into a SourcePosition object for rendering.
928 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const {
929 return Diags->Report(Loc, DiagID);
932 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const {
933 return Diags->Report(Tok.getLocation(), DiagID);
936 /// getSpelling() - Return the 'spelling' of the token at the given
937 /// location; does not go up to the spelling location or down to the
938 /// expansion location.
940 /// \param buffer A buffer which will be used only if the token requires
941 /// "cleaning", e.g. if it contains trigraphs or escaped newlines
942 /// \param invalid If non-null, will be set \c true if an error occurs.
943 StringRef getSpelling(SourceLocation loc,
944 SmallVectorImpl<char> &buffer,
945 bool *invalid = 0) const {
946 return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid);
949 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a
950 /// token is the characters used to represent the token in the source file
951 /// after trigraph expansion and escaped-newline folding. In particular, this
952 /// wants to get the true, uncanonicalized, spelling of things like digraphs
955 /// \param Invalid If non-null, will be set \c true if an error occurs.
956 std::string getSpelling(const Token &Tok, bool *Invalid = 0) const {
957 return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid);
960 /// getSpelling - This method is used to get the spelling of a token into a
961 /// preallocated buffer, instead of as an std::string. The caller is required
962 /// to allocate enough space for the token, which is guaranteed to be at least
963 /// Tok.getLength() bytes long. The length of the actual result is returned.
965 /// Note that this method may do two possible things: it may either fill in
966 /// the buffer specified with characters, or it may *change the input pointer*
967 /// to point to a constant buffer with the data already in it (avoiding a
968 /// copy). The caller is not allowed to modify the returned buffer pointer
969 /// if an internal buffer is returned.
970 unsigned getSpelling(const Token &Tok, const char *&Buffer,
971 bool *Invalid = 0) const {
972 return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid);
975 /// getSpelling - This method is used to get the spelling of a token into a
976 /// SmallVector. Note that the returned StringRef may not point to the
977 /// supplied buffer if a copy can be avoided.
978 StringRef getSpelling(const Token &Tok,
979 SmallVectorImpl<char> &Buffer,
980 bool *Invalid = 0) const;
982 /// \brief Relex the token at the specified location.
983 /// \returns true if there was a failure, false on success.
984 bool getRawToken(SourceLocation Loc, Token &Result) {
985 return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts);
988 /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric constant
989 /// with length 1, return the character.
990 char getSpellingOfSingleCharacterNumericConstant(const Token &Tok,
991 bool *Invalid = 0) const {
992 assert(Tok.is(tok::numeric_constant) &&
993 Tok.getLength() == 1 && "Called on unsupported token");
994 assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
996 // If the token is carrying a literal data pointer, just use it.
997 if (const char *D = Tok.getLiteralData())
1000 // Otherwise, fall back on getCharacterData, which is slower, but always
1002 return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid);
1005 /// \brief Retrieve the name of the immediate macro expansion.
1007 /// This routine starts from a source location, and finds the name of the macro
1008 /// responsible for its immediate expansion. It looks through any intervening
1009 /// macro argument expansions to compute this. It returns a StringRef which
1010 /// refers to the SourceManager-owned buffer of the source where that macro
1011 /// name is spelled. Thus, the result shouldn't out-live the SourceManager.
1012 StringRef getImmediateMacroName(SourceLocation Loc) {
1013 return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts());
1016 /// CreateString - Plop the specified string into a scratch buffer and set the
1017 /// specified token's location and length to it. If specified, the source
1018 /// location provides a location of the expansion point of the token.
1019 void CreateString(StringRef Str, Token &Tok,
1020 SourceLocation ExpansionLocStart = SourceLocation(),
1021 SourceLocation ExpansionLocEnd = SourceLocation());
1023 /// \brief Computes the source location just past the end of the
1024 /// token at this source location.
1026 /// This routine can be used to produce a source location that
1027 /// points just past the end of the token referenced by \p Loc, and
1028 /// is generally used when a diagnostic needs to point just after a
1029 /// token where it expected something different that it received. If
1030 /// the returned source location would not be meaningful (e.g., if
1031 /// it points into a macro), this routine returns an invalid
1032 /// source location.
1034 /// \param Offset an offset from the end of the token, where the source
1035 /// location should refer to. The default offset (0) produces a source
1036 /// location pointing just past the end of the token; an offset of 1 produces
1037 /// a source location pointing to the last character in the token, etc.
1038 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0) {
1039 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
1042 /// \brief Returns true if the given MacroID location points at the first
1043 /// token of the macro expansion.
1045 /// \param MacroBegin If non-null and function returns true, it is set to
1046 /// begin location of the macro.
1047 bool isAtStartOfMacroExpansion(SourceLocation loc,
1048 SourceLocation *MacroBegin = 0) const {
1049 return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts,
1053 /// \brief Returns true if the given MacroID location points at the last
1054 /// token of the macro expansion.
1056 /// \param MacroEnd If non-null and function returns true, it is set to
1057 /// end location of the macro.
1058 bool isAtEndOfMacroExpansion(SourceLocation loc,
1059 SourceLocation *MacroEnd = 0) const {
1060 return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd);
1063 /// DumpToken - Print the token to stderr, used for debugging.
1065 void DumpToken(const Token &Tok, bool DumpFlags = false) const;
1066 void DumpLocation(SourceLocation Loc) const;
1067 void DumpMacro(const MacroInfo &MI) const;
1069 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
1070 /// token, return a new location that specifies a character within the token.
1071 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
1072 unsigned Char) const {
1073 return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts);
1076 /// IncrementPasteCounter - Increment the counters for the number of token
1077 /// paste operations performed. If fast was specified, this is a 'fast paste'
1078 /// case we handled.
1080 void IncrementPasteCounter(bool isFast) {
1082 ++NumFastTokenPaste;
1089 size_t getTotalMemory() const;
1091 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
1092 /// comment (/##/) in microsoft mode, this method handles updating the current
1093 /// state, returning the token on the next source line.
1094 void HandleMicrosoftCommentPaste(Token &Tok);
1096 //===--------------------------------------------------------------------===//
1097 // Preprocessor callback methods. These are invoked by a lexer as various
1098 // directives and events are found.
1100 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
1101 /// identifier information for the token and install it into the token,
1102 /// updating the token kind accordingly.
1103 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const;
1106 llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons;
1110 // SetPoisonReason - Call this function to indicate the reason for
1111 // poisoning an identifier. If that identifier is accessed while
1112 // poisoned, then this reason will be used instead of the default
1113 // "poisoned" diagnostic.
1114 void SetPoisonReason(IdentifierInfo *II, unsigned DiagID);
1116 // HandlePoisonedIdentifier - Display reason for poisoned
1118 void HandlePoisonedIdentifier(Token & Tok);
1120 void MaybeHandlePoisonedIdentifier(Token & Identifier) {
1121 if(IdentifierInfo * II = Identifier.getIdentifierInfo()) {
1122 if(II->isPoisoned()) {
1123 HandlePoisonedIdentifier(Identifier);
1129 /// Identifiers used for SEH handling in Borland. These are only
1130 /// allowed in particular circumstances
1132 IdentifierInfo *Ident__exception_code,
1133 *Ident___exception_code,
1134 *Ident_GetExceptionCode;
1135 // __except filter expression
1136 IdentifierInfo *Ident__exception_info,
1137 *Ident___exception_info,
1138 *Ident_GetExceptionInfo;
1140 IdentifierInfo *Ident__abnormal_termination,
1141 *Ident___abnormal_termination,
1142 *Ident_AbnormalTermination;
1144 void PoisonSEHIdentifiers(bool Poison = true); // Borland
1146 /// HandleIdentifier - This callback is invoked when the lexer reads an
1147 /// identifier and has filled in the tokens IdentifierInfo member. This
1148 /// callback potentially macro expands it or turns it into a named token (like
1150 void HandleIdentifier(Token &Identifier);
1153 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1154 /// the current file. This either returns the EOF token and returns true, or
1155 /// pops a level off the include stack and returns false, at which point the
1156 /// client should call lex again.
1157 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
1159 /// HandleEndOfTokenLexer - This callback is invoked when the current
1160 /// TokenLexer hits the end of its token stream.
1161 bool HandleEndOfTokenLexer(Token &Result);
1163 /// HandleDirective - This callback is invoked when the lexer sees a # token
1164 /// at the start of a line. This consumes the directive, modifies the
1165 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
1166 /// read is the correct one.
1167 void HandleDirective(Token &Result);
1169 /// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
1170 /// not, emit a diagnostic and consume up until the eod. If EnableMacros is
1171 /// true, then we consider macros that expand to zero tokens as being ok.
1172 void CheckEndOfDirective(const char *Directive, bool EnableMacros = false);
1174 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1175 /// current line until the tok::eod token is found.
1176 void DiscardUntilEndOfDirective();
1178 /// SawDateOrTime - This returns true if the preprocessor has seen a use of
1179 /// __DATE__ or __TIME__ in the file so far.
1180 bool SawDateOrTime() const {
1181 return DATELoc != SourceLocation() || TIMELoc != SourceLocation();
1183 unsigned getCounterValue() const { return CounterValue; }
1184 void setCounterValue(unsigned V) { CounterValue = V; }
1186 /// \brief Retrieves the module that we're currently building, if any.
1187 Module *getCurrentModule();
1189 /// \brief Allocate a new MacroInfo object with the provided SourceLocation.
1190 MacroInfo *AllocateMacroInfo(SourceLocation L);
1192 /// \brief Allocate a new MacroInfo object loaded from an AST file.
1193 MacroInfo *AllocateDeserializedMacroInfo(SourceLocation L,
1194 unsigned SubModuleID);
1196 /// \brief Turn the specified lexer token into a fully checked and spelled
1197 /// filename, e.g. as an operand of \#include.
1199 /// The caller is expected to provide a buffer that is large enough to hold
1200 /// the spelling of the filename, but is also expected to handle the case
1201 /// when this method decides to use a different buffer.
1203 /// \returns true if the input filename was in <>'s or false if it was
1205 bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Filename);
1207 /// \brief Given a "foo" or \<foo> reference, look up the indicated file.
1209 /// Returns null on failure. \p isAngled indicates whether the file
1210 /// reference is for system \#include's or not (i.e. using <> instead of "").
1211 const FileEntry *LookupFile(StringRef Filename,
1212 bool isAngled, const DirectoryLookup *FromDir,
1213 const DirectoryLookup *&CurDir,
1214 SmallVectorImpl<char> *SearchPath,
1215 SmallVectorImpl<char> *RelativePath,
1216 Module **SuggestedModule,
1217 bool SkipCache = false);
1219 /// GetCurLookup - The DirectoryLookup structure used to find the current
1220 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to
1221 /// implement \#include_next and find directory-specific properties.
1222 const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; }
1224 /// \brief Return true if we're in the top-level file, not in a \#include.
1225 bool isInPrimaryFile() const;
1227 /// ConcatenateIncludeName - Handle cases where the \#include name is expanded
1228 /// from a macro as multiple tokens, which need to be glued together. This
1229 /// occurs for code like:
1231 /// \#define FOO <x/y.h>
1234 /// because in this case, "<x/y.h>" is returned as 7 tokens, not one.
1236 /// This code concatenates and consumes tokens up to the '>' token. It
1237 /// returns false if the > was found, otherwise it returns true if it finds
1238 /// and consumes the EOD marker.
1239 bool ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
1240 SourceLocation &End);
1242 /// LexOnOffSwitch - Lex an on-off-switch (C99 6.10.6p2) and verify that it is
1243 /// followed by EOD. Return true if the token is not a valid on-off-switch.
1244 bool LexOnOffSwitch(tok::OnOffSwitch &OOS);
1248 void PushIncludeMacroStack() {
1249 IncludeMacroStack.push_back(IncludeStackInfo(CurLexerKind,
1253 CurTokenLexer.take(),
1258 void PopIncludeMacroStack() {
1259 CurLexer.reset(IncludeMacroStack.back().TheLexer);
1260 CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer);
1261 CurPPLexer = IncludeMacroStack.back().ThePPLexer;
1262 CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer);
1263 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
1264 CurLexerKind = IncludeMacroStack.back().CurLexerKind;
1265 IncludeMacroStack.pop_back();
1268 /// \brief Allocate a new MacroInfo object.
1269 MacroInfo *AllocateMacroInfo();
1271 DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI,
1274 UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc);
1275 VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc,
1278 /// \brief Release the specified MacroInfo for re-use.
1280 /// This memory will be reused for allocating new MacroInfo objects.
1281 void ReleaseMacroInfo(MacroInfo* MI);
1283 /// ReadMacroName - Lex and validate a macro name, which occurs after a
1284 /// \#define or \#undef. This emits a diagnostic, sets the token kind to eod,
1285 /// and discards the rest of the macro line if the macro name is invalid.
1286 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0);
1288 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1289 /// definition has just been read. Lex the rest of the arguments and the
1290 /// closing ), updating MI with what we learn and saving in LastTok the
1291 /// last token read.
1292 /// Return true if an error occurs parsing the arg list.
1293 bool ReadMacroDefinitionArgList(MacroInfo *MI, Token& LastTok);
1295 /// We just read a \#if or related directive and decided that the
1296 /// subsequent tokens are in the \#if'd out portion of the
1297 /// file. Lex the rest of the file, until we see an \#endif. If \p
1298 /// FoundNonSkipPortion is true, then we have already emitted code for part of
1299 /// this \#if directive, so \#else/\#elif blocks should never be entered. If
1300 /// \p FoundElse is false, then \#else directives are ok, if not, then we have
1301 /// already seen one so a \#else directive is a duplicate. When this returns,
1302 /// the caller can lex the first valid token.
1303 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1304 bool FoundNonSkipPortion, bool FoundElse,
1305 SourceLocation ElseLoc = SourceLocation());
1307 /// \brief A fast PTH version of SkipExcludedConditionalBlock.
1308 void PTHSkipExcludedConditionalBlock();
1310 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
1311 /// may occur after a #if or #elif directive and return it as a bool. If the
1312 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro.
1313 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
1315 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1316 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1317 void RegisterBuiltinPragmas();
1319 /// \brief Register builtin macros such as __LINE__ with the identifier table.
1320 void RegisterBuiltinMacros();
1322 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to
1323 /// be expanded as a macro, handle it and return the next token as 'Tok'. If
1324 /// the macro should not be expanded return true, otherwise return false.
1325 bool HandleMacroExpandedIdentifier(Token &Tok, MacroDirective *MD);
1327 /// \brief Cache macro expanded tokens for TokenLexers.
1329 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1330 /// going to lex in the cache and when it finishes the tokens are removed
1331 /// from the end of the cache.
1332 Token *cacheMacroExpandedTokens(TokenLexer *tokLexer,
1333 ArrayRef<Token> tokens);
1334 void removeCachedMacroExpandedTokensOfLastLexer();
1335 friend void TokenLexer::ExpandFunctionArguments();
1337 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
1338 /// lexed is a '('. If so, consume the token and return true, if not, this
1339 /// method should have no observable side-effect on the lexed tokens.
1340 bool isNextPPTokenLParen();
1342 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
1343 /// invoked to read all of the formal arguments specified for the macro
1344 /// invocation. This returns null on error.
1345 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI,
1346 SourceLocation &ExpansionEnd);
1348 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1349 /// as a builtin macro, handle it and return the next token as 'Tok'.
1350 void ExpandBuiltinMacro(Token &Tok);
1352 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
1353 /// return the first token after the directive. The _Pragma token has just
1354 /// been read into 'Tok'.
1355 void Handle_Pragma(Token &Tok);
1357 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
1358 /// is not enclosed within a string literal.
1359 void HandleMicrosoft__pragma(Token &Tok);
1361 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and
1362 /// start lexing tokens from it instead of the current buffer.
1363 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
1365 /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and
1366 /// start getting tokens from it using the PTH cache.
1367 void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir);
1369 /// \brief Set the file ID for the preprocessor predefines.
1370 void setPredefinesFileID(FileID FID) {
1371 assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!");
1372 PredefinesFileID = FID;
1375 /// IsFileLexer - Returns true if we are lexing from a file and not a
1376 /// pragma or a macro.
1377 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
1378 return L ? !L->isPragmaLexer() : P != 0;
1381 static bool IsFileLexer(const IncludeStackInfo& I) {
1382 return IsFileLexer(I.TheLexer, I.ThePPLexer);
1385 bool IsFileLexer() const {
1386 return IsFileLexer(CurLexer.get(), CurPPLexer);
1389 //===--------------------------------------------------------------------===//
1391 void CachingLex(Token &Result);
1392 bool InCachingLexMode() const {
1393 // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means
1394 // that we are past EOF, not that we are in CachingLex mode.
1395 return CurPPLexer == 0 && CurTokenLexer == 0 && CurPTHLexer == 0 &&
1396 !IncludeMacroStack.empty();
1398 void EnterCachingLexMode();
1399 void ExitCachingLexMode() {
1400 if (InCachingLexMode())
1401 RemoveTopOfLexerStack();
1403 const Token &PeekAhead(unsigned N);
1404 void AnnotatePreviousCachedTokens(const Token &Tok);
1406 //===--------------------------------------------------------------------===//
1407 /// Handle*Directive - implement the various preprocessor directives. These
1408 /// should side-effect the current preprocessor object so that the next call
1409 /// to Lex() will return the appropriate token next.
1410 void HandleLineDirective(Token &Tok);
1411 void HandleDigitDirective(Token &Tok);
1412 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
1413 void HandleIdentSCCSDirective(Token &Tok);
1414 void HandleMacroPublicDirective(Token &Tok);
1415 void HandleMacroPrivateDirective(Token &Tok);
1418 void HandleIncludeDirective(SourceLocation HashLoc,
1420 const DirectoryLookup *LookupFrom = 0,
1421 bool isImport = false);
1422 void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok);
1423 void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok);
1424 void HandleImportDirective(SourceLocation HashLoc, Token &Tok);
1425 void HandleMicrosoftImportDirective(Token &Tok);
1428 void HandleDefineDirective(Token &Tok);
1429 void HandleUndefDirective(Token &Tok);
1431 // Conditional Inclusion.
1432 void HandleIfdefDirective(Token &Tok, bool isIfndef,
1433 bool ReadAnyTokensBeforeDirective);
1434 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective);
1435 void HandleEndifDirective(Token &Tok);
1436 void HandleElseDirective(Token &Tok);
1437 void HandleElifDirective(Token &Tok);
1440 void HandlePragmaDirective(unsigned Introducer);
1442 void HandlePragmaOnce(Token &OnceTok);
1443 void HandlePragmaMark();
1444 void HandlePragmaPoison(Token &PoisonTok);
1445 void HandlePragmaSystemHeader(Token &SysHeaderTok);
1446 void HandlePragmaDependency(Token &DependencyTok);
1447 void HandlePragmaComment(Token &CommentTok);
1448 void HandlePragmaMessage(Token &MessageTok);
1449 void HandlePragmaPushMacro(Token &Tok);
1450 void HandlePragmaPopMacro(Token &Tok);
1451 void HandlePragmaIncludeAlias(Token &Tok);
1452 IdentifierInfo *ParsePragmaPushOrPopMacro(Token &Tok);
1454 // Return true and store the first token only if any CommentHandler
1455 // has inserted some tokens and getCommentRetentionState() is false.
1456 bool HandleComment(Token &Token, SourceRange Comment);
1458 /// \brief A macro is used, update information about macros that need unused
1460 void markMacroAsUsed(MacroInfo *MI);
1463 /// \brief Abstract base class that describes a handler that will receive
1464 /// source ranges for each of the comments encountered in the source file.
1465 class CommentHandler {
1467 virtual ~CommentHandler();
1469 // The handler shall return true if it has pushed any tokens
1470 // to be read using e.g. EnterToken or EnterTokenStream.
1471 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
1474 } // end namespace clang