Preprocessor.h revision 148772a841cae6f32db16d890e788b92a763bb3f
1//===--- Preprocessor.h - C Language Family Preprocessor --------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LEX_PREPROCESSOR_H
15#define LLVM_CLANG_LEX_PREPROCESSOR_H
16
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/Diagnostic.h"
23#include "clang/Basic/IdentifierTable.h"
24#include "clang/Basic/SourceLocation.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/OwningPtr.h"
27#include "llvm/Support/Allocator.h"
28
29namespace clang {
30
31class SourceManager;
32class FileManager;
33class FileEntry;
34class HeaderSearch;
35class PragmaNamespace;
36class PragmaHandler;
37class ScratchBuffer;
38class TargetInfo;
39class PPCallbacks;
40class DirectoryLookup;
41
42/// Preprocessor - This object engages in a tight little dance with the lexer to
43/// efficiently preprocess tokens.  Lexers know only about tokens within a
44/// single source file, and don't know anything about preprocessor-level issues
45/// like the #include stack, token expansion, etc.
46///
47class Preprocessor {
48  Diagnostic        *Diags;
49  const LangOptions &Features;
50  TargetInfo        &Target;
51  FileManager       &FileMgr;
52  SourceManager     &SourceMgr;
53  ScratchBuffer     *ScratchBuf;
54  HeaderSearch      &HeaderInfo;
55
56  /// PTH - An optional PTHManager object used for getting tokens from
57  ///  a token cache rather than lexing the original source file.
58  llvm::OwningPtr<PTHManager> PTH;
59
60  /// BP - A BumpPtrAllocator object used to quickly allocate and release
61  ///  objects internal to the Preprocessor.
62  llvm::BumpPtrAllocator BP;
63
64  /// Identifiers for builtin macros and other builtins.
65  IdentifierInfo *Ident__LINE__, *Ident__FILE__;   // __LINE__, __FILE__
66  IdentifierInfo *Ident__DATE__, *Ident__TIME__;   // __DATE__, __TIME__
67  IdentifierInfo *Ident__INCLUDE_LEVEL__;          // __INCLUDE_LEVEL__
68  IdentifierInfo *Ident__BASE_FILE__;              // __BASE_FILE__
69  IdentifierInfo *Ident__TIMESTAMP__;              // __TIMESTAMP__
70  IdentifierInfo *Ident__COUNTER__;                // __COUNTER__
71  IdentifierInfo *Ident_Pragma, *Ident__VA_ARGS__; // _Pragma, __VA_ARGS__
72  IdentifierInfo *Ident__has_feature;              // __has_feature
73  IdentifierInfo *Ident__has_builtin;              // __has_builtin
74
75  SourceLocation DATELoc, TIMELoc;
76  unsigned CounterValue;  // Next __COUNTER__ value.
77
78  enum {
79    /// MaxIncludeStackDepth - Maximum depth of #includes.
80    MaxAllowedIncludeStackDepth = 200
81  };
82
83  // State that is set before the preprocessor begins.
84  bool KeepComments : 1;
85  bool KeepMacroComments : 1;
86
87  // State that changes while the preprocessor runs:
88  bool DisableMacroExpansion : 1;  // True if macro expansion is disabled.
89  bool InMacroArgs : 1;            // True if parsing fn macro invocation args.
90
91  /// Identifiers - This is mapping/lookup information for all identifiers in
92  /// the program, including program keywords.
93  IdentifierTable Identifiers;
94
95  /// Selectors - This table contains all the selectors in the program. Unlike
96  /// IdentifierTable above, this table *isn't* populated by the preprocessor.
97  /// It is declared/instantiated here because it's role/lifetime is
98  /// conceptually similar the IdentifierTable. In addition, the current control
99  /// flow (in clang::ParseAST()), make it convenient to put here.
100  /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to
101  /// the lifetime fo the preprocessor.
102  SelectorTable Selectors;
103
104  /// PragmaHandlers - This tracks all of the pragmas that the client registered
105  /// with this preprocessor.
106  PragmaNamespace *PragmaHandlers;
107
108  /// CurLexer - This is the current top of the stack that we're lexing from if
109  /// not expanding a macro and we are lexing directly from source code.
110  ///  Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
111  llvm::OwningPtr<Lexer> CurLexer;
112
113  /// CurPTHLexer - This is the current top of stack that we're lexing from if
114  ///  not expanding from a macro and we are lexing from a PTH cache.
115  ///  Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null.
116  llvm::OwningPtr<PTHLexer> CurPTHLexer;
117
118  /// CurPPLexer - This is the current top of the stack what we're lexing from
119  ///  if not expanding a macro.  This is an alias for either CurLexer or
120  ///  CurPTHLexer.
121  PreprocessorLexer* CurPPLexer;
122
123  /// CurLookup - The DirectoryLookup structure used to find the current
124  /// FileEntry, if CurLexer is non-null and if applicable.  This allows us to
125  /// implement #include_next and find directory-specific properties.
126  const DirectoryLookup *CurDirLookup;
127
128  /// CurTokenLexer - This is the current macro we are expanding, if we are
129  /// expanding a macro.  One of CurLexer and CurTokenLexer must be null.
130  llvm::OwningPtr<TokenLexer> CurTokenLexer;
131
132  /// IncludeMacroStack - This keeps track of the stack of files currently
133  /// #included, and macros currently being expanded from, not counting
134  /// CurLexer/CurTokenLexer.
135  struct IncludeStackInfo {
136    Lexer                 *TheLexer;
137    PTHLexer              *ThePTHLexer;
138    PreprocessorLexer     *ThePPLexer;
139    TokenLexer            *TheTokenLexer;
140    const DirectoryLookup *TheDirLookup;
141
142    IncludeStackInfo(Lexer *L, PTHLexer* P, PreprocessorLexer* PPL,
143                     TokenLexer* TL, const DirectoryLookup *D)
144      : TheLexer(L), ThePTHLexer(P), ThePPLexer(PPL), TheTokenLexer(TL),
145        TheDirLookup(D) {}
146  };
147  std::vector<IncludeStackInfo> IncludeMacroStack;
148
149  /// Callbacks - These are actions invoked when some preprocessor activity is
150  /// encountered (e.g. a file is #included, etc).
151  PPCallbacks *Callbacks;
152
153  /// Macros - For each IdentifierInfo with 'HasMacro' set, we keep a mapping
154  /// to the actual definition of the macro.
155  llvm::DenseMap<IdentifierInfo*, MacroInfo*> Macros;
156
157  /// MICache - A "freelist" of MacroInfo objects that can be reused for quick
158  ///  allocation.
159  std::vector<MacroInfo*> MICache;
160
161  // Various statistics we track for performance analysis.
162  unsigned NumDirectives, NumIncluded, NumDefined, NumUndefined, NumPragma;
163  unsigned NumIf, NumElse, NumEndif;
164  unsigned NumEnteredSourceFiles, MaxIncludeStackDepth;
165  unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded;
166  unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste;
167  unsigned NumSkipped;
168
169  /// Predefines - This string is the predefined macros that preprocessor
170  /// should use from the command line etc.
171  std::string Predefines;
172
173  /// TokenLexerCache - Cache macro expanders to reduce malloc traffic.
174  enum { TokenLexerCacheSize = 8 };
175  unsigned NumCachedTokenLexers;
176  TokenLexer *TokenLexerCache[TokenLexerCacheSize];
177
178private:  // Cached tokens state.
179  typedef std::vector<Token> CachedTokensTy;
180
181  /// CachedTokens - Cached tokens are stored here when we do backtracking or
182  /// lookahead. They are "lexed" by the CachingLex() method.
183  CachedTokensTy CachedTokens;
184
185  /// CachedLexPos - The position of the cached token that CachingLex() should
186  /// "lex" next. If it points beyond the CachedTokens vector, it means that
187  /// a normal Lex() should be invoked.
188  CachedTokensTy::size_type CachedLexPos;
189
190  /// BacktrackPositions - Stack of backtrack positions, allowing nested
191  /// backtracks. The EnableBacktrackAtThisPos() method pushes a position to
192  /// indicate where CachedLexPos should be set when the BackTrack() method is
193  /// invoked (at which point the last position is popped).
194  std::vector<CachedTokensTy::size_type> BacktrackPositions;
195
196public:
197  Preprocessor(Diagnostic &diags, const LangOptions &opts, TargetInfo &target,
198               SourceManager &SM, HeaderSearch &Headers,
199               IdentifierInfoLookup *IILookup = 0);
200
201  ~Preprocessor();
202
203  Diagnostic &getDiagnostics() const { return *Diags; }
204  void setDiagnostics(Diagnostic &D) { Diags = &D; }
205
206  const LangOptions &getLangOptions() const { return Features; }
207  TargetInfo &getTargetInfo() const { return Target; }
208  FileManager &getFileManager() const { return FileMgr; }
209  SourceManager &getSourceManager() const { return SourceMgr; }
210  HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
211
212  IdentifierTable &getIdentifierTable() { return Identifiers; }
213  SelectorTable &getSelectorTable() { return Selectors; }
214  llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
215
216  void setPTHManager(PTHManager* pm);
217
218  PTHManager *getPTHManager() { return PTH.get(); }
219
220  /// SetCommentRetentionState - Control whether or not the preprocessor retains
221  /// comments in output.
222  void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
223    this->KeepComments = KeepComments | KeepMacroComments;
224    this->KeepMacroComments = KeepMacroComments;
225  }
226
227  bool getCommentRetentionState() const { return KeepComments; }
228
229  /// isCurrentLexer - Return true if we are lexing directly from the specified
230  /// lexer.
231  bool isCurrentLexer(const PreprocessorLexer *L) const {
232    return CurPPLexer == L;
233  }
234
235  /// getCurrentLexer - Return the current file lexer being lexed from.  Note
236  /// that this ignores any potentially active macro expansions and _Pragma
237  /// expansions going on at the time.
238  PreprocessorLexer *getCurrentFileLexer() const;
239
240  /// getPPCallbacks/setPPCallbacks - Accessors for preprocessor callbacks.
241  /// Note that this class takes ownership of any PPCallbacks object given to
242  /// it.
243  PPCallbacks *getPPCallbacks() const { return Callbacks; }
244  void setPPCallbacks(PPCallbacks *C) {
245    if (Callbacks)
246      C = new PPChainedCallbacks(C, Callbacks);
247    Callbacks = C;
248  }
249
250  /// getMacroInfo - Given an identifier, return the MacroInfo it is #defined to
251  /// or null if it isn't #define'd.
252  MacroInfo *getMacroInfo(IdentifierInfo *II) const {
253    return II->hasMacroDefinition() ? Macros.find(II)->second : 0;
254  }
255
256  /// setMacroInfo - Specify a macro for this identifier.
257  ///
258  void setMacroInfo(IdentifierInfo *II, MacroInfo *MI);
259
260  /// macro_iterator/macro_begin/macro_end - This allows you to walk the current
261  /// state of the macro table.  This visits every currently-defined macro.
262  typedef llvm::DenseMap<IdentifierInfo*,
263                         MacroInfo*>::const_iterator macro_iterator;
264  macro_iterator macro_begin() const { return Macros.begin(); }
265  macro_iterator macro_end() const { return Macros.end(); }
266
267
268
269  const std::string &getPredefines() const { return Predefines; }
270  /// setPredefines - Set the predefines for this Preprocessor.  These
271  /// predefines are automatically injected when parsing the main file.
272  void setPredefines(const char *P) { Predefines = P; }
273  void setPredefines(const std::string &P) { Predefines = P; }
274
275  /// getIdentifierInfo - Return information about the specified preprocessor
276  /// identifier token.  The version of this method that takes two character
277  /// pointers is preferred unless the identifier is already available as a
278  /// string (this avoids allocation and copying of memory to construct an
279  /// std::string).
280  IdentifierInfo *getIdentifierInfo(const char *NameStart,
281                                    const char *NameEnd) {
282    return &Identifiers.get(NameStart, NameEnd);
283  }
284  IdentifierInfo *getIdentifierInfo(const char *NameStr) {
285    return getIdentifierInfo(NameStr, NameStr+strlen(NameStr));
286  }
287
288  /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
289  /// If 'Namespace' is non-null, then it is a token required to exist on the
290  /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
291  void AddPragmaHandler(const char *Namespace, PragmaHandler *Handler);
292
293  /// RemovePragmaHandler - Remove the specific pragma handler from
294  /// the preprocessor. If \arg Namespace is non-null, then it should
295  /// be the namespace that \arg Handler was added to. It is an error
296  /// to remove a handler that has not been registered.
297  void RemovePragmaHandler(const char *Namespace, PragmaHandler *Handler);
298
299  /// EnterMainSourceFile - Enter the specified FileID as the main source file,
300  /// which implicitly adds the builtin defines etc.
301  void EnterMainSourceFile();
302
303  /// EnterSourceFile - Add a source file to the top of the include stack and
304  /// start lexing tokens from it instead of the current buffer.  If isMainFile
305  /// is true, this is the main file for the translation unit.
306  void EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir);
307
308  /// EnterMacro - Add a Macro to the top of the include stack and start lexing
309  /// tokens from it instead of the current buffer.  Args specifies the
310  /// tokens input to a function-like macro.
311  ///
312  /// ILEnd specifies the location of the ')' for a function-like macro or the
313  /// identifier for an object-like macro.
314  void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroArgs *Args);
315
316  /// EnterTokenStream - Add a "macro" context to the top of the include stack,
317  /// which will cause the lexer to start returning the specified tokens.
318  ///
319  /// If DisableMacroExpansion is true, tokens lexed from the token stream will
320  /// not be subject to further macro expansion.  Otherwise, these tokens will
321  /// be re-macro-expanded when/if expansion is enabled.
322  ///
323  /// If OwnsTokens is false, this method assumes that the specified stream of
324  /// tokens has a permanent owner somewhere, so they do not need to be copied.
325  /// If it is true, it assumes the array of tokens is allocated with new[] and
326  /// must be freed.
327  ///
328  void EnterTokenStream(const Token *Toks, unsigned NumToks,
329                        bool DisableMacroExpansion, bool OwnsTokens);
330
331  /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
332  /// lexer stack.  This should only be used in situations where the current
333  /// state of the top-of-stack lexer is known.
334  void RemoveTopOfLexerStack();
335
336  /// EnableBacktrackAtThisPos - From the point that this method is called, and
337  /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
338  /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
339  /// make the Preprocessor re-lex the same tokens.
340  ///
341  /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
342  /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
343  /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
344  ///
345  /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
346  /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
347  /// tokens will continue indefinitely.
348  ///
349  void EnableBacktrackAtThisPos();
350
351  /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call.
352  void CommitBacktrackedTokens();
353
354  /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since
355  /// EnableBacktrackAtThisPos() was previously called.
356  void Backtrack();
357
358  /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and
359  /// caching of tokens is on.
360  bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
361
362  /// Lex - To lex a token from the preprocessor, just pull a token from the
363  /// current lexer or macro object.
364  void Lex(Token &Result) {
365    if (CurLexer)
366      CurLexer->Lex(Result);
367    else if (CurPTHLexer)
368      CurPTHLexer->Lex(Result);
369    else if (CurTokenLexer)
370      CurTokenLexer->Lex(Result);
371    else
372      CachingLex(Result);
373  }
374
375  /// LexNonComment - Lex a token.  If it's a comment, keep lexing until we get
376  /// something not a comment.  This is useful in -E -C mode where comments
377  /// would foul up preprocessor directive handling.
378  void LexNonComment(Token &Result) {
379    do
380      Lex(Result);
381    while (Result.getKind() == tok::comment);
382  }
383
384  /// LexUnexpandedToken - This is just like Lex, but this disables macro
385  /// expansion of identifier tokens.
386  void LexUnexpandedToken(Token &Result) {
387    // Disable macro expansion.
388    bool OldVal = DisableMacroExpansion;
389    DisableMacroExpansion = true;
390    // Lex the token.
391    Lex(Result);
392
393    // Reenable it.
394    DisableMacroExpansion = OldVal;
395  }
396
397  /// LookAhead - This peeks ahead N tokens and returns that token without
398  /// consuming any tokens.  LookAhead(0) returns the next token that would be
399  /// returned by Lex(), LookAhead(1) returns the token after it, etc.  This
400  /// returns normal tokens after phase 5.  As such, it is equivalent to using
401  /// 'Lex', not 'LexUnexpandedToken'.
402  const Token &LookAhead(unsigned N) {
403    if (CachedLexPos + N < CachedTokens.size())
404      return CachedTokens[CachedLexPos+N];
405    else
406      return PeekAhead(N+1);
407  }
408
409  /// RevertCachedTokens - When backtracking is enabled and tokens are cached,
410  /// this allows to revert a specific number of tokens.
411  /// Note that the number of tokens being reverted should be up to the last
412  /// backtrack position, not more.
413  void RevertCachedTokens(unsigned N) {
414    assert(isBacktrackEnabled() &&
415           "Should only be called when tokens are cached for backtracking");
416    assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back())
417         && "Should revert tokens up to the last backtrack position, not more");
418    assert(signed(CachedLexPos) - signed(N) >= 0 &&
419           "Corrupted backtrack positions ?");
420    CachedLexPos -= N;
421  }
422
423  /// EnterToken - Enters a token in the token stream to be lexed next. If
424  /// BackTrack() is called afterwards, the token will remain at the insertion
425  /// point.
426  void EnterToken(const Token &Tok) {
427    EnterCachingLexMode();
428    CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
429  }
430
431  /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching
432  /// tokens (because backtrack is enabled) it should replace the most recent
433  /// cached tokens with the given annotation token. This function has no effect
434  /// if backtracking is not enabled.
435  ///
436  /// Note that the use of this function is just for optimization; so that the
437  /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
438  /// invoked.
439  void AnnotateCachedTokens(const Token &Tok) {
440    assert(Tok.isAnnotation() && "Expected annotation token");
441    if (CachedLexPos != 0 && isBacktrackEnabled())
442      AnnotatePreviousCachedTokens(Tok);
443  }
444
445  /// \brief Replace the last token with an annotation token.
446  ///
447  /// Like AnnotateCachedTokens(), this routine replaces an
448  /// already-parsed (and resolved) token with an annotation
449  /// token. However, this routine only replaces the last token with
450  /// the annotation token; it does not affect any other cached
451  /// tokens. This function has no effect if backtracking is not
452  /// enabled.
453  void ReplaceLastTokenWithAnnotation(const Token &Tok) {
454    assert(Tok.isAnnotation() && "Expected annotation token");
455    if (CachedLexPos != 0 && isBacktrackEnabled())
456      CachedTokens[CachedLexPos-1] = Tok;
457  }
458
459  /// Diag - Forwarding function for diagnostics.  This emits a diagnostic at
460  /// the specified Token's location, translating the token's start
461  /// position in the current buffer into a SourcePosition object for rendering.
462  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
463    return Diags->Report(FullSourceLoc(Loc, getSourceManager()), DiagID);
464  }
465
466  DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) {
467    return Diags->Report(FullSourceLoc(Tok.getLocation(), getSourceManager()),
468                         DiagID);
469  }
470
471  /// getSpelling() - Return the 'spelling' of the Tok token.  The spelling of a
472  /// token is the characters used to represent the token in the source file
473  /// after trigraph expansion and escaped-newline folding.  In particular, this
474  /// wants to get the true, uncanonicalized, spelling of things like digraphs
475  /// UCNs, etc.
476  std::string getSpelling(const Token &Tok) const;
477
478  /// getSpelling - This method is used to get the spelling of a token into a
479  /// preallocated buffer, instead of as an std::string.  The caller is required
480  /// to allocate enough space for the token, which is guaranteed to be at least
481  /// Tok.getLength() bytes long.  The length of the actual result is returned.
482  ///
483  /// Note that this method may do two possible things: it may either fill in
484  /// the buffer specified with characters, or it may *change the input pointer*
485  /// to point to a constant buffer with the data already in it (avoiding a
486  /// copy).  The caller is not allowed to modify the returned buffer pointer
487  /// if an internal buffer is returned.
488  unsigned getSpelling(const Token &Tok, const char *&Buffer) const;
489
490  /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric constant
491  /// with length 1, return the character.
492  char getSpellingOfSingleCharacterNumericConstant(const Token &Tok) const {
493    assert(Tok.is(tok::numeric_constant) &&
494           Tok.getLength() == 1 && "Called on unsupported token");
495    assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
496
497    // If the token is carrying a literal data pointer, just use it.
498    if (const char *D = Tok.getLiteralData())
499      return *D;
500
501    // Otherwise, fall back on getCharacterData, which is slower, but always
502    // works.
503    return *SourceMgr.getCharacterData(Tok.getLocation());
504  }
505
506  /// CreateString - Plop the specified string into a scratch buffer and set the
507  /// specified token's location and length to it.  If specified, the source
508  /// location provides a location of the instantiation point of the token.
509  void CreateString(const char *Buf, unsigned Len,
510                    Token &Tok, SourceLocation SourceLoc = SourceLocation());
511
512  /// \brief Computes the source location just past the end of the
513  /// token at this source location.
514  ///
515  /// This routine can be used to produce a source location that
516  /// points just past the end of the token referenced by \p Loc, and
517  /// is generally used when a diagnostic needs to point just after a
518  /// token where it expected something different that it received. If
519  /// the returned source location would not be meaningful (e.g., if
520  /// it points into a macro), this routine returns an invalid
521  /// source location.
522  SourceLocation getLocForEndOfToken(SourceLocation Loc);
523
524  /// DumpToken - Print the token to stderr, used for debugging.
525  ///
526  void DumpToken(const Token &Tok, bool DumpFlags = false) const;
527  void DumpLocation(SourceLocation Loc) const;
528  void DumpMacro(const MacroInfo &MI) const;
529
530  /// AdvanceToTokenCharacter - Given a location that specifies the start of a
531  /// token, return a new location that specifies a character within the token.
532  SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char);
533
534  /// IncrementPasteCounter - Increment the counters for the number of token
535  /// paste operations performed.  If fast was specified, this is a 'fast paste'
536  /// case we handled.
537  ///
538  void IncrementPasteCounter(bool isFast) {
539    if (isFast)
540      ++NumFastTokenPaste;
541    else
542      ++NumTokenPaste;
543  }
544
545  void PrintStats();
546
547  /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
548  /// comment (/##/) in microsoft mode, this method handles updating the current
549  /// state, returning the token on the next source line.
550  void HandleMicrosoftCommentPaste(Token &Tok);
551
552  //===--------------------------------------------------------------------===//
553  // Preprocessor callback methods.  These are invoked by a lexer as various
554  // directives and events are found.
555
556  /// LookUpIdentifierInfo - Given a tok::identifier token, look up the
557  /// identifier information for the token and install it into the token.
558  IdentifierInfo *LookUpIdentifierInfo(Token &Identifier,
559                                       const char *BufPtr = 0);
560
561  /// HandleIdentifier - This callback is invoked when the lexer reads an
562  /// identifier and has filled in the tokens IdentifierInfo member.  This
563  /// callback potentially macro expands it or turns it into a named token (like
564  /// 'for').
565  void HandleIdentifier(Token &Identifier);
566
567
568  /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
569  /// the current file.  This either returns the EOF token and returns true, or
570  /// pops a level off the include stack and returns false, at which point the
571  /// client should call lex again.
572  bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
573
574  /// HandleEndOfTokenLexer - This callback is invoked when the current
575  /// TokenLexer hits the end of its token stream.
576  bool HandleEndOfTokenLexer(Token &Result);
577
578  /// HandleDirective - This callback is invoked when the lexer sees a # token
579  /// at the start of a line.  This consumes the directive, modifies the
580  /// lexer/preprocessor state, and advances the lexer(s) so that the next token
581  /// read is the correct one.
582  void HandleDirective(Token &Result);
583
584  /// CheckEndOfDirective - Ensure that the next token is a tok::eom token.  If
585  /// not, emit a diagnostic and consume up until the eom.  If EnableMacros is
586  /// true, then we consider macros that expand to zero tokens as being ok.
587  void CheckEndOfDirective(const char *Directive, bool EnableMacros = false);
588
589  /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
590  /// current line until the tok::eom token is found.
591  void DiscardUntilEndOfDirective();
592
593  /// SawDateOrTime - This returns true if the preprocessor has seen a use of
594  /// __DATE__ or __TIME__ in the file so far.
595  bool SawDateOrTime() const {
596    return DATELoc != SourceLocation() || TIMELoc != SourceLocation();
597  }
598  unsigned getCounterValue() const { return CounterValue; }
599  void setCounterValue(unsigned V) { CounterValue = V; }
600
601  /// AllocateMacroInfo - Allocate a new MacroInfo object with the provide
602  ///  SourceLocation.
603  MacroInfo* AllocateMacroInfo(SourceLocation L);
604
605private:
606
607  void PushIncludeMacroStack() {
608    IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(),
609                                                 CurPTHLexer.take(),
610                                                 CurPPLexer,
611                                                 CurTokenLexer.take(),
612                                                 CurDirLookup));
613    CurPPLexer = 0;
614  }
615
616  void PopIncludeMacroStack() {
617    CurLexer.reset(IncludeMacroStack.back().TheLexer);
618    CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer);
619    CurPPLexer = IncludeMacroStack.back().ThePPLexer;
620    CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer);
621    CurDirLookup  = IncludeMacroStack.back().TheDirLookup;
622    IncludeMacroStack.pop_back();
623  }
624
625  /// ReleaseMacroInfo - Release the specified MacroInfo.  This memory will
626  ///  be reused for allocating new MacroInfo objects.
627  void ReleaseMacroInfo(MacroInfo* MI);
628
629  /// isInPrimaryFile - Return true if we're in the top-level file, not in a
630  /// #include.
631  bool isInPrimaryFile() const;
632
633  /// ReadMacroName - Lex and validate a macro name, which occurs after a
634  /// #define or #undef.  This emits a diagnostic, sets the token kind to eom,
635  /// and discards the rest of the macro line if the macro name is invalid.
636  void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0);
637
638  /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
639  /// definition has just been read.  Lex the rest of the arguments and the
640  /// closing ), updating MI with what we learn.  Return true if an error occurs
641  /// parsing the arg list.
642  bool ReadMacroDefinitionArgList(MacroInfo *MI);
643
644  /// SkipExcludedConditionalBlock - We just read a #if or related directive and
645  /// decided that the subsequent tokens are in the #if'd out portion of the
646  /// file.  Lex the rest of the file, until we see an #endif.  If
647  /// FoundNonSkipPortion is true, then we have already emitted code for part of
648  /// this #if directive, so #else/#elif blocks should never be entered. If
649  /// FoundElse is false, then #else directives are ok, if not, then we have
650  /// already seen one so a #else directive is a duplicate.  When this returns,
651  /// the caller can lex the first valid token.
652  void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
653                                    bool FoundNonSkipPortion, bool FoundElse);
654
655  /// PTHSkipExcludedConditionalBlock - A fast PTH version of
656  ///  SkipExcludedConditionalBlock.
657  void PTHSkipExcludedConditionalBlock();
658
659  /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
660  /// may occur after a #if or #elif directive and return it as a bool.  If the
661  /// expression is equivalent to "!defined(X)" return X in IfNDefMacro.
662  bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
663
664  /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
665  /// #pragma GCC poison/system_header/dependency and #pragma once.
666  void RegisterBuiltinPragmas();
667
668  /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
669  /// identifier table.
670  void RegisterBuiltinMacros();
671
672  /// HandleMacroExpandedIdentifier - If an identifier token is read that is to
673  /// be expanded as a macro, handle it and return the next token as 'Tok'.  If
674  /// the macro should not be expanded return true, otherwise return false.
675  bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI);
676
677  /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
678  /// lexed is a '('.  If so, consume the token and return true, if not, this
679  /// method should have no observable side-effect on the lexed tokens.
680  bool isNextPPTokenLParen();
681
682  /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
683  /// invoked to read all of the formal arguments specified for the macro
684  /// invocation.  This returns null on error.
685  MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI,
686                                       SourceLocation &InstantiationEnd);
687
688  /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
689  /// as a builtin macro, handle it and return the next token as 'Tok'.
690  void ExpandBuiltinMacro(Token &Tok);
691
692  /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
693  /// return the first token after the directive.  The _Pragma token has just
694  /// been read into 'Tok'.
695  void Handle_Pragma(Token &Tok);
696
697  /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and
698  /// start lexing tokens from it instead of the current buffer.
699  void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
700
701  /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and
702  /// start getting tokens from it using the PTH cache.
703  void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir);
704
705  /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
706  /// checked and spelled filename, e.g. as an operand of #include. This returns
707  /// true if the input filename was in <>'s or false if it were in ""'s.  The
708  /// caller is expected to provide a buffer that is large enough to hold the
709  /// spelling of the filename, but is also expected to handle the case when
710  /// this method decides to use a different buffer.
711  bool GetIncludeFilenameSpelling(SourceLocation Loc,
712                                  const char *&BufStart, const char *&BufEnd);
713
714  /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
715  /// return null on failure.  isAngled indicates whether the file reference is
716  /// for system #include's or not (i.e. using <> instead of "").
717  const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd,
718                              bool isAngled, const DirectoryLookup *FromDir,
719                              const DirectoryLookup *&CurDir);
720
721
722
723  /// IsFileLexer - Returns true if we are lexing from a file and not a
724  ///  pragma or a macro.
725  static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
726    return L ? !L->isPragmaLexer() : P != 0;
727  }
728
729  static bool IsFileLexer(const IncludeStackInfo& I) {
730    return IsFileLexer(I.TheLexer, I.ThePPLexer);
731  }
732
733  bool IsFileLexer() const {
734    return IsFileLexer(CurLexer.get(), CurPPLexer);
735  }
736
737  //===--------------------------------------------------------------------===//
738  // Caching stuff.
739  void CachingLex(Token &Result);
740  bool InCachingLexMode() const { return CurPPLexer == 0 && CurTokenLexer == 0;}
741  void EnterCachingLexMode();
742  void ExitCachingLexMode() {
743    if (InCachingLexMode())
744      RemoveTopOfLexerStack();
745  }
746  const Token &PeekAhead(unsigned N);
747  void AnnotatePreviousCachedTokens(const Token &Tok);
748
749  //===--------------------------------------------------------------------===//
750  /// Handle*Directive - implement the various preprocessor directives.  These
751  /// should side-effect the current preprocessor object so that the next call
752  /// to Lex() will return the appropriate token next.
753  void HandleLineDirective(Token &Tok);
754  void HandleDigitDirective(Token &Tok);
755  void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
756  void HandleIdentSCCSDirective(Token &Tok);
757
758  // File inclusion.
759  void HandleIncludeDirective(Token &Tok,
760                              const DirectoryLookup *LookupFrom = 0,
761                              bool isImport = false);
762  void HandleIncludeNextDirective(Token &Tok);
763  void HandleIncludeMacrosDirective(Token &Tok);
764  void HandleImportDirective(Token &Tok);
765
766  // Macro handling.
767  void HandleDefineDirective(Token &Tok);
768  void HandleUndefDirective(Token &Tok);
769  // HandleAssertDirective(Token &Tok);
770  // HandleUnassertDirective(Token &Tok);
771
772  // Conditional Inclusion.
773  void HandleIfdefDirective(Token &Tok, bool isIfndef,
774                            bool ReadAnyTokensBeforeDirective);
775  void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective);
776  void HandleEndifDirective(Token &Tok);
777  void HandleElseDirective(Token &Tok);
778  void HandleElifDirective(Token &Tok);
779
780  // Pragmas.
781  void HandlePragmaDirective();
782public:
783  void HandlePragmaOnce(Token &OnceTok);
784  void HandlePragmaMark();
785  void HandlePragmaPoison(Token &PoisonTok);
786  void HandlePragmaSystemHeader(Token &SysHeaderTok);
787  void HandlePragmaDependency(Token &DependencyTok);
788  void HandlePragmaComment(Token &CommentTok);
789};
790
791/// PreprocessorFactory - A generic factory interface for lazily creating
792///  Preprocessor objects on-demand when they are needed.
793class PreprocessorFactory {
794public:
795  virtual ~PreprocessorFactory();
796  virtual Preprocessor* CreatePreprocessor() = 0;
797};
798
799}  // end namespace clang
800
801#endif
802