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