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