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