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