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