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