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