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