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