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