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