Preprocessor.h revision 2df37b8eaecc5382e0e511a738f88918f48d9454
153e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)//===--- Preprocessor.h - C Language Family Preprocessor --------*- C++ -*-===// 253e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)// 353e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)// The LLVM Compiler Infrastructure 453e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)// 553e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source 653e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)// License. See LICENSE.TXT for details. 753e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)// 853e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)//===----------------------------------------------------------------------===// 953e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)// 1053e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)// This file defines the Preprocessor interface. 1153e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)// 1253e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)//===----------------------------------------------------------------------===// 1353e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) 1453e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#ifndef LLVM_CLANG_LEX_PREPROCESSOR_H 1553e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#define LLVM_CLANG_LEX_PREPROCESSOR_H 1653e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) 1753e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include "clang/Lex/Lexer.h" 1853e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include "clang/Lex/PTHLexer.h" 1953e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include "clang/Lex/PPCallbacks.h" 2053e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include "clang/Lex/TokenLexer.h" 2153e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include "clang/Basic/IdentifierTable.h" 2253e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include "clang/Basic/SourceLocation.h" 2353e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include "llvm/ADT/DenseMap.h" 2453e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include "llvm/ADT/OwningPtr.h" 2553e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) 2653e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)namespace clang { 2753e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) 2853e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)class SourceManager; 2953e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)class FileManager; 3053e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)class FileEntry; 3153e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)class HeaderSearch; 321e202183a5dc46166763171984b285173f8585e5Torne (Richard Coles)class PragmaNamespace; 3353e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)class PragmaHandler; 3402772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdochclass ScratchBuffer; 3502772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdochclass TargetInfo; 36c1847b1379d12d0e05df27436bf19a9b1bf12deaTorne (Richard Coles)class PPCallbacks; 3753e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)class DirectoryLookup; 38d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) 39d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles)/// Preprocessor - This object engages in a tight little dance with the lexer to 40d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles)/// efficiently preprocess tokens. Lexers know only about tokens within a 41d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles)/// single source file, and don't know anything about preprocessor-level issues 42d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles)/// like the #include stack, token expansion, etc. 4302772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch/// 4402772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdochclass Preprocessor { 45d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) Diagnostic &Diags; 46d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) const LangOptions &Features; 47d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) TargetInfo &Target; 4802772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch FileManager &FileMgr; 4902772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch SourceManager &SourceMgr; 50e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) ScratchBuffer *ScratchBuf; 51d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) HeaderSearch &HeaderInfo; 5202772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch 5302772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch /// Identifiers for builtin macros and other builtins. 54e69819bd8e388ea4ad1636a19aa6b2eed4952191Ben Murdoch IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__ 5553e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__ 56e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__ 5702772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__ 5802772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__ 59f79f16f17ddc4f842d7b7a38603e280e94be826aTorne (Richard Coles) IdentifierInfo *Ident_Pragma, *Ident__VA_ARGS__; // _Pragma, __VA_ARGS__ 6053e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) 61e69819bd8e388ea4ad1636a19aa6b2eed4952191Ben Murdoch SourceLocation DATELoc, TIMELoc; 6209380295ba73501a205346becac22c6978e4671dTorne (Richard Coles) 6353e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) enum { 64d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) /// MaxIncludeStackDepth - Maximum depth of #includes. 6509380295ba73501a205346becac22c6978e4671dTorne (Richard Coles) MaxAllowedIncludeStackDepth = 200 66d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) }; 6709380295ba73501a205346becac22c6978e4671dTorne (Richard Coles) 6853e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) // State that is set before the preprocessor begins. 6953e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) bool KeepComments : 1; 70e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) bool KeepMacroComments : 1; 71e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) 72e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) // State that changes while the preprocessor runs: 737757ec2eadfa2dd8ac2aeed0a4399e9b07ec38cbBen Murdoch bool DisableMacroExpansion : 1; // True if macro expansion is disabled. 7451b2906e11752df6c18351cf520e30522d3b53a1Torne (Richard Coles) bool InMacroArgs : 1; // True if parsing fn macro invocation args. 7553e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) 767757ec2eadfa2dd8ac2aeed0a4399e9b07ec38cbBen Murdoch /// CacheTokens - True when the lexed tokens are cached for backtracking. 7751b2906e11752df6c18351cf520e30522d3b53a1Torne (Richard Coles) bool CacheTokens : 1; 78d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) 797757ec2eadfa2dd8ac2aeed0a4399e9b07ec38cbBen Murdoch /// Identifiers - This is mapping/lookup information for all identifiers in 8053e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) /// the program, including program keywords. 8153e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) IdentifierTable Identifiers; 82e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) 8353e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) /// Selectors - This table contains all the selectors in the program. Unlike 84e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) /// IdentifierTable above, this table *isn't* populated by the preprocessor. 85e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) /// It is declared/instantiated here because it's role/lifetime is 86e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) /// conceptually similar the IdentifierTable. In addition, the current control 8753e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) /// flow (in clang::ParseAST()), make it convenient to put here. 8853e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to 89e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) /// the lifetime fo the preprocessor. 9002772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch SelectorTable Selectors; 91e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) 9251b2906e11752df6c18351cf520e30522d3b53a1Torne (Richard Coles) /// PragmaHandlers - This tracks all of the pragmas that the client registered 9302772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch /// with this preprocessor. 94e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) PragmaNamespace *PragmaHandlers; 9551b2906e11752df6c18351cf520e30522d3b53a1Torne (Richard Coles) 96d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) /// CurLexer - This is the current top of the stack that we're lexing from if 9702772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch /// not expanding a macro and we are lexing directly from source code. 9802772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. 99d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) llvm::OwningPtr<Lexer> CurLexer; 10002772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch 101d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) /// CurPTHLexer - This is the current top of stack that we're lexing from if 10202772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch /// not expanding from a macro and we are lexing from a PTH cache. 103d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. 104d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) llvm::OwningPtr<PTHLexer> CurPTHLexer; 105d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) 106d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) /// CurPPLexer - This is the current top of the stack what we're lexing from 107e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) /// if not expanding a macro. This is an alias for either CurLexer or 108e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) /// CurPTHLexer. 109e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) PreprocessorLexer* CurPPLexer; 110d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) 111d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) /// CurLookup - The DirectoryLookup structure used to find the current 112e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles) /// FileEntry, if CurLexer is non-null and if applicable. This allows us to 113d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) /// implement #include_next and find directory-specific properties. 114d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) const DirectoryLookup *CurDirLookup; 115c1847b1379d12d0e05df27436bf19a9b1bf12deaTorne (Richard Coles) 116d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) /// CurTokenLexer - This is the current macro we are expanding, if we are 117d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) /// expanding a macro. One of CurLexer and CurTokenLexer must be null. 118c1847b1379d12d0e05df27436bf19a9b1bf12deaTorne (Richard Coles) llvm::OwningPtr<TokenLexer> CurTokenLexer; 119d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles) 12002772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch /// IncludeMacroStack - This keeps track of the stack of files currently 12102772c6a72f1ee0b226341a4f4439970c29fc861Ben Murdoch /// #included, and macros currently being expanded from, not counting 12253e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles) /// 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 (CurPTHLexer) 334 CurPTHLexer->Lex(Result); 335 else if (CurTokenLexer) 336 CurTokenLexer->Lex(Result); 337 else 338 CachingLex(Result); 339 } 340 341 /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get 342 /// something not a comment. This is useful in -E -C mode where comments 343 /// would foul up preprocessor directive handling. 344 void LexNonComment(Token &Result) { 345 do 346 Lex(Result); 347 while (Result.getKind() == tok::comment); 348 } 349 350 /// LexUnexpandedToken - This is just like Lex, but this disables macro 351 /// expansion of identifier tokens. 352 void LexUnexpandedToken(Token &Result) { 353 // Disable macro expansion. 354 bool OldVal = DisableMacroExpansion; 355 DisableMacroExpansion = true; 356 // Lex the token. 357 Lex(Result); 358 359 // Reenable it. 360 DisableMacroExpansion = OldVal; 361 } 362 363 /// LookAhead - This peeks ahead N tokens and returns that token without 364 /// consuming any tokens. LookAhead(0) returns the next token that would be 365 /// returned by Lex(), LookAhead(1) returns the token after it, etc. This 366 /// returns normal tokens after phase 5. As such, it is equivalent to using 367 /// 'Lex', not 'LexUnexpandedToken'. 368 const Token &LookAhead(unsigned N) { 369 if (CachedLexPos + N < CachedTokens.size()) 370 return CachedTokens[CachedLexPos+N]; 371 else 372 return PeekAhead(N+1); 373 } 374 375 /// EnterToken - Enters a token in the token stream to be lexed next. If 376 /// BackTrack() is called afterwards, the token will remain at the insertion 377 /// point. 378 void EnterToken(const Token &Tok) { 379 EnterCachingLexMode(); 380 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok); 381 } 382 383 /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching 384 /// tokens (because backtrack is enabled) it should replace the most recent 385 /// cached tokens with the given annotation token. This function has no effect 386 /// if backtracking is not enabled. 387 /// 388 /// Note that the use of this function is just for optimization; so that the 389 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is 390 /// invoked. 391 void AnnotateCachedTokens(const Token &Tok) { 392 assert(Tok.isAnnotationToken() && "Expected annotation token"); 393 if (CachedLexPos != 0 && InCachingLexMode()) 394 AnnotatePreviousCachedTokens(Tok); 395 } 396 397 /// Diag - Forwarding function for diagnostics. This emits a diagnostic at 398 /// the specified Token's location, translating the token's start 399 /// position in the current buffer into a SourcePosition object for rendering. 400 DiagnosticInfo Diag(SourceLocation Loc, unsigned DiagID); 401 DiagnosticInfo Diag(const Token &Tok, unsigned DiagID); 402 403 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a 404 /// token is the characters used to represent the token in the source file 405 /// after trigraph expansion and escaped-newline folding. In particular, this 406 /// wants to get the true, uncanonicalized, spelling of things like digraphs 407 /// UCNs, etc. 408 std::string getSpelling(const Token &Tok) const; 409 410 /// getSpelling - This method is used to get the spelling of a token into a 411 /// preallocated buffer, instead of as an std::string. The caller is required 412 /// to allocate enough space for the token, which is guaranteed to be at least 413 /// Tok.getLength() bytes long. The length of the actual result is returned. 414 /// 415 /// Note that this method may do two possible things: it may either fill in 416 /// the buffer specified with characters, or it may *change the input pointer* 417 /// to point to a constant buffer with the data already in it (avoiding a 418 /// copy). The caller is not allowed to modify the returned buffer pointer 419 /// if an internal buffer is returned. 420 unsigned getSpelling(const Token &Tok, const char *&Buffer) const; 421 422 423 /// CreateString - Plop the specified string into a scratch buffer and return 424 /// a location for it. If specified, the source location provides a source 425 /// location for the token. 426 SourceLocation CreateString(const char *Buf, unsigned Len, 427 SourceLocation SourceLoc = SourceLocation()); 428 429 /// DumpToken - Print the token to stderr, used for debugging. 430 /// 431 void DumpToken(const Token &Tok, bool DumpFlags = false) const; 432 void DumpLocation(SourceLocation Loc) const; 433 void DumpMacro(const MacroInfo &MI) const; 434 435 /// AdvanceToTokenCharacter - Given a location that specifies the start of a 436 /// token, return a new location that specifies a character within the token. 437 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char); 438 439 /// IncrementPasteCounter - Increment the counters for the number of token 440 /// paste operations performed. If fast was specified, this is a 'fast paste' 441 /// case we handled. 442 /// 443 void IncrementPasteCounter(bool isFast) { 444 if (isFast) 445 ++NumFastTokenPaste; 446 else 447 ++NumTokenPaste; 448 } 449 450 void PrintStats(); 451 452 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a 453 /// comment (/##/) in microsoft mode, this method handles updating the current 454 /// state, returning the token on the next source line. 455 void HandleMicrosoftCommentPaste(Token &Tok); 456 457 //===--------------------------------------------------------------------===// 458 // Preprocessor callback methods. These are invoked by a lexer as various 459 // directives and events are found. 460 461 /// LookUpIdentifierInfo - Given a tok::identifier token, look up the 462 /// identifier information for the token and install it into the token. 463 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier, 464 const char *BufPtr = 0); 465 466 /// HandleIdentifier - This callback is invoked when the lexer reads an 467 /// identifier and has filled in the tokens IdentifierInfo member. This 468 /// callback potentially macro expands it or turns it into a named token (like 469 /// 'for'). 470 void HandleIdentifier(Token &Identifier); 471 472 473 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of 474 /// the current file. This either returns the EOF token and returns true, or 475 /// pops a level off the include stack and returns false, at which point the 476 /// client should call lex again. 477 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); 478 479 /// HandleEndOfTokenLexer - This callback is invoked when the current 480 /// TokenLexer hits the end of its token stream. 481 bool HandleEndOfTokenLexer(Token &Result); 482 483 /// HandleDirective - This callback is invoked when the lexer sees a # token 484 /// at the start of a line. This consumes the directive, modifies the 485 /// lexer/preprocessor state, and advances the lexer(s) so that the next token 486 /// read is the correct one. 487 void HandleDirective(Token &Result); 488 489 /// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If 490 /// not, emit a diagnostic and consume up until the eom. 491 void CheckEndOfDirective(const char *Directive); 492private: 493 494 void PushIncludeMacroStack() { 495 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(), 496 CurPTHLexer.take(), 497 CurPPLexer, 498 CurTokenLexer.take(), 499 CurDirLookup)); 500 CurPPLexer = 0; 501 } 502 503 void PopIncludeMacroStack() { 504 CurLexer.reset(IncludeMacroStack.back().TheLexer); 505 CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer); 506 CurPPLexer = IncludeMacroStack.back().ThePPLexer; 507 CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer); 508 CurDirLookup = IncludeMacroStack.back().TheDirLookup; 509 IncludeMacroStack.pop_back(); 510 } 511 512 /// isInPrimaryFile - Return true if we're in the top-level file, not in a 513 /// #include. 514 bool isInPrimaryFile() const; 515 516 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the 517 /// current line until the tok::eom token is found. 518 void DiscardUntilEndOfDirective(); 519 520 /// ReadMacroName - Lex and validate a macro name, which occurs after a 521 /// #define or #undef. This emits a diagnostic, sets the token kind to eom, 522 /// and discards the rest of the macro line if the macro name is invalid. 523 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0); 524 525 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 526 /// definition has just been read. Lex the rest of the arguments and the 527 /// closing ), updating MI with what we learn. Return true if an error occurs 528 /// parsing the arg list. 529 bool ReadMacroDefinitionArgList(MacroInfo *MI); 530 531 /// SkipExcludedConditionalBlock - We just read a #if or related directive and 532 /// decided that the subsequent tokens are in the #if'd out portion of the 533 /// file. Lex the rest of the file, until we see an #endif. If 534 /// FoundNonSkipPortion is true, then we have already emitted code for part of 535 /// this #if directive, so #else/#elif blocks should never be entered. If 536 /// FoundElse is false, then #else directives are ok, if not, then we have 537 /// already seen one so a #else directive is a duplicate. When this returns, 538 /// the caller can lex the first valid token. 539 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 540 bool FoundNonSkipPortion, bool FoundElse); 541 542 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that 543 /// may occur after a #if or #elif directive and return it as a bool. If the 544 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro. 545 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); 546 547 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 548 /// #pragma GCC poison/system_header/dependency and #pragma once. 549 void RegisterBuiltinPragmas(); 550 551 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 552 /// identifier table. 553 void RegisterBuiltinMacros(); 554 IdentifierInfo *RegisterBuiltinMacro(const char *Name); 555 556 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to 557 /// be expanded as a macro, handle it and return the next token as 'Tok'. If 558 /// the macro should not be expanded return true, otherwise return false. 559 bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI); 560 561 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 562 /// lexed is a '('. If so, consume the token and return true, if not, this 563 /// method should have no observable side-effect on the lexed tokens. 564 bool isNextPPTokenLParen(); 565 566 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is 567 /// invoked to read all of the formal arguments specified for the macro 568 /// invocation. This returns null on error. 569 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI); 570 571 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 572 /// as a builtin macro, handle it and return the next token as 'Tok'. 573 void ExpandBuiltinMacro(Token &Tok); 574 575 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 576 /// return the first token after the directive. The _Pragma token has just 577 /// been read into 'Tok'. 578 void Handle_Pragma(Token &Tok); 579 580 581 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and 582 /// start lexing tokens from it instead of the current buffer. 583 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); 584 585 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 586 /// checked and spelled filename, e.g. as an operand of #include. This returns 587 /// true if the input filename was in <>'s or false if it were in ""'s. The 588 /// caller is expected to provide a buffer that is large enough to hold the 589 /// spelling of the filename, but is also expected to handle the case when 590 /// this method decides to use a different buffer. 591 bool GetIncludeFilenameSpelling(SourceLocation Loc, 592 const char *&BufStart, const char *&BufEnd); 593 594 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 595 /// return null on failure. isAngled indicates whether the file reference is 596 /// for system #include's or not (i.e. using <> instead of ""). 597 const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd, 598 bool isAngled, const DirectoryLookup *FromDir, 599 const DirectoryLookup *&CurDir); 600 601 //===--------------------------------------------------------------------===// 602 // Caching stuff. 603 void CachingLex(Token &Result); 604 bool InCachingLexMode() const { return CurLexer == 0 && CurTokenLexer == 0; } 605 void EnterCachingLexMode(); 606 void ExitCachingLexMode() { 607 if (InCachingLexMode()) 608 RemoveTopOfLexerStack(); 609 } 610 const Token &PeekAhead(unsigned N); 611 void AnnotatePreviousCachedTokens(const Token &Tok); 612 613 //===--------------------------------------------------------------------===// 614 /// Handle*Directive - implement the various preprocessor directives. These 615 /// should side-effect the current preprocessor object so that the next call 616 /// to Lex() will return the appropriate token next. 617 618 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); 619 void HandleIdentSCCSDirective(Token &Tok); 620 621 // File inclusion. 622 void HandleIncludeDirective(Token &Tok, 623 const DirectoryLookup *LookupFrom = 0, 624 bool isImport = false); 625 void HandleIncludeNextDirective(Token &Tok); 626 void HandleImportDirective(Token &Tok); 627 628 // Macro handling. 629 void HandleDefineDirective(Token &Tok); 630 void HandleUndefDirective(Token &Tok); 631 // HandleAssertDirective(Token &Tok); 632 // HandleUnassertDirective(Token &Tok); 633 634 // Conditional Inclusion. 635 void HandleIfdefDirective(Token &Tok, bool isIfndef, 636 bool ReadAnyTokensBeforeDirective); 637 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective); 638 void HandleEndifDirective(Token &Tok); 639 void HandleElseDirective(Token &Tok); 640 void HandleElifDirective(Token &Tok); 641 642 // Pragmas. 643 void HandlePragmaDirective(); 644public: 645 void HandlePragmaOnce(Token &OnceTok); 646 void HandlePragmaMark(); 647 void HandlePragmaPoison(Token &PoisonTok); 648 void HandlePragmaSystemHeader(Token &SysHeaderTok); 649 void HandlePragmaDependency(Token &DependencyTok); 650}; 651 652/// PreprocessorFactory - A generic factory interface for lazily creating 653/// Preprocessor objects on-demand when they are needed. 654class PreprocessorFactory { 655public: 656 virtual ~PreprocessorFactory(); 657 virtual Preprocessor* CreatePreprocessor() = 0; 658}; 659 660} // end namespace clang 661 662#endif 663