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