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