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