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