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