Preprocessor.h revision 34eaa24e6c2dc72bbbd5ad09694368cfd09c5f14
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 inline FullSourceLoc getFullLoc(SourceLocation Loc) const { 193 return FullSourceLoc(Loc, getSourceManager()); 194 } 195 196 /// SetCommentRetentionState - Control whether or not the preprocessor retains 197 /// comments in output. 198 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) { 199 this->KeepComments = KeepComments | KeepMacroComments; 200 this->KeepMacroComments = KeepMacroComments; 201 } 202 203 bool getCommentRetentionState() const { return KeepComments; } 204 205 /// isCurrentLexer - Return true if we are lexing directly from the specified 206 /// lexer. 207 bool isCurrentLexer(const PreprocessorLexer *L) const { 208 return CurPPLexer == L; 209 } 210 211 /// getCurrentLexer - Return the current file lexer being lexed from. Note 212 /// that this ignores any potentially active macro expansions and _Pragma 213 /// expansions going on at the time. 214 PreprocessorLexer *getCurrentFileLexer() const; 215 216 /// getPPCallbacks/setPPCallbacks - Accessors for preprocessor callbacks. 217 /// Note that this class takes ownership of any PPCallbacks object given to 218 /// it. 219 PPCallbacks *getPPCallbacks() const { return Callbacks; } 220 void setPPCallbacks(PPCallbacks *C) { 221 delete Callbacks; 222 Callbacks = C; 223 } 224 225 /// getMacroInfo - Given an identifier, return the MacroInfo it is #defined to 226 /// or null if it isn't #define'd. 227 MacroInfo *getMacroInfo(IdentifierInfo *II) const { 228 return II->hasMacroDefinition() ? Macros.find(II)->second : 0; 229 } 230 231 /// setMacroInfo - Specify a macro for this identifier. 232 /// 233 void setMacroInfo(IdentifierInfo *II, MacroInfo *MI); 234 235 const std::string &getPredefines() const { return Predefines; } 236 /// setPredefines - Set the predefines for this Preprocessor. These 237 /// predefines are automatically injected when parsing the main file. 238 void setPredefines(const char *P) { Predefines = P; } 239 void setPredefines(const std::string &P) { Predefines = P; } 240 241 /// getIdentifierInfo - Return information about the specified preprocessor 242 /// identifier token. The version of this method that takes two character 243 /// pointers is preferred unless the identifier is already available as a 244 /// string (this avoids allocation and copying of memory to construct an 245 /// std::string). 246 IdentifierInfo *getIdentifierInfo(const char *NameStart, 247 const char *NameEnd) { 248 return &Identifiers.get(NameStart, NameEnd); 249 } 250 IdentifierInfo *getIdentifierInfo(const char *NameStr) { 251 return getIdentifierInfo(NameStr, NameStr+strlen(NameStr)); 252 } 253 254 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 255 /// If 'Namespace' is non-null, then it is a token required to exist on the 256 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 257 void AddPragmaHandler(const char *Namespace, PragmaHandler *Handler); 258 259 /// RemovePragmaHandler - Remove the specific pragma handler from 260 /// the preprocessor. If \arg Namespace is non-null, then it should 261 /// be the namespace that \arg Handler was added to. It is an error 262 /// to remove a handler that has not been registered. 263 void RemovePragmaHandler(const char *Namespace, PragmaHandler *Handler); 264 265 /// EnterMainSourceFile - Enter the specified FileID as the main source file, 266 /// which implicitly adds the builtin defines etc. 267 void EnterMainSourceFile(); 268 269 /// EnterSourceFile - Add a source file to the top of the include stack and 270 /// start lexing tokens from it instead of the current buffer. If isMainFile 271 /// is true, this is the main file for the translation unit. 272 void EnterSourceFile(unsigned CurFileID, const DirectoryLookup *Dir); 273 274 /// EnterMacro - Add a Macro to the top of the include stack and start lexing 275 /// tokens from it instead of the current buffer. Args specifies the 276 /// tokens input to a function-like macro. 277 void EnterMacro(Token &Identifier, MacroArgs *Args); 278 279 /// EnterTokenStream - Add a "macro" context to the top of the include stack, 280 /// which will cause the lexer to start returning the specified tokens. 281 /// 282 /// If DisableMacroExpansion is true, tokens lexed from the token stream will 283 /// not be subject to further macro expansion. Otherwise, these tokens will 284 /// be re-macro-expanded when/if expansion is enabled. 285 /// 286 /// If OwnsTokens is false, this method assumes that the specified stream of 287 /// tokens has a permanent owner somewhere, so they do not need to be copied. 288 /// If it is true, it assumes the array of tokens is allocated with new[] and 289 /// must be freed. 290 /// 291 void EnterTokenStream(const Token *Toks, unsigned NumToks, 292 bool DisableMacroExpansion, bool OwnsTokens); 293 294 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the 295 /// lexer stack. This should only be used in situations where the current 296 /// state of the top-of-stack lexer is known. 297 void RemoveTopOfLexerStack(); 298 299 /// EnableBacktrackAtThisPos - From the point that this method is called, and 300 /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor 301 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will 302 /// make the Preprocessor re-lex the same tokens. 303 /// 304 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can 305 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will 306 /// be combined with the EnableBacktrackAtThisPos calls in reverse order. 307 /// 308 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack 309 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of 310 /// tokens will continue indefinitely. 311 /// 312 void EnableBacktrackAtThisPos(); 313 314 /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call. 315 void CommitBacktrackedTokens(); 316 317 /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since 318 /// EnableBacktrackAtThisPos() was previously called. 319 void Backtrack(); 320 321 /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and 322 /// caching of tokens is on. 323 bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); } 324 325 /// Lex - To lex a token from the preprocessor, just pull a token from the 326 /// current lexer or macro object. 327 void Lex(Token &Result) { 328 if (CurLexer) 329 CurLexer->Lex(Result); 330 else if (CurPTHLexer) 331 CurPTHLexer->Lex(Result); 332 else if (CurTokenLexer) 333 CurTokenLexer->Lex(Result); 334 else 335 CachingLex(Result); 336 } 337 338 /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get 339 /// something not a comment. This is useful in -E -C mode where comments 340 /// would foul up preprocessor directive handling. 341 void LexNonComment(Token &Result) { 342 do 343 Lex(Result); 344 while (Result.getKind() == tok::comment); 345 } 346 347 /// LexUnexpandedToken - This is just like Lex, but this disables macro 348 /// expansion of identifier tokens. 349 void LexUnexpandedToken(Token &Result) { 350 // Disable macro expansion. 351 bool OldVal = DisableMacroExpansion; 352 DisableMacroExpansion = true; 353 // Lex the token. 354 Lex(Result); 355 356 // Reenable it. 357 DisableMacroExpansion = OldVal; 358 } 359 360 /// LookAhead - This peeks ahead N tokens and returns that token without 361 /// consuming any tokens. LookAhead(0) returns the next token that would be 362 /// returned by Lex(), LookAhead(1) returns the token after it, etc. This 363 /// returns normal tokens after phase 5. As such, it is equivalent to using 364 /// 'Lex', not 'LexUnexpandedToken'. 365 const Token &LookAhead(unsigned N) { 366 if (CachedLexPos + N < CachedTokens.size()) 367 return CachedTokens[CachedLexPos+N]; 368 else 369 return PeekAhead(N+1); 370 } 371 372 /// RevertCachedTokens - When backtracking is enabled and tokens are cached, 373 /// this allows to revert a specific number of tokens. 374 /// Note that the number of tokens being reverted should be up to the last 375 /// backtrack position, not more. 376 void RevertCachedTokens(unsigned N) { 377 assert(isBacktrackEnabled() && 378 "Should only be called when tokens are cached for backtracking"); 379 assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back()) 380 && "Should revert tokens up to the last backtrack position, not more"); 381 assert(signed(CachedLexPos) - signed(N) >= 0 && 382 "Corrupted backtrack positions ?"); 383 CachedLexPos -= N; 384 } 385 386 /// EnterToken - Enters a token in the token stream to be lexed next. If 387 /// BackTrack() is called afterwards, the token will remain at the insertion 388 /// point. 389 void EnterToken(const Token &Tok) { 390 EnterCachingLexMode(); 391 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok); 392 } 393 394 /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching 395 /// tokens (because backtrack is enabled) it should replace the most recent 396 /// cached tokens with the given annotation token. This function has no effect 397 /// if backtracking is not enabled. 398 /// 399 /// Note that the use of this function is just for optimization; so that the 400 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is 401 /// invoked. 402 void AnnotateCachedTokens(const Token &Tok) { 403 assert(Tok.isAnnotationToken() && "Expected annotation token"); 404 if (CachedLexPos != 0 && InCachingLexMode()) 405 AnnotatePreviousCachedTokens(Tok); 406 } 407 408 /// Diag - Forwarding function for diagnostics. This emits a diagnostic at 409 /// the specified Token's location, translating the token's start 410 /// position in the current buffer into a SourcePosition object for rendering. 411 DiagnosticInfo Diag(SourceLocation Loc, unsigned DiagID); 412 DiagnosticInfo Diag(const Token &Tok, unsigned DiagID); 413 414 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a 415 /// token is the characters used to represent the token in the source file 416 /// after trigraph expansion and escaped-newline folding. In particular, this 417 /// wants to get the true, uncanonicalized, spelling of things like digraphs 418 /// UCNs, etc. 419 std::string getSpelling(const Token &Tok) const; 420 421 /// getSpelling - This method is used to get the spelling of a token into a 422 /// preallocated buffer, instead of as an std::string. The caller is required 423 /// to allocate enough space for the token, which is guaranteed to be at least 424 /// Tok.getLength() bytes long. The length of the actual result is returned. 425 /// 426 /// Note that this method may do two possible things: it may either fill in 427 /// the buffer specified with characters, or it may *change the input pointer* 428 /// to point to a constant buffer with the data already in it (avoiding a 429 /// copy). The caller is not allowed to modify the returned buffer pointer 430 /// if an internal buffer is returned. 431 unsigned getSpelling(const Token &Tok, const char *&Buffer) const; 432 433 434 /// CreateString - Plop the specified string into a scratch buffer and return 435 /// a location for it. If specified, the source location provides a source 436 /// location for the token. 437 SourceLocation CreateString(const char *Buf, unsigned Len, 438 SourceLocation SourceLoc = SourceLocation()); 439 440 /// DumpToken - Print the token to stderr, used for debugging. 441 /// 442 void DumpToken(const Token &Tok, bool DumpFlags = false) const; 443 void DumpLocation(SourceLocation Loc) const; 444 void DumpMacro(const MacroInfo &MI) const; 445 446 /// AdvanceToTokenCharacter - Given a location that specifies the start of a 447 /// token, return a new location that specifies a character within the token. 448 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char); 449 450 /// IncrementPasteCounter - Increment the counters for the number of token 451 /// paste operations performed. If fast was specified, this is a 'fast paste' 452 /// case we handled. 453 /// 454 void IncrementPasteCounter(bool isFast) { 455 if (isFast) 456 ++NumFastTokenPaste; 457 else 458 ++NumTokenPaste; 459 } 460 461 void PrintStats(); 462 463 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a 464 /// comment (/##/) in microsoft mode, this method handles updating the current 465 /// state, returning the token on the next source line. 466 void HandleMicrosoftCommentPaste(Token &Tok); 467 468 //===--------------------------------------------------------------------===// 469 // Preprocessor callback methods. These are invoked by a lexer as various 470 // directives and events are found. 471 472 /// LookUpIdentifierInfo - Given a tok::identifier token, look up the 473 /// identifier information for the token and install it into the token. 474 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier, 475 const char *BufPtr = 0); 476 477 /// HandleIdentifier - This callback is invoked when the lexer reads an 478 /// identifier and has filled in the tokens IdentifierInfo member. This 479 /// callback potentially macro expands it or turns it into a named token (like 480 /// 'for'). 481 void HandleIdentifier(Token &Identifier); 482 483 484 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of 485 /// the current file. This either returns the EOF token and returns true, or 486 /// pops a level off the include stack and returns false, at which point the 487 /// client should call lex again. 488 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); 489 490 /// HandleEndOfTokenLexer - This callback is invoked when the current 491 /// TokenLexer hits the end of its token stream. 492 bool HandleEndOfTokenLexer(Token &Result); 493 494 /// HandleDirective - This callback is invoked when the lexer sees a # token 495 /// at the start of a line. This consumes the directive, modifies the 496 /// lexer/preprocessor state, and advances the lexer(s) so that the next token 497 /// read is the correct one. 498 void HandleDirective(Token &Result); 499 500 /// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If 501 /// not, emit a diagnostic and consume up until the eom. 502 void CheckEndOfDirective(const char *Directive); 503private: 504 505 void PushIncludeMacroStack() { 506 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer.take(), 507 CurPTHLexer.take(), 508 CurPPLexer, 509 CurTokenLexer.take(), 510 CurDirLookup)); 511 CurPPLexer = 0; 512 } 513 514 void PopIncludeMacroStack() { 515 CurLexer.reset(IncludeMacroStack.back().TheLexer); 516 CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer); 517 CurPPLexer = IncludeMacroStack.back().ThePPLexer; 518 CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer); 519 CurDirLookup = IncludeMacroStack.back().TheDirLookup; 520 IncludeMacroStack.pop_back(); 521 } 522 523 /// isInPrimaryFile - Return true if we're in the top-level file, not in a 524 /// #include. 525 bool isInPrimaryFile() const; 526 527 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the 528 /// current line until the tok::eom token is found. 529 void DiscardUntilEndOfDirective(); 530 531 /// ReadMacroName - Lex and validate a macro name, which occurs after a 532 /// #define or #undef. This emits a diagnostic, sets the token kind to eom, 533 /// and discards the rest of the macro line if the macro name is invalid. 534 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0); 535 536 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 537 /// definition has just been read. Lex the rest of the arguments and the 538 /// closing ), updating MI with what we learn. Return true if an error occurs 539 /// parsing the arg list. 540 bool ReadMacroDefinitionArgList(MacroInfo *MI); 541 542 /// SkipExcludedConditionalBlock - We just read a #if or related directive and 543 /// decided that the subsequent tokens are in the #if'd out portion of the 544 /// file. Lex the rest of the file, until we see an #endif. If 545 /// FoundNonSkipPortion is true, then we have already emitted code for part of 546 /// this #if directive, so #else/#elif blocks should never be entered. If 547 /// FoundElse is false, then #else directives are ok, if not, then we have 548 /// already seen one so a #else directive is a duplicate. When this returns, 549 /// the caller can lex the first valid token. 550 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 551 bool FoundNonSkipPortion, bool FoundElse); 552 553 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that 554 /// may occur after a #if or #elif directive and return it as a bool. If the 555 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro. 556 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); 557 558 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 559 /// #pragma GCC poison/system_header/dependency and #pragma once. 560 void RegisterBuiltinPragmas(); 561 562 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 563 /// identifier table. 564 void RegisterBuiltinMacros(); 565 IdentifierInfo *RegisterBuiltinMacro(const char *Name); 566 567 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to 568 /// be expanded as a macro, handle it and return the next token as 'Tok'. If 569 /// the macro should not be expanded return true, otherwise return false. 570 bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI); 571 572 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 573 /// lexed is a '('. If so, consume the token and return true, if not, this 574 /// method should have no observable side-effect on the lexed tokens. 575 bool isNextPPTokenLParen(); 576 577 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is 578 /// invoked to read all of the formal arguments specified for the macro 579 /// invocation. This returns null on error. 580 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI); 581 582 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 583 /// as a builtin macro, handle it and return the next token as 'Tok'. 584 void ExpandBuiltinMacro(Token &Tok); 585 586 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 587 /// return the first token after the directive. The _Pragma token has just 588 /// been read into 'Tok'. 589 void Handle_Pragma(Token &Tok); 590 591 592 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and 593 /// start lexing tokens from it instead of the current buffer. 594 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); 595 596 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 597 /// checked and spelled filename, e.g. as an operand of #include. This returns 598 /// true if the input filename was in <>'s or false if it were in ""'s. The 599 /// caller is expected to provide a buffer that is large enough to hold the 600 /// spelling of the filename, but is also expected to handle the case when 601 /// this method decides to use a different buffer. 602 bool GetIncludeFilenameSpelling(SourceLocation Loc, 603 const char *&BufStart, const char *&BufEnd); 604 605 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 606 /// return null on failure. isAngled indicates whether the file reference is 607 /// for system #include's or not (i.e. using <> instead of ""). 608 const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd, 609 bool isAngled, const DirectoryLookup *FromDir, 610 const DirectoryLookup *&CurDir); 611 612 613 614 /// IsFileLexer - Returns true if we are lexing from a file and not a 615 /// pragma or a macro. 616 static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) { 617 return L ? !L->isPragmaLexer() : P != 0; 618 } 619 620 static bool IsFileLexer(const IncludeStackInfo& I) { 621 return IsFileLexer(I.TheLexer, I.ThePPLexer); 622 } 623 624 bool IsFileLexer() const { 625 return IsFileLexer(CurLexer.get(), CurPPLexer); 626 } 627 628 //===--------------------------------------------------------------------===// 629 // Caching stuff. 630 void CachingLex(Token &Result); 631 bool InCachingLexMode() const { return CurLexer == 0 && CurTokenLexer == 0; } 632 void EnterCachingLexMode(); 633 void ExitCachingLexMode() { 634 if (InCachingLexMode()) 635 RemoveTopOfLexerStack(); 636 } 637 const Token &PeekAhead(unsigned N); 638 void AnnotatePreviousCachedTokens(const Token &Tok); 639 640 //===--------------------------------------------------------------------===// 641 /// Handle*Directive - implement the various preprocessor directives. These 642 /// should side-effect the current preprocessor object so that the next call 643 /// to Lex() will return the appropriate token next. 644 645 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); 646 void HandleIdentSCCSDirective(Token &Tok); 647 648 // File inclusion. 649 void HandleIncludeDirective(Token &Tok, 650 const DirectoryLookup *LookupFrom = 0, 651 bool isImport = false); 652 void HandleIncludeNextDirective(Token &Tok); 653 void HandleImportDirective(Token &Tok); 654 655 // Macro handling. 656 void HandleDefineDirective(Token &Tok); 657 void HandleUndefDirective(Token &Tok); 658 // HandleAssertDirective(Token &Tok); 659 // HandleUnassertDirective(Token &Tok); 660 661 // Conditional Inclusion. 662 void HandleIfdefDirective(Token &Tok, bool isIfndef, 663 bool ReadAnyTokensBeforeDirective); 664 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective); 665 void HandleEndifDirective(Token &Tok); 666 void HandleElseDirective(Token &Tok); 667 void HandleElifDirective(Token &Tok); 668 669 // Pragmas. 670 void HandlePragmaDirective(); 671public: 672 void HandlePragmaOnce(Token &OnceTok); 673 void HandlePragmaMark(); 674 void HandlePragmaPoison(Token &PoisonTok); 675 void HandlePragmaSystemHeader(Token &SysHeaderTok); 676 void HandlePragmaDependency(Token &DependencyTok); 677}; 678 679/// PreprocessorFactory - A generic factory interface for lazily creating 680/// Preprocessor objects on-demand when they are needed. 681class PreprocessorFactory { 682public: 683 virtual ~PreprocessorFactory(); 684 virtual Preprocessor* CreatePreprocessor() = 0; 685}; 686 687} // end namespace clang 688 689#endif 690