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