Preprocessor.h revision 0301b3ff132a4d986c092d161cb77d74b04cd2a6
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  const LangOptions &getLangOptions() const { return Features; }
201  TargetInfo &getTargetInfo() const { return Target; }
202  FileManager &getFileManager() const { return FileMgr; }
203  SourceManager &getSourceManager() const { return SourceMgr; }
204  HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
205
206  IdentifierTable &getIdentifierTable() { return Identifiers; }
207  SelectorTable &getSelectorTable() { return Selectors; }
208
209  void setPTHManager(PTHManager* pm);
210
211  /// SetCommentRetentionState - Control whether or not the preprocessor retains
212  /// comments in output.
213  void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
214    this->KeepComments = KeepComments | KeepMacroComments;
215    this->KeepMacroComments = KeepMacroComments;
216  }
217
218  bool getCommentRetentionState() const { return KeepComments; }
219
220  /// isCurrentLexer - Return true if we are lexing directly from the specified
221  /// lexer.
222  bool isCurrentLexer(const PreprocessorLexer *L) const {
223    return CurPPLexer == L;
224  }
225
226  /// getCurrentLexer - Return the current file lexer being lexed from.  Note
227  /// that this ignores any potentially active macro expansions and _Pragma
228  /// expansions going on at the time.
229  PreprocessorLexer *getCurrentFileLexer() const;
230
231  /// getPPCallbacks/setPPCallbacks - Accessors for preprocessor callbacks.
232  /// Note that this class takes ownership of any PPCallbacks object given to
233  /// it.
234  PPCallbacks *getPPCallbacks() const { return Callbacks; }
235  void setPPCallbacks(PPCallbacks *C) {
236    delete Callbacks;
237    Callbacks = C;
238  }
239
240  /// getMacroInfo - Given an identifier, return the MacroInfo it is #defined to
241  /// or null if it isn't #define'd.
242  MacroInfo *getMacroInfo(IdentifierInfo *II) const {
243    return II->hasMacroDefinition() ? Macros.find(II)->second : 0;
244  }
245
246  /// setMacroInfo - Specify a macro for this identifier.
247  ///
248  void setMacroInfo(IdentifierInfo *II, MacroInfo *MI);
249
250  /// macro_iterator/macro_begin/macro_end - This allows you to walk the current
251  /// state of the macro table.  This visits every currently-defined macro.
252  typedef llvm::DenseMap<IdentifierInfo*,
253                         MacroInfo*>::const_iterator macro_iterator;
254  macro_iterator macro_begin() const { return Macros.begin(); }
255  macro_iterator macro_end() const { return Macros.end(); }
256
257
258
259  const std::string &getPredefines() const { return Predefines; }
260  /// setPredefines - Set the predefines for this Preprocessor.  These
261  /// predefines are automatically injected when parsing the main file.
262  void setPredefines(const char *P) { Predefines = P; }
263  void setPredefines(const std::string &P) { Predefines = P; }
264
265  /// getIdentifierInfo - Return information about the specified preprocessor
266  /// identifier token.  The version of this method that takes two character
267  /// pointers is preferred unless the identifier is already available as a
268  /// string (this avoids allocation and copying of memory to construct an
269  /// std::string).
270  IdentifierInfo *getIdentifierInfo(const char *NameStart,
271                                    const char *NameEnd) {
272    return &Identifiers.get(NameStart, NameEnd);
273  }
274  IdentifierInfo *getIdentifierInfo(const char *NameStr) {
275    return getIdentifierInfo(NameStr, NameStr+strlen(NameStr));
276  }
277
278  /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
279  /// If 'Namespace' is non-null, then it is a token required to exist on the
280  /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
281  void AddPragmaHandler(const char *Namespace, PragmaHandler *Handler);
282
283  /// RemovePragmaHandler - Remove the specific pragma handler from
284  /// the preprocessor. If \arg Namespace is non-null, then it should
285  /// be the namespace that \arg Handler was added to. It is an error
286  /// to remove a handler that has not been registered.
287  void RemovePragmaHandler(const char *Namespace, PragmaHandler *Handler);
288
289  /// EnterMainSourceFile - Enter the specified FileID as the main source file,
290  /// which implicitly adds the builtin defines etc.
291  void EnterMainSourceFile();
292
293  /// EnterSourceFile - Add a source file to the top of the include stack and
294  /// start lexing tokens from it instead of the current buffer.  If isMainFile
295  /// is true, this is the main file for the translation unit.
296  void EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir);
297
298  /// EnterMacro - Add a Macro to the top of the include stack and start lexing
299  /// tokens from it instead of the current buffer.  Args specifies the
300  /// tokens input to a function-like macro.
301  ///
302  /// ILEnd specifies the location of the ')' for a function-like macro or the
303  /// identifier for an object-like macro.
304  void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroArgs *Args);
305
306  /// EnterTokenStream - Add a "macro" context to the top of the include stack,
307  /// which will cause the lexer to start returning the specified tokens.
308  ///
309  /// If DisableMacroExpansion is true, tokens lexed from the token stream will
310  /// not be subject to further macro expansion.  Otherwise, these tokens will
311  /// be re-macro-expanded when/if expansion is enabled.
312  ///
313  /// If OwnsTokens is false, this method assumes that the specified stream of
314  /// tokens has a permanent owner somewhere, so they do not need to be copied.
315  /// If it is true, it assumes the array of tokens is allocated with new[] and
316  /// must be freed.
317  ///
318  void EnterTokenStream(const Token *Toks, unsigned NumToks,
319                        bool DisableMacroExpansion, bool OwnsTokens);
320
321  /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
322  /// lexer stack.  This should only be used in situations where the current
323  /// state of the top-of-stack lexer is known.
324  void RemoveTopOfLexerStack();
325
326  /// EnableBacktrackAtThisPos - From the point that this method is called, and
327  /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
328  /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
329  /// make the Preprocessor re-lex the same tokens.
330  ///
331  /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
332  /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
333  /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
334  ///
335  /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
336  /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
337  /// tokens will continue indefinitely.
338  ///
339  void EnableBacktrackAtThisPos();
340
341  /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call.
342  void CommitBacktrackedTokens();
343
344  /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since
345  /// EnableBacktrackAtThisPos() was previously called.
346  void Backtrack();
347
348  /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and
349  /// caching of tokens is on.
350  bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
351
352  /// Lex - To lex a token from the preprocessor, just pull a token from the
353  /// current lexer or macro object.
354  void Lex(Token &Result) {
355    if (CurLexer)
356      CurLexer->Lex(Result);
357    else if (CurPTHLexer)
358      CurPTHLexer->Lex(Result);
359    else if (CurTokenLexer)
360      CurTokenLexer->Lex(Result);
361    else
362      CachingLex(Result);
363  }
364
365  /// LexNonComment - Lex a token.  If it's a comment, keep lexing until we get
366  /// something not a comment.  This is useful in -E -C mode where comments
367  /// would foul up preprocessor directive handling.
368  void LexNonComment(Token &Result) {
369    do
370      Lex(Result);
371    while (Result.getKind() == tok::comment);
372  }
373
374  /// LexUnexpandedToken - This is just like Lex, but this disables macro
375  /// expansion of identifier tokens.
376  void LexUnexpandedToken(Token &Result) {
377    // Disable macro expansion.
378    bool OldVal = DisableMacroExpansion;
379    DisableMacroExpansion = true;
380    // Lex the token.
381    Lex(Result);
382
383    // Reenable it.
384    DisableMacroExpansion = OldVal;
385  }
386
387  /// LookAhead - This peeks ahead N tokens and returns that token without
388  /// consuming any tokens.  LookAhead(0) returns the next token that would be
389  /// returned by Lex(), LookAhead(1) returns the token after it, etc.  This
390  /// returns normal tokens after phase 5.  As such, it is equivalent to using
391  /// 'Lex', not 'LexUnexpandedToken'.
392  const Token &LookAhead(unsigned N) {
393    if (CachedLexPos + N < CachedTokens.size())
394      return CachedTokens[CachedLexPos+N];
395    else
396      return PeekAhead(N+1);
397  }
398
399  /// RevertCachedTokens - When backtracking is enabled and tokens are cached,
400  /// this allows to revert a specific number of tokens.
401  /// Note that the number of tokens being reverted should be up to the last
402  /// backtrack position, not more.
403  void RevertCachedTokens(unsigned N) {
404    assert(isBacktrackEnabled() &&
405           "Should only be called when tokens are cached for backtracking");
406    assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back())
407         && "Should revert tokens up to the last backtrack position, not more");
408    assert(signed(CachedLexPos) - signed(N) >= 0 &&
409           "Corrupted backtrack positions ?");
410    CachedLexPos -= N;
411  }
412
413  /// EnterToken - Enters a token in the token stream to be lexed next. If
414  /// BackTrack() is called afterwards, the token will remain at the insertion
415  /// point.
416  void EnterToken(const Token &Tok) {
417    EnterCachingLexMode();
418    CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
419  }
420
421  /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching
422  /// tokens (because backtrack is enabled) it should replace the most recent
423  /// cached tokens with the given annotation token. This function has no effect
424  /// if backtracking is not enabled.
425  ///
426  /// Note that the use of this function is just for optimization; so that the
427  /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
428  /// invoked.
429  void AnnotateCachedTokens(const Token &Tok) {
430    assert(Tok.isAnnotation() && "Expected annotation token");
431    if (CachedLexPos != 0 && isBacktrackEnabled())
432      AnnotatePreviousCachedTokens(Tok);
433  }
434
435  /// Diag - Forwarding function for diagnostics.  This emits a diagnostic at
436  /// the specified Token's location, translating the token's start
437  /// position in the current buffer into a SourcePosition object for rendering.
438  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
439    return Diags.Report(FullSourceLoc(Loc, getSourceManager()), DiagID);
440  }
441
442  DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) {
443    return Diags.Report(FullSourceLoc(Tok.getLocation(), getSourceManager()),
444                        DiagID);
445  }
446
447  /// getSpelling() - Return the 'spelling' of the Tok token.  The spelling of a
448  /// token is the characters used to represent the token in the source file
449  /// after trigraph expansion and escaped-newline folding.  In particular, this
450  /// wants to get the true, uncanonicalized, spelling of things like digraphs
451  /// UCNs, etc.
452  std::string getSpelling(const Token &Tok) const;
453
454  /// getSpelling - This method is used to get the spelling of a token into a
455  /// preallocated buffer, instead of as an std::string.  The caller is required
456  /// to allocate enough space for the token, which is guaranteed to be at least
457  /// Tok.getLength() bytes long.  The length of the actual result is returned.
458  ///
459  /// Note that this method may do two possible things: it may either fill in
460  /// the buffer specified with characters, or it may *change the input pointer*
461  /// to point to a constant buffer with the data already in it (avoiding a
462  /// copy).  The caller is not allowed to modify the returned buffer pointer
463  /// if an internal buffer is returned.
464  unsigned getSpelling(const Token &Tok, const char *&Buffer) const;
465
466  /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric constant
467  /// with length 1, return the character.
468  char getSpellingOfSingleCharacterNumericConstant(const Token &Tok) const {
469    assert(Tok.is(tok::numeric_constant) &&
470           Tok.getLength() == 1 && "Called on unsupported token");
471    assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
472
473    // If the token is carrying a literal data pointer, just use it.
474    if (const char *D = Tok.getLiteralData())
475      return *D;
476
477    // Otherwise, fall back on getCharacterData, which is slower, but always
478    // works.
479    return *SourceMgr.getCharacterData(Tok.getLocation());
480  }
481
482  /// CreateString - Plop the specified string into a scratch buffer and set the
483  /// specified token's location and length to it.  If specified, the source
484  /// location provides a location of the instantiation point of the token.
485  void CreateString(const char *Buf, unsigned Len,
486                    Token &Tok, SourceLocation SourceLoc = SourceLocation());
487
488  /// DumpToken - Print the token to stderr, used for debugging.
489  ///
490  void DumpToken(const Token &Tok, bool DumpFlags = false) const;
491  void DumpLocation(SourceLocation Loc) const;
492  void DumpMacro(const MacroInfo &MI) const;
493
494  /// AdvanceToTokenCharacter - Given a location that specifies the start of a
495  /// token, return a new location that specifies a character within the token.
496  SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char);
497
498  /// IncrementPasteCounter - Increment the counters for the number of token
499  /// paste operations performed.  If fast was specified, this is a 'fast paste'
500  /// case we handled.
501  ///
502  void IncrementPasteCounter(bool isFast) {
503    if (isFast)
504      ++NumFastTokenPaste;
505    else
506      ++NumTokenPaste;
507  }
508
509  void PrintStats();
510
511  /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
512  /// comment (/##/) in microsoft mode, this method handles updating the current
513  /// state, returning the token on the next source line.
514  void HandleMicrosoftCommentPaste(Token &Tok);
515
516  //===--------------------------------------------------------------------===//
517  // Preprocessor callback methods.  These are invoked by a lexer as various
518  // directives and events are found.
519
520  /// LookUpIdentifierInfo - Given a tok::identifier token, look up the
521  /// identifier information for the token and install it into the token.
522  IdentifierInfo *LookUpIdentifierInfo(Token &Identifier,
523                                       const char *BufPtr = 0);
524
525  /// HandleIdentifier - This callback is invoked when the lexer reads an
526  /// identifier and has filled in the tokens IdentifierInfo member.  This
527  /// callback potentially macro expands it or turns it into a named token (like
528  /// 'for').
529  void HandleIdentifier(Token &Identifier);
530
531
532  /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
533  /// the current file.  This either returns the EOF token and returns true, or
534  /// pops a level off the include stack and returns false, at which point the
535  /// client should call lex again.
536  bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false);
537
538  /// HandleEndOfTokenLexer - This callback is invoked when the current
539  /// TokenLexer hits the end of its token stream.
540  bool HandleEndOfTokenLexer(Token &Result);
541
542  /// HandleDirective - This callback is invoked when the lexer sees a # token
543  /// at the start of a line.  This consumes the directive, modifies the
544  /// lexer/preprocessor state, and advances the lexer(s) so that the next token
545  /// read is the correct one.
546  void HandleDirective(Token &Result);
547
548  /// CheckEndOfDirective - Ensure that the next token is a tok::eom token.  If
549  /// not, emit a diagnostic and consume up until the eom.
550  void CheckEndOfDirective(const char *Directive);
551
552  /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
553  /// current line until the tok::eom token is found.
554  void DiscardUntilEndOfDirective();
555
556private:
557
558  void PushIncludeMacroStack() {
559    IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(),
560                                                 CurPTHLexer.take(),
561                                                 CurPPLexer,
562                                                 CurTokenLexer.take(),
563                                                 CurDirLookup));
564    CurPPLexer = 0;
565  }
566
567  void PopIncludeMacroStack() {
568    CurLexer.reset(IncludeMacroStack.back().TheLexer);
569    CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer);
570    CurPPLexer = IncludeMacroStack.back().ThePPLexer;
571    CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer);
572    CurDirLookup  = IncludeMacroStack.back().TheDirLookup;
573    IncludeMacroStack.pop_back();
574  }
575
576  /// AllocateMacroInfo - Allocate a new MacroInfo object with the provide
577  ///  SourceLocation.
578  MacroInfo* AllocateMacroInfo(SourceLocation L);
579
580  /// ReleaseMacroInfo - Release the specified MacroInfo.  This memory will
581  ///  be reused for allocating new MacroInfo objects.
582  void ReleaseMacroInfo(MacroInfo* MI);
583
584  /// isInPrimaryFile - Return true if we're in the top-level file, not in a
585  /// #include.
586  bool isInPrimaryFile() const;
587
588  /// ReadMacroName - Lex and validate a macro name, which occurs after a
589  /// #define or #undef.  This emits a diagnostic, sets the token kind to eom,
590  /// and discards the rest of the macro line if the macro name is invalid.
591  void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0);
592
593  /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
594  /// definition has just been read.  Lex the rest of the arguments and the
595  /// closing ), updating MI with what we learn.  Return true if an error occurs
596  /// parsing the arg list.
597  bool ReadMacroDefinitionArgList(MacroInfo *MI);
598
599  /// SkipExcludedConditionalBlock - We just read a #if or related directive and
600  /// decided that the subsequent tokens are in the #if'd out portion of the
601  /// file.  Lex the rest of the file, until we see an #endif.  If
602  /// FoundNonSkipPortion is true, then we have already emitted code for part of
603  /// this #if directive, so #else/#elif blocks should never be entered. If
604  /// FoundElse is false, then #else directives are ok, if not, then we have
605  /// already seen one so a #else directive is a duplicate.  When this returns,
606  /// the caller can lex the first valid token.
607  void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
608                                    bool FoundNonSkipPortion, bool FoundElse);
609
610  /// PTHSkipExcludedConditionalBlock - A fast PTH version of
611  ///  SkipExcludedConditionalBlock.
612  void PTHSkipExcludedConditionalBlock();
613
614  /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
615  /// may occur after a #if or #elif directive and return it as a bool.  If the
616  /// expression is equivalent to "!defined(X)" return X in IfNDefMacro.
617  bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
618
619  /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
620  /// #pragma GCC poison/system_header/dependency and #pragma once.
621  void RegisterBuiltinPragmas();
622
623  /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
624  /// identifier table.
625  void RegisterBuiltinMacros();
626  IdentifierInfo *RegisterBuiltinMacro(const char *Name);
627
628  /// HandleMacroExpandedIdentifier - If an identifier token is read that is to
629  /// be expanded as a macro, handle it and return the next token as 'Tok'.  If
630  /// the macro should not be expanded return true, otherwise return false.
631  bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI);
632
633  /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
634  /// lexed is a '('.  If so, consume the token and return true, if not, this
635  /// method should have no observable side-effect on the lexed tokens.
636  bool isNextPPTokenLParen();
637
638  /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
639  /// invoked to read all of the formal arguments specified for the macro
640  /// invocation.  This returns null on error.
641  MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI,
642                                       SourceLocation &InstantiationEnd);
643
644  /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
645  /// as a builtin macro, handle it and return the next token as 'Tok'.
646  void ExpandBuiltinMacro(Token &Tok);
647
648  /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
649  /// return the first token after the directive.  The _Pragma token has just
650  /// been read into 'Tok'.
651  void Handle_Pragma(Token &Tok);
652
653  /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and
654  /// start lexing tokens from it instead of the current buffer.
655  void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
656
657  /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and
658  /// start getting tokens from it using the PTH cache.
659  void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir);
660
661  /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
662  /// checked and spelled filename, e.g. as an operand of #include. This returns
663  /// true if the input filename was in <>'s or false if it were in ""'s.  The
664  /// caller is expected to provide a buffer that is large enough to hold the
665  /// spelling of the filename, but is also expected to handle the case when
666  /// this method decides to use a different buffer.
667  bool GetIncludeFilenameSpelling(SourceLocation Loc,
668                                  const char *&BufStart, const char *&BufEnd);
669
670  /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
671  /// return null on failure.  isAngled indicates whether the file reference is
672  /// for system #include's or not (i.e. using <> instead of "").
673  const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd,
674                              bool isAngled, const DirectoryLookup *FromDir,
675                              const DirectoryLookup *&CurDir);
676
677
678
679  /// IsFileLexer - Returns true if we are lexing from a file and not a
680  ///  pragma or a macro.
681  static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
682    return L ? !L->isPragmaLexer() : P != 0;
683  }
684
685  static bool IsFileLexer(const IncludeStackInfo& I) {
686    return IsFileLexer(I.TheLexer, I.ThePPLexer);
687  }
688
689  bool IsFileLexer() const {
690    return IsFileLexer(CurLexer.get(), CurPPLexer);
691  }
692
693  //===--------------------------------------------------------------------===//
694  // Caching stuff.
695  void CachingLex(Token &Result);
696  bool InCachingLexMode() const { return CurPPLexer == 0 && CurTokenLexer == 0;}
697  void EnterCachingLexMode();
698  void ExitCachingLexMode() {
699    if (InCachingLexMode())
700      RemoveTopOfLexerStack();
701  }
702  const Token &PeekAhead(unsigned N);
703  void AnnotatePreviousCachedTokens(const Token &Tok);
704
705  //===--------------------------------------------------------------------===//
706  /// Handle*Directive - implement the various preprocessor directives.  These
707  /// should side-effect the current preprocessor object so that the next call
708  /// to Lex() will return the appropriate token next.
709  void HandleLineDirective(Token &Tok);
710  void HandleDigitDirective(Token &Tok);
711  void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
712  void HandleIdentSCCSDirective(Token &Tok);
713
714  // File inclusion.
715  void HandleIncludeDirective(Token &Tok,
716                              const DirectoryLookup *LookupFrom = 0,
717                              bool isImport = false);
718  void HandleIncludeNextDirective(Token &Tok);
719  void HandleImportDirective(Token &Tok);
720
721  // Macro handling.
722  void HandleDefineDirective(Token &Tok);
723  void HandleUndefDirective(Token &Tok);
724  // HandleAssertDirective(Token &Tok);
725  // HandleUnassertDirective(Token &Tok);
726
727  // Conditional Inclusion.
728  void HandleIfdefDirective(Token &Tok, bool isIfndef,
729                            bool ReadAnyTokensBeforeDirective);
730  void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective);
731  void HandleEndifDirective(Token &Tok);
732  void HandleElseDirective(Token &Tok);
733  void HandleElifDirective(Token &Tok);
734
735  // Pragmas.
736  void HandlePragmaDirective();
737public:
738  void HandlePragmaOnce(Token &OnceTok);
739  void HandlePragmaMark();
740  void HandlePragmaPoison(Token &PoisonTok);
741  void HandlePragmaSystemHeader(Token &SysHeaderTok);
742  void HandlePragmaDependency(Token &DependencyTok);
743  void HandlePragmaComment(Token &CommentTok);
744};
745
746/// PreprocessorFactory - A generic factory interface for lazily creating
747///  Preprocessor objects on-demand when they are needed.
748class PreprocessorFactory {
749public:
750  virtual ~PreprocessorFactory();
751  virtual Preprocessor* CreatePreprocessor() = 0;
752};
753
754}  // end namespace clang
755
756#endif
757