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