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