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