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/Lex/Lexer.h"
18 #include "clang/Lex/PTHLexer.h"
19 #include "clang/Lex/PPCallbacks.h"
20 #include "clang/Lex/TokenLexer.h"
21 #include "clang/Lex/PTHManager.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "clang/Basic/IdentifierTable.h"
25 #include "clang/Basic/SourceLocation.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/OwningPtr.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Allocator.h"
35 class ExternalPreprocessorSource;
39 class PragmaNamespace;
45 class DirectoryLookup;
46 class PreprocessingRecord;
48 /// Preprocessor - This object engages in a tight little dance with the lexer to
49 /// efficiently preprocess tokens. Lexers know only about tokens within a
50 /// single source file, and don't know anything about preprocessor-level issues
51 /// like the #include stack, token expansion, etc.
56 const TargetInfo &Target;
58 SourceManager &SourceMgr;
59 ScratchBuffer *ScratchBuf;
60 HeaderSearch &HeaderInfo;
62 /// \brief External source of macros.
63 ExternalPreprocessorSource *ExternalSource;
65 /// PTH - An optional PTHManager object used for getting tokens from
66 /// a token cache rather than lexing the original source file.
67 llvm::OwningPtr<PTHManager> PTH;
69 /// BP - A BumpPtrAllocator object used to quickly allocate and release
70 /// objects internal to the Preprocessor.
71 llvm::BumpPtrAllocator BP;
73 /// Identifiers for builtin macros and other builtins.
74 IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__
75 IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__
76 IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__
77 IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__
78 IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__
79 IdentifierInfo *Ident__COUNTER__; // __COUNTER__
80 IdentifierInfo *Ident_Pragma, *Ident__VA_ARGS__; // _Pragma, __VA_ARGS__
81 IdentifierInfo *Ident__has_feature; // __has_feature
82 IdentifierInfo *Ident__has_builtin; // __has_builtin
83 IdentifierInfo *Ident__has_include; // __has_include
84 IdentifierInfo *Ident__has_include_next; // __has_include_next
86 SourceLocation DATELoc, TIMELoc;
87 unsigned CounterValue; // Next __COUNTER__ value.
90 /// MaxIncludeStackDepth - Maximum depth of #includes.
91 MaxAllowedIncludeStackDepth = 200
94 // State that is set before the preprocessor begins.
95 bool KeepComments : 1;
96 bool KeepMacroComments : 1;
98 // State that changes while the preprocessor runs:
99 bool InMacroArgs : 1; // True if parsing fn macro invocation args.
101 /// Whether the preprocessor owns the header search object.
102 bool OwnsHeaderSearch : 1;
104 /// DisableMacroExpansion - True if macro expansion is disabled.
105 bool DisableMacroExpansion : 1;
107 /// \brief Whether we have already loaded macros from the external source.
108 mutable bool ReadMacrosFromExternalSource : 1;
110 /// Identifiers - This is mapping/lookup information for all identifiers in
111 /// the program, including program keywords.
112 mutable IdentifierTable Identifiers;
114 /// Selectors - This table contains all the selectors in the program. Unlike
115 /// IdentifierTable above, this table *isn't* populated by the preprocessor.
116 /// It is declared/instantiated here because it's role/lifetime is
117 /// conceptually similar the IdentifierTable. In addition, the current control
118 /// flow (in clang::ParseAST()), make it convenient to put here.
119 /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to
120 /// the lifetime fo the preprocessor.
121 SelectorTable Selectors;
123 /// BuiltinInfo - Information about builtins.
124 Builtin::Context BuiltinInfo;
126 /// PragmaHandlers - This tracks all of the pragmas that the client registered
127 /// with this preprocessor.
128 PragmaNamespace *PragmaHandlers;
130 /// \brief Tracks all of the comment handlers that the client registered
131 /// with this preprocessor.
132 std::vector<CommentHandler *> CommentHandlers;
134 /// \brief The file that we're performing code-completion for, if any.
135 const FileEntry *CodeCompletionFile;
137 /// CurLexer - This is the current top of the stack that we're lexing from if
138 /// not expanding a macro and we are lexing directly from source code.
139 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
140 llvm::OwningPtr<Lexer> CurLexer;
142 /// CurPTHLexer - This is the current top of stack that we're lexing from if
143 /// not expanding from a macro and we are lexing from a PTH cache.
144 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
145 llvm::OwningPtr<PTHLexer> CurPTHLexer;
147 /// CurPPLexer - This is the current top of the stack what we're lexing from
148 /// if not expanding a macro. This is an alias for either CurLexer or
150 PreprocessorLexer *CurPPLexer;
152 /// CurLookup - The DirectoryLookup structure used to find the current
153 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to
154 /// implement #include_next and find directory-specific properties.
155 const DirectoryLookup *CurDirLookup;
157 /// CurTokenLexer - This is the current macro we are expanding, if we are
158 /// expanding a macro. One of CurLexer and CurTokenLexer must be null.
159 llvm::OwningPtr<TokenLexer> CurTokenLexer;
161 /// IncludeMacroStack - This keeps track of the stack of files currently
162 /// #included, and macros currently being expanded from, not counting
163 /// CurLexer/CurTokenLexer.
164 struct IncludeStackInfo {
166 PTHLexer *ThePTHLexer;
167 PreprocessorLexer *ThePPLexer;
168 TokenLexer *TheTokenLexer;
169 const DirectoryLookup *TheDirLookup;
171 IncludeStackInfo(Lexer *L, PTHLexer* P, PreprocessorLexer* PPL,
172 TokenLexer* TL, const DirectoryLookup *D)
173 : TheLexer(L), ThePTHLexer(P), ThePPLexer(PPL), TheTokenLexer(TL),
176 std::vector<IncludeStackInfo> IncludeMacroStack;
178 /// Callbacks - These are actions invoked when some preprocessor activity is
179 /// encountered (e.g. a file is #included, etc).
180 PPCallbacks *Callbacks;
182 /// Macros - For each IdentifierInfo with 'HasMacro' set, we keep a mapping
183 /// to the actual definition of the macro.
184 llvm::DenseMap<IdentifierInfo*, MacroInfo*> Macros;
186 /// MICache - A "freelist" of MacroInfo objects that can be reused for quick
188 /// FIXME: why not use a singly linked list?
189 std::vector<MacroInfo*> MICache;
191 /// MacroArgCache - This is a "freelist" of MacroArg objects that can be
192 /// reused for quick allocation.
193 MacroArgs *MacroArgCache;
194 friend class MacroArgs;
196 // Various statistics we track for performance analysis.
197 unsigned NumDirectives, NumIncluded, NumDefined, NumUndefined, NumPragma;
198 unsigned NumIf, NumElse, NumEndif;
199 unsigned NumEnteredSourceFiles, MaxIncludeStackDepth;
200 unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded;
201 unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste;
204 /// Predefines - This string is the predefined macros that preprocessor
205 /// should use from the command line etc.
206 std::string Predefines;
208 /// TokenLexerCache - Cache macro expanders to reduce malloc traffic.
209 enum { TokenLexerCacheSize = 8 };
210 unsigned NumCachedTokenLexers;
211 TokenLexer *TokenLexerCache[TokenLexerCacheSize];
213 /// \brief A record of the macro definitions and instantiations that
214 /// occurred during preprocessing.
216 /// This is an optional side structure that can be enabled with
217 /// \c createPreprocessingRecord() prior to preprocessing.
218 PreprocessingRecord *Record;
220 private: // Cached tokens state.
221 typedef llvm::SmallVector<Token, 1> CachedTokensTy;
223 /// CachedTokens - Cached tokens are stored here when we do backtracking or
224 /// lookahead. They are "lexed" by the CachingLex() method.
225 CachedTokensTy CachedTokens;
227 /// CachedLexPos - The position of the cached token that CachingLex() should
228 /// "lex" next. If it points beyond the CachedTokens vector, it means that
229 /// a normal Lex() should be invoked.
230 CachedTokensTy::size_type CachedLexPos;
232 /// BacktrackPositions - Stack of backtrack positions, allowing nested
233 /// backtracks. The EnableBacktrackAtThisPos() method pushes a position to
234 /// indicate where CachedLexPos should be set when the BackTrack() method is
235 /// invoked (at which point the last position is popped).
236 std::vector<CachedTokensTy::size_type> BacktrackPositions;
239 Preprocessor(Diagnostic &diags, const LangOptions &opts,
240 const TargetInfo &target,
241 SourceManager &SM, HeaderSearch &Headers,
242 IdentifierInfoLookup *IILookup = 0,
243 bool OwnsHeaderSearch = false);
247 Diagnostic &getDiagnostics() const { return *Diags; }
248 void setDiagnostics(Diagnostic &D) { Diags = &D; }
250 const LangOptions &getLangOptions() const { return Features; }
251 const TargetInfo &getTargetInfo() const { return Target; }
252 FileManager &getFileManager() const { return FileMgr; }
253 SourceManager &getSourceManager() const { return SourceMgr; }
254 HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
256 IdentifierTable &getIdentifierTable() { return Identifiers; }
257 SelectorTable &getSelectorTable() { return Selectors; }
258 Builtin::Context &getBuiltinInfo() { return BuiltinInfo; }
259 llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
261 void setPTHManager(PTHManager* pm);
263 PTHManager *getPTHManager() { return PTH.get(); }
265 void setExternalSource(ExternalPreprocessorSource *Source) {
266 ExternalSource = Source;
269 ExternalPreprocessorSource *getExternalSource() const {
270 return ExternalSource;
273 /// SetCommentRetentionState - Control whether or not the preprocessor retains
274 /// comments in output.
275 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
276 this->KeepComments = KeepComments | KeepMacroComments;
277 this->KeepMacroComments = KeepMacroComments;
280 bool getCommentRetentionState() const { return KeepComments; }
282 /// isCurrentLexer - Return true if we are lexing directly from the specified
284 bool isCurrentLexer(const PreprocessorLexer *L) const {
285 return CurPPLexer == L;
288 /// getCurrentLexer - Return the current lexer being lexed from. Note
289 /// that this ignores any potentially active macro expansions and _Pragma
290 /// expansions going on at the time.
291 PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; }
293 /// getCurrentFileLexer - Return the current file lexer being lexed from. Note
294 /// that this ignores any potentially active macro expansions and _Pragma
295 /// expansions going on at the time.
296 PreprocessorLexer *getCurrentFileLexer() const;
298 /// getPPCallbacks/addPPCallbacks - Accessors for preprocessor callbacks.
299 /// Note that this class takes ownership of any PPCallbacks object given to
301 PPCallbacks *getPPCallbacks() const { return Callbacks; }
302 void addPPCallbacks(PPCallbacks *C) {
304 C = new PPChainedCallbacks(C, Callbacks);
308 /// getMacroInfo - Given an identifier, return the MacroInfo it is #defined to
309 /// or null if it isn't #define'd.
310 MacroInfo *getMacroInfo(IdentifierInfo *II) const {
311 return II->hasMacroDefinition() ? Macros.find(II)->second : 0;
314 /// setMacroInfo - Specify a macro for this identifier.
316 void setMacroInfo(IdentifierInfo *II, MacroInfo *MI);
318 /// macro_iterator/macro_begin/macro_end - This allows you to walk the current
319 /// state of the macro table. This visits every currently-defined macro.
320 typedef llvm::DenseMap<IdentifierInfo*,
321 MacroInfo*>::const_iterator macro_iterator;
322 macro_iterator macro_begin(bool IncludeExternalMacros = true) const;
323 macro_iterator macro_end(bool IncludeExternalMacros = true) const;
325 const std::string &getPredefines() const { return Predefines; }
326 /// setPredefines - Set the predefines for this Preprocessor. These
327 /// predefines are automatically injected when parsing the main file.
328 void setPredefines(const char *P) { Predefines = P; }
329 void setPredefines(const std::string &P) { Predefines = P; }
331 /// getIdentifierInfo - Return information about the specified preprocessor
332 /// identifier token. The version of this method that takes two character
333 /// pointers is preferred unless the identifier is already available as a
334 /// string (this avoids allocation and copying of memory to construct an
336 IdentifierInfo *getIdentifierInfo(llvm::StringRef Name) const {
337 return &Identifiers.get(Name);
340 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
341 /// If 'Namespace' is non-null, then it is a token required to exist on the
342 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
343 void AddPragmaHandler(const char *Namespace, PragmaHandler *Handler);
345 /// RemovePragmaHandler - Remove the specific pragma handler from
346 /// the preprocessor. If \arg Namespace is non-null, then it should
347 /// be the namespace that \arg Handler was added to. It is an error
348 /// to remove a handler that has not been registered.
349 void RemovePragmaHandler(const char *Namespace, PragmaHandler *Handler);
351 /// \brief Add the specified comment handler to the preprocessor.
352 void AddCommentHandler(CommentHandler *Handler);
354 /// \brief Remove the specified comment handler.
356 /// It is an error to remove a handler that has not been registered.
357 void RemoveCommentHandler(CommentHandler *Handler);
359 /// \brief Retrieve the preprocessing record, or NULL if there is no
360 /// preprocessing record.
361 PreprocessingRecord *getPreprocessingRecord() const { return Record; }
363 /// \brief Create a new preprocessing record, which will keep track of
364 /// all macro expansions, macro definitions, etc.
365 void createPreprocessingRecord();
367 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
368 /// which implicitly adds the builtin defines etc.
369 bool EnterMainSourceFile();
371 /// EnterSourceFile - Add a source file to the top of the include stack and
372 /// start lexing tokens from it instead of the current buffer. Return true
373 /// and fill in ErrorStr with the error information on failure.
374 bool EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir,
375 std::string &ErrorStr);
377 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
378 /// tokens from it instead of the current buffer. Args specifies the
379 /// tokens input to a function-like macro.
381 /// ILEnd specifies the location of the ')' for a function-like macro or the
382 /// identifier for an object-like macro.
383 void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroArgs *Args);
385 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
386 /// which will cause the lexer to start returning the specified tokens.
388 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
389 /// not be subject to further macro expansion. Otherwise, these tokens will
390 /// be re-macro-expanded when/if expansion is enabled.
392 /// If OwnsTokens is false, this method assumes that the specified stream of
393 /// tokens has a permanent owner somewhere, so they do not need to be copied.
394 /// If it is true, it assumes the array of tokens is allocated with new[] and
397 void EnterTokenStream(const Token *Toks, unsigned NumToks,
398 bool DisableMacroExpansion, bool OwnsTokens);
400 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
401 /// lexer stack. This should only be used in situations where the current
402 /// state of the top-of-stack lexer is known.
403 void RemoveTopOfLexerStack();
405 /// EnableBacktrackAtThisPos - From the point that this method is called, and
406 /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
407 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
408 /// make the Preprocessor re-lex the same tokens.
410 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
411 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
412 /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
414 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
415 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
416 /// tokens will continue indefinitely.
418 void EnableBacktrackAtThisPos();
420 /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call.
421 void CommitBacktrackedTokens();
423 /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since
424 /// EnableBacktrackAtThisPos() was previously called.
427 /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and
428 /// caching of tokens is on.
429 bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
431 /// Lex - To lex a token from the preprocessor, just pull a token from the
432 /// current lexer or macro object.
433 void Lex(Token &Result) {
435 CurLexer->Lex(Result);
436 else if (CurPTHLexer)
437 CurPTHLexer->Lex(Result);
438 else if (CurTokenLexer)
439 CurTokenLexer->Lex(Result);
444 /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get
445 /// something not a comment. This is useful in -E -C mode where comments
446 /// would foul up preprocessor directive handling.
447 void LexNonComment(Token &Result) {
450 while (Result.getKind() == tok::comment);
453 /// LexUnexpandedToken - This is just like Lex, but this disables macro
454 /// expansion of identifier tokens.
455 void LexUnexpandedToken(Token &Result) {
456 // Disable macro expansion.
457 bool OldVal = DisableMacroExpansion;
458 DisableMacroExpansion = true;
463 DisableMacroExpansion = OldVal;
466 /// LookAhead - This peeks ahead N tokens and returns that token without
467 /// consuming any tokens. LookAhead(0) returns the next token that would be
468 /// returned by Lex(), LookAhead(1) returns the token after it, etc. This
469 /// returns normal tokens after phase 5. As such, it is equivalent to using
470 /// 'Lex', not 'LexUnexpandedToken'.
471 const Token &LookAhead(unsigned N) {
472 if (CachedLexPos + N < CachedTokens.size())
473 return CachedTokens[CachedLexPos+N];
475 return PeekAhead(N+1);
478 /// RevertCachedTokens - When backtracking is enabled and tokens are cached,
479 /// this allows to revert a specific number of tokens.
480 /// Note that the number of tokens being reverted should be up to the last
481 /// backtrack position, not more.
482 void RevertCachedTokens(unsigned N) {
483 assert(isBacktrackEnabled() &&
484 "Should only be called when tokens are cached for backtracking");
485 assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back())
486 && "Should revert tokens up to the last backtrack position, not more");
487 assert(signed(CachedLexPos) - signed(N) >= 0 &&
488 "Corrupted backtrack positions ?");
492 /// EnterToken - Enters a token in the token stream to be lexed next. If
493 /// BackTrack() is called afterwards, the token will remain at the insertion
495 void EnterToken(const Token &Tok) {
496 EnterCachingLexMode();
497 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
500 /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching
501 /// tokens (because backtrack is enabled) it should replace the most recent
502 /// cached tokens with the given annotation token. This function has no effect
503 /// if backtracking is not enabled.
505 /// Note that the use of this function is just for optimization; so that the
506 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
508 void AnnotateCachedTokens(const Token &Tok) {
509 assert(Tok.isAnnotation() && "Expected annotation token");
510 if (CachedLexPos != 0 && isBacktrackEnabled())
511 AnnotatePreviousCachedTokens(Tok);
514 /// \brief Replace the last token with an annotation token.
516 /// Like AnnotateCachedTokens(), this routine replaces an
517 /// already-parsed (and resolved) token with an annotation
518 /// token. However, this routine only replaces the last token with
519 /// the annotation token; it does not affect any other cached
520 /// tokens. This function has no effect if backtracking is not
522 void ReplaceLastTokenWithAnnotation(const Token &Tok) {
523 assert(Tok.isAnnotation() && "Expected annotation token");
524 if (CachedLexPos != 0 && isBacktrackEnabled())
525 CachedTokens[CachedLexPos-1] = Tok;
528 /// \brief Specify the point at which code-completion will be performed.
530 /// \param File the file in which code completion should occur. If
531 /// this file is included multiple times, code-completion will
532 /// perform completion the first time it is included. If NULL, this
533 /// function clears out the code-completion point.
535 /// \param Line the line at which code completion should occur
538 /// \param Column the column at which code completion should occur
541 /// \returns true if an error occurred, false otherwise.
542 bool SetCodeCompletionPoint(const FileEntry *File,
543 unsigned Line, unsigned Column);
545 /// \brief Determine if this source location refers into the file
546 /// for which we are performing code completion.
547 bool isCodeCompletionFile(SourceLocation FileLoc) const;
549 /// Diag - Forwarding function for diagnostics. This emits a diagnostic at
550 /// the specified Token's location, translating the token's start
551 /// position in the current buffer into a SourcePosition object for rendering.
552 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
553 return Diags->Report(FullSourceLoc(Loc, getSourceManager()), DiagID);
556 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) {
557 return Diags->Report(FullSourceLoc(Tok.getLocation(), getSourceManager()),
561 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a
562 /// token is the characters used to represent the token in the source file
563 /// after trigraph expansion and escaped-newline folding. In particular, this
564 /// wants to get the true, uncanonicalized, spelling of things like digraphs
567 /// \param Invalid If non-NULL, will be set \c true if an error occurs.
568 std::string getSpelling(const Token &Tok, bool *Invalid = 0) const;
570 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a
571 /// token is the characters used to represent the token in the source file
572 /// after trigraph expansion and escaped-newline folding. In particular, this
573 /// wants to get the true, uncanonicalized, spelling of things like digraphs
575 static std::string getSpelling(const Token &Tok,
576 const SourceManager &SourceMgr,
577 const LangOptions &Features,
580 /// getSpelling - This method is used to get the spelling of a token into a
581 /// preallocated buffer, instead of as an std::string. The caller is required
582 /// to allocate enough space for the token, which is guaranteed to be at least
583 /// Tok.getLength() bytes long. The length of the actual result is returned.
585 /// Note that this method may do two possible things: it may either fill in
586 /// the buffer specified with characters, or it may *change the input pointer*
587 /// to point to a constant buffer with the data already in it (avoiding a
588 /// copy). The caller is not allowed to modify the returned buffer pointer
589 /// if an internal buffer is returned.
590 unsigned getSpelling(const Token &Tok, const char *&Buffer,
591 bool *Invalid = 0) const;
593 /// getSpelling - This method is used to get the spelling of a token into a
594 /// SmallVector. Note that the returned StringRef may not point to the
595 /// supplied buffer if a copy can be avoided.
596 llvm::StringRef getSpelling(const Token &Tok,
597 llvm::SmallVectorImpl<char> &Buffer,
598 bool *Invalid = 0) const;
600 /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric constant
601 /// with length 1, return the character.
602 char getSpellingOfSingleCharacterNumericConstant(const Token &Tok,
603 bool *Invalid = 0) const {
604 assert(Tok.is(tok::numeric_constant) &&
605 Tok.getLength() == 1 && "Called on unsupported token");
606 assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
608 // If the token is carrying a literal data pointer, just use it.
609 if (const char *D = Tok.getLiteralData())
612 // Otherwise, fall back on getCharacterData, which is slower, but always
614 return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid);
617 /// CreateString - Plop the specified string into a scratch buffer and set the
618 /// specified token's location and length to it. If specified, the source
619 /// location provides a location of the instantiation point of the token.
620 void CreateString(const char *Buf, unsigned Len,
621 Token &Tok, SourceLocation SourceLoc = SourceLocation());
623 /// \brief Computes the source location just past the end of the
624 /// token at this source location.
626 /// This routine can be used to produce a source location that
627 /// points just past the end of the token referenced by \p Loc, and
628 /// is generally used when a diagnostic needs to point just after a
629 /// token where it expected something different that it received. If
630 /// the returned source location would not be meaningful (e.g., if
631 /// it points into a macro), this routine returns an invalid
634 /// \param Offset an offset from the end of the token, where the source
635 /// location should refer to. The default offset (0) produces a source
636 /// location pointing just past the end of the token; an offset of 1 produces
637 /// a source location pointing to the last character in the token, etc.
638 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
640 /// DumpToken - Print the token to stderr, used for debugging.
642 void DumpToken(const Token &Tok, bool DumpFlags = false) const;
643 void DumpLocation(SourceLocation Loc) const;
644 void DumpMacro(const MacroInfo &MI) const;
646 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
647 /// token, return a new location that specifies a character within the token.
648 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char);
650 /// IncrementPasteCounter - Increment the counters for the number of token
651 /// paste operations performed. If fast was specified, this is a 'fast paste'
654 void IncrementPasteCounter(bool isFast) {
663 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
664 /// comment (/##/) in microsoft mode, this method handles updating the current
665 /// state, returning the token on the next source line.
666 void HandleMicrosoftCommentPaste(Token &Tok);
668 //===--------------------------------------------------------------------===//
669 // Preprocessor callback methods. These are invoked by a lexer as various
670 // directives and events are found.
672 /// LookUpIdentifierInfo - Given a tok::identifier token, look up the
673 /// identifier information for the token and install it into the token.
674 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier,
675 const char *BufPtr = 0) const;
677 /// HandleIdentifier - This callback is invoked when the lexer reads an
678 /// identifier and has filled in the tokens IdentifierInfo member. This
679 /// callback potentially macro expands it or turns it into a named token (like
681 void HandleIdentifier(Token &Identifier);
684 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
685 /// the current file. This either returns the EOF token and returns true, or
686 /// pops a level off the include stack and returns false, at which point the
687 /// client should call lex again.
688 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
690 /// HandleEndOfTokenLexer - This callback is invoked when the current
691 /// TokenLexer hits the end of its token stream.
692 bool HandleEndOfTokenLexer(Token &Result);
694 /// HandleDirective - This callback is invoked when the lexer sees a # token
695 /// at the start of a line. This consumes the directive, modifies the
696 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
697 /// read is the correct one.
698 void HandleDirective(Token &Result);
700 /// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
701 /// not, emit a diagnostic and consume up until the eom. If EnableMacros is
702 /// true, then we consider macros that expand to zero tokens as being ok.
703 void CheckEndOfDirective(const char *Directive, bool EnableMacros = false);
705 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
706 /// current line until the tok::eom token is found.
707 void DiscardUntilEndOfDirective();
709 /// SawDateOrTime - This returns true if the preprocessor has seen a use of
710 /// __DATE__ or __TIME__ in the file so far.
711 bool SawDateOrTime() const {
712 return DATELoc != SourceLocation() || TIMELoc != SourceLocation();
714 unsigned getCounterValue() const { return CounterValue; }
715 void setCounterValue(unsigned V) { CounterValue = V; }
717 /// AllocateMacroInfo - Allocate a new MacroInfo object with the provide
719 MacroInfo* AllocateMacroInfo(SourceLocation L);
721 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
722 /// checked and spelled filename, e.g. as an operand of #include. This returns
723 /// true if the input filename was in <>'s or false if it were in ""'s. The
724 /// caller is expected to provide a buffer that is large enough to hold the
725 /// spelling of the filename, but is also expected to handle the case when
726 /// this method decides to use a different buffer.
727 bool GetIncludeFilenameSpelling(SourceLocation Loc,llvm::StringRef &Filename);
729 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
730 /// return null on failure. isAngled indicates whether the file reference is
731 /// for system #include's or not (i.e. using <> instead of "").
732 const FileEntry *LookupFile(llvm::StringRef Filename,
733 bool isAngled, const DirectoryLookup *FromDir,
734 const DirectoryLookup *&CurDir);
736 /// GetCurLookup - The DirectoryLookup structure used to find the current
737 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to
738 /// implement #include_next and find directory-specific properties.
739 const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; }
741 /// isInPrimaryFile - Return true if we're in the top-level file, not in a
743 bool isInPrimaryFile() const;
745 /// ConcatenateIncludeName - Handle cases where the #include name is expanded
746 /// from a macro as multiple tokens, which need to be glued together. This
747 /// occurs for code like:
748 /// #define FOO <a/b.h>
750 /// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
752 /// This code concatenates and consumes tokens up to the '>' token. It returns
753 /// false if the > was found, otherwise it returns true if it finds and consumes
755 bool ConcatenateIncludeName(llvm::SmallString<128> &FilenameBuffer);
759 void PushIncludeMacroStack() {
760 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(),
763 CurTokenLexer.take(),
768 void PopIncludeMacroStack() {
769 CurLexer.reset(IncludeMacroStack.back().TheLexer);
770 CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer);
771 CurPPLexer = IncludeMacroStack.back().ThePPLexer;
772 CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer);
773 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
774 IncludeMacroStack.pop_back();
777 /// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
778 /// be reused for allocating new MacroInfo objects.
779 void ReleaseMacroInfo(MacroInfo* MI);
781 /// ReadMacroName - Lex and validate a macro name, which occurs after a
782 /// #define or #undef. This emits a diagnostic, sets the token kind to eom,
783 /// and discards the rest of the macro line if the macro name is invalid.
784 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0);
786 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
787 /// definition has just been read. Lex the rest of the arguments and the
788 /// closing ), updating MI with what we learn. Return true if an error occurs
789 /// parsing the arg list.
790 bool ReadMacroDefinitionArgList(MacroInfo *MI);
792 /// SkipExcludedConditionalBlock - We just read a #if or related directive and
793 /// decided that the subsequent tokens are in the #if'd out portion of the
794 /// file. Lex the rest of the file, until we see an #endif. If
795 /// FoundNonSkipPortion is true, then we have already emitted code for part of
796 /// this #if directive, so #else/#elif blocks should never be entered. If
797 /// FoundElse is false, then #else directives are ok, if not, then we have
798 /// already seen one so a #else directive is a duplicate. When this returns,
799 /// the caller can lex the first valid token.
800 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
801 bool FoundNonSkipPortion, bool FoundElse);
803 /// PTHSkipExcludedConditionalBlock - A fast PTH version of
804 /// SkipExcludedConditionalBlock.
805 void PTHSkipExcludedConditionalBlock();
807 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
808 /// may occur after a #if or #elif directive and return it as a bool. If the
809 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro.
810 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
812 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
813 /// #pragma GCC poison/system_header/dependency and #pragma once.
814 void RegisterBuiltinPragmas();
816 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
817 /// identifier table.
818 void RegisterBuiltinMacros();
820 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to
821 /// be expanded as a macro, handle it and return the next token as 'Tok'. If
822 /// the macro should not be expanded return true, otherwise return false.
823 bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI);
825 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
826 /// lexed is a '('. If so, consume the token and return true, if not, this
827 /// method should have no observable side-effect on the lexed tokens.
828 bool isNextPPTokenLParen();
830 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
831 /// invoked to read all of the formal arguments specified for the macro
832 /// invocation. This returns null on error.
833 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI,
834 SourceLocation &InstantiationEnd);
836 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
837 /// as a builtin macro, handle it and return the next token as 'Tok'.
838 void ExpandBuiltinMacro(Token &Tok);
840 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
841 /// return the first token after the directive. The _Pragma token has just
842 /// been read into 'Tok'.
843 void Handle_Pragma(Token &Tok);
845 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and
846 /// start lexing tokens from it instead of the current buffer.
847 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
849 /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and
850 /// start getting tokens from it using the PTH cache.
851 void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir);
853 /// IsFileLexer - Returns true if we are lexing from a file and not a
854 /// pragma or a macro.
855 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
856 return L ? !L->isPragmaLexer() : P != 0;
859 static bool IsFileLexer(const IncludeStackInfo& I) {
860 return IsFileLexer(I.TheLexer, I.ThePPLexer);
863 bool IsFileLexer() const {
864 return IsFileLexer(CurLexer.get(), CurPPLexer);
867 //===--------------------------------------------------------------------===//
869 void CachingLex(Token &Result);
870 bool InCachingLexMode() const { return CurPPLexer == 0 && CurTokenLexer == 0;}
871 void EnterCachingLexMode();
872 void ExitCachingLexMode() {
873 if (InCachingLexMode())
874 RemoveTopOfLexerStack();
876 const Token &PeekAhead(unsigned N);
877 void AnnotatePreviousCachedTokens(const Token &Tok);
879 //===--------------------------------------------------------------------===//
880 /// Handle*Directive - implement the various preprocessor directives. These
881 /// should side-effect the current preprocessor object so that the next call
882 /// to Lex() will return the appropriate token next.
883 void HandleLineDirective(Token &Tok);
884 void HandleDigitDirective(Token &Tok);
885 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
886 void HandleIdentSCCSDirective(Token &Tok);
889 void HandleIncludeDirective(Token &Tok,
890 const DirectoryLookup *LookupFrom = 0,
891 bool isImport = false);
892 void HandleIncludeNextDirective(Token &Tok);
893 void HandleIncludeMacrosDirective(Token &Tok);
894 void HandleImportDirective(Token &Tok);
897 void HandleDefineDirective(Token &Tok);
898 void HandleUndefDirective(Token &Tok);
899 // HandleAssertDirective(Token &Tok);
900 // HandleUnassertDirective(Token &Tok);
902 // Conditional Inclusion.
903 void HandleIfdefDirective(Token &Tok, bool isIfndef,
904 bool ReadAnyTokensBeforeDirective);
905 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective);
906 void HandleEndifDirective(Token &Tok);
907 void HandleElseDirective(Token &Tok);
908 void HandleElifDirective(Token &Tok);
911 void HandlePragmaDirective();
913 void HandlePragmaOnce(Token &OnceTok);
914 void HandlePragmaMark();
915 void HandlePragmaPoison(Token &PoisonTok);
916 void HandlePragmaSystemHeader(Token &SysHeaderTok);
917 void HandlePragmaDependency(Token &DependencyTok);
918 void HandlePragmaComment(Token &CommentTok);
919 // Return true and store the first token only if any CommentHandler
920 // has inserted some tokens and getCommentRetentionState() is false.
921 bool HandleComment(Token &Token, SourceRange Comment);
924 /// \brief Abstract base class that describes a handler that will receive
925 /// source ranges for each of the comments encountered in the source file.
926 class CommentHandler {
928 virtual ~CommentHandler();
930 // The handler shall return true if it has pushed any tokens
931 // to be read using e.g. EnterToken or EnterTokenStream.
932 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
935 } // end namespace clang