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