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