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