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