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