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