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