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