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