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