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