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