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/ModuleMap.h"
24 #include "clang/Lex/PPCallbacks.h"
25 #include "clang/Lex/PTHLexer.h"
26 #include "clang/Lex/PTHManager.h"
27 #include "clang/Lex/TokenLexer.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/IntrusiveRefCntPtr.h"
31 #include "llvm/ADT/OwningPtr.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/Support/Allocator.h"
38 template<unsigned InternalLen> class SmallString;
44 class ExternalPreprocessorSource;
48 class PragmaNamespace;
54 class CodeCompletionHandler;
55 class DirectoryLookup;
56 class PreprocessingRecord;
58 class PreprocessorOptions;
60 /// \brief Stores token information for comparing actual tokens with
61 /// predefined values. Only handles simple tokens and identifiers.
67 TokenValue(tok::TokenKind Kind) : Kind(Kind), II(0) {
68 assert(Kind != tok::raw_identifier && "Raw identifiers are not supported.");
69 assert(Kind != tok::identifier &&
70 "Identifiers should be created by TokenValue(IdentifierInfo *)");
71 assert(!tok::isLiteral(Kind) && "Literals are not supported.");
72 assert(!tok::isAnnotation(Kind) && "Annotations are not supported.");
74 TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {}
75 bool operator==(const Token &Tok) const {
76 return Tok.getKind() == Kind &&
77 (!II || II == Tok.getIdentifierInfo());
81 /// Preprocessor - This object engages in a tight little dance with the lexer to
82 /// efficiently preprocess tokens. Lexers know only about tokens within a
83 /// single source file, and don't know anything about preprocessor-level issues
84 /// like the \#include stack, token expansion, etc.
86 class Preprocessor : public RefCountedBase<Preprocessor> {
87 IntrusiveRefCntPtr<PreprocessorOptions> PPOpts;
88 DiagnosticsEngine *Diags;
89 LangOptions &LangOpts;
90 const TargetInfo *Target;
92 SourceManager &SourceMgr;
93 ScratchBuffer *ScratchBuf;
94 HeaderSearch &HeaderInfo;
95 ModuleLoader &TheModuleLoader;
97 /// \brief External source of macros.
98 ExternalPreprocessorSource *ExternalSource;
101 /// PTH - An optional PTHManager object used for getting tokens from
102 /// a token cache rather than lexing the original source file.
103 OwningPtr<PTHManager> PTH;
105 /// BP - A BumpPtrAllocator object used to quickly allocate and release
106 /// objects internal to the Preprocessor.
107 llvm::BumpPtrAllocator BP;
109 /// Identifiers for builtin macros and other builtins.
110 IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__
111 IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__
112 IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__
113 IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__
114 IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__
115 IdentifierInfo *Ident__COUNTER__; // __COUNTER__
116 IdentifierInfo *Ident_Pragma, *Ident__pragma; // _Pragma, __pragma
117 IdentifierInfo *Ident__VA_ARGS__; // __VA_ARGS__
118 IdentifierInfo *Ident__has_feature; // __has_feature
119 IdentifierInfo *Ident__has_extension; // __has_extension
120 IdentifierInfo *Ident__has_builtin; // __has_builtin
121 IdentifierInfo *Ident__has_attribute; // __has_attribute
122 IdentifierInfo *Ident__has_include; // __has_include
123 IdentifierInfo *Ident__has_include_next; // __has_include_next
124 IdentifierInfo *Ident__has_warning; // __has_warning
125 IdentifierInfo *Ident__building_module; // __building_module
126 IdentifierInfo *Ident__MODULE__; // __MODULE__
128 SourceLocation DATELoc, TIMELoc;
129 unsigned CounterValue; // Next __COUNTER__ value.
132 /// MaxIncludeStackDepth - Maximum depth of \#includes.
133 MaxAllowedIncludeStackDepth = 200
136 // State that is set before the preprocessor begins.
137 bool KeepComments : 1;
138 bool KeepMacroComments : 1;
139 bool SuppressIncludeNotFoundError : 1;
141 // State that changes while the preprocessor runs:
142 bool InMacroArgs : 1; // True if parsing fn macro invocation args.
144 /// Whether the preprocessor owns the header search object.
145 bool OwnsHeaderSearch : 1;
147 /// DisableMacroExpansion - True if macro expansion is disabled.
148 bool DisableMacroExpansion : 1;
150 /// MacroExpansionInDirectivesOverride - Temporarily disables
151 /// DisableMacroExpansion (i.e. enables expansion) when parsing preprocessor
153 bool MacroExpansionInDirectivesOverride : 1;
155 class ResetMacroExpansionHelper;
157 /// \brief Whether we have already loaded macros from the external source.
158 mutable bool ReadMacrosFromExternalSource : 1;
160 /// \brief True if pragmas are enabled.
161 bool PragmasEnabled : 1;
163 /// \brief True if the current build action is a preprocessing action.
164 bool PreprocessedOutput : 1;
166 /// \brief True if we are currently preprocessing a #if or #elif directive
167 bool ParsingIfOrElifDirective;
169 /// \brief True if we are pre-expanding macro arguments.
170 bool InMacroArgPreExpansion;
172 /// Identifiers - This is mapping/lookup information for all identifiers in
173 /// the program, including program keywords.
174 mutable IdentifierTable Identifiers;
176 /// Selectors - This table contains all the selectors in the program. Unlike
177 /// IdentifierTable above, this table *isn't* populated by the preprocessor.
178 /// It is declared/expanded here because it's role/lifetime is
179 /// conceptually similar the IdentifierTable. In addition, the current control
180 /// flow (in clang::ParseAST()), make it convenient to put here.
181 /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to
182 /// the lifetime of the preprocessor.
183 SelectorTable Selectors;
185 /// BuiltinInfo - Information about builtins.
186 Builtin::Context BuiltinInfo;
188 /// PragmaHandlers - This tracks all of the pragmas that the client registered
189 /// with this preprocessor.
190 PragmaNamespace *PragmaHandlers;
192 /// \brief Tracks all of the comment handlers that the client registered
193 /// with this preprocessor.
194 std::vector<CommentHandler *> CommentHandlers;
196 /// \brief True if we want to ignore EOF token and continue later on (thus
197 /// avoid tearing the Lexer and etc. down).
198 bool IncrementalProcessing;
200 /// \brief The code-completion handler.
201 CodeCompletionHandler *CodeComplete;
203 /// \brief The file that we're performing code-completion for, if any.
204 const FileEntry *CodeCompletionFile;
206 /// \brief The offset in file for the code-completion point.
207 unsigned CodeCompletionOffset;
209 /// \brief The location for the code-completion point. This gets instantiated
210 /// when the CodeCompletionFile gets \#include'ed for preprocessing.
211 SourceLocation CodeCompletionLoc;
213 /// \brief The start location for the file of the code-completion point.
215 /// This gets instantiated when the CodeCompletionFile gets \#include'ed
216 /// for preprocessing.
217 SourceLocation CodeCompletionFileLoc;
219 /// \brief The source location of the 'import' contextual keyword we just
221 SourceLocation ModuleImportLoc;
223 /// \brief The module import path that we're currently processing.
224 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> ModuleImportPath;
226 /// \brief Whether the last token we lexed was an '@'.
229 /// \brief Whether the module import expectes an identifier next. Otherwise,
230 /// it expects a '.' or ';'.
231 bool ModuleImportExpectsIdentifier;
233 /// \brief The source location of the currently-active
234 /// #pragma clang arc_cf_code_audited begin.
235 SourceLocation PragmaARCCFCodeAuditedLoc;
237 /// \brief True if we hit the code-completion point.
238 bool CodeCompletionReached;
240 /// \brief The number of bytes that we will initially skip when entering the
241 /// main file, which is used when loading a precompiled preamble, along
242 /// with a flag that indicates whether skipping this number of bytes will
243 /// place the lexer at the start of a line.
244 std::pair<unsigned, bool> SkipMainFilePreamble;
246 /// CurLexer - This is the current top of the stack that we're lexing from if
247 /// not expanding a macro and we are lexing directly from source code.
248 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
249 OwningPtr<Lexer> CurLexer;
251 /// CurPTHLexer - This is the current top of stack that we're lexing from if
252 /// not expanding from a macro and we are lexing from a PTH cache.
253 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
254 OwningPtr<PTHLexer> CurPTHLexer;
256 /// CurPPLexer - This is the current top of the stack what we're lexing from
257 /// if not expanding a macro. This is an alias for either CurLexer or
259 PreprocessorLexer *CurPPLexer;
261 /// CurLookup - The DirectoryLookup structure used to find the current
262 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to
263 /// implement \#include_next and find directory-specific properties.
264 const DirectoryLookup *CurDirLookup;
266 /// CurTokenLexer - This is the current macro we are expanding, if we are
267 /// expanding a macro. One of CurLexer and CurTokenLexer must be null.
268 OwningPtr<TokenLexer> CurTokenLexer;
270 /// \brief The kind of lexer we're currently working with.
276 CLK_LexAfterModuleImport
279 /// IncludeMacroStack - This keeps track of the stack of files currently
280 /// \#included, and macros currently being expanded from, not counting
281 /// CurLexer/CurTokenLexer.
282 struct IncludeStackInfo {
283 enum CurLexerKind CurLexerKind;
285 PTHLexer *ThePTHLexer;
286 PreprocessorLexer *ThePPLexer;
287 TokenLexer *TheTokenLexer;
288 const DirectoryLookup *TheDirLookup;
290 IncludeStackInfo(enum CurLexerKind K, Lexer *L, PTHLexer* P,
291 PreprocessorLexer* PPL,
292 TokenLexer* TL, const DirectoryLookup *D)
293 : CurLexerKind(K), TheLexer(L), ThePTHLexer(P), ThePPLexer(PPL),
294 TheTokenLexer(TL), TheDirLookup(D) {}
296 std::vector<IncludeStackInfo> IncludeMacroStack;
298 /// Callbacks - These are actions invoked when some preprocessor activity is
299 /// encountered (e.g. a file is \#included, etc).
300 PPCallbacks *Callbacks;
302 struct MacroExpandsInfo {
306 MacroExpandsInfo(Token Tok, MacroDirective *MD, SourceRange Range)
307 : Tok(Tok), MD(MD), Range(Range) { }
309 SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks;
311 /// Macros - For each IdentifierInfo that was associated with a macro, we
312 /// keep a mapping to the history of all macro definitions and #undefs in
313 /// the reverse order (the latest one is in the head of the list).
314 llvm::DenseMap<const IdentifierInfo*, MacroDirective*> Macros;
315 friend class ASTReader;
317 /// \brief Macros that we want to warn because they are not used at the end
318 /// of the translation unit; we store just their SourceLocations instead
319 /// something like MacroInfo*. The benefit of this is that when we are
320 /// deserializing from PCH, we don't need to deserialize identifier & macros
321 /// just so that we can report that they are unused, we just warn using
322 /// the SourceLocations of this set (that will be filled by the ASTReader).
323 /// We are using SmallPtrSet instead of a vector for faster removal.
324 typedef llvm::SmallPtrSet<SourceLocation, 32> WarnUnusedMacroLocsTy;
325 WarnUnusedMacroLocsTy WarnUnusedMacroLocs;
327 /// MacroArgCache - This is a "freelist" of MacroArg objects that can be
328 /// reused for quick allocation.
329 MacroArgs *MacroArgCache;
330 friend class MacroArgs;
332 /// PragmaPushMacroInfo - For each IdentifierInfo used in a #pragma
333 /// push_macro directive, we keep a MacroInfo stack used to restore
334 /// previous macro value.
335 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> > PragmaPushMacroInfo;
337 // Various statistics we track for performance analysis.
338 unsigned NumDirectives, NumIncluded, NumDefined, NumUndefined, NumPragma;
339 unsigned NumIf, NumElse, NumEndif;
340 unsigned NumEnteredSourceFiles, MaxIncludeStackDepth;
341 unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded;
342 unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste;
345 /// Predefines - This string is the predefined macros that preprocessor
346 /// should use from the command line etc.
347 std::string Predefines;
349 /// \brief The file ID for the preprocessor predefines.
350 FileID PredefinesFileID;
352 /// TokenLexerCache - Cache macro expanders to reduce malloc traffic.
353 enum { TokenLexerCacheSize = 8 };
354 unsigned NumCachedTokenLexers;
355 TokenLexer *TokenLexerCache[TokenLexerCacheSize];
357 /// \brief Keeps macro expanded tokens for TokenLexers.
359 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
360 /// going to lex in the cache and when it finishes the tokens are removed
361 /// from the end of the cache.
362 SmallVector<Token, 16> MacroExpandedTokens;
363 std::vector<std::pair<TokenLexer *, size_t> > MacroExpandingLexersStack;
365 /// \brief A record of the macro definitions and expansions that
366 /// occurred during preprocessing.
368 /// This is an optional side structure that can be enabled with
369 /// \c createPreprocessingRecord() prior to preprocessing.
370 PreprocessingRecord *Record;
372 private: // Cached tokens state.
373 typedef SmallVector<Token, 1> CachedTokensTy;
375 /// CachedTokens - Cached tokens are stored here when we do backtracking or
376 /// lookahead. They are "lexed" by the CachingLex() method.
377 CachedTokensTy CachedTokens;
379 /// CachedLexPos - The position of the cached token that CachingLex() should
380 /// "lex" next. If it points beyond the CachedTokens vector, it means that
381 /// a normal Lex() should be invoked.
382 CachedTokensTy::size_type CachedLexPos;
384 /// BacktrackPositions - Stack of backtrack positions, allowing nested
385 /// backtracks. The EnableBacktrackAtThisPos() method pushes a position to
386 /// indicate where CachedLexPos should be set when the BackTrack() method is
387 /// invoked (at which point the last position is popped).
388 std::vector<CachedTokensTy::size_type> BacktrackPositions;
390 struct MacroInfoChain {
392 MacroInfoChain *Next;
393 MacroInfoChain *Prev;
396 /// MacroInfos are managed as a chain for easy disposal. This is the head
398 MacroInfoChain *MIChainHead;
400 /// MICache - A "freelist" of MacroInfo objects that can be reused for quick
402 MacroInfoChain *MICache;
404 struct DeserializedMacroInfoChain {
406 unsigned OwningModuleID; // MUST be immediately after the MacroInfo object
407 // so it can be accessed by MacroInfo::getOwningModuleID().
408 DeserializedMacroInfoChain *Next;
410 DeserializedMacroInfoChain *DeserialMIChainHead;
413 Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
414 DiagnosticsEngine &diags, LangOptions &opts,
415 const TargetInfo *target,
416 SourceManager &SM, HeaderSearch &Headers,
417 ModuleLoader &TheModuleLoader,
418 IdentifierInfoLookup *IILookup = 0,
419 bool OwnsHeaderSearch = false,
420 bool DelayInitialization = false,
421 bool IncrProcessing = false);
425 /// \brief Initialize the preprocessor, if the constructor did not already
426 /// perform the initialization.
428 /// \param Target Information about the target.
429 void Initialize(const TargetInfo &Target);
431 /// \brief Retrieve the preprocessor options used to initialize this
433 PreprocessorOptions &getPreprocessorOpts() const { return *PPOpts; }
435 DiagnosticsEngine &getDiagnostics() const { return *Diags; }
436 void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; }
438 const LangOptions &getLangOpts() const { return LangOpts; }
439 const TargetInfo &getTargetInfo() const { return *Target; }
440 FileManager &getFileManager() const { return FileMgr; }
441 SourceManager &getSourceManager() const { return SourceMgr; }
442 HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
444 IdentifierTable &getIdentifierTable() { return Identifiers; }
445 SelectorTable &getSelectorTable() { return Selectors; }
446 Builtin::Context &getBuiltinInfo() { return BuiltinInfo; }
447 llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
449 void setPTHManager(PTHManager* pm);
451 PTHManager *getPTHManager() { return PTH.get(); }
453 void setExternalSource(ExternalPreprocessorSource *Source) {
454 ExternalSource = Source;
457 ExternalPreprocessorSource *getExternalSource() const {
458 return ExternalSource;
461 /// \brief Retrieve the module loader associated with this preprocessor.
462 ModuleLoader &getModuleLoader() const { return TheModuleLoader; }
464 bool hadModuleLoaderFatalFailure() const {
465 return TheModuleLoader.HadFatalFailure;
468 /// \brief True if we are currently preprocessing a #if or #elif directive
469 bool isParsingIfOrElifDirective() const {
470 return ParsingIfOrElifDirective;
473 /// SetCommentRetentionState - Control whether or not the preprocessor retains
474 /// comments in output.
475 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
476 this->KeepComments = KeepComments | KeepMacroComments;
477 this->KeepMacroComments = KeepMacroComments;
480 bool getCommentRetentionState() const { return KeepComments; }
482 void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; }
483 bool getPragmasEnabled() const { return PragmasEnabled; }
485 void SetSuppressIncludeNotFoundError(bool Suppress) {
486 SuppressIncludeNotFoundError = Suppress;
489 bool GetSuppressIncludeNotFoundError() {
490 return SuppressIncludeNotFoundError;
493 /// Sets whether the preprocessor is responsible for producing output or if
494 /// it is producing tokens to be consumed by Parse and Sema.
495 void setPreprocessedOutput(bool IsPreprocessedOutput) {
496 PreprocessedOutput = IsPreprocessedOutput;
499 /// Returns true if the preprocessor is responsible for generating output,
500 /// false if it is producing tokens to be consumed by Parse and Sema.
501 bool isPreprocessedOutput() const { return PreprocessedOutput; }
503 /// isCurrentLexer - Return true if we are lexing directly from the specified
505 bool isCurrentLexer(const PreprocessorLexer *L) const {
506 return CurPPLexer == L;
509 /// getCurrentLexer - Return the current lexer being lexed from. Note
510 /// that this ignores any potentially active macro expansions and _Pragma
511 /// expansions going on at the time.
512 PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; }
514 /// getCurrentFileLexer - Return the current file lexer being lexed from.
515 /// Note that this ignores any potentially active macro expansions and _Pragma
516 /// expansions going on at the time.
517 PreprocessorLexer *getCurrentFileLexer() const;
519 /// \brief Returns the file ID for the preprocessor predefines.
520 FileID getPredefinesFileID() const { return PredefinesFileID; }
522 /// getPPCallbacks/addPPCallbacks - Accessors for preprocessor callbacks.
523 /// Note that this class takes ownership of any PPCallbacks object given to
525 PPCallbacks *getPPCallbacks() const { return Callbacks; }
526 void addPPCallbacks(PPCallbacks *C) {
528 C = new PPChainedCallbacks(C, Callbacks);
532 /// \brief Given an identifier, return its latest MacroDirective if it is
533 // \#defined or null if it isn't \#define'd.
534 MacroDirective *getMacroDirective(IdentifierInfo *II) const {
535 if (!II->hasMacroDefinition())
538 MacroDirective *MD = getMacroDirectiveHistory(II);
539 assert(MD->isDefined() && "Macro is undefined!");
543 const MacroInfo *getMacroInfo(IdentifierInfo *II) const {
544 return const_cast<Preprocessor*>(this)->getMacroInfo(II);
547 MacroInfo *getMacroInfo(IdentifierInfo *II) {
548 if (MacroDirective *MD = getMacroDirective(II))
549 return MD->getMacroInfo();
553 /// \brief Given an identifier, return the (probably #undef'd) MacroInfo
554 /// representing the most recent macro definition. One can iterate over all
555 /// previous macro definitions from it. This method should only be called for
556 /// identifiers that hadMacroDefinition().
557 MacroDirective *getMacroDirectiveHistory(const IdentifierInfo *II) const;
559 /// \brief Add a directive to the macro directive history for this identifier.
560 void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD);
561 DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI,
564 DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc, isImported);
565 appendMacroDirective(II, MD);
568 DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI){
569 return appendDefMacroDirective(II, MI, MI->getDefinitionLoc(), false);
571 /// \brief Set a MacroDirective that was loaded from a PCH file.
572 void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *MD);
574 /// macro_iterator/macro_begin/macro_end - This allows you to walk the macro
575 /// history table. Currently defined macros have
576 /// IdentifierInfo::hasMacroDefinition() set and an empty
577 /// MacroInfo::getUndefLoc() at the head of the list.
578 typedef llvm::DenseMap<const IdentifierInfo *,
579 MacroDirective*>::const_iterator macro_iterator;
580 macro_iterator macro_begin(bool IncludeExternalMacros = true) const;
581 macro_iterator macro_end(bool IncludeExternalMacros = true) const;
583 /// \brief Return the name of the macro defined before \p Loc that has
584 /// spelling \p Tokens. If there are multiple macros with same spelling,
585 /// return the last one defined.
586 StringRef getLastMacroWithSpelling(SourceLocation Loc,
587 ArrayRef<TokenValue> Tokens) const;
589 const std::string &getPredefines() const { return Predefines; }
590 /// setPredefines - Set the predefines for this Preprocessor. These
591 /// predefines are automatically injected when parsing the main file.
592 void setPredefines(const char *P) { Predefines = P; }
593 void setPredefines(const std::string &P) { Predefines = P; }
595 /// Return information about the specified preprocessor
596 /// identifier token.
597 IdentifierInfo *getIdentifierInfo(StringRef Name) const {
598 return &Identifiers.get(Name);
601 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
602 /// If 'Namespace' is non-null, then it is a token required to exist on the
603 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
604 void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler);
605 void AddPragmaHandler(PragmaHandler *Handler) {
606 AddPragmaHandler(StringRef(), Handler);
609 /// RemovePragmaHandler - Remove the specific pragma handler from
610 /// the preprocessor. If \p Namespace is non-null, then it should
611 /// be the namespace that \p Handler was added to. It is an error
612 /// to remove a handler that has not been registered.
613 void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler);
614 void RemovePragmaHandler(PragmaHandler *Handler) {
615 RemovePragmaHandler(StringRef(), Handler);
618 /// \brief Add the specified comment handler to the preprocessor.
619 void addCommentHandler(CommentHandler *Handler);
621 /// \brief Remove the specified comment handler.
623 /// It is an error to remove a handler that has not been registered.
624 void removeCommentHandler(CommentHandler *Handler);
626 /// \brief Set the code completion handler to the given object.
627 void setCodeCompletionHandler(CodeCompletionHandler &Handler) {
628 CodeComplete = &Handler;
631 /// \brief Retrieve the current code-completion handler.
632 CodeCompletionHandler *getCodeCompletionHandler() const {
636 /// \brief Clear out the code completion handler.
637 void clearCodeCompletionHandler() {
641 /// \brief Hook used by the lexer to invoke the "natural language" code
642 /// completion point.
643 void CodeCompleteNaturalLanguage();
645 /// \brief Retrieve the preprocessing record, or NULL if there is no
646 /// preprocessing record.
647 PreprocessingRecord *getPreprocessingRecord() const { return Record; }
649 /// \brief Create a new preprocessing record, which will keep track of
650 /// all macro expansions, macro definitions, etc.
651 void createPreprocessingRecord();
653 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
654 /// which implicitly adds the builtin defines etc.
655 void EnterMainSourceFile();
657 /// EndSourceFile - Inform the preprocessor callbacks that processing is
659 void EndSourceFile();
661 /// EnterSourceFile - Add a source file to the top of the include stack and
662 /// start lexing tokens from it instead of the current buffer. Emit an error
663 /// and don't enter the file on error.
664 void EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir,
667 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
668 /// tokens from it instead of the current buffer. Args specifies the
669 /// tokens input to a function-like macro.
671 /// ILEnd specifies the location of the ')' for a function-like macro or the
672 /// identifier for an object-like macro.
673 void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroInfo *Macro,
676 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
677 /// which will cause the lexer to start returning the specified tokens.
679 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
680 /// not be subject to further macro expansion. Otherwise, these tokens will
681 /// be re-macro-expanded when/if expansion is enabled.
683 /// If OwnsTokens is false, this method assumes that the specified stream of
684 /// tokens has a permanent owner somewhere, so they do not need to be copied.
685 /// If it is true, it assumes the array of tokens is allocated with new[] and
688 void EnterTokenStream(const Token *Toks, unsigned NumToks,
689 bool DisableMacroExpansion, bool OwnsTokens);
691 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
692 /// lexer stack. This should only be used in situations where the current
693 /// state of the top-of-stack lexer is known.
694 void RemoveTopOfLexerStack();
696 /// EnableBacktrackAtThisPos - From the point that this method is called, and
697 /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
698 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
699 /// make the Preprocessor re-lex the same tokens.
701 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
702 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
703 /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
705 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
706 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
707 /// tokens will continue indefinitely.
709 void EnableBacktrackAtThisPos();
711 /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call.
712 void CommitBacktrackedTokens();
714 /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since
715 /// EnableBacktrackAtThisPos() was previously called.
718 /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and
719 /// caching of tokens is on.
720 bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
722 /// Lex - Lex the next token for this preprocessor.
723 void Lex(Token &Result);
725 void LexAfterModuleImport(Token &Result);
727 /// \brief Lex a string literal, which may be the concatenation of multiple
728 /// string literals and may even come from macro expansion.
729 /// \returns true on success, false if a error diagnostic has been generated.
730 bool LexStringLiteral(Token &Result, std::string &String,
731 const char *DiagnosticTag, bool AllowMacroExpansion) {
732 if (AllowMacroExpansion)
735 LexUnexpandedToken(Result);
736 return FinishLexStringLiteral(Result, String, DiagnosticTag,
737 AllowMacroExpansion);
740 /// \brief Complete the lexing of a string literal where the first token has
741 /// already been lexed (see LexStringLiteral).
742 bool FinishLexStringLiteral(Token &Result, std::string &String,
743 const char *DiagnosticTag,
744 bool AllowMacroExpansion);
746 /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get
747 /// something not a comment. This is useful in -E -C mode where comments
748 /// would foul up preprocessor directive handling.
749 void LexNonComment(Token &Result) {
752 while (Result.getKind() == tok::comment);
755 /// LexUnexpandedToken - This is just like Lex, but this disables macro
756 /// expansion of identifier tokens.
757 void LexUnexpandedToken(Token &Result) {
758 // Disable macro expansion.
759 bool OldVal = DisableMacroExpansion;
760 DisableMacroExpansion = true;
765 DisableMacroExpansion = OldVal;
768 /// LexUnexpandedNonComment - Like LexNonComment, but this disables macro
769 /// expansion of identifier tokens.
770 void LexUnexpandedNonComment(Token &Result) {
772 LexUnexpandedToken(Result);
773 while (Result.getKind() == tok::comment);
776 /// Disables macro expansion everywhere except for preprocessor directives.
777 void SetMacroExpansionOnlyInDirectives() {
778 DisableMacroExpansion = true;
779 MacroExpansionInDirectivesOverride = true;
782 /// LookAhead - This peeks ahead N tokens and returns that token without
783 /// consuming any tokens. LookAhead(0) returns the next token that would be
784 /// returned by Lex(), LookAhead(1) returns the token after it, etc. This
785 /// returns normal tokens after phase 5. As such, it is equivalent to using
786 /// 'Lex', not 'LexUnexpandedToken'.
787 const Token &LookAhead(unsigned N) {
788 if (CachedLexPos + N < CachedTokens.size())
789 return CachedTokens[CachedLexPos+N];
791 return PeekAhead(N+1);
794 /// RevertCachedTokens - When backtracking is enabled and tokens are cached,
795 /// this allows to revert a specific number of tokens.
796 /// Note that the number of tokens being reverted should be up to the last
797 /// backtrack position, not more.
798 void RevertCachedTokens(unsigned N) {
799 assert(isBacktrackEnabled() &&
800 "Should only be called when tokens are cached for backtracking");
801 assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back())
802 && "Should revert tokens up to the last backtrack position, not more");
803 assert(signed(CachedLexPos) - signed(N) >= 0 &&
804 "Corrupted backtrack positions ?");
808 /// EnterToken - Enters a token in the token stream to be lexed next. If
809 /// BackTrack() is called afterwards, the token will remain at the insertion
811 void EnterToken(const Token &Tok) {
812 EnterCachingLexMode();
813 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
816 /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching
817 /// tokens (because backtrack is enabled) it should replace the most recent
818 /// cached tokens with the given annotation token. This function has no effect
819 /// if backtracking is not enabled.
821 /// Note that the use of this function is just for optimization; so that the
822 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
824 void AnnotateCachedTokens(const Token &Tok) {
825 assert(Tok.isAnnotation() && "Expected annotation token");
826 if (CachedLexPos != 0 && isBacktrackEnabled())
827 AnnotatePreviousCachedTokens(Tok);
830 /// Get the location of the last cached token, suitable for setting the end
831 /// location of an annotation token.
832 SourceLocation getLastCachedTokenLocation() const {
833 assert(CachedLexPos != 0);
834 return CachedTokens[CachedLexPos-1].getLocation();
837 /// \brief Replace the last token with an annotation token.
839 /// Like AnnotateCachedTokens(), this routine replaces an
840 /// already-parsed (and resolved) token with an annotation
841 /// token. However, this routine only replaces the last token with
842 /// the annotation token; it does not affect any other cached
843 /// tokens. This function has no effect if backtracking is not
845 void ReplaceLastTokenWithAnnotation(const Token &Tok) {
846 assert(Tok.isAnnotation() && "Expected annotation token");
847 if (CachedLexPos != 0 && isBacktrackEnabled())
848 CachedTokens[CachedLexPos-1] = Tok;
851 /// TypoCorrectToken - Update the current token to represent the provided
852 /// identifier, in order to cache an action performed by typo correction.
853 void TypoCorrectToken(const Token &Tok) {
854 assert(Tok.getIdentifierInfo() && "Expected identifier token");
855 if (CachedLexPos != 0 && isBacktrackEnabled())
856 CachedTokens[CachedLexPos-1] = Tok;
859 /// \brief Recompute the current lexer kind based on the CurLexer/CurPTHLexer/
860 /// CurTokenLexer pointers.
861 void recomputeCurLexerKind();
863 /// \brief Returns true if incremental processing is enabled
864 bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; }
866 /// \brief Enables the incremental processing
867 void enableIncrementalProcessing(bool value = true) {
868 IncrementalProcessing = value;
871 /// \brief Specify the point at which code-completion will be performed.
873 /// \param File the file in which code completion should occur. If
874 /// this file is included multiple times, code-completion will
875 /// perform completion the first time it is included. If NULL, this
876 /// function clears out the code-completion point.
878 /// \param Line the line at which code completion should occur
881 /// \param Column the column at which code completion should occur
884 /// \returns true if an error occurred, false otherwise.
885 bool SetCodeCompletionPoint(const FileEntry *File,
886 unsigned Line, unsigned Column);
888 /// \brief Determine if we are performing code completion.
889 bool isCodeCompletionEnabled() const { return CodeCompletionFile != 0; }
891 /// \brief Returns the location of the code-completion point.
892 /// Returns an invalid location if code-completion is not enabled or the file
893 /// containing the code-completion point has not been lexed yet.
894 SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; }
896 /// \brief Returns the start location of the file of code-completion point.
897 /// Returns an invalid location if code-completion is not enabled or the file
898 /// containing the code-completion point has not been lexed yet.
899 SourceLocation getCodeCompletionFileLoc() const {
900 return CodeCompletionFileLoc;
903 /// \brief Returns true if code-completion is enabled and we have hit the
904 /// code-completion point.
905 bool isCodeCompletionReached() const { return CodeCompletionReached; }
907 /// \brief Note that we hit the code-completion point.
908 void setCodeCompletionReached() {
909 assert(isCodeCompletionEnabled() && "Code-completion not enabled!");
910 CodeCompletionReached = true;
911 // Silence any diagnostics that occur after we hit the code-completion.
912 getDiagnostics().setSuppressAllDiagnostics(true);
915 /// \brief The location of the currently-active \#pragma clang
916 /// arc_cf_code_audited begin. Returns an invalid location if there
917 /// is no such pragma active.
918 SourceLocation getPragmaARCCFCodeAuditedLoc() const {
919 return PragmaARCCFCodeAuditedLoc;
922 /// \brief Set the location of the currently-active \#pragma clang
923 /// arc_cf_code_audited begin. An invalid location ends the pragma.
924 void setPragmaARCCFCodeAuditedLoc(SourceLocation Loc) {
925 PragmaARCCFCodeAuditedLoc = Loc;
928 /// \brief Instruct the preprocessor to skip part of the main source file.
930 /// \param Bytes The number of bytes in the preamble to skip.
932 /// \param StartOfLine Whether skipping these bytes puts the lexer at the
934 void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) {
935 SkipMainFilePreamble.first = Bytes;
936 SkipMainFilePreamble.second = StartOfLine;
939 /// Diag - Forwarding function for diagnostics. This emits a diagnostic at
940 /// the specified Token's location, translating the token's start
941 /// position in the current buffer into a SourcePosition object for rendering.
942 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const {
943 return Diags->Report(Loc, DiagID);
946 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const {
947 return Diags->Report(Tok.getLocation(), DiagID);
950 /// getSpelling() - Return the 'spelling' of the token at the given
951 /// location; does not go up to the spelling location or down to the
952 /// expansion location.
954 /// \param buffer A buffer which will be used only if the token requires
955 /// "cleaning", e.g. if it contains trigraphs or escaped newlines
956 /// \param invalid If non-null, will be set \c true if an error occurs.
957 StringRef getSpelling(SourceLocation loc,
958 SmallVectorImpl<char> &buffer,
959 bool *invalid = 0) const {
960 return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid);
963 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a
964 /// token is the characters used to represent the token in the source file
965 /// after trigraph expansion and escaped-newline folding. In particular, this
966 /// wants to get the true, uncanonicalized, spelling of things like digraphs
969 /// \param Invalid If non-null, will be set \c true if an error occurs.
970 std::string getSpelling(const Token &Tok, bool *Invalid = 0) const {
971 return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid);
974 /// getSpelling - This method is used to get the spelling of a token into a
975 /// preallocated buffer, instead of as an std::string. The caller is required
976 /// to allocate enough space for the token, which is guaranteed to be at least
977 /// Tok.getLength() bytes long. The length of the actual result is returned.
979 /// Note that this method may do two possible things: it may either fill in
980 /// the buffer specified with characters, or it may *change the input pointer*
981 /// to point to a constant buffer with the data already in it (avoiding a
982 /// copy). The caller is not allowed to modify the returned buffer pointer
983 /// if an internal buffer is returned.
984 unsigned getSpelling(const Token &Tok, const char *&Buffer,
985 bool *Invalid = 0) const {
986 return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid);
989 /// getSpelling - This method is used to get the spelling of a token into a
990 /// SmallVector. Note that the returned StringRef may not point to the
991 /// supplied buffer if a copy can be avoided.
992 StringRef getSpelling(const Token &Tok,
993 SmallVectorImpl<char> &Buffer,
994 bool *Invalid = 0) const;
996 /// \brief Relex the token at the specified location.
997 /// \returns true if there was a failure, false on success.
998 bool getRawToken(SourceLocation Loc, Token &Result,
999 bool IgnoreWhiteSpace = false) {
1000 return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts, IgnoreWhiteSpace);
1003 /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric constant
1004 /// with length 1, return the character.
1005 char getSpellingOfSingleCharacterNumericConstant(const Token &Tok,
1006 bool *Invalid = 0) const {
1007 assert(Tok.is(tok::numeric_constant) &&
1008 Tok.getLength() == 1 && "Called on unsupported token");
1009 assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
1011 // If the token is carrying a literal data pointer, just use it.
1012 if (const char *D = Tok.getLiteralData())
1015 // Otherwise, fall back on getCharacterData, which is slower, but always
1017 return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid);
1020 /// \brief Retrieve the name of the immediate macro expansion.
1022 /// This routine starts from a source location, and finds the name of the macro
1023 /// responsible for its immediate expansion. It looks through any intervening
1024 /// macro argument expansions to compute this. It returns a StringRef which
1025 /// refers to the SourceManager-owned buffer of the source where that macro
1026 /// name is spelled. Thus, the result shouldn't out-live the SourceManager.
1027 StringRef getImmediateMacroName(SourceLocation Loc) {
1028 return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts());
1031 /// CreateString - Plop the specified string into a scratch buffer and set the
1032 /// specified token's location and length to it. If specified, the source
1033 /// location provides a location of the expansion point of the token.
1034 void CreateString(StringRef Str, Token &Tok,
1035 SourceLocation ExpansionLocStart = SourceLocation(),
1036 SourceLocation ExpansionLocEnd = SourceLocation());
1038 /// \brief Computes the source location just past the end of the
1039 /// token at this source location.
1041 /// This routine can be used to produce a source location that
1042 /// points just past the end of the token referenced by \p Loc, and
1043 /// is generally used when a diagnostic needs to point just after a
1044 /// token where it expected something different that it received. If
1045 /// the returned source location would not be meaningful (e.g., if
1046 /// it points into a macro), this routine returns an invalid
1047 /// source location.
1049 /// \param Offset an offset from the end of the token, where the source
1050 /// location should refer to. The default offset (0) produces a source
1051 /// location pointing just past the end of the token; an offset of 1 produces
1052 /// a source location pointing to the last character in the token, etc.
1053 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0) {
1054 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
1057 /// \brief Returns true if the given MacroID location points at the first
1058 /// token of the macro expansion.
1060 /// \param MacroBegin If non-null and function returns true, it is set to
1061 /// begin location of the macro.
1062 bool isAtStartOfMacroExpansion(SourceLocation loc,
1063 SourceLocation *MacroBegin = 0) const {
1064 return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts,
1068 /// \brief Returns true if the given MacroID location points at the last
1069 /// token of the macro expansion.
1071 /// \param MacroEnd If non-null and function returns true, it is set to
1072 /// end location of the macro.
1073 bool isAtEndOfMacroExpansion(SourceLocation loc,
1074 SourceLocation *MacroEnd = 0) const {
1075 return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd);
1078 /// DumpToken - Print the token to stderr, used for debugging.
1080 void DumpToken(const Token &Tok, bool DumpFlags = false) const;
1081 void DumpLocation(SourceLocation Loc) const;
1082 void DumpMacro(const MacroInfo &MI) const;
1084 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
1085 /// token, return a new location that specifies a character within the token.
1086 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
1087 unsigned Char) const {
1088 return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts);
1091 /// IncrementPasteCounter - Increment the counters for the number of token
1092 /// paste operations performed. If fast was specified, this is a 'fast paste'
1093 /// case we handled.
1095 void IncrementPasteCounter(bool isFast) {
1097 ++NumFastTokenPaste;
1104 size_t getTotalMemory() const;
1106 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
1107 /// comment (/##/) in microsoft mode, this method handles updating the current
1108 /// state, returning the token on the next source line.
1109 void HandleMicrosoftCommentPaste(Token &Tok);
1111 //===--------------------------------------------------------------------===//
1112 // Preprocessor callback methods. These are invoked by a lexer as various
1113 // directives and events are found.
1115 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
1116 /// identifier information for the token and install it into the token,
1117 /// updating the token kind accordingly.
1118 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const;
1121 llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons;
1125 // SetPoisonReason - Call this function to indicate the reason for
1126 // poisoning an identifier. If that identifier is accessed while
1127 // poisoned, then this reason will be used instead of the default
1128 // "poisoned" diagnostic.
1129 void SetPoisonReason(IdentifierInfo *II, unsigned DiagID);
1131 // HandlePoisonedIdentifier - Display reason for poisoned
1133 void HandlePoisonedIdentifier(Token & Tok);
1135 void MaybeHandlePoisonedIdentifier(Token & Identifier) {
1136 if(IdentifierInfo * II = Identifier.getIdentifierInfo()) {
1137 if(II->isPoisoned()) {
1138 HandlePoisonedIdentifier(Identifier);
1144 /// Identifiers used for SEH handling in Borland. These are only
1145 /// allowed in particular circumstances
1147 IdentifierInfo *Ident__exception_code,
1148 *Ident___exception_code,
1149 *Ident_GetExceptionCode;
1150 // __except filter expression
1151 IdentifierInfo *Ident__exception_info,
1152 *Ident___exception_info,
1153 *Ident_GetExceptionInfo;
1155 IdentifierInfo *Ident__abnormal_termination,
1156 *Ident___abnormal_termination,
1157 *Ident_AbnormalTermination;
1159 void PoisonSEHIdentifiers(bool Poison = true); // Borland
1161 /// HandleIdentifier - This callback is invoked when the lexer reads an
1162 /// identifier and has filled in the tokens IdentifierInfo member. This
1163 /// callback potentially macro expands it or turns it into a named token (like
1166 /// \returns true if we actually computed a token, false if we need to
1168 bool HandleIdentifier(Token &Identifier);
1171 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1172 /// the current file. This either returns the EOF token and returns true, or
1173 /// pops a level off the include stack and returns false, at which point the
1174 /// client should call lex again.
1175 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
1177 /// HandleEndOfTokenLexer - This callback is invoked when the current
1178 /// TokenLexer hits the end of its token stream.
1179 bool HandleEndOfTokenLexer(Token &Result);
1181 /// HandleDirective - This callback is invoked when the lexer sees a # token
1182 /// at the start of a line. This consumes the directive, modifies the
1183 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
1184 /// read is the correct one.
1185 void HandleDirective(Token &Result);
1187 /// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
1188 /// not, emit a diagnostic and consume up until the eod. If EnableMacros is
1189 /// true, then we consider macros that expand to zero tokens as being ok.
1190 void CheckEndOfDirective(const char *Directive, bool EnableMacros = false);
1192 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1193 /// current line until the tok::eod token is found.
1194 void DiscardUntilEndOfDirective();
1196 /// SawDateOrTime - This returns true if the preprocessor has seen a use of
1197 /// __DATE__ or __TIME__ in the file so far.
1198 bool SawDateOrTime() const {
1199 return DATELoc != SourceLocation() || TIMELoc != SourceLocation();
1201 unsigned getCounterValue() const { return CounterValue; }
1202 void setCounterValue(unsigned V) { CounterValue = V; }
1204 /// \brief Retrieves the module that we're currently building, if any.
1205 Module *getCurrentModule();
1207 /// \brief Allocate a new MacroInfo object with the provided SourceLocation.
1208 MacroInfo *AllocateMacroInfo(SourceLocation L);
1210 /// \brief Allocate a new MacroInfo object loaded from an AST file.
1211 MacroInfo *AllocateDeserializedMacroInfo(SourceLocation L,
1212 unsigned SubModuleID);
1214 /// \brief Turn the specified lexer token into a fully checked and spelled
1215 /// filename, e.g. as an operand of \#include.
1217 /// The caller is expected to provide a buffer that is large enough to hold
1218 /// the spelling of the filename, but is also expected to handle the case
1219 /// when this method decides to use a different buffer.
1221 /// \returns true if the input filename was in <>'s or false if it was
1223 bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Filename);
1225 /// \brief Given a "foo" or \<foo> reference, look up the indicated file.
1227 /// Returns null on failure. \p isAngled indicates whether the file
1228 /// reference is for system \#include's or not (i.e. using <> instead of "").
1229 const FileEntry *LookupFile(SourceLocation FilenameLoc, StringRef Filename,
1230 bool isAngled, const DirectoryLookup *FromDir,
1231 const DirectoryLookup *&CurDir,
1232 SmallVectorImpl<char> *SearchPath,
1233 SmallVectorImpl<char> *RelativePath,
1234 ModuleMap::KnownHeader *SuggestedModule,
1235 bool SkipCache = false);
1237 /// GetCurLookup - The DirectoryLookup structure used to find the current
1238 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to
1239 /// implement \#include_next and find directory-specific properties.
1240 const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; }
1242 /// \brief Return true if we're in the top-level file, not in a \#include.
1243 bool isInPrimaryFile() const;
1245 /// ConcatenateIncludeName - Handle cases where the \#include name is expanded
1246 /// from a macro as multiple tokens, which need to be glued together. This
1247 /// occurs for code like:
1249 /// \#define FOO <x/y.h>
1252 /// because in this case, "<x/y.h>" is returned as 7 tokens, not one.
1254 /// This code concatenates and consumes tokens up to the '>' token. It
1255 /// returns false if the > was found, otherwise it returns true if it finds
1256 /// and consumes the EOD marker.
1257 bool ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
1258 SourceLocation &End);
1260 /// LexOnOffSwitch - Lex an on-off-switch (C99 6.10.6p2) and verify that it is
1261 /// followed by EOD. Return true if the token is not a valid on-off-switch.
1262 bool LexOnOffSwitch(tok::OnOffSwitch &OOS);
1266 void PushIncludeMacroStack() {
1267 IncludeMacroStack.push_back(IncludeStackInfo(CurLexerKind,
1271 CurTokenLexer.take(),
1276 void PopIncludeMacroStack() {
1277 CurLexer.reset(IncludeMacroStack.back().TheLexer);
1278 CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer);
1279 CurPPLexer = IncludeMacroStack.back().ThePPLexer;
1280 CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer);
1281 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
1282 CurLexerKind = IncludeMacroStack.back().CurLexerKind;
1283 IncludeMacroStack.pop_back();
1286 void PropagateLineStartLeadingSpaceInfo(Token &Result);
1288 /// \brief Allocate a new MacroInfo object.
1289 MacroInfo *AllocateMacroInfo();
1291 DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI,
1294 UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc);
1295 VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc,
1298 /// \brief Release the specified MacroInfo for re-use.
1300 /// This memory will be reused for allocating new MacroInfo objects.
1301 void ReleaseMacroInfo(MacroInfo* MI);
1303 /// ReadMacroName - Lex and validate a macro name, which occurs after a
1304 /// \#define or \#undef. This emits a diagnostic, sets the token kind to eod,
1305 /// and discards the rest of the macro line if the macro name is invalid.
1306 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0);
1308 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1309 /// definition has just been read. Lex the rest of the arguments and the
1310 /// closing ), updating MI with what we learn and saving in LastTok the
1311 /// last token read.
1312 /// Return true if an error occurs parsing the arg list.
1313 bool ReadMacroDefinitionArgList(MacroInfo *MI, Token& LastTok);
1315 /// We just read a \#if or related directive and decided that the
1316 /// subsequent tokens are in the \#if'd out portion of the
1317 /// file. Lex the rest of the file, until we see an \#endif. If \p
1318 /// FoundNonSkipPortion is true, then we have already emitted code for part of
1319 /// this \#if directive, so \#else/\#elif blocks should never be entered. If
1320 /// \p FoundElse is false, then \#else directives are ok, if not, then we have
1321 /// already seen one so a \#else directive is a duplicate. When this returns,
1322 /// the caller can lex the first valid token.
1323 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1324 bool FoundNonSkipPortion, bool FoundElse,
1325 SourceLocation ElseLoc = SourceLocation());
1327 /// \brief A fast PTH version of SkipExcludedConditionalBlock.
1328 void PTHSkipExcludedConditionalBlock();
1330 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
1331 /// may occur after a #if or #elif directive and return it as a bool. If the
1332 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro.
1333 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
1335 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1336 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1337 void RegisterBuiltinPragmas();
1339 /// \brief Register builtin macros such as __LINE__ with the identifier table.
1340 void RegisterBuiltinMacros();
1342 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to
1343 /// be expanded as a macro, handle it and return the next token as 'Tok'. If
1344 /// we lexed a token, return true; otherwise the caller should lex again.
1345 bool HandleMacroExpandedIdentifier(Token &Tok, MacroDirective *MD);
1347 /// \brief Cache macro expanded tokens for TokenLexers.
1349 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1350 /// going to lex in the cache and when it finishes the tokens are removed
1351 /// from the end of the cache.
1352 Token *cacheMacroExpandedTokens(TokenLexer *tokLexer,
1353 ArrayRef<Token> tokens);
1354 void removeCachedMacroExpandedTokensOfLastLexer();
1355 friend void TokenLexer::ExpandFunctionArguments();
1357 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
1358 /// lexed is a '('. If so, consume the token and return true, if not, this
1359 /// method should have no observable side-effect on the lexed tokens.
1360 bool isNextPPTokenLParen();
1362 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
1363 /// invoked to read all of the formal arguments specified for the macro
1364 /// invocation. This returns null on error.
1365 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI,
1366 SourceLocation &ExpansionEnd);
1368 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1369 /// as a builtin macro, handle it and return the next token as 'Tok'.
1370 void ExpandBuiltinMacro(Token &Tok);
1372 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
1373 /// return the first token after the directive. The _Pragma token has just
1374 /// been read into 'Tok'.
1375 void Handle_Pragma(Token &Tok);
1377 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
1378 /// is not enclosed within a string literal.
1379 void HandleMicrosoft__pragma(Token &Tok);
1381 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and
1382 /// start lexing tokens from it instead of the current buffer.
1383 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
1385 /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and
1386 /// start getting tokens from it using the PTH cache.
1387 void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir);
1389 /// \brief Set the file ID for the preprocessor predefines.
1390 void setPredefinesFileID(FileID FID) {
1391 assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!");
1392 PredefinesFileID = FID;
1395 /// IsFileLexer - Returns true if we are lexing from a file and not a
1396 /// pragma or a macro.
1397 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
1398 return L ? !L->isPragmaLexer() : P != 0;
1401 static bool IsFileLexer(const IncludeStackInfo& I) {
1402 return IsFileLexer(I.TheLexer, I.ThePPLexer);
1405 bool IsFileLexer() const {
1406 return IsFileLexer(CurLexer.get(), CurPPLexer);
1409 //===--------------------------------------------------------------------===//
1411 void CachingLex(Token &Result);
1412 bool InCachingLexMode() const {
1413 // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means
1414 // that we are past EOF, not that we are in CachingLex mode.
1415 return !CurPPLexer && !CurTokenLexer && !CurPTHLexer &&
1416 !IncludeMacroStack.empty();
1418 void EnterCachingLexMode();
1419 void ExitCachingLexMode() {
1420 if (InCachingLexMode())
1421 RemoveTopOfLexerStack();
1423 const Token &PeekAhead(unsigned N);
1424 void AnnotatePreviousCachedTokens(const Token &Tok);
1426 //===--------------------------------------------------------------------===//
1427 /// Handle*Directive - implement the various preprocessor directives. These
1428 /// should side-effect the current preprocessor object so that the next call
1429 /// to Lex() will return the appropriate token next.
1430 void HandleLineDirective(Token &Tok);
1431 void HandleDigitDirective(Token &Tok);
1432 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
1433 void HandleIdentSCCSDirective(Token &Tok);
1434 void HandleMacroPublicDirective(Token &Tok);
1435 void HandleMacroPrivateDirective(Token &Tok);
1438 void HandleIncludeDirective(SourceLocation HashLoc,
1440 const DirectoryLookup *LookupFrom = 0,
1441 bool isImport = false);
1442 void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok);
1443 void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok);
1444 void HandleImportDirective(SourceLocation HashLoc, Token &Tok);
1445 void HandleMicrosoftImportDirective(Token &Tok);
1447 // Module inclusion testing.
1448 /// \brief Find the module for the source or header file that \p FilenameLoc
1450 Module *getModuleForLocation(SourceLocation FilenameLoc);
1452 /// \brief Verify that a private header is included only from within its
1454 bool violatesPrivateInclude(Module *RequestingModule,
1455 const FileEntry *IncFileEnt,
1456 ModuleMap::ModuleHeaderRole Role,
1457 Module *RequestedModule);
1459 /// \brief Verify that a module includes headers only from modules that it
1460 /// has declared that it uses.
1461 bool violatesUseDeclarations(Module *RequestingModule,
1462 Module *RequestedModule);
1464 /// \brief Verify that it is legal for the source file that \p FilenameLoc
1465 /// points to to include the file \p Filename.
1467 /// Tries to reuse \p IncFileEnt.
1468 void verifyModuleInclude(SourceLocation FilenameLoc, StringRef Filename,
1469 const FileEntry *IncFileEnt);
1472 void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterTopLevelIfndef);
1473 void HandleUndefDirective(Token &Tok);
1475 // Conditional Inclusion.
1476 void HandleIfdefDirective(Token &Tok, bool isIfndef,
1477 bool ReadAnyTokensBeforeDirective);
1478 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective);
1479 void HandleEndifDirective(Token &Tok);
1480 void HandleElseDirective(Token &Tok);
1481 void HandleElifDirective(Token &Tok);
1484 void HandlePragmaDirective(SourceLocation IntroducerLoc,
1485 PragmaIntroducerKind Introducer);
1487 void HandlePragmaOnce(Token &OnceTok);
1488 void HandlePragmaMark();
1489 void HandlePragmaPoison(Token &PoisonTok);
1490 void HandlePragmaSystemHeader(Token &SysHeaderTok);
1491 void HandlePragmaDependency(Token &DependencyTok);
1492 void HandlePragmaPushMacro(Token &Tok);
1493 void HandlePragmaPopMacro(Token &Tok);
1494 void HandlePragmaIncludeAlias(Token &Tok);
1495 IdentifierInfo *ParsePragmaPushOrPopMacro(Token &Tok);
1497 // Return true and store the first token only if any CommentHandler
1498 // has inserted some tokens and getCommentRetentionState() is false.
1499 bool HandleComment(Token &Token, SourceRange Comment);
1501 /// \brief A macro is used, update information about macros that need unused
1503 void markMacroAsUsed(MacroInfo *MI);
1506 /// \brief Abstract base class that describes a handler that will receive
1507 /// source ranges for each of the comments encountered in the source file.
1508 class CommentHandler {
1510 virtual ~CommentHandler();
1512 // The handler shall return true if it has pushed any tokens
1513 // to be read using e.g. EnterToken or EnterTokenStream.
1514 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
1517 } // end namespace clang