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