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