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