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