Preprocessor.h revision 2e1cd4264d363ca869bf37ef160902f211d21b8c
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===--- Preprocessor.h - C Language Family Preprocessor --------*- C++ -*-===//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details.
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//  This file defines the Preprocessor interface.
115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifndef LLVM_CLANG_LEX_PREPROCESSOR_H
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define LLVM_CLANG_LEX_PREPROCESSOR_H
162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
17a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Lex/Lexer.h"
185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Lex/PPCallbacks.h"
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Lex/TokenLexer.h"
205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/IdentifierTable.h"
215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/SourceLocation.h"
225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/DenseMap.h"
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/OwningPtr.h"
245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace clang {
262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class SourceManager;
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class FileManager;
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class FileEntry;
305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class HeaderSearch;
315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class PragmaNamespace;
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class PragmaHandler;
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class ScratchBuffer;
345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class TargetInfo;
355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class PPCallbacks;
365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class DirectoryLookup;
375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
385d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// Preprocessor - This object engages in a tight little dance with the lexer to
395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// efficiently preprocess tokens.  Lexers know only about tokens within a
405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// single source file, and don't know anything about preprocessor-level issues
415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// like the #include stack, token expansion, etc.
425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)///
435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class Preprocessor {
445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Diagnostic        &Diags;
455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  const LangOptions &Features;
465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  TargetInfo        &Target;
475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  FileManager       &FileMgr;
485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  SourceManager     &SourceMgr;
495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ScratchBuffer     *ScratchBuf;
505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  HeaderSearch      &HeaderInfo;
515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// Identifiers for builtin macros and other builtins.
535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  IdentifierInfo *Ident__LINE__, *Ident__FILE__;   // __LINE__, __FILE__
545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  IdentifierInfo *Ident__DATE__, *Ident__TIME__;   // __DATE__, __TIME__
555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  IdentifierInfo *Ident__INCLUDE_LEVEL__;          // __INCLUDE_LEVEL__
56effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch  IdentifierInfo *Ident__BASE_FILE__;              // __BASE_FILE__
575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  IdentifierInfo *Ident__TIMESTAMP__;              // __TIMESTAMP__
58effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch  IdentifierInfo *Ident_Pragma, *Ident__VA_ARGS__; // _Pragma, __VA_ARGS__
595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  SourceLocation DATELoc, TIMELoc;
615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  enum {
635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    /// MaxIncludeStackDepth - Maximum depth of #includes.
645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    MaxAllowedIncludeStackDepth = 200
655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  };
665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // State that is set before the preprocessor begins.
685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  bool KeepComments : 1;
695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  bool KeepMacroComments : 1;
705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // State that changes while the preprocessor runs:
725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  bool DisableMacroExpansion : 1;  // True if macro expansion is disabled.
735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  bool InMacroArgs : 1;            // True if parsing fn macro invocation args.
742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// CacheTokens - True when the lexed tokens are cached for backtracking.
765f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  bool CacheTokens : 1;
775f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
785f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  /// Identifiers - This is mapping/lookup information for all identifiers in
795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// the program, including program keywords.
805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  IdentifierTable Identifiers;
815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// Selectors - This table contains all the selectors in the program. Unlike
835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// IdentifierTable above, this table *isn't* populated by the preprocessor.
845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// It is declared/instantiated here because it's role/lifetime is
855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// conceptually similar the IdentifierTable. In addition, the current control
865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// flow (in clang::ParseAST()), make it convenient to put here.
875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to
885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// the lifetime fo the preprocessor.
895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  SelectorTable Selectors;
905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// PragmaHandlers - This tracks all of the pragmas that the client registered
925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// with this preprocessor.
935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  PragmaNamespace *PragmaHandlers;
945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// CurLexer - This is the current top of the stack that we're lexing from if
965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// not expanding a macro.  One of CurLexer and CurTokenLexer must be null.
97  llvm::OwningPtr<Lexer> CurLexer;
98
99  /// CurLookup - The DirectoryLookup structure used to find the current
100  /// FileEntry, if CurLexer is non-null and if applicable.  This allows us to
101  /// implement #include_next and find directory-specific properties.
102  const DirectoryLookup *CurDirLookup;
103
104  /// CurTokenLexer - This is the current macro we are expanding, if we are
105  /// expanding a macro.  One of CurLexer and CurTokenLexer must be null.
106  llvm::OwningPtr<TokenLexer> CurTokenLexer;
107
108  /// IncludeMacroStack - This keeps track of the stack of files currently
109  /// #included, and macros currently being expanded from, not counting
110  /// CurLexer/CurTokenLexer.
111  struct IncludeStackInfo {
112    Lexer *TheLexer;
113    const DirectoryLookup *TheDirLookup;
114    TokenLexer *TheTokenLexer;
115    IncludeStackInfo(Lexer *L, const DirectoryLookup *D, TokenLexer *TL)
116      : TheLexer(L), TheDirLookup(D), TheTokenLexer(TL) {
117    }
118  };
119  std::vector<IncludeStackInfo> IncludeMacroStack;
120
121  /// Callbacks - These are actions invoked when some preprocessor activity is
122  /// encountered (e.g. a file is #included, etc).
123  PPCallbacks *Callbacks;
124
125  /// Macros - For each IdentifierInfo with 'HasMacro' set, we keep a mapping
126  /// to the actual definition of the macro.
127  llvm::DenseMap<IdentifierInfo*, MacroInfo*> Macros;
128
129  // Various statistics we track for performance analysis.
130  unsigned NumDirectives, NumIncluded, NumDefined, NumUndefined, NumPragma;
131  unsigned NumIf, NumElse, NumEndif;
132  unsigned NumEnteredSourceFiles, MaxIncludeStackDepth;
133  unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded;
134  unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste;
135  unsigned NumSkipped;
136
137  /// Predefines - This string is the predefined macros that preprocessor
138  /// should use from the command line etc.
139  std::string Predefines;
140
141  /// TokenLexerCache - Cache macro expanders to reduce malloc traffic.
142  enum { TokenLexerCacheSize = 8 };
143  unsigned NumCachedTokenLexers;
144  TokenLexer *TokenLexerCache[TokenLexerCacheSize];
145
146private:  // Cached tokens state.
147  typedef std::vector<Token> CachedTokensTy;
148
149  /// CachedTokens - Cached tokens are stored here when we do backtracking or
150  /// lookahead. They are "lexed" by the CachingLex() method.
151  CachedTokensTy CachedTokens;
152
153  /// CachedLexPos - The position of the cached token that CachingLex() should
154  /// "lex" next. If it points beyond the CachedTokens vector, it means that
155  /// a normal Lex() should be invoked.
156  CachedTokensTy::size_type CachedLexPos;
157
158  /// BacktrackPositions - Stack of backtrack positions, allowing nested
159  /// backtracks. The EnableBacktrackAtThisPos() method pushes a position to
160  /// indicate where CachedLexPos should be set when the BackTrack() method is
161  /// invoked (at which point the last position is popped).
162  std::vector<CachedTokensTy::size_type> BacktrackPositions;
163
164public:
165  Preprocessor(Diagnostic &diags, const LangOptions &opts, TargetInfo &target,
166               SourceManager &SM, HeaderSearch &Headers);
167  ~Preprocessor();
168
169  Diagnostic &getDiagnostics() const { return Diags; }
170  const LangOptions &getLangOptions() const { return Features; }
171  TargetInfo &getTargetInfo() const { return Target; }
172  FileManager &getFileManager() const { return FileMgr; }
173  SourceManager &getSourceManager() const { return SourceMgr; }
174  HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
175
176  IdentifierTable &getIdentifierTable() { return Identifiers; }
177  SelectorTable &getSelectorTable() { return Selectors; }
178
179  inline FullSourceLoc getFullLoc(SourceLocation Loc) const {
180    return FullSourceLoc(Loc, getSourceManager());
181  }
182
183  /// SetCommentRetentionState - Control whether or not the preprocessor retains
184  /// comments in output.
185  void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
186    this->KeepComments = KeepComments | KeepMacroComments;
187    this->KeepMacroComments = KeepMacroComments;
188  }
189
190  bool getCommentRetentionState() const { return KeepComments; }
191
192  /// isCurrentLexer - Return true if we are lexing directly from the specified
193  /// lexer.
194  bool isCurrentLexer(const Lexer *L) const {
195    return CurLexer.get() == L;
196  }
197
198  /// getCurrentLexer - Return the current file lexer being lexed from.  Note
199  /// that this ignores any potentially active macro expansions and _Pragma
200  /// expansions going on at the time.
201  Lexer *getCurrentFileLexer() const;
202
203  /// getPPCallbacks/setPPCallbacks - Accessors for preprocessor callbacks.
204  /// Note that this class takes ownership of any PPCallbacks object given to
205  /// it.
206  PPCallbacks *getPPCallbacks() const { return Callbacks; }
207  void setPPCallbacks(PPCallbacks *C) {
208    delete Callbacks;
209    Callbacks = C;
210  }
211
212  /// getMacroInfo - Given an identifier, return the MacroInfo it is #defined to
213  /// or null if it isn't #define'd.
214  MacroInfo *getMacroInfo(IdentifierInfo *II) const {
215    return II->hasMacroDefinition() ? Macros.find(II)->second : 0;
216  }
217
218  /// setMacroInfo - Specify a macro for this identifier.
219  ///
220  void setMacroInfo(IdentifierInfo *II, MacroInfo *MI);
221
222  const std::string &getPredefines() const { return Predefines; }
223  /// setPredefines - Set the predefines for this Preprocessor.  These
224  /// predefines are automatically injected when parsing the main file.
225  void setPredefines(const char *P) { Predefines = P; }
226  void setPredefines(const std::string &P) { Predefines = P; }
227
228  /// getIdentifierInfo - Return information about the specified preprocessor
229  /// identifier token.  The version of this method that takes two character
230  /// pointers is preferred unless the identifier is already available as a
231  /// string (this avoids allocation and copying of memory to construct an
232  /// std::string).
233  IdentifierInfo *getIdentifierInfo(const char *NameStart,
234                                    const char *NameEnd) {
235    return &Identifiers.get(NameStart, NameEnd);
236  }
237  IdentifierInfo *getIdentifierInfo(const char *NameStr) {
238    return getIdentifierInfo(NameStr, NameStr+strlen(NameStr));
239  }
240
241  /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
242  /// If 'Namespace' is non-null, then it is a token required to exist on the
243  /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
244  void AddPragmaHandler(const char *Namespace, PragmaHandler *Handler);
245
246  /// RemovePragmaHandler - Remove the specific pragma handler from
247  /// the preprocessor. If \arg Namespace is non-null, then it should
248  /// be the namespace that \arg Handler was added to. It is an error
249  /// to remove a handler that has not been registered.
250  void RemovePragmaHandler(const char *Namespace, PragmaHandler *Handler);
251
252  /// EnterMainSourceFile - Enter the specified FileID as the main source file,
253  /// which implicitly adds the builtin defines etc.
254  void EnterMainSourceFile();
255
256  /// EnterSourceFile - Add a source file to the top of the include stack and
257  /// start lexing tokens from it instead of the current buffer.  If isMainFile
258  /// is true, this is the main file for the translation unit.
259  void EnterSourceFile(unsigned CurFileID, const DirectoryLookup *Dir);
260
261  /// EnterMacro - Add a Macro to the top of the include stack and start lexing
262  /// tokens from it instead of the current buffer.  Args specifies the
263  /// tokens input to a function-like macro.
264  void EnterMacro(Token &Identifier, MacroArgs *Args);
265
266  /// EnterTokenStream - Add a "macro" context to the top of the include stack,
267  /// which will cause the lexer to start returning the specified tokens.
268  ///
269  /// If DisableMacroExpansion is true, tokens lexed from the token stream will
270  /// not be subject to further macro expansion.  Otherwise, these tokens will
271  /// be re-macro-expanded when/if expansion is enabled.
272  ///
273  /// If OwnsTokens is false, this method assumes that the specified stream of
274  /// tokens has a permanent owner somewhere, so they do not need to be copied.
275  /// If it is true, it assumes the array of tokens is allocated with new[] and
276  /// must be freed.
277  ///
278  void EnterTokenStream(const Token *Toks, unsigned NumToks,
279                        bool DisableMacroExpansion, bool OwnsTokens);
280
281  /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
282  /// lexer stack.  This should only be used in situations where the current
283  /// state of the top-of-stack lexer is known.
284  void RemoveTopOfLexerStack();
285
286  /// EnableBacktrackAtThisPos - From the point that this method is called, and
287  /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
288  /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
289  /// make the Preprocessor re-lex the same tokens.
290  ///
291  /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
292  /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
293  /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
294  ///
295  /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
296  /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
297  /// tokens will continue indefinitely.
298  ///
299  void EnableBacktrackAtThisPos();
300
301  /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call.
302  void CommitBacktrackedTokens();
303
304  /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since
305  /// EnableBacktrackAtThisPos() was previously called.
306  void Backtrack();
307
308  /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and
309  /// caching of tokens is on.
310  bool isBacktrackEnabled() const { return CacheTokens; }
311
312  /// Lex - To lex a token from the preprocessor, just pull a token from the
313  /// current lexer or macro object.
314  void Lex(Token &Result) {
315    if (CurLexer)
316      CurLexer->Lex(Result);
317    else if (CurTokenLexer)
318      CurTokenLexer->Lex(Result);
319    else
320      CachingLex(Result);
321  }
322
323  /// LexNonComment - Lex a token.  If it's a comment, keep lexing until we get
324  /// something not a comment.  This is useful in -E -C mode where comments
325  /// would foul up preprocessor directive handling.
326  void LexNonComment(Token &Result) {
327    do
328      Lex(Result);
329    while (Result.getKind() == tok::comment);
330  }
331
332  /// LexUnexpandedToken - This is just like Lex, but this disables macro
333  /// expansion of identifier tokens.
334  void LexUnexpandedToken(Token &Result) {
335    // Disable macro expansion.
336    bool OldVal = DisableMacroExpansion;
337    DisableMacroExpansion = true;
338    // Lex the token.
339    Lex(Result);
340
341    // Reenable it.
342    DisableMacroExpansion = OldVal;
343  }
344
345  /// LookAhead - This peeks ahead N tokens and returns that token without
346  /// consuming any tokens.  LookAhead(0) returns the next token that would be
347  /// returned by Lex(), LookAhead(1) returns the token after it, etc.  This
348  /// returns normal tokens after phase 5.  As such, it is equivalent to using
349  /// 'Lex', not 'LexUnexpandedToken'.
350  const Token &LookAhead(unsigned N) {
351    if (CachedLexPos + N < CachedTokens.size())
352      return CachedTokens[CachedLexPos+N];
353    else
354      return PeekAhead(N+1);
355  }
356
357  /// EnterToken - Enters a token in the token stream to be lexed next. If
358  /// BackTrack() is called afterwards, the token will remain at the insertion
359  /// point.
360  void EnterToken(const Token &Tok) {
361    EnterCachingLexMode();
362    CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
363  }
364
365  /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching
366  /// tokens (because backtrack is enabled) it should replace the most recent
367  /// cached tokens with the given annotation token. This function has no effect
368  /// if backtracking is not enabled.
369  ///
370  /// Note that the use of this function is just for optimization; so that the
371  /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
372  /// invoked.
373  void AnnotateCachedTokens(const Token &Tok) {
374    assert(Tok.isAnnotationToken() && "Expected annotation token");
375    if (CachedLexPos != 0 && InCachingLexMode())
376      AnnotatePreviousCachedTokens(Tok);
377  }
378
379  /// Diag - Forwarding function for diagnostics.  This emits a diagnostic at
380  /// the specified Token's location, translating the token's start
381  /// position in the current buffer into a SourcePosition object for rendering.
382  void Diag(SourceLocation Loc, unsigned DiagID);
383  void Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg);
384  void Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg,
385            const SourceRange &R1, const SourceRange &R2);
386  void Diag(SourceLocation Loc, unsigned DiagID, const SourceRange &R);
387  void Diag(SourceLocation Loc, unsigned DiagID, const SourceRange &R1,
388            const SourceRange &R2);
389  void Diag(const Token &Tok, unsigned DiagID) {
390    Diag(Tok.getLocation(), DiagID);
391  }
392  void Diag(const Token &Tok, unsigned DiagID, const std::string &Msg) {
393    Diag(Tok.getLocation(), DiagID, Msg);
394  }
395
396  /// getSpelling() - Return the 'spelling' of the Tok token.  The spelling of a
397  /// token is the characters used to represent the token in the source file
398  /// after trigraph expansion and escaped-newline folding.  In particular, this
399  /// wants to get the true, uncanonicalized, spelling of things like digraphs
400  /// UCNs, etc.
401  std::string getSpelling(const Token &Tok) const;
402
403  /// getSpelling - This method is used to get the spelling of a token into a
404  /// preallocated buffer, instead of as an std::string.  The caller is required
405  /// to allocate enough space for the token, which is guaranteed to be at least
406  /// Tok.getLength() bytes long.  The length of the actual result is returned.
407  ///
408  /// Note that this method may do two possible things: it may either fill in
409  /// the buffer specified with characters, or it may *change the input pointer*
410  /// to point to a constant buffer with the data already in it (avoiding a
411  /// copy).  The caller is not allowed to modify the returned buffer pointer
412  /// if an internal buffer is returned.
413  unsigned getSpelling(const Token &Tok, const char *&Buffer) const;
414
415
416  /// CreateString - Plop the specified string into a scratch buffer and return
417  /// a location for it.  If specified, the source location provides a source
418  /// location for the token.
419  SourceLocation CreateString(const char *Buf, unsigned Len,
420                              SourceLocation SourceLoc = SourceLocation());
421
422  /// DumpToken - Print the token to stderr, used for debugging.
423  ///
424  void DumpToken(const Token &Tok, bool DumpFlags = false) const;
425  void DumpLocation(SourceLocation Loc) const;
426  void DumpMacro(const MacroInfo &MI) const;
427
428  /// AdvanceToTokenCharacter - Given a location that specifies the start of a
429  /// token, return a new location that specifies a character within the token.
430  SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char);
431
432  /// IncrementPasteCounter - Increment the counters for the number of token
433  /// paste operations performed.  If fast was specified, this is a 'fast paste'
434  /// case we handled.
435  ///
436  void IncrementPasteCounter(bool isFast) {
437    if (isFast)
438      ++NumFastTokenPaste;
439    else
440      ++NumTokenPaste;
441  }
442
443  void PrintStats();
444
445  /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
446  /// comment (/##/) in microsoft mode, this method handles updating the current
447  /// state, returning the token on the next source line.
448  void HandleMicrosoftCommentPaste(Token &Tok);
449
450  //===--------------------------------------------------------------------===//
451  // Preprocessor callback methods.  These are invoked by a lexer as various
452  // directives and events are found.
453
454  /// LookUpIdentifierInfo - Given a tok::identifier token, look up the
455  /// identifier information for the token and install it into the token.
456  IdentifierInfo *LookUpIdentifierInfo(Token &Identifier,
457                                       const char *BufPtr = 0);
458
459  /// HandleIdentifier - This callback is invoked when the lexer reads an
460  /// identifier and has filled in the tokens IdentifierInfo member.  This
461  /// callback potentially macro expands it or turns it into a named token (like
462  /// 'for').
463  void HandleIdentifier(Token &Identifier);
464
465
466  /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
467  /// the current file.  This either returns the EOF token and returns true, or
468  /// pops a level off the include stack and returns false, at which point the
469  /// client should call lex again.
470  bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
471
472  /// HandleEndOfTokenLexer - This callback is invoked when the current
473  /// TokenLexer hits the end of its token stream.
474  bool HandleEndOfTokenLexer(Token &Result);
475
476  /// HandleDirective - This callback is invoked when the lexer sees a # token
477  /// at the start of a line.  This consumes the directive, modifies the
478  /// lexer/preprocessor state, and advances the lexer(s) so that the next token
479  /// read is the correct one.
480  void HandleDirective(Token &Result);
481
482  /// CheckEndOfDirective - Ensure that the next token is a tok::eom token.  If
483  /// not, emit a diagnostic and consume up until the eom.
484  void CheckEndOfDirective(const char *Directive);
485private:
486
487  void PushIncludeMacroStack() {
488    IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(), CurDirLookup,
489                                                 CurTokenLexer.take()));
490  }
491
492  void PopIncludeMacroStack() {
493    CurLexer.reset(IncludeMacroStack.back().TheLexer);
494    CurDirLookup  = IncludeMacroStack.back().TheDirLookup;
495    CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer);
496    IncludeMacroStack.pop_back();
497  }
498
499  /// isInPrimaryFile - Return true if we're in the top-level file, not in a
500  /// #include.
501  bool isInPrimaryFile() const;
502
503  /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
504  /// current line until the tok::eom token is found.
505  void DiscardUntilEndOfDirective();
506
507  /// ReadMacroName - Lex and validate a macro name, which occurs after a
508  /// #define or #undef.  This emits a diagnostic, sets the token kind to eom,
509  /// and discards the rest of the macro line if the macro name is invalid.
510  void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0);
511
512  /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
513  /// definition has just been read.  Lex the rest of the arguments and the
514  /// closing ), updating MI with what we learn.  Return true if an error occurs
515  /// parsing the arg list.
516  bool ReadMacroDefinitionArgList(MacroInfo *MI);
517
518  /// SkipExcludedConditionalBlock - We just read a #if or related directive and
519  /// decided that the subsequent tokens are in the #if'd out portion of the
520  /// file.  Lex the rest of the file, until we see an #endif.  If
521  /// FoundNonSkipPortion is true, then we have already emitted code for part of
522  /// this #if directive, so #else/#elif blocks should never be entered. If
523  /// FoundElse is false, then #else directives are ok, if not, then we have
524  /// already seen one so a #else directive is a duplicate.  When this returns,
525  /// the caller can lex the first valid token.
526  void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
527                                    bool FoundNonSkipPortion, bool FoundElse);
528
529  /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
530  /// may occur after a #if or #elif directive and return it as a bool.  If the
531  /// expression is equivalent to "!defined(X)" return X in IfNDefMacro.
532  bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
533
534  /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
535  /// #pragma GCC poison/system_header/dependency and #pragma once.
536  void RegisterBuiltinPragmas();
537
538  /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
539  /// identifier table.
540  void RegisterBuiltinMacros();
541  IdentifierInfo *RegisterBuiltinMacro(const char *Name);
542
543  /// HandleMacroExpandedIdentifier - If an identifier token is read that is to
544  /// be expanded as a macro, handle it and return the next token as 'Tok'.  If
545  /// the macro should not be expanded return true, otherwise return false.
546  bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI);
547
548  /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
549  /// lexed is a '('.  If so, consume the token and return true, if not, this
550  /// method should have no observable side-effect on the lexed tokens.
551  bool isNextPPTokenLParen();
552
553  /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
554  /// invoked to read all of the formal arguments specified for the macro
555  /// invocation.  This returns null on error.
556  MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI);
557
558  /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
559  /// as a builtin macro, handle it and return the next token as 'Tok'.
560  void ExpandBuiltinMacro(Token &Tok);
561
562  /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
563  /// return the first token after the directive.  The _Pragma token has just
564  /// been read into 'Tok'.
565  void Handle_Pragma(Token &Tok);
566
567
568  /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and
569  /// start lexing tokens from it instead of the current buffer.
570  void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
571
572  /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
573  /// checked and spelled filename, e.g. as an operand of #include. This returns
574  /// true if the input filename was in <>'s or false if it were in ""'s.  The
575  /// caller is expected to provide a buffer that is large enough to hold the
576  /// spelling of the filename, but is also expected to handle the case when
577  /// this method decides to use a different buffer.
578  bool GetIncludeFilenameSpelling(SourceLocation Loc,
579                                  const char *&BufStart, const char *&BufEnd);
580
581  /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
582  /// return null on failure.  isAngled indicates whether the file reference is
583  /// for system #include's or not (i.e. using <> instead of "").
584  const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd,
585                              bool isAngled, const DirectoryLookup *FromDir,
586                              const DirectoryLookup *&CurDir);
587
588  //===--------------------------------------------------------------------===//
589  // Caching stuff.
590  void CachingLex(Token &Result);
591  bool InCachingLexMode() const { return CurLexer == 0 && CurTokenLexer == 0; }
592  void EnterCachingLexMode();
593  void ExitCachingLexMode() {
594    if (InCachingLexMode())
595      RemoveTopOfLexerStack();
596  }
597  const Token &PeekAhead(unsigned N);
598  void AnnotatePreviousCachedTokens(const Token &Tok);
599
600  //===--------------------------------------------------------------------===//
601  /// Handle*Directive - implement the various preprocessor directives.  These
602  /// should side-effect the current preprocessor object so that the next call
603  /// to Lex() will return the appropriate token next.
604
605  void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
606  void HandleIdentSCCSDirective(Token &Tok);
607
608  // File inclusion.
609  void HandleIncludeDirective(Token &Tok,
610                              const DirectoryLookup *LookupFrom = 0,
611                              bool isImport = false);
612  void HandleIncludeNextDirective(Token &Tok);
613  void HandleImportDirective(Token &Tok);
614
615  // Macro handling.
616  void HandleDefineDirective(Token &Tok);
617  void HandleUndefDirective(Token &Tok);
618  // HandleAssertDirective(Token &Tok);
619  // HandleUnassertDirective(Token &Tok);
620
621  // Conditional Inclusion.
622  void HandleIfdefDirective(Token &Tok, bool isIfndef,
623                            bool ReadAnyTokensBeforeDirective);
624  void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective);
625  void HandleEndifDirective(Token &Tok);
626  void HandleElseDirective(Token &Tok);
627  void HandleElifDirective(Token &Tok);
628
629  // Pragmas.
630  void HandlePragmaDirective();
631public:
632  void HandlePragmaOnce(Token &OnceTok);
633  void HandlePragmaMark();
634  void HandlePragmaPoison(Token &PoisonTok);
635  void HandlePragmaSystemHeader(Token &SysHeaderTok);
636  void HandlePragmaDependency(Token &DependencyTok);
637};
638
639/// PreprocessorFactory - A generic factory interface for lazily creating
640///  Preprocessor objects on-demand when they are needed.
641class PreprocessorFactory {
642public:
643  virtual ~PreprocessorFactory();
644  virtual Preprocessor* CreatePreprocessor() = 0;
645};
646
647}  // end namespace clang
648
649#endif
650