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