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