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