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