Preprocessor.h revision dbf8ee630e4c86e5150492eaf8dbceea3c718ee1
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 bool 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 /// 551 /// \param Invalid If non-NULL, will be set \c true if an error occurs. 552 std::string getSpelling(const Token &Tok, bool *Invalid = 0) const; 553 554 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a 555 /// token is the characters used to represent the token in the source file 556 /// after trigraph expansion and escaped-newline folding. In particular, this 557 /// wants to get the true, uncanonicalized, spelling of things like digraphs 558 /// UCNs, etc. 559 static std::string getSpelling(const Token &Tok, 560 const SourceManager &SourceMgr, 561 const LangOptions &Features, 562 bool *Invalid = 0); 563 564 /// getSpelling - This method is used to get the spelling of a token into a 565 /// preallocated buffer, instead of as an std::string. The caller is required 566 /// to allocate enough space for the token, which is guaranteed to be at least 567 /// Tok.getLength() bytes long. The length of the actual result is returned. 568 /// 569 /// Note that this method may do two possible things: it may either fill in 570 /// the buffer specified with characters, or it may *change the input pointer* 571 /// to point to a constant buffer with the data already in it (avoiding a 572 /// copy). The caller is not allowed to modify the returned buffer pointer 573 /// if an internal buffer is returned. 574 unsigned getSpelling(const Token &Tok, const char *&Buffer, 575 bool *Invalid = 0) const; 576 577 /// getSpelling - This method is used to get the spelling of a token into a 578 /// SmallVector. Note that the returned StringRef may not point to the 579 /// supplied buffer if a copy can be avoided. 580 llvm::StringRef getSpelling(const Token &Tok, 581 llvm::SmallVectorImpl<char> &Buffer, 582 bool *Invalid = 0) const; 583 584 /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric constant 585 /// with length 1, return the character. 586 char getSpellingOfSingleCharacterNumericConstant(const Token &Tok, 587 bool *Invalid = 0) const { 588 assert(Tok.is(tok::numeric_constant) && 589 Tok.getLength() == 1 && "Called on unsupported token"); 590 assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1"); 591 592 // If the token is carrying a literal data pointer, just use it. 593 if (const char *D = Tok.getLiteralData()) 594 return *D; 595 596 // Otherwise, fall back on getCharacterData, which is slower, but always 597 // works. 598 return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid); 599 } 600 601 /// CreateString - Plop the specified string into a scratch buffer and set the 602 /// specified token's location and length to it. If specified, the source 603 /// location provides a location of the instantiation point of the token. 604 void CreateString(const char *Buf, unsigned Len, 605 Token &Tok, SourceLocation SourceLoc = SourceLocation()); 606 607 /// \brief Computes the source location just past the end of the 608 /// token at this source location. 609 /// 610 /// This routine can be used to produce a source location that 611 /// points just past the end of the token referenced by \p Loc, and 612 /// is generally used when a diagnostic needs to point just after a 613 /// token where it expected something different that it received. If 614 /// the returned source location would not be meaningful (e.g., if 615 /// it points into a macro), this routine returns an invalid 616 /// source location. 617 /// 618 /// \param Offset an offset from the end of the token, where the source 619 /// location should refer to. The default offset (0) produces a source 620 /// location pointing just past the end of the token; an offset of 1 produces 621 /// a source location pointing to the last character in the token, etc. 622 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); 623 624 /// DumpToken - Print the token to stderr, used for debugging. 625 /// 626 void DumpToken(const Token &Tok, bool DumpFlags = false) const; 627 void DumpLocation(SourceLocation Loc) const; 628 void DumpMacro(const MacroInfo &MI) const; 629 630 /// AdvanceToTokenCharacter - Given a location that specifies the start of a 631 /// token, return a new location that specifies a character within the token. 632 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char); 633 634 /// IncrementPasteCounter - Increment the counters for the number of token 635 /// paste operations performed. If fast was specified, this is a 'fast paste' 636 /// case we handled. 637 /// 638 void IncrementPasteCounter(bool isFast) { 639 if (isFast) 640 ++NumFastTokenPaste; 641 else 642 ++NumTokenPaste; 643 } 644 645 void PrintStats(); 646 647 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a 648 /// comment (/##/) in microsoft mode, this method handles updating the current 649 /// state, returning the token on the next source line. 650 void HandleMicrosoftCommentPaste(Token &Tok); 651 652 //===--------------------------------------------------------------------===// 653 // Preprocessor callback methods. These are invoked by a lexer as various 654 // directives and events are found. 655 656 /// LookUpIdentifierInfo - Given a tok::identifier token, look up the 657 /// identifier information for the token and install it into the token. 658 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier, 659 const char *BufPtr = 0) const; 660 661 /// HandleIdentifier - This callback is invoked when the lexer reads an 662 /// identifier and has filled in the tokens IdentifierInfo member. This 663 /// callback potentially macro expands it or turns it into a named token (like 664 /// 'for'). 665 void HandleIdentifier(Token &Identifier); 666 667 668 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of 669 /// the current file. This either returns the EOF token and returns true, or 670 /// pops a level off the include stack and returns false, at which point the 671 /// client should call lex again. 672 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); 673 674 /// HandleEndOfTokenLexer - This callback is invoked when the current 675 /// TokenLexer hits the end of its token stream. 676 bool HandleEndOfTokenLexer(Token &Result); 677 678 /// HandleDirective - This callback is invoked when the lexer sees a # token 679 /// at the start of a line. This consumes the directive, modifies the 680 /// lexer/preprocessor state, and advances the lexer(s) so that the next token 681 /// read is the correct one. 682 void HandleDirective(Token &Result); 683 684 /// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If 685 /// not, emit a diagnostic and consume up until the eom. If EnableMacros is 686 /// true, then we consider macros that expand to zero tokens as being ok. 687 void CheckEndOfDirective(const char *Directive, bool EnableMacros = false); 688 689 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the 690 /// current line until the tok::eom token is found. 691 void DiscardUntilEndOfDirective(); 692 693 /// SawDateOrTime - This returns true if the preprocessor has seen a use of 694 /// __DATE__ or __TIME__ in the file so far. 695 bool SawDateOrTime() const { 696 return DATELoc != SourceLocation() || TIMELoc != SourceLocation(); 697 } 698 unsigned getCounterValue() const { return CounterValue; } 699 void setCounterValue(unsigned V) { CounterValue = V; } 700 701 /// AllocateMacroInfo - Allocate a new MacroInfo object with the provide 702 /// SourceLocation. 703 MacroInfo* AllocateMacroInfo(SourceLocation L); 704 705 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 706 /// checked and spelled filename, e.g. as an operand of #include. This returns 707 /// true if the input filename was in <>'s or false if it were in ""'s. The 708 /// caller is expected to provide a buffer that is large enough to hold the 709 /// spelling of the filename, but is also expected to handle the case when 710 /// this method decides to use a different buffer. 711 bool GetIncludeFilenameSpelling(SourceLocation Loc,llvm::StringRef &Filename); 712 713 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 714 /// return null on failure. isAngled indicates whether the file reference is 715 /// for system #include's or not (i.e. using <> instead of ""). 716 const FileEntry *LookupFile(llvm::StringRef Filename, 717 bool isAngled, const DirectoryLookup *FromDir, 718 const DirectoryLookup *&CurDir); 719 720 /// GetCurLookup - The DirectoryLookup structure used to find the current 721 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to 722 /// implement #include_next and find directory-specific properties. 723 const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; } 724 725 /// isInPrimaryFile - Return true if we're in the top-level file, not in a 726 /// #include. 727 bool isInPrimaryFile() const; 728 729 /// ConcatenateIncludeName - Handle cases where the #include name is expanded 730 /// from a macro as multiple tokens, which need to be glued together. This 731 /// occurs for code like: 732 /// #define FOO <a/b.h> 733 /// #include FOO 734 /// because in this case, "<a/b.h>" is returned as 7 tokens, not one. 735 /// 736 /// This code concatenates and consumes tokens up to the '>' token. It returns 737 /// false if the > was found, otherwise it returns true if it finds and consumes 738 /// the EOM marker. 739 bool ConcatenateIncludeName(llvm::SmallString<128> &FilenameBuffer); 740 741private: 742 743 void PushIncludeMacroStack() { 744 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(), 745 CurPTHLexer.take(), 746 CurPPLexer, 747 CurTokenLexer.take(), 748 CurDirLookup)); 749 CurPPLexer = 0; 750 } 751 752 void PopIncludeMacroStack() { 753 CurLexer.reset(IncludeMacroStack.back().TheLexer); 754 CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer); 755 CurPPLexer = IncludeMacroStack.back().ThePPLexer; 756 CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer); 757 CurDirLookup = IncludeMacroStack.back().TheDirLookup; 758 IncludeMacroStack.pop_back(); 759 } 760 761 /// ReleaseMacroInfo - Release the specified MacroInfo. This memory will 762 /// be reused for allocating new MacroInfo objects. 763 void ReleaseMacroInfo(MacroInfo* MI); 764 765 /// ReadMacroName - Lex and validate a macro name, which occurs after a 766 /// #define or #undef. This emits a diagnostic, sets the token kind to eom, 767 /// and discards the rest of the macro line if the macro name is invalid. 768 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0); 769 770 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 771 /// definition has just been read. Lex the rest of the arguments and the 772 /// closing ), updating MI with what we learn. Return true if an error occurs 773 /// parsing the arg list. 774 bool ReadMacroDefinitionArgList(MacroInfo *MI); 775 776 /// SkipExcludedConditionalBlock - We just read a #if or related directive and 777 /// decided that the subsequent tokens are in the #if'd out portion of the 778 /// file. Lex the rest of the file, until we see an #endif. If 779 /// FoundNonSkipPortion is true, then we have already emitted code for part of 780 /// this #if directive, so #else/#elif blocks should never be entered. If 781 /// FoundElse is false, then #else directives are ok, if not, then we have 782 /// already seen one so a #else directive is a duplicate. When this returns, 783 /// the caller can lex the first valid token. 784 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 785 bool FoundNonSkipPortion, bool FoundElse); 786 787 /// PTHSkipExcludedConditionalBlock - A fast PTH version of 788 /// SkipExcludedConditionalBlock. 789 void PTHSkipExcludedConditionalBlock(); 790 791 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that 792 /// may occur after a #if or #elif directive and return it as a bool. If the 793 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro. 794 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); 795 796 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 797 /// #pragma GCC poison/system_header/dependency and #pragma once. 798 void RegisterBuiltinPragmas(); 799 800 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 801 /// identifier table. 802 void RegisterBuiltinMacros(); 803 804 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to 805 /// be expanded as a macro, handle it and return the next token as 'Tok'. If 806 /// the macro should not be expanded return true, otherwise return false. 807 bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI); 808 809 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 810 /// lexed is a '('. If so, consume the token and return true, if not, this 811 /// method should have no observable side-effect on the lexed tokens. 812 bool isNextPPTokenLParen(); 813 814 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is 815 /// invoked to read all of the formal arguments specified for the macro 816 /// invocation. This returns null on error. 817 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI, 818 SourceLocation &InstantiationEnd); 819 820 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 821 /// as a builtin macro, handle it and return the next token as 'Tok'. 822 void ExpandBuiltinMacro(Token &Tok); 823 824 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 825 /// return the first token after the directive. The _Pragma token has just 826 /// been read into 'Tok'. 827 void Handle_Pragma(Token &Tok); 828 829 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and 830 /// start lexing tokens from it instead of the current buffer. 831 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); 832 833 /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and 834 /// start getting tokens from it using the PTH cache. 835 void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir); 836 837 /// IsFileLexer - Returns true if we are lexing from a file and not a 838 /// pragma or a macro. 839 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) { 840 return L ? !L->isPragmaLexer() : P != 0; 841 } 842 843 static bool IsFileLexer(const IncludeStackInfo& I) { 844 return IsFileLexer(I.TheLexer, I.ThePPLexer); 845 } 846 847 bool IsFileLexer() const { 848 return IsFileLexer(CurLexer.get(), CurPPLexer); 849 } 850 851 //===--------------------------------------------------------------------===// 852 // Caching stuff. 853 void CachingLex(Token &Result); 854 bool InCachingLexMode() const { return CurPPLexer == 0 && CurTokenLexer == 0;} 855 void EnterCachingLexMode(); 856 void ExitCachingLexMode() { 857 if (InCachingLexMode()) 858 RemoveTopOfLexerStack(); 859 } 860 const Token &PeekAhead(unsigned N); 861 void AnnotatePreviousCachedTokens(const Token &Tok); 862 863 //===--------------------------------------------------------------------===// 864 /// Handle*Directive - implement the various preprocessor directives. These 865 /// should side-effect the current preprocessor object so that the next call 866 /// to Lex() will return the appropriate token next. 867 void HandleLineDirective(Token &Tok); 868 void HandleDigitDirective(Token &Tok); 869 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); 870 void HandleIdentSCCSDirective(Token &Tok); 871 872 // File inclusion. 873 void HandleIncludeDirective(Token &Tok, 874 const DirectoryLookup *LookupFrom = 0, 875 bool isImport = false); 876 void HandleIncludeNextDirective(Token &Tok); 877 void HandleIncludeMacrosDirective(Token &Tok); 878 void HandleImportDirective(Token &Tok); 879 880 // Macro handling. 881 void HandleDefineDirective(Token &Tok); 882 void HandleUndefDirective(Token &Tok); 883 // HandleAssertDirective(Token &Tok); 884 // HandleUnassertDirective(Token &Tok); 885 886 // Conditional Inclusion. 887 void HandleIfdefDirective(Token &Tok, bool isIfndef, 888 bool ReadAnyTokensBeforeDirective); 889 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective); 890 void HandleEndifDirective(Token &Tok); 891 void HandleElseDirective(Token &Tok); 892 void HandleElifDirective(Token &Tok); 893 894 // Pragmas. 895 void HandlePragmaDirective(); 896public: 897 void HandlePragmaOnce(Token &OnceTok); 898 void HandlePragmaMark(); 899 void HandlePragmaPoison(Token &PoisonTok); 900 void HandlePragmaSystemHeader(Token &SysHeaderTok); 901 void HandlePragmaDependency(Token &DependencyTok); 902 void HandlePragmaComment(Token &CommentTok); 903 // Return true and store the first token only if any CommentHandler 904 // has inserted some tokens and getCommentRetentionState() is false. 905 bool HandleComment(Token &Token, SourceRange Comment); 906}; 907 908/// \brief Abstract base class that describes a handler that will receive 909/// source ranges for each of the comments encountered in the source file. 910class CommentHandler { 911public: 912 virtual ~CommentHandler(); 913 914 // The handler shall return true if it has pushed any tokens 915 // to be read using e.g. EnterToken or EnterTokenStream. 916 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0; 917}; 918 919} // end namespace clang 920 921#endif 922