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