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