Preprocessor.h revision 337edcdbec05316b407d0d64865c88ff8597d910
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 void EnterMacro(Token &Identifier, MacroArgs *Args); 302 303 /// EnterTokenStream - Add a "macro" context to the top of the include stack, 304 /// which will cause the lexer to start returning the specified tokens. 305 /// 306 /// If DisableMacroExpansion is true, tokens lexed from the token stream will 307 /// not be subject to further macro expansion. Otherwise, these tokens will 308 /// be re-macro-expanded when/if expansion is enabled. 309 /// 310 /// If OwnsTokens is false, this method assumes that the specified stream of 311 /// tokens has a permanent owner somewhere, so they do not need to be copied. 312 /// If it is true, it assumes the array of tokens is allocated with new[] and 313 /// must be freed. 314 /// 315 void EnterTokenStream(const Token *Toks, unsigned NumToks, 316 bool DisableMacroExpansion, bool OwnsTokens); 317 318 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the 319 /// lexer stack. This should only be used in situations where the current 320 /// state of the top-of-stack lexer is known. 321 void RemoveTopOfLexerStack(); 322 323 /// EnableBacktrackAtThisPos - From the point that this method is called, and 324 /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor 325 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will 326 /// make the Preprocessor re-lex the same tokens. 327 /// 328 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can 329 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will 330 /// be combined with the EnableBacktrackAtThisPos calls in reverse order. 331 /// 332 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack 333 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of 334 /// tokens will continue indefinitely. 335 /// 336 void EnableBacktrackAtThisPos(); 337 338 /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call. 339 void CommitBacktrackedTokens(); 340 341 /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since 342 /// EnableBacktrackAtThisPos() was previously called. 343 void Backtrack(); 344 345 /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and 346 /// caching of tokens is on. 347 bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); } 348 349 /// Lex - To lex a token from the preprocessor, just pull a token from the 350 /// current lexer or macro object. 351 void Lex(Token &Result) { 352 if (CurLexer) 353 CurLexer->Lex(Result); 354 else if (CurPTHLexer) 355 CurPTHLexer->Lex(Result); 356 else if (CurTokenLexer) 357 CurTokenLexer->Lex(Result); 358 else 359 CachingLex(Result); 360 } 361 362 /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get 363 /// something not a comment. This is useful in -E -C mode where comments 364 /// would foul up preprocessor directive handling. 365 void LexNonComment(Token &Result) { 366 do 367 Lex(Result); 368 while (Result.getKind() == tok::comment); 369 } 370 371 /// LexUnexpandedToken - This is just like Lex, but this disables macro 372 /// expansion of identifier tokens. 373 void LexUnexpandedToken(Token &Result) { 374 // Disable macro expansion. 375 bool OldVal = DisableMacroExpansion; 376 DisableMacroExpansion = true; 377 // Lex the token. 378 Lex(Result); 379 380 // Reenable it. 381 DisableMacroExpansion = OldVal; 382 } 383 384 /// LookAhead - This peeks ahead N tokens and returns that token without 385 /// consuming any tokens. LookAhead(0) returns the next token that would be 386 /// returned by Lex(), LookAhead(1) returns the token after it, etc. This 387 /// returns normal tokens after phase 5. As such, it is equivalent to using 388 /// 'Lex', not 'LexUnexpandedToken'. 389 const Token &LookAhead(unsigned N) { 390 if (CachedLexPos + N < CachedTokens.size()) 391 return CachedTokens[CachedLexPos+N]; 392 else 393 return PeekAhead(N+1); 394 } 395 396 /// RevertCachedTokens - When backtracking is enabled and tokens are cached, 397 /// this allows to revert a specific number of tokens. 398 /// Note that the number of tokens being reverted should be up to the last 399 /// backtrack position, not more. 400 void RevertCachedTokens(unsigned N) { 401 assert(isBacktrackEnabled() && 402 "Should only be called when tokens are cached for backtracking"); 403 assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back()) 404 && "Should revert tokens up to the last backtrack position, not more"); 405 assert(signed(CachedLexPos) - signed(N) >= 0 && 406 "Corrupted backtrack positions ?"); 407 CachedLexPos -= N; 408 } 409 410 /// EnterToken - Enters a token in the token stream to be lexed next. If 411 /// BackTrack() is called afterwards, the token will remain at the insertion 412 /// point. 413 void EnterToken(const Token &Tok) { 414 EnterCachingLexMode(); 415 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok); 416 } 417 418 /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching 419 /// tokens (because backtrack is enabled) it should replace the most recent 420 /// cached tokens with the given annotation token. This function has no effect 421 /// if backtracking is not enabled. 422 /// 423 /// Note that the use of this function is just for optimization; so that the 424 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is 425 /// invoked. 426 void AnnotateCachedTokens(const Token &Tok) { 427 assert(Tok.isAnnotation() && "Expected annotation token"); 428 if (CachedLexPos != 0 && isBacktrackEnabled()) 429 AnnotatePreviousCachedTokens(Tok); 430 } 431 432 /// Diag - Forwarding function for diagnostics. This emits a diagnostic at 433 /// the specified Token's location, translating the token's start 434 /// position in the current buffer into a SourcePosition object for rendering. 435 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { 436 return Diags.Report(FullSourceLoc(Loc, getSourceManager()), DiagID); 437 } 438 439 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) { 440 return Diags.Report(FullSourceLoc(Tok.getLocation(), getSourceManager()), 441 DiagID); 442 } 443 444 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a 445 /// token is the characters used to represent the token in the source file 446 /// after trigraph expansion and escaped-newline folding. In particular, this 447 /// wants to get the true, uncanonicalized, spelling of things like digraphs 448 /// UCNs, etc. 449 std::string getSpelling(const Token &Tok) const; 450 451 /// getSpelling - This method is used to get the spelling of a token into a 452 /// preallocated buffer, instead of as an std::string. The caller is required 453 /// to allocate enough space for the token, which is guaranteed to be at least 454 /// Tok.getLength() bytes long. The length of the actual result is returned. 455 /// 456 /// Note that this method may do two possible things: it may either fill in 457 /// the buffer specified with characters, or it may *change the input pointer* 458 /// to point to a constant buffer with the data already in it (avoiding a 459 /// copy). The caller is not allowed to modify the returned buffer pointer 460 /// if an internal buffer is returned. 461 unsigned getSpelling(const Token &Tok, const char *&Buffer) const; 462 463 /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric constant 464 /// with length 1, return the character. 465 char getSpellingOfSingleCharacterNumericConstant(const Token &Tok) const { 466 assert(Tok.is(tok::numeric_constant) && 467 Tok.getLength() == 1 && "Called on unsupported token"); 468 assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1"); 469 470 // If the token is carrying a literal data pointer, just use it. 471 if (const char *D = Tok.getLiteralData()) 472 return *D; 473 474 // Otherwise, fall back on getCharacterData, which is slower, but always 475 // works. 476 return *SourceMgr.getCharacterData(Tok.getLocation()); 477 } 478 479 /// CreateString - Plop the specified string into a scratch buffer and set the 480 /// specified token's location and length to it. If specified, the source 481 /// location provides a location of the instantiation point of the token. 482 void CreateString(const char *Buf, unsigned Len, 483 Token &Tok, SourceLocation SourceLoc = SourceLocation()); 484 485 /// DumpToken - Print the token to stderr, used for debugging. 486 /// 487 void DumpToken(const Token &Tok, bool DumpFlags = false) const; 488 void DumpLocation(SourceLocation Loc) const; 489 void DumpMacro(const MacroInfo &MI) const; 490 491 /// AdvanceToTokenCharacter - Given a location that specifies the start of a 492 /// token, return a new location that specifies a character within the token. 493 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char); 494 495 /// IncrementPasteCounter - Increment the counters for the number of token 496 /// paste operations performed. If fast was specified, this is a 'fast paste' 497 /// case we handled. 498 /// 499 void IncrementPasteCounter(bool isFast) { 500 if (isFast) 501 ++NumFastTokenPaste; 502 else 503 ++NumTokenPaste; 504 } 505 506 void PrintStats(); 507 508 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a 509 /// comment (/##/) in microsoft mode, this method handles updating the current 510 /// state, returning the token on the next source line. 511 void HandleMicrosoftCommentPaste(Token &Tok); 512 513 //===--------------------------------------------------------------------===// 514 // Preprocessor callback methods. These are invoked by a lexer as various 515 // directives and events are found. 516 517 /// LookUpIdentifierInfo - Given a tok::identifier token, look up the 518 /// identifier information for the token and install it into the token. 519 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier, 520 const char *BufPtr = 0); 521 522 /// HandleIdentifier - This callback is invoked when the lexer reads an 523 /// identifier and has filled in the tokens IdentifierInfo member. This 524 /// callback potentially macro expands it or turns it into a named token (like 525 /// 'for'). 526 void HandleIdentifier(Token &Identifier); 527 528 529 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of 530 /// the current file. This either returns the EOF token and returns true, or 531 /// pops a level off the include stack and returns false, at which point the 532 /// client should call lex again. 533 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); 534 535 /// HandleEndOfTokenLexer - This callback is invoked when the current 536 /// TokenLexer hits the end of its token stream. 537 bool HandleEndOfTokenLexer(Token &Result); 538 539 /// HandleDirective - This callback is invoked when the lexer sees a # token 540 /// at the start of a line. This consumes the directive, modifies the 541 /// lexer/preprocessor state, and advances the lexer(s) so that the next token 542 /// read is the correct one. 543 void HandleDirective(Token &Result); 544 545 /// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If 546 /// not, emit a diagnostic and consume up until the eom. 547 void CheckEndOfDirective(const char *Directive); 548 549 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the 550 /// current line until the tok::eom token is found. 551 void DiscardUntilEndOfDirective(); 552 553private: 554 555 void PushIncludeMacroStack() { 556 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(), 557 CurPTHLexer.take(), 558 CurPPLexer, 559 CurTokenLexer.take(), 560 CurDirLookup)); 561 CurPPLexer = 0; 562 } 563 564 void PopIncludeMacroStack() { 565 CurLexer.reset(IncludeMacroStack.back().TheLexer); 566 CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer); 567 CurPPLexer = IncludeMacroStack.back().ThePPLexer; 568 CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer); 569 CurDirLookup = IncludeMacroStack.back().TheDirLookup; 570 IncludeMacroStack.pop_back(); 571 } 572 573 /// AllocateMacroInfo - Allocate a new MacroInfo object with the provide 574 /// SourceLocation. 575 MacroInfo* AllocateMacroInfo(SourceLocation L); 576 577 /// ReleaseMacroInfo - Release the specified MacroInfo. This memory will 578 /// be reused for allocating new MacroInfo objects. 579 void ReleaseMacroInfo(MacroInfo* MI) { 580 MICache.push_back(MI); 581 } 582 583 /// isInPrimaryFile - Return true if we're in the top-level file, not in a 584 /// #include. 585 bool isInPrimaryFile() const; 586 587 /// ReadMacroName - Lex and validate a macro name, which occurs after a 588 /// #define or #undef. This emits a diagnostic, sets the token kind to eom, 589 /// and discards the rest of the macro line if the macro name is invalid. 590 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0); 591 592 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 593 /// definition has just been read. Lex the rest of the arguments and the 594 /// closing ), updating MI with what we learn. Return true if an error occurs 595 /// parsing the arg list. 596 bool ReadMacroDefinitionArgList(MacroInfo *MI); 597 598 /// SkipExcludedConditionalBlock - We just read a #if or related directive and 599 /// decided that the subsequent tokens are in the #if'd out portion of the 600 /// file. Lex the rest of the file, until we see an #endif. If 601 /// FoundNonSkipPortion is true, then we have already emitted code for part of 602 /// this #if directive, so #else/#elif blocks should never be entered. If 603 /// FoundElse is false, then #else directives are ok, if not, then we have 604 /// already seen one so a #else directive is a duplicate. When this returns, 605 /// the caller can lex the first valid token. 606 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 607 bool FoundNonSkipPortion, bool FoundElse); 608 609 /// PTHSkipExcludedConditionalBlock - A fast PTH version of 610 /// SkipExcludedConditionalBlock. 611 void PTHSkipExcludedConditionalBlock(); 612 613 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that 614 /// may occur after a #if or #elif directive and return it as a bool. If the 615 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro. 616 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); 617 618 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 619 /// #pragma GCC poison/system_header/dependency and #pragma once. 620 void RegisterBuiltinPragmas(); 621 622 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 623 /// identifier table. 624 void RegisterBuiltinMacros(); 625 IdentifierInfo *RegisterBuiltinMacro(const char *Name); 626 627 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to 628 /// be expanded as a macro, handle it and return the next token as 'Tok'. If 629 /// the macro should not be expanded return true, otherwise return false. 630 bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI); 631 632 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 633 /// lexed is a '('. If so, consume the token and return true, if not, this 634 /// method should have no observable side-effect on the lexed tokens. 635 bool isNextPPTokenLParen(); 636 637 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is 638 /// invoked to read all of the formal arguments specified for the macro 639 /// invocation. This returns null on error. 640 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI); 641 642 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 643 /// as a builtin macro, handle it and return the next token as 'Tok'. 644 void ExpandBuiltinMacro(Token &Tok); 645 646 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 647 /// return the first token after the directive. The _Pragma token has just 648 /// been read into 'Tok'. 649 void Handle_Pragma(Token &Tok); 650 651 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and 652 /// start lexing tokens from it instead of the current buffer. 653 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); 654 655 /// EnterSourceFileWithPTH - Add a lexer to the top of the include stack and 656 /// start getting tokens from it using the PTH cache. 657 void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir); 658 659 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 660 /// checked and spelled filename, e.g. as an operand of #include. This returns 661 /// true if the input filename was in <>'s or false if it were in ""'s. The 662 /// caller is expected to provide a buffer that is large enough to hold the 663 /// spelling of the filename, but is also expected to handle the case when 664 /// this method decides to use a different buffer. 665 bool GetIncludeFilenameSpelling(SourceLocation Loc, 666 const char *&BufStart, const char *&BufEnd); 667 668 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 669 /// return null on failure. isAngled indicates whether the file reference is 670 /// for system #include's or not (i.e. using <> instead of ""). 671 const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd, 672 bool isAngled, const DirectoryLookup *FromDir, 673 const DirectoryLookup *&CurDir); 674 675 676 677 /// IsFileLexer - Returns true if we are lexing from a file and not a 678 /// pragma or a macro. 679 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) { 680 return L ? !L->isPragmaLexer() : P != 0; 681 } 682 683 static bool IsFileLexer(const IncludeStackInfo& I) { 684 return IsFileLexer(I.TheLexer, I.ThePPLexer); 685 } 686 687 bool IsFileLexer() const { 688 return IsFileLexer(CurLexer.get(), CurPPLexer); 689 } 690 691 //===--------------------------------------------------------------------===// 692 // Caching stuff. 693 void CachingLex(Token &Result); 694 bool InCachingLexMode() const { return CurPPLexer == 0 && CurTokenLexer == 0;} 695 void EnterCachingLexMode(); 696 void ExitCachingLexMode() { 697 if (InCachingLexMode()) 698 RemoveTopOfLexerStack(); 699 } 700 const Token &PeekAhead(unsigned N); 701 void AnnotatePreviousCachedTokens(const Token &Tok); 702 703 //===--------------------------------------------------------------------===// 704 /// Handle*Directive - implement the various preprocessor directives. These 705 /// should side-effect the current preprocessor object so that the next call 706 /// to Lex() will return the appropriate token next. 707 void HandleLineDirective(Token &Tok); 708 void HandleDigitDirective(Token &Tok); 709 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); 710 void HandleIdentSCCSDirective(Token &Tok); 711 712 // File inclusion. 713 void HandleIncludeDirective(Token &Tok, 714 const DirectoryLookup *LookupFrom = 0, 715 bool isImport = false); 716 void HandleIncludeNextDirective(Token &Tok); 717 void HandleImportDirective(Token &Tok); 718 719 // Macro handling. 720 void HandleDefineDirective(Token &Tok); 721 void HandleUndefDirective(Token &Tok); 722 // HandleAssertDirective(Token &Tok); 723 // HandleUnassertDirective(Token &Tok); 724 725 // Conditional Inclusion. 726 void HandleIfdefDirective(Token &Tok, bool isIfndef, 727 bool ReadAnyTokensBeforeDirective); 728 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective); 729 void HandleEndifDirective(Token &Tok); 730 void HandleElseDirective(Token &Tok); 731 void HandleElifDirective(Token &Tok); 732 733 // Pragmas. 734 void HandlePragmaDirective(); 735public: 736 void HandlePragmaOnce(Token &OnceTok); 737 void HandlePragmaMark(); 738 void HandlePragmaPoison(Token &PoisonTok); 739 void HandlePragmaSystemHeader(Token &SysHeaderTok); 740 void HandlePragmaDependency(Token &DependencyTok); 741 void HandlePragmaComment(Token &CommentTok); 742}; 743 744/// PreprocessorFactory - A generic factory interface for lazily creating 745/// Preprocessor objects on-demand when they are needed. 746class PreprocessorFactory { 747public: 748 virtual ~PreprocessorFactory(); 749 virtual Preprocessor* CreatePreprocessor() = 0; 750}; 751 752} // end namespace clang 753 754#endif 755