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