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