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