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