Preprocessor.h revision 5814e657c9ad9ef6049a2a4af0d2aad248a8a15c
1a5728872c7702ddd09537c95bc3cbd20e1f2fb09Daniel Dunbar//===--- Preprocessor.h - C Language Family Preprocessor --------*- C++ -*-===// 23218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor// 33218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor// The LLVM Compiler Infrastructure 43218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor// 53218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor// This file is distributed under the University of Illinois Open Source 63218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor// License. See LICENSE.TXT for details. 73218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor// 83218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor//===----------------------------------------------------------------------===// 93218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor// 103218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor// This file defines the Preprocessor interface. 113218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor// 123218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor//===----------------------------------------------------------------------===// 133218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor 143218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#ifndef LLVM_CLANG_LEX_PREPROCESSOR_H 153218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#define LLVM_CLANG_LEX_PREPROCESSOR_H 163218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor 173218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "clang/Lex/Lexer.h" 183218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "clang/Lex/PTHLexer.h" 193218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "clang/Lex/PPCallbacks.h" 203218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "clang/Lex/TokenLexer.h" 213218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "clang/Lex/PTHManager.h" 228d3607bf22a6a70acce3722a758f02d4ea84fc3aKaelyn Uhrain#include "clang/Basic/Builtins.h" 233218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "clang/Basic/Diagnostic.h" 243218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "clang/Basic/IdentifierTable.h" 25a41a8c5972c2632247ae7913cf6ce65d45f7e702Douglas Gregor#include "clang/Basic/SourceLocation.h" 263218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "llvm/ADT/DenseMap.h" 273218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "llvm/ADT/OwningPtr.h" 283218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "llvm/ADT/SmallVector.h" 293218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor#include "llvm/Support/Allocator.h" 307c2342dd4c9947806842e5aca3d2bb2e542853c9John McCall#include <vector> 313218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor 323218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregornamespace clang { 333218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor 343218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregorclass SourceManager; 353218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregorclass FileManager; 363218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregorclass FileEntry; 373218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregorclass HeaderSearch; 388d3607bf22a6a70acce3722a758f02d4ea84fc3aKaelyn Uhrainclass PragmaNamespace; 393218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregorclass PragmaHandler; 403218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregorclass CommentHandler; 413218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregorclass ScratchBuffer; 423218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregorclass TargetInfo; 430c6db9417dceeb082296c4e097be5de3ee1c5eb7Douglas Gregorclass PPCallbacks; 443218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregorclass DirectoryLookup; 453218c4bb3b5d7250f12420de6db7ef3e3f805a75Douglas Gregor 466bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines/// Preprocessor - This object engages in a tight little dance with the lexer to 476bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines/// efficiently preprocess tokens. Lexers know only about tokens within a 486bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines/// single source file, and don't know anything about preprocessor-level issues 496bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines/// like the #include stack, token expansion, etc. 506bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines/// 516bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hinesclass Preprocessor { 526bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines Diagnostic *Diags; 536bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines LangOptions Features; 546bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines TargetInfo &Target; 55 FileManager &FileMgr; 56 SourceManager &SourceMgr; 57 ScratchBuffer *ScratchBuf; 58 HeaderSearch &HeaderInfo; 59 60 /// PTH - An optional PTHManager object used for getting tokens from 61 /// a token cache rather than lexing the original source file. 62 llvm::OwningPtr<PTHManager> PTH; 63 64 /// BP - A BumpPtrAllocator object used to quickly allocate and release 65 /// objects internal to the Preprocessor. 66 llvm::BumpPtrAllocator BP; 67 68 /// Identifiers for builtin macros and other builtins. 69 IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__ 70 IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__ 71 IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__ 72 IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__ 73 IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__ 74 IdentifierInfo *Ident__COUNTER__; // __COUNTER__ 75 IdentifierInfo *Ident_Pragma, *Ident__VA_ARGS__; // _Pragma, __VA_ARGS__ 76 IdentifierInfo *Ident__has_feature; // __has_feature 77 IdentifierInfo *Ident__has_builtin; // __has_builtin 78 IdentifierInfo *Ident__has_include; // __has_include 79 IdentifierInfo *Ident__has_include_next; // __has_include_next 80 81 SourceLocation DATELoc, TIMELoc; 82 unsigned CounterValue; // Next __COUNTER__ value. 83 84 enum { 85 /// MaxIncludeStackDepth - Maximum depth of #includes. 86 MaxAllowedIncludeStackDepth = 200 87 }; 88 89 // State that is set before the preprocessor begins. 90 bool KeepComments : 1; 91 bool KeepMacroComments : 1; 92 93 // State that changes while the preprocessor runs: 94 bool DisableMacroExpansion : 1; // True if macro expansion is disabled. 95 bool InMacroArgs : 1; // True if parsing fn macro invocation args. 96 97 /// Whether the preprocessor owns the header search object. 98 bool OwnsHeaderSearch : 1; 99 100 /// Identifiers - This is mapping/lookup information for all identifiers in 101 /// the program, including program keywords. 102 mutable IdentifierTable Identifiers; 103 104 /// Selectors - This table contains all the selectors in the program. Unlike 105 /// IdentifierTable above, this table *isn't* populated by the preprocessor. 106 /// It is declared/instantiated here because it's role/lifetime is 107 /// conceptually similar the IdentifierTable. In addition, the current control 108 /// flow (in clang::ParseAST()), make it convenient to put here. 109 /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to 110 /// the lifetime fo the preprocessor. 111 SelectorTable Selectors; 112 113 /// BuiltinInfo - Information about builtins. 114 Builtin::Context BuiltinInfo; 115 116 /// PragmaHandlers - This tracks all of the pragmas that the client registered 117 /// with this preprocessor. 118 PragmaNamespace *PragmaHandlers; 119 120 /// \brief Tracks all of the comment handlers that the client registered 121 /// with this preprocessor. 122 std::vector<CommentHandler *> CommentHandlers; 123 124 /// CurLexer - This is the current top of the stack that we're lexing from if 125 /// not expanding a macro and we are lexing directly from source code. 126 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. 127 llvm::OwningPtr<Lexer> CurLexer; 128 129 /// CurPTHLexer - This is the current top of stack that we're lexing from if 130 /// not expanding from a macro and we are lexing from a PTH cache. 131 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. 132 llvm::OwningPtr<PTHLexer> CurPTHLexer; 133 134 /// CurPPLexer - This is the current top of the stack what we're lexing from 135 /// if not expanding a macro. This is an alias for either CurLexer or 136 /// CurPTHLexer. 137 PreprocessorLexer* CurPPLexer; 138 139 /// CurLookup - The DirectoryLookup structure used to find the current 140 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to 141 /// implement #include_next and find directory-specific properties. 142 const DirectoryLookup *CurDirLookup; 143 144 /// CurTokenLexer - This is the current macro we are expanding, if we are 145 /// expanding a macro. One of CurLexer and CurTokenLexer must be null. 146 llvm::OwningPtr<TokenLexer> CurTokenLexer; 147 148 /// IncludeMacroStack - This keeps track of the stack of files currently 149 /// #included, and macros currently being expanded from, not counting 150 /// CurLexer/CurTokenLexer. 151 struct IncludeStackInfo { 152 Lexer *TheLexer; 153 PTHLexer *ThePTHLexer; 154 PreprocessorLexer *ThePPLexer; 155 TokenLexer *TheTokenLexer; 156 const DirectoryLookup *TheDirLookup; 157 158 IncludeStackInfo(Lexer *L, PTHLexer* P, PreprocessorLexer* PPL, 159 TokenLexer* TL, const DirectoryLookup *D) 160 : TheLexer(L), ThePTHLexer(P), ThePPLexer(PPL), TheTokenLexer(TL), 161 TheDirLookup(D) {} 162 }; 163 std::vector<IncludeStackInfo> IncludeMacroStack; 164 165 /// Callbacks - These are actions invoked when some preprocessor activity is 166 /// encountered (e.g. a file is #included, etc). 167 PPCallbacks *Callbacks; 168 169 /// Macros - For each IdentifierInfo with 'HasMacro' set, we keep a mapping 170 /// to the actual definition of the macro. 171 llvm::DenseMap<IdentifierInfo*, MacroInfo*> Macros; 172 173 /// MICache - A "freelist" of MacroInfo objects that can be reused for quick 174 /// allocation. 175 std::vector<MacroInfo*> MICache; 176 177 // Various statistics we track for performance analysis. 178 unsigned NumDirectives, NumIncluded, NumDefined, NumUndefined, NumPragma; 179 unsigned NumIf, NumElse, NumEndif; 180 unsigned NumEnteredSourceFiles, MaxIncludeStackDepth; 181 unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded; 182 unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste; 183 unsigned NumSkipped; 184 185 /// Predefines - This string is the predefined macros that preprocessor 186 /// should use from the command line etc. 187 std::string Predefines; 188 189 /// TokenLexerCache - Cache macro expanders to reduce malloc traffic. 190 enum { TokenLexerCacheSize = 8 }; 191 unsigned NumCachedTokenLexers; 192 TokenLexer *TokenLexerCache[TokenLexerCacheSize]; 193 194private: // Cached tokens state. 195 typedef llvm::SmallVector<Token, 1> CachedTokensTy; 196 197 /// CachedTokens - Cached tokens are stored here when we do backtracking or 198 /// lookahead. They are "lexed" by the CachingLex() method. 199 CachedTokensTy CachedTokens; 200 201 /// CachedLexPos - The position of the cached token that CachingLex() should 202 /// "lex" next. If it points beyond the CachedTokens vector, it means that 203 /// a normal Lex() should be invoked. 204 CachedTokensTy::size_type CachedLexPos; 205 206 /// BacktrackPositions - Stack of backtrack positions, allowing nested 207 /// backtracks. The EnableBacktrackAtThisPos() method pushes a position to 208 /// indicate where CachedLexPos should be set when the BackTrack() method is 209 /// invoked (at which point the last position is popped). 210 std::vector<CachedTokensTy::size_type> BacktrackPositions; 211 212public: 213 Preprocessor(Diagnostic &diags, const LangOptions &opts, TargetInfo &target, 214 SourceManager &SM, HeaderSearch &Headers, 215 IdentifierInfoLookup *IILookup = 0, 216 bool OwnsHeaderSearch = false); 217 218 ~Preprocessor(); 219 220 Diagnostic &getDiagnostics() const { return *Diags; } 221 void setDiagnostics(Diagnostic &D) { Diags = &D; } 222 223 const LangOptions &getLangOptions() const { return Features; } 224 TargetInfo &getTargetInfo() const { return Target; } 225 FileManager &getFileManager() const { return FileMgr; } 226 SourceManager &getSourceManager() const { return SourceMgr; } 227 HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; } 228 229 IdentifierTable &getIdentifierTable() { return Identifiers; } 230 SelectorTable &getSelectorTable() { return Selectors; } 231 Builtin::Context &getBuiltinInfo() { return BuiltinInfo; } 232 llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; } 233 234 void setPTHManager(PTHManager* pm); 235 236 PTHManager *getPTHManager() { return PTH.get(); } 237 238 /// SetCommentRetentionState - Control whether or not the preprocessor retains 239 /// comments in output. 240 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) { 241 this->KeepComments = KeepComments | KeepMacroComments; 242 this->KeepMacroComments = KeepMacroComments; 243 } 244 245 bool getCommentRetentionState() const { return KeepComments; } 246 247 /// isCurrentLexer - Return true if we are lexing directly from the specified 248 /// lexer. 249 bool isCurrentLexer(const PreprocessorLexer *L) const { 250 return CurPPLexer == L; 251 } 252 253 /// getCurrentLexer - Return the current lexer being lexed from. Note 254 /// that this ignores any potentially active macro expansions and _Pragma 255 /// expansions going on at the time. 256 PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; } 257 258 /// getCurrentFileLexer - Return the current file lexer being lexed from. Note 259 /// that this ignores any potentially active macro expansions and _Pragma 260 /// expansions going on at the time. 261 PreprocessorLexer *getCurrentFileLexer() const; 262 263 /// getPPCallbacks/setPPCallbacks - Accessors for preprocessor callbacks. 264 /// Note that this class takes ownership of any PPCallbacks object given to 265 /// it. 266 PPCallbacks *getPPCallbacks() const { return Callbacks; } 267 void setPPCallbacks(PPCallbacks *C) { 268 if (Callbacks) 269 C = new PPChainedCallbacks(C, Callbacks); 270 Callbacks = C; 271 } 272 273 /// getMacroInfo - Given an identifier, return the MacroInfo it is #defined to 274 /// or null if it isn't #define'd. 275 MacroInfo *getMacroInfo(IdentifierInfo *II) const { 276 return II->hasMacroDefinition() ? Macros.find(II)->second : 0; 277 } 278 279 /// setMacroInfo - Specify a macro for this identifier. 280 /// 281 void setMacroInfo(IdentifierInfo *II, MacroInfo *MI); 282 283 /// macro_iterator/macro_begin/macro_end - This allows you to walk the current 284 /// state of the macro table. This visits every currently-defined macro. 285 typedef llvm::DenseMap<IdentifierInfo*, 286 MacroInfo*>::const_iterator macro_iterator; 287 macro_iterator macro_begin() const { return Macros.begin(); } 288 macro_iterator macro_end() const { return Macros.end(); } 289 290 291 292 const std::string &getPredefines() const { return Predefines; } 293 /// setPredefines - Set the predefines for this Preprocessor. These 294 /// predefines are automatically injected when parsing the main file. 295 void setPredefines(const char *P) { Predefines = P; } 296 void setPredefines(const std::string &P) { Predefines = P; } 297 298 /// getIdentifierInfo - Return information about the specified preprocessor 299 /// identifier token. The version of this method that takes two character 300 /// pointers is preferred unless the identifier is already available as a 301 /// string (this avoids allocation and copying of memory to construct an 302 /// std::string). 303 IdentifierInfo *getIdentifierInfo(llvm::StringRef Name) const { 304 return &Identifiers.get(Name); 305 } 306 307 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 308 /// If 'Namespace' is non-null, then it is a token required to exist on the 309 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 310 void AddPragmaHandler(const char *Namespace, PragmaHandler *Handler); 311 312 /// RemovePragmaHandler - Remove the specific pragma handler from 313 /// the preprocessor. If \arg Namespace is non-null, then it should 314 /// be the namespace that \arg Handler was added to. It is an error 315 /// to remove a handler that has not been registered. 316 void RemovePragmaHandler(const char *Namespace, PragmaHandler *Handler); 317 318 /// \brief Add the specified comment handler to the preprocessor. 319 void AddCommentHandler(CommentHandler *Handler); 320 321 /// \brief Remove the specified comment handler. 322 /// 323 /// It is an error to remove a handler that has not been registered. 324 void RemoveCommentHandler(CommentHandler *Handler); 325 326 /// EnterMainSourceFile - Enter the specified FileID as the main source file, 327 /// which implicitly adds the builtin defines etc. 328 void EnterMainSourceFile(); 329 330 /// EnterSourceFile - Add a source file to the top of the include stack and 331 /// start lexing tokens from it instead of the current buffer. If isMainFile 332 /// is true, this is the main file for the translation unit. 333 void EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir); 334 335 /// EnterMacro - Add a Macro to the top of the include stack and start lexing 336 /// tokens from it instead of the current buffer. Args specifies the 337 /// tokens input to a function-like macro. 338 /// 339 /// ILEnd specifies the location of the ')' for a function-like macro or the 340 /// identifier for an object-like macro. 341 void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroArgs *Args); 342 343 /// EnterTokenStream - Add a "macro" context to the top of the include stack, 344 /// which will cause the lexer to start returning the specified tokens. 345 /// 346 /// If DisableMacroExpansion is true, tokens lexed from the token stream will 347 /// not be subject to further macro expansion. Otherwise, these tokens will 348 /// be re-macro-expanded when/if expansion is enabled. 349 /// 350 /// If OwnsTokens is false, this method assumes that the specified stream of 351 /// tokens has a permanent owner somewhere, so they do not need to be copied. 352 /// If it is true, it assumes the array of tokens is allocated with new[] and 353 /// must be freed. 354 /// 355 void EnterTokenStream(const Token *Toks, unsigned NumToks, 356 bool DisableMacroExpansion, bool OwnsTokens); 357 358 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the 359 /// lexer stack. This should only be used in situations where the current 360 /// state of the top-of-stack lexer is known. 361 void RemoveTopOfLexerStack(); 362 363 /// EnableBacktrackAtThisPos - From the point that this method is called, and 364 /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor 365 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will 366 /// make the Preprocessor re-lex the same tokens. 367 /// 368 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can 369 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will 370 /// be combined with the EnableBacktrackAtThisPos calls in reverse order. 371 /// 372 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack 373 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of 374 /// tokens will continue indefinitely. 375 /// 376 void EnableBacktrackAtThisPos(); 377 378 /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call. 379 void CommitBacktrackedTokens(); 380 381 /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since 382 /// EnableBacktrackAtThisPos() was previously called. 383 void Backtrack(); 384 385 /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and 386 /// caching of tokens is on. 387 bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); } 388 389 /// Lex - To lex a token from the preprocessor, just pull a token from the 390 /// current lexer or macro object. 391 void Lex(Token &Result) { 392 if (CurLexer) 393 CurLexer->Lex(Result); 394 else if (CurPTHLexer) 395 CurPTHLexer->Lex(Result); 396 else if (CurTokenLexer) 397 CurTokenLexer->Lex(Result); 398 else 399 CachingLex(Result); 400 } 401 402 /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get 403 /// something not a comment. This is useful in -E -C mode where comments 404 /// would foul up preprocessor directive handling. 405 void LexNonComment(Token &Result) { 406 do 407 Lex(Result); 408 while (Result.getKind() == tok::comment); 409 } 410 411 /// LexUnexpandedToken - This is just like Lex, but this disables macro 412 /// expansion of identifier tokens. 413 void LexUnexpandedToken(Token &Result) { 414 // Disable macro expansion. 415 bool OldVal = DisableMacroExpansion; 416 DisableMacroExpansion = true; 417 // Lex the token. 418 Lex(Result); 419 420 // Reenable it. 421 DisableMacroExpansion = OldVal; 422 } 423 424 /// LookAhead - This peeks ahead N tokens and returns that token without 425 /// consuming any tokens. LookAhead(0) returns the next token that would be 426 /// returned by Lex(), LookAhead(1) returns the token after it, etc. This 427 /// returns normal tokens after phase 5. As such, it is equivalent to using 428 /// 'Lex', not 'LexUnexpandedToken'. 429 const Token &LookAhead(unsigned N) { 430 if (CachedLexPos + N < CachedTokens.size()) 431 return CachedTokens[CachedLexPos+N]; 432 else 433 return PeekAhead(N+1); 434 } 435 436 /// RevertCachedTokens - When backtracking is enabled and tokens are cached, 437 /// this allows to revert a specific number of tokens. 438 /// Note that the number of tokens being reverted should be up to the last 439 /// backtrack position, not more. 440 void RevertCachedTokens(unsigned N) { 441 assert(isBacktrackEnabled() && 442 "Should only be called when tokens are cached for backtracking"); 443 assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back()) 444 && "Should revert tokens up to the last backtrack position, not more"); 445 assert(signed(CachedLexPos) - signed(N) >= 0 && 446 "Corrupted backtrack positions ?"); 447 CachedLexPos -= N; 448 } 449 450 /// EnterToken - Enters a token in the token stream to be lexed next. If 451 /// BackTrack() is called afterwards, the token will remain at the insertion 452 /// point. 453 void EnterToken(const Token &Tok) { 454 EnterCachingLexMode(); 455 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok); 456 } 457 458 /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching 459 /// tokens (because backtrack is enabled) it should replace the most recent 460 /// cached tokens with the given annotation token. This function has no effect 461 /// if backtracking is not enabled. 462 /// 463 /// Note that the use of this function is just for optimization; so that the 464 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is 465 /// invoked. 466 void AnnotateCachedTokens(const Token &Tok) { 467 assert(Tok.isAnnotation() && "Expected annotation token"); 468 if (CachedLexPos != 0 && isBacktrackEnabled()) 469 AnnotatePreviousCachedTokens(Tok); 470 } 471 472 /// \brief Replace the last token with an annotation token. 473 /// 474 /// Like AnnotateCachedTokens(), this routine replaces an 475 /// already-parsed (and resolved) token with an annotation 476 /// token. However, this routine only replaces the last token with 477 /// the annotation token; it does not affect any other cached 478 /// tokens. This function has no effect if backtracking is not 479 /// enabled. 480 void ReplaceLastTokenWithAnnotation(const Token &Tok) { 481 assert(Tok.isAnnotation() && "Expected annotation token"); 482 if (CachedLexPos != 0 && isBacktrackEnabled()) 483 CachedTokens[CachedLexPos-1] = Tok; 484 } 485 486 /// Diag - Forwarding function for diagnostics. This emits a diagnostic at 487 /// the specified Token's location, translating the token's start 488 /// position in the current buffer into a SourcePosition object for rendering. 489 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { 490 return Diags->Report(FullSourceLoc(Loc, getSourceManager()), DiagID); 491 } 492 493 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) { 494 return Diags->Report(FullSourceLoc(Tok.getLocation(), getSourceManager()), 495 DiagID); 496 } 497 498 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a 499 /// token is the characters used to represent the token in the source file 500 /// after trigraph expansion and escaped-newline folding. In particular, this 501 /// wants to get the true, uncanonicalized, spelling of things like digraphs 502 /// UCNs, etc. 503 std::string getSpelling(const Token &Tok) const; 504 505 /// getSpelling - This method is used to get the spelling of a token into a 506 /// preallocated buffer, instead of as an std::string. The caller is required 507 /// to allocate enough space for the token, which is guaranteed to be at least 508 /// Tok.getLength() bytes long. The length of the actual result is returned. 509 /// 510 /// Note that this method may do two possible things: it may either fill in 511 /// the buffer specified with characters, or it may *change the input pointer* 512 /// to point to a constant buffer with the data already in it (avoiding a 513 /// copy). The caller is not allowed to modify the returned buffer pointer 514 /// if an internal buffer is returned. 515 unsigned getSpelling(const Token &Tok, const char *&Buffer) const; 516 517 /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric constant 518 /// with length 1, return the character. 519 char getSpellingOfSingleCharacterNumericConstant(const Token &Tok) const { 520 assert(Tok.is(tok::numeric_constant) && 521 Tok.getLength() == 1 && "Called on unsupported token"); 522 assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1"); 523 524 // If the token is carrying a literal data pointer, just use it. 525 if (const char *D = Tok.getLiteralData()) 526 return *D; 527 528 // Otherwise, fall back on getCharacterData, which is slower, but always 529 // works. 530 return *SourceMgr.getCharacterData(Tok.getLocation()); 531 } 532 533 /// CreateString - Plop the specified string into a scratch buffer and set the 534 /// specified token's location and length to it. If specified, the source 535 /// location provides a location of the instantiation point of the token. 536 void CreateString(const char *Buf, unsigned Len, 537 Token &Tok, SourceLocation SourceLoc = SourceLocation()); 538 539 /// \brief Computes the source location just past the end of the 540 /// token at this source location. 541 /// 542 /// This routine can be used to produce a source location that 543 /// points just past the end of the token referenced by \p Loc, and 544 /// is generally used when a diagnostic needs to point just after a 545 /// token where it expected something different that it received. If 546 /// the returned source location would not be meaningful (e.g., if 547 /// it points into a macro), this routine returns an invalid 548 /// source location. 549 SourceLocation getLocForEndOfToken(SourceLocation Loc); 550 551 /// DumpToken - Print the token to stderr, used for debugging. 552 /// 553 void DumpToken(const Token &Tok, bool DumpFlags = false) const; 554 void DumpLocation(SourceLocation Loc) const; 555 void DumpMacro(const MacroInfo &MI) const; 556 557 /// AdvanceToTokenCharacter - Given a location that specifies the start of a 558 /// token, return a new location that specifies a character within the token. 559 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char); 560 561 /// IncrementPasteCounter - Increment the counters for the number of token 562 /// paste operations performed. If fast was specified, this is a 'fast paste' 563 /// case we handled. 564 /// 565 void IncrementPasteCounter(bool isFast) { 566 if (isFast) 567 ++NumFastTokenPaste; 568 else 569 ++NumTokenPaste; 570 } 571 572 void PrintStats(); 573 574 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a 575 /// comment (/##/) in microsoft mode, this method handles updating the current 576 /// state, returning the token on the next source line. 577 void HandleMicrosoftCommentPaste(Token &Tok); 578 579 //===--------------------------------------------------------------------===// 580 // Preprocessor callback methods. These are invoked by a lexer as various 581 // directives and events are found. 582 583 /// LookUpIdentifierInfo - Given a tok::identifier token, look up the 584 /// identifier information for the token and install it into the token. 585 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier, 586 const char *BufPtr = 0) const; 587 588 /// HandleIdentifier - This callback is invoked when the lexer reads an 589 /// identifier and has filled in the tokens IdentifierInfo member. This 590 /// callback potentially macro expands it or turns it into a named token (like 591 /// 'for'). 592 void HandleIdentifier(Token &Identifier); 593 594 595 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of 596 /// the current file. This either returns the EOF token and returns true, or 597 /// pops a level off the include stack and returns false, at which point the 598 /// client should call lex again. 599 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); 600 601 /// HandleEndOfTokenLexer - This callback is invoked when the current 602 /// TokenLexer hits the end of its token stream. 603 bool HandleEndOfTokenLexer(Token &Result); 604 605 /// HandleDirective - This callback is invoked when the lexer sees a # token 606 /// at the start of a line. This consumes the directive, modifies the 607 /// lexer/preprocessor state, and advances the lexer(s) so that the next token 608 /// read is the correct one. 609 void HandleDirective(Token &Result); 610 611 /// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If 612 /// not, emit a diagnostic and consume up until the eom. If EnableMacros is 613 /// true, then we consider macros that expand to zero tokens as being ok. 614 void CheckEndOfDirective(const char *Directive, bool EnableMacros = false); 615 616 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the 617 /// current line until the tok::eom token is found. 618 void DiscardUntilEndOfDirective(); 619 620 /// SawDateOrTime - This returns true if the preprocessor has seen a use of 621 /// __DATE__ or __TIME__ in the file so far. 622 bool SawDateOrTime() const { 623 return DATELoc != SourceLocation() || TIMELoc != SourceLocation(); 624 } 625 unsigned getCounterValue() const { return CounterValue; } 626 void setCounterValue(unsigned V) { CounterValue = V; } 627 628 /// AllocateMacroInfo - Allocate a new MacroInfo object with the provide 629 /// SourceLocation. 630 MacroInfo* AllocateMacroInfo(SourceLocation L); 631 632 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 633 /// checked and spelled filename, e.g. as an operand of #include. This returns 634 /// true if the input filename was in <>'s or false if it were in ""'s. The 635 /// caller is expected to provide a buffer that is large enough to hold the 636 /// spelling of the filename, but is also expected to handle the case when 637 /// this method decides to use a different buffer. 638 bool GetIncludeFilenameSpelling(SourceLocation Loc, 639 const char *&BufStart, const char *&BufEnd); 640 641 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 642 /// return null on failure. isAngled indicates whether the file reference is 643 /// for system #include's or not (i.e. using <> instead of ""). 644 const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd, 645 bool isAngled, const DirectoryLookup *FromDir, 646 const DirectoryLookup *&CurDir); 647 648 /// GetCurLookup - The DirectoryLookup structure used to find the current 649 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to 650 /// implement #include_next and find directory-specific properties. 651 const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; } 652 653 /// isInPrimaryFile - Return true if we're in the top-level file, not in a 654 /// #include. 655 bool isInPrimaryFile() const; 656 657 /// ConcatenateIncludeName - Handle cases where the #include name is expanded 658 /// from a macro as multiple tokens, which need to be glued together. This 659 /// occurs for code like: 660 /// #define FOO <a/b.h> 661 /// #include FOO 662 /// because in this case, "<a/b.h>" is returned as 7 tokens, not one. 663 /// 664 /// This code concatenates and consumes tokens up to the '>' token. It returns 665 /// false if the > was found, otherwise it returns true if it finds and consumes 666 /// the EOM marker. 667 bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer); 668 669private: 670 671 void PushIncludeMacroStack() { 672 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(), 673 CurPTHLexer.take(), 674 CurPPLexer, 675 CurTokenLexer.take(), 676 CurDirLookup)); 677 CurPPLexer = 0; 678 } 679 680 void PopIncludeMacroStack() { 681 CurLexer.reset(IncludeMacroStack.back().TheLexer); 682 CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer); 683 CurPPLexer = IncludeMacroStack.back().ThePPLexer; 684 CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer); 685 CurDirLookup = IncludeMacroStack.back().TheDirLookup; 686 IncludeMacroStack.pop_back(); 687 } 688 689 /// ReleaseMacroInfo - Release the specified MacroInfo. This memory will 690 /// be reused for allocating new MacroInfo objects. 691 void ReleaseMacroInfo(MacroInfo* MI); 692 693 /// ReadMacroName - Lex and validate a macro name, which occurs after a 694 /// #define or #undef. This emits a diagnostic, sets the token kind to eom, 695 /// and discards the rest of the macro line if the macro name is invalid. 696 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0); 697 698 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 699 /// definition has just been read. Lex the rest of the arguments and the 700 /// closing ), updating MI with what we learn. Return true if an error occurs 701 /// parsing the arg list. 702 bool ReadMacroDefinitionArgList(MacroInfo *MI); 703 704 /// SkipExcludedConditionalBlock - We just read a #if or related directive and 705 /// decided that the subsequent tokens are in the #if'd out portion of the 706 /// file. Lex the rest of the file, until we see an #endif. If 707 /// FoundNonSkipPortion is true, then we have already emitted code for part of 708 /// this #if directive, so #else/#elif blocks should never be entered. If 709 /// FoundElse is false, then #else directives are ok, if not, then we have 710 /// already seen one so a #else directive is a duplicate. When this returns, 711 /// the caller can lex the first valid token. 712 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 713 bool FoundNonSkipPortion, bool FoundElse); 714 715 /// PTHSkipExcludedConditionalBlock - A fast PTH version of 716 /// SkipExcludedConditionalBlock. 717 void PTHSkipExcludedConditionalBlock(); 718 719 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that 720 /// may occur after a #if or #elif directive and return it as a bool. If the 721 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro. 722 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); 723 724 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 725 /// #pragma GCC poison/system_header/dependency and #pragma once. 726 void RegisterBuiltinPragmas(); 727 728 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 729 /// identifier table. 730 void RegisterBuiltinMacros(); 731 732 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to 733 /// be expanded as a macro, handle it and return the next token as 'Tok'. If 734 /// the macro should not be expanded return true, otherwise return false. 735 bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI); 736 737 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 738 /// lexed is a '('. If so, consume the token and return true, if not, this 739 /// method should have no observable side-effect on the lexed tokens. 740 bool isNextPPTokenLParen(); 741 742 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is 743 /// invoked to read all of the formal arguments specified for the macro 744 /// invocation. This returns null on error. 745 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI, 746 SourceLocation &InstantiationEnd); 747 748 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 749 /// as a builtin macro, handle it and return the next token as 'Tok'. 750 void ExpandBuiltinMacro(Token &Tok); 751 752 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 753 /// return the first token after the directive. The _Pragma token has just 754 /// been read into 'Tok'. 755 void Handle_Pragma(Token &Tok); 756 757 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and 758 /// start lexing tokens from it instead of the current buffer. 759 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); 760 761 /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and 762 /// start getting tokens from it using the PTH cache. 763 void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir); 764 765 /// IsFileLexer - Returns true if we are lexing from a file and not a 766 /// pragma or a macro. 767 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) { 768 return L ? !L->isPragmaLexer() : P != 0; 769 } 770 771 static bool IsFileLexer(const IncludeStackInfo& I) { 772 return IsFileLexer(I.TheLexer, I.ThePPLexer); 773 } 774 775 bool IsFileLexer() const { 776 return IsFileLexer(CurLexer.get(), CurPPLexer); 777 } 778 779 //===--------------------------------------------------------------------===// 780 // Caching stuff. 781 void CachingLex(Token &Result); 782 bool InCachingLexMode() const { return CurPPLexer == 0 && CurTokenLexer == 0;} 783 void EnterCachingLexMode(); 784 void ExitCachingLexMode() { 785 if (InCachingLexMode()) 786 RemoveTopOfLexerStack(); 787 } 788 const Token &PeekAhead(unsigned N); 789 void AnnotatePreviousCachedTokens(const Token &Tok); 790 791 //===--------------------------------------------------------------------===// 792 /// Handle*Directive - implement the various preprocessor directives. These 793 /// should side-effect the current preprocessor object so that the next call 794 /// to Lex() will return the appropriate token next. 795 void HandleLineDirective(Token &Tok); 796 void HandleDigitDirective(Token &Tok); 797 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); 798 void HandleIdentSCCSDirective(Token &Tok); 799 800 // File inclusion. 801 void HandleIncludeDirective(Token &Tok, 802 const DirectoryLookup *LookupFrom = 0, 803 bool isImport = false); 804 void HandleIncludeNextDirective(Token &Tok); 805 void HandleIncludeMacrosDirective(Token &Tok); 806 void HandleImportDirective(Token &Tok); 807 808 // Macro handling. 809 void HandleDefineDirective(Token &Tok); 810 void HandleUndefDirective(Token &Tok); 811 // HandleAssertDirective(Token &Tok); 812 // HandleUnassertDirective(Token &Tok); 813 814 // Conditional Inclusion. 815 void HandleIfdefDirective(Token &Tok, bool isIfndef, 816 bool ReadAnyTokensBeforeDirective); 817 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective); 818 void HandleEndifDirective(Token &Tok); 819 void HandleElseDirective(Token &Tok); 820 void HandleElifDirective(Token &Tok); 821 822 // Pragmas. 823 void HandlePragmaDirective(); 824public: 825 void HandlePragmaOnce(Token &OnceTok); 826 void HandlePragmaMark(); 827 void HandlePragmaPoison(Token &PoisonTok); 828 void HandlePragmaSystemHeader(Token &SysHeaderTok); 829 void HandlePragmaDependency(Token &DependencyTok); 830 void HandlePragmaComment(Token &CommentTok); 831 void HandleComment(SourceRange Comment); 832}; 833 834/// \brief Abstract base class that describes a handler that will receive 835/// source ranges for each of the comments encountered in the source file. 836class CommentHandler { 837public: 838 virtual ~CommentHandler(); 839 840 virtual void HandleComment(Preprocessor &PP, SourceRange Comment) = 0; 841}; 842 843} // end namespace clang 844 845#endif 846