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