Preprocessor.h revision 90b1827c1c1cf075266b96b416eefcf37924333b
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  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(const char *NameStart,
300                                    const char *NameEnd) {
301    return &Identifiers.get(NameStart, NameEnd);
302  }
303  IdentifierInfo *getIdentifierInfo(const char *NameStr) {
304    return getIdentifierInfo(NameStr, NameStr+strlen(NameStr));
305  }
306
307  /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
308  /// If 'Namespace' is non-null, then it is a token required to exist on the
309  /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
310  void AddPragmaHandler(const char *Namespace, PragmaHandler *Handler);
311
312  /// RemovePragmaHandler - Remove the specific pragma handler from
313  /// the preprocessor. If \arg Namespace is non-null, then it should
314  /// be the namespace that \arg Handler was added to. It is an error
315  /// to remove a handler that has not been registered.
316  void RemovePragmaHandler(const char *Namespace, PragmaHandler *Handler);
317
318  /// \brief Add the specified comment handler to the preprocessor.
319  void AddCommentHandler(CommentHandler *Handler);
320
321  /// \brief Remove the specified comment handler.
322  ///
323  /// It is an error to remove a handler that has not been registered.
324  void RemoveCommentHandler(CommentHandler *Handler);
325
326  /// EnterMainSourceFile - Enter the specified FileID as the main source file,
327  /// which implicitly adds the builtin defines etc.
328  void EnterMainSourceFile();
329
330  /// EnterSourceFile - Add a source file to the top of the include stack and
331  /// start lexing tokens from it instead of the current buffer.  If isMainFile
332  /// is true, this is the main file for the translation unit.
333  void EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir);
334
335  /// EnterMacro - Add a Macro to the top of the include stack and start lexing
336  /// tokens from it instead of the current buffer.  Args specifies the
337  /// tokens input to a function-like macro.
338  ///
339  /// ILEnd specifies the location of the ')' for a function-like macro or the
340  /// identifier for an object-like macro.
341  void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroArgs *Args);
342
343  /// EnterTokenStream - Add a "macro" context to the top of the include stack,
344  /// which will cause the lexer to start returning the specified tokens.
345  ///
346  /// If DisableMacroExpansion is true, tokens lexed from the token stream will
347  /// not be subject to further macro expansion.  Otherwise, these tokens will
348  /// be re-macro-expanded when/if expansion is enabled.
349  ///
350  /// If OwnsTokens is false, this method assumes that the specified stream of
351  /// tokens has a permanent owner somewhere, so they do not need to be copied.
352  /// If it is true, it assumes the array of tokens is allocated with new[] and
353  /// must be freed.
354  ///
355  void EnterTokenStream(const Token *Toks, unsigned NumToks,
356                        bool DisableMacroExpansion, bool OwnsTokens);
357
358  /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
359  /// lexer stack.  This should only be used in situations where the current
360  /// state of the top-of-stack lexer is known.
361  void RemoveTopOfLexerStack();
362
363  /// EnableBacktrackAtThisPos - From the point that this method is called, and
364  /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
365  /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
366  /// make the Preprocessor re-lex the same tokens.
367  ///
368  /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
369  /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
370  /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
371  ///
372  /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
373  /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
374  /// tokens will continue indefinitely.
375  ///
376  void EnableBacktrackAtThisPos();
377
378  /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call.
379  void CommitBacktrackedTokens();
380
381  /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since
382  /// EnableBacktrackAtThisPos() was previously called.
383  void Backtrack();
384
385  /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and
386  /// caching of tokens is on.
387  bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
388
389  /// Lex - To lex a token from the preprocessor, just pull a token from the
390  /// current lexer or macro object.
391  void Lex(Token &Result) {
392    if (CurLexer)
393      CurLexer->Lex(Result);
394    else if (CurPTHLexer)
395      CurPTHLexer->Lex(Result);
396    else if (CurTokenLexer)
397      CurTokenLexer->Lex(Result);
398    else
399      CachingLex(Result);
400  }
401
402  /// LexNonComment - Lex a token.  If it's a comment, keep lexing until we get
403  /// something not a comment.  This is useful in -E -C mode where comments
404  /// would foul up preprocessor directive handling.
405  void LexNonComment(Token &Result) {
406    do
407      Lex(Result);
408    while (Result.getKind() == tok::comment);
409  }
410
411  /// LexUnexpandedToken - This is just like Lex, but this disables macro
412  /// expansion of identifier tokens.
413  void LexUnexpandedToken(Token &Result) {
414    // Disable macro expansion.
415    bool OldVal = DisableMacroExpansion;
416    DisableMacroExpansion = true;
417    // Lex the token.
418    Lex(Result);
419
420    // Reenable it.
421    DisableMacroExpansion = OldVal;
422  }
423
424  /// LookAhead - This peeks ahead N tokens and returns that token without
425  /// consuming any tokens.  LookAhead(0) returns the next token that would be
426  /// returned by Lex(), LookAhead(1) returns the token after it, etc.  This
427  /// returns normal tokens after phase 5.  As such, it is equivalent to using
428  /// 'Lex', not 'LexUnexpandedToken'.
429  const Token &LookAhead(unsigned N) {
430    if (CachedLexPos + N < CachedTokens.size())
431      return CachedTokens[CachedLexPos+N];
432    else
433      return PeekAhead(N+1);
434  }
435
436  /// RevertCachedTokens - When backtracking is enabled and tokens are cached,
437  /// this allows to revert a specific number of tokens.
438  /// Note that the number of tokens being reverted should be up to the last
439  /// backtrack position, not more.
440  void RevertCachedTokens(unsigned N) {
441    assert(isBacktrackEnabled() &&
442           "Should only be called when tokens are cached for backtracking");
443    assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back())
444         && "Should revert tokens up to the last backtrack position, not more");
445    assert(signed(CachedLexPos) - signed(N) >= 0 &&
446           "Corrupted backtrack positions ?");
447    CachedLexPos -= N;
448  }
449
450  /// EnterToken - Enters a token in the token stream to be lexed next. If
451  /// BackTrack() is called afterwards, the token will remain at the insertion
452  /// point.
453  void EnterToken(const Token &Tok) {
454    EnterCachingLexMode();
455    CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
456  }
457
458  /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching
459  /// tokens (because backtrack is enabled) it should replace the most recent
460  /// cached tokens with the given annotation token. This function has no effect
461  /// if backtracking is not enabled.
462  ///
463  /// Note that the use of this function is just for optimization; so that the
464  /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
465  /// invoked.
466  void AnnotateCachedTokens(const Token &Tok) {
467    assert(Tok.isAnnotation() && "Expected annotation token");
468    if (CachedLexPos != 0 && isBacktrackEnabled())
469      AnnotatePreviousCachedTokens(Tok);
470  }
471
472  /// \brief Replace the last token with an annotation token.
473  ///
474  /// Like AnnotateCachedTokens(), this routine replaces an
475  /// already-parsed (and resolved) token with an annotation
476  /// token. However, this routine only replaces the last token with
477  /// the annotation token; it does not affect any other cached
478  /// tokens. This function has no effect if backtracking is not
479  /// enabled.
480  void ReplaceLastTokenWithAnnotation(const Token &Tok) {
481    assert(Tok.isAnnotation() && "Expected annotation token");
482    if (CachedLexPos != 0 && isBacktrackEnabled())
483      CachedTokens[CachedLexPos-1] = Tok;
484  }
485
486  /// Diag - Forwarding function for diagnostics.  This emits a diagnostic at
487  /// the specified Token's location, translating the token's start
488  /// position in the current buffer into a SourcePosition object for rendering.
489  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
490    return Diags->Report(FullSourceLoc(Loc, getSourceManager()), DiagID);
491  }
492
493  DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) {
494    return Diags->Report(FullSourceLoc(Tok.getLocation(), getSourceManager()),
495                         DiagID);
496  }
497
498  /// getSpelling() - Return the 'spelling' of the Tok token.  The spelling of a
499  /// token is the characters used to represent the token in the source file
500  /// after trigraph expansion and escaped-newline folding.  In particular, this
501  /// wants to get the true, uncanonicalized, spelling of things like digraphs
502  /// UCNs, etc.
503  std::string getSpelling(const Token &Tok) const;
504
505  /// getSpelling - This method is used to get the spelling of a token into a
506  /// preallocated buffer, instead of as an std::string.  The caller is required
507  /// to allocate enough space for the token, which is guaranteed to be at least
508  /// Tok.getLength() bytes long.  The length of the actual result is returned.
509  ///
510  /// Note that this method may do two possible things: it may either fill in
511  /// the buffer specified with characters, or it may *change the input pointer*
512  /// to point to a constant buffer with the data already in it (avoiding a
513  /// copy).  The caller is not allowed to modify the returned buffer pointer
514  /// if an internal buffer is returned.
515  unsigned getSpelling(const Token &Tok, const char *&Buffer) const;
516
517  /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric constant
518  /// with length 1, return the character.
519  char getSpellingOfSingleCharacterNumericConstant(const Token &Tok) const {
520    assert(Tok.is(tok::numeric_constant) &&
521           Tok.getLength() == 1 && "Called on unsupported token");
522    assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
523
524    // If the token is carrying a literal data pointer, just use it.
525    if (const char *D = Tok.getLiteralData())
526      return *D;
527
528    // Otherwise, fall back on getCharacterData, which is slower, but always
529    // works.
530    return *SourceMgr.getCharacterData(Tok.getLocation());
531  }
532
533  /// CreateString - Plop the specified string into a scratch buffer and set the
534  /// specified token's location and length to it.  If specified, the source
535  /// location provides a location of the instantiation point of the token.
536  void CreateString(const char *Buf, unsigned Len,
537                    Token &Tok, SourceLocation SourceLoc = SourceLocation());
538
539  /// \brief Computes the source location just past the end of the
540  /// token at this source location.
541  ///
542  /// This routine can be used to produce a source location that
543  /// points just past the end of the token referenced by \p Loc, and
544  /// is generally used when a diagnostic needs to point just after a
545  /// token where it expected something different that it received. If
546  /// the returned source location would not be meaningful (e.g., if
547  /// it points into a macro), this routine returns an invalid
548  /// source location.
549  SourceLocation getLocForEndOfToken(SourceLocation Loc);
550
551  /// DumpToken - Print the token to stderr, used for debugging.
552  ///
553  void DumpToken(const Token &Tok, bool DumpFlags = false) const;
554  void DumpLocation(SourceLocation Loc) const;
555  void DumpMacro(const MacroInfo &MI) const;
556
557  /// AdvanceToTokenCharacter - Given a location that specifies the start of a
558  /// token, return a new location that specifies a character within the token.
559  SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char);
560
561  /// IncrementPasteCounter - Increment the counters for the number of token
562  /// paste operations performed.  If fast was specified, this is a 'fast paste'
563  /// case we handled.
564  ///
565  void IncrementPasteCounter(bool isFast) {
566    if (isFast)
567      ++NumFastTokenPaste;
568    else
569      ++NumTokenPaste;
570  }
571
572  void PrintStats();
573
574  /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
575  /// comment (/##/) in microsoft mode, this method handles updating the current
576  /// state, returning the token on the next source line.
577  void HandleMicrosoftCommentPaste(Token &Tok);
578
579  //===--------------------------------------------------------------------===//
580  // Preprocessor callback methods.  These are invoked by a lexer as various
581  // directives and events are found.
582
583  /// LookUpIdentifierInfo - Given a tok::identifier token, look up the
584  /// identifier information for the token and install it into the token.
585  IdentifierInfo *LookUpIdentifierInfo(Token &Identifier,
586                                       const char *BufPtr = 0);
587
588  /// HandleIdentifier - This callback is invoked when the lexer reads an
589  /// identifier and has filled in the tokens IdentifierInfo member.  This
590  /// callback potentially macro expands it or turns it into a named token (like
591  /// 'for').
592  void HandleIdentifier(Token &Identifier);
593
594
595  /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
596  /// the current file.  This either returns the EOF token and returns true, or
597  /// pops a level off the include stack and returns false, at which point the
598  /// client should call lex again.
599  bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
600
601  /// HandleEndOfTokenLexer - This callback is invoked when the current
602  /// TokenLexer hits the end of its token stream.
603  bool HandleEndOfTokenLexer(Token &Result);
604
605  /// HandleDirective - This callback is invoked when the lexer sees a # token
606  /// at the start of a line.  This consumes the directive, modifies the
607  /// lexer/preprocessor state, and advances the lexer(s) so that the next token
608  /// read is the correct one.
609  void HandleDirective(Token &Result);
610
611  /// CheckEndOfDirective - Ensure that the next token is a tok::eom token.  If
612  /// not, emit a diagnostic and consume up until the eom.  If EnableMacros is
613  /// true, then we consider macros that expand to zero tokens as being ok.
614  void CheckEndOfDirective(const char *Directive, bool EnableMacros = false);
615
616  /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
617  /// current line until the tok::eom token is found.
618  void DiscardUntilEndOfDirective();
619
620  /// SawDateOrTime - This returns true if the preprocessor has seen a use of
621  /// __DATE__ or __TIME__ in the file so far.
622  bool SawDateOrTime() const {
623    return DATELoc != SourceLocation() || TIMELoc != SourceLocation();
624  }
625  unsigned getCounterValue() const { return CounterValue; }
626  void setCounterValue(unsigned V) { CounterValue = V; }
627
628  /// AllocateMacroInfo - Allocate a new MacroInfo object with the provide
629  ///  SourceLocation.
630  MacroInfo* AllocateMacroInfo(SourceLocation L);
631
632  /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
633  /// checked and spelled filename, e.g. as an operand of #include. This returns
634  /// true if the input filename was in <>'s or false if it were in ""'s.  The
635  /// caller is expected to provide a buffer that is large enough to hold the
636  /// spelling of the filename, but is also expected to handle the case when
637  /// this method decides to use a different buffer.
638  bool GetIncludeFilenameSpelling(SourceLocation Loc,
639                                  const char *&BufStart, const char *&BufEnd);
640
641  /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
642  /// return null on failure.  isAngled indicates whether the file reference is
643  /// for system #include's or not (i.e. using <> instead of "").
644  const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd,
645                              bool isAngled, const DirectoryLookup *FromDir,
646                              const DirectoryLookup *&CurDir);
647
648  /// GetCurLookup - The DirectoryLookup structure used to find the current
649  /// FileEntry, if CurLexer is non-null and if applicable.  This allows us to
650  /// implement #include_next and find directory-specific properties.
651  const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; }
652
653  /// isInPrimaryFile - Return true if we're in the top-level file, not in a
654  /// #include.
655  bool isInPrimaryFile() const;
656
657  /// ConcatenateIncludeName - Handle cases where the #include name is expanded
658  /// from a macro as multiple tokens, which need to be glued together.  This
659  /// occurs for code like:
660  ///    #define FOO <a/b.h>
661  ///    #include FOO
662  /// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
663  ///
664  /// This code concatenates and consumes tokens up to the '>' token.  It returns
665  /// false if the > was found, otherwise it returns true if it finds and consumes
666  /// the EOM marker.
667  bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer);
668
669private:
670
671  void PushIncludeMacroStack() {
672    IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(),
673                                                 CurPTHLexer.take(),
674                                                 CurPPLexer,
675                                                 CurTokenLexer.take(),
676                                                 CurDirLookup));
677    CurPPLexer = 0;
678  }
679
680  void PopIncludeMacroStack() {
681    CurLexer.reset(IncludeMacroStack.back().TheLexer);
682    CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer);
683    CurPPLexer = IncludeMacroStack.back().ThePPLexer;
684    CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer);
685    CurDirLookup  = IncludeMacroStack.back().TheDirLookup;
686    IncludeMacroStack.pop_back();
687  }
688
689  /// ReleaseMacroInfo - Release the specified MacroInfo.  This memory will
690  ///  be reused for allocating new MacroInfo objects.
691  void ReleaseMacroInfo(MacroInfo* MI);
692
693  /// ReadMacroName - Lex and validate a macro name, which occurs after a
694  /// #define or #undef.  This emits a diagnostic, sets the token kind to eom,
695  /// and discards the rest of the macro line if the macro name is invalid.
696  void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0);
697
698  /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
699  /// definition has just been read.  Lex the rest of the arguments and the
700  /// closing ), updating MI with what we learn.  Return true if an error occurs
701  /// parsing the arg list.
702  bool ReadMacroDefinitionArgList(MacroInfo *MI);
703
704  /// SkipExcludedConditionalBlock - We just read a #if or related directive and
705  /// decided that the subsequent tokens are in the #if'd out portion of the
706  /// file.  Lex the rest of the file, until we see an #endif.  If
707  /// FoundNonSkipPortion is true, then we have already emitted code for part of
708  /// this #if directive, so #else/#elif blocks should never be entered. If
709  /// FoundElse is false, then #else directives are ok, if not, then we have
710  /// already seen one so a #else directive is a duplicate.  When this returns,
711  /// the caller can lex the first valid token.
712  void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
713                                    bool FoundNonSkipPortion, bool FoundElse);
714
715  /// PTHSkipExcludedConditionalBlock - A fast PTH version of
716  ///  SkipExcludedConditionalBlock.
717  void PTHSkipExcludedConditionalBlock();
718
719  /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
720  /// may occur after a #if or #elif directive and return it as a bool.  If the
721  /// expression is equivalent to "!defined(X)" return X in IfNDefMacro.
722  bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
723
724  /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
725  /// #pragma GCC poison/system_header/dependency and #pragma once.
726  void RegisterBuiltinPragmas();
727
728  /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
729  /// identifier table.
730  void RegisterBuiltinMacros();
731
732  /// HandleMacroExpandedIdentifier - If an identifier token is read that is to
733  /// be expanded as a macro, handle it and return the next token as 'Tok'.  If
734  /// the macro should not be expanded return true, otherwise return false.
735  bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI);
736
737  /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
738  /// lexed is a '('.  If so, consume the token and return true, if not, this
739  /// method should have no observable side-effect on the lexed tokens.
740  bool isNextPPTokenLParen();
741
742  /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
743  /// invoked to read all of the formal arguments specified for the macro
744  /// invocation.  This returns null on error.
745  MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI,
746                                       SourceLocation &InstantiationEnd);
747
748  /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
749  /// as a builtin macro, handle it and return the next token as 'Tok'.
750  void ExpandBuiltinMacro(Token &Tok);
751
752  /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
753  /// return the first token after the directive.  The _Pragma token has just
754  /// been read into 'Tok'.
755  void Handle_Pragma(Token &Tok);
756
757  /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and
758  /// start lexing tokens from it instead of the current buffer.
759  void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
760
761  /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and
762  /// start getting tokens from it using the PTH cache.
763  void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir);
764
765  /// IsFileLexer - Returns true if we are lexing from a file and not a
766  ///  pragma or a macro.
767  static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
768    return L ? !L->isPragmaLexer() : P != 0;
769  }
770
771  static bool IsFileLexer(const IncludeStackInfo& I) {
772    return IsFileLexer(I.TheLexer, I.ThePPLexer);
773  }
774
775  bool IsFileLexer() const {
776    return IsFileLexer(CurLexer.get(), CurPPLexer);
777  }
778
779  //===--------------------------------------------------------------------===//
780  // Caching stuff.
781  void CachingLex(Token &Result);
782  bool InCachingLexMode() const { return CurPPLexer == 0 && CurTokenLexer == 0;}
783  void EnterCachingLexMode();
784  void ExitCachingLexMode() {
785    if (InCachingLexMode())
786      RemoveTopOfLexerStack();
787  }
788  const Token &PeekAhead(unsigned N);
789  void AnnotatePreviousCachedTokens(const Token &Tok);
790
791  //===--------------------------------------------------------------------===//
792  /// Handle*Directive - implement the various preprocessor directives.  These
793  /// should side-effect the current preprocessor object so that the next call
794  /// to Lex() will return the appropriate token next.
795  void HandleLineDirective(Token &Tok);
796  void HandleDigitDirective(Token &Tok);
797  void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
798  void HandleIdentSCCSDirective(Token &Tok);
799
800  // File inclusion.
801  void HandleIncludeDirective(Token &Tok,
802                              const DirectoryLookup *LookupFrom = 0,
803                              bool isImport = false);
804  void HandleIncludeNextDirective(Token &Tok);
805  void HandleIncludeMacrosDirective(Token &Tok);
806  void HandleImportDirective(Token &Tok);
807
808  // Macro handling.
809  void HandleDefineDirective(Token &Tok);
810  void HandleUndefDirective(Token &Tok);
811  // HandleAssertDirective(Token &Tok);
812  // HandleUnassertDirective(Token &Tok);
813
814  // Conditional Inclusion.
815  void HandleIfdefDirective(Token &Tok, bool isIfndef,
816                            bool ReadAnyTokensBeforeDirective);
817  void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective);
818  void HandleEndifDirective(Token &Tok);
819  void HandleElseDirective(Token &Tok);
820  void HandleElifDirective(Token &Tok);
821
822  // Pragmas.
823  void HandlePragmaDirective();
824public:
825  void HandlePragmaOnce(Token &OnceTok);
826  void HandlePragmaMark();
827  void HandlePragmaPoison(Token &PoisonTok);
828  void HandlePragmaSystemHeader(Token &SysHeaderTok);
829  void HandlePragmaDependency(Token &DependencyTok);
830  void HandlePragmaComment(Token &CommentTok);
831  void HandleComment(SourceRange Comment);
832};
833
834/// \brief Abstract base class that describes a handler that will receive
835/// source ranges for each of the comments encountered in the source file.
836class CommentHandler {
837public:
838  virtual ~CommentHandler();
839
840  virtual void HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
841};
842
843}  // end namespace clang
844
845#endif
846