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