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