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