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