Preprocessor.h revision f6452c5421c5db5a7ceff581525f286931d97f1a
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 /// CacheTokens - True when the lexed tokens are cached for backtracking. 77 bool CacheTokens : 1; 78 79 /// Identifiers - This is mapping/lookup information for all identifiers in 80 /// the program, including program keywords. 81 IdentifierTable Identifiers; 82 83 /// Selectors - This table contains all the selectors in the program. Unlike 84 /// IdentifierTable above, this table *isn't* populated by the preprocessor. 85 /// It is declared/instantiated here because it's role/lifetime is 86 /// conceptually similar the IdentifierTable. In addition, the current control 87 /// flow (in clang::ParseAST()), make it convenient to put here. 88 /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to 89 /// the lifetime fo the preprocessor. 90 SelectorTable Selectors; 91 92 /// PragmaHandlers - This tracks all of the pragmas that the client registered 93 /// with this preprocessor. 94 PragmaNamespace *PragmaHandlers; 95 96 /// CurLexer - This is the current top of the stack that we're lexing from if 97 /// not expanding a macro and we are lexing directly from source code. 98 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. 99 llvm::OwningPtr<Lexer> CurLexer; 100 101 /// CurPTHLexer - This is the current top of stack that we're lexing from if 102 /// not expanding from a macro and we are lexing from a PTH cache. 103 /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. 104 llvm::OwningPtr<PTHLexer> CurPTHLexer; 105 106 /// CurPPLexer - This is the current top of the stack what we're lexing from 107 /// if not expanding a macro. This is an alias for either CurLexer or 108 /// CurPTHLexer. 109 PreprocessorLexer* CurPPLexer; 110 111 /// CurLookup - The DirectoryLookup structure used to find the current 112 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to 113 /// implement #include_next and find directory-specific properties. 114 const DirectoryLookup *CurDirLookup; 115 116 /// CurTokenLexer - This is the current macro we are expanding, if we are 117 /// expanding a macro. One of CurLexer and CurTokenLexer must be null. 118 llvm::OwningPtr<TokenLexer> CurTokenLexer; 119 120 /// IncludeMacroStack - This keeps track of the stack of files currently 121 /// #included, and macros currently being expanded from, not counting 122 /// CurLexer/CurTokenLexer. 123 struct IncludeStackInfo { 124 Lexer *TheLexer; 125 PTHLexer *ThePTHLexer; 126 PreprocessorLexer *ThePPLexer; 127 TokenLexer *TheTokenLexer; 128 const DirectoryLookup *TheDirLookup; 129 130 IncludeStackInfo(Lexer *L, PTHLexer* P, PreprocessorLexer* PPL, 131 TokenLexer* TL, const DirectoryLookup *D) 132 : TheLexer(L), ThePTHLexer(P), ThePPLexer(PPL), TheTokenLexer(TL), 133 TheDirLookup(D) {} 134 }; 135 std::vector<IncludeStackInfo> IncludeMacroStack; 136 137 /// Callbacks - These are actions invoked when some preprocessor activity is 138 /// encountered (e.g. a file is #included, etc). 139 PPCallbacks *Callbacks; 140 141 /// Macros - For each IdentifierInfo with 'HasMacro' set, we keep a mapping 142 /// to the actual definition of the macro. 143 llvm::DenseMap<IdentifierInfo*, MacroInfo*> Macros; 144 145 // Various statistics we track for performance analysis. 146 unsigned NumDirectives, NumIncluded, NumDefined, NumUndefined, NumPragma; 147 unsigned NumIf, NumElse, NumEndif; 148 unsigned NumEnteredSourceFiles, MaxIncludeStackDepth; 149 unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded; 150 unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste; 151 unsigned NumSkipped; 152 153 /// Predefines - This string is the predefined macros that preprocessor 154 /// should use from the command line etc. 155 std::string Predefines; 156 157 /// TokenLexerCache - Cache macro expanders to reduce malloc traffic. 158 enum { TokenLexerCacheSize = 8 }; 159 unsigned NumCachedTokenLexers; 160 TokenLexer *TokenLexerCache[TokenLexerCacheSize]; 161 162private: // Cached tokens state. 163 typedef std::vector<Token> CachedTokensTy; 164 165 /// CachedTokens - Cached tokens are stored here when we do backtracking or 166 /// lookahead. They are "lexed" by the CachingLex() method. 167 CachedTokensTy CachedTokens; 168 169 /// CachedLexPos - The position of the cached token that CachingLex() should 170 /// "lex" next. If it points beyond the CachedTokens vector, it means that 171 /// a normal Lex() should be invoked. 172 CachedTokensTy::size_type CachedLexPos; 173 174 /// BacktrackPositions - Stack of backtrack positions, allowing nested 175 /// backtracks. The EnableBacktrackAtThisPos() method pushes a position to 176 /// indicate where CachedLexPos should be set when the BackTrack() method is 177 /// invoked (at which point the last position is popped). 178 std::vector<CachedTokensTy::size_type> BacktrackPositions; 179 180public: 181 Preprocessor(Diagnostic &diags, const LangOptions &opts, TargetInfo &target, 182 SourceManager &SM, HeaderSearch &Headers); 183 ~Preprocessor(); 184 185 Diagnostic &getDiagnostics() const { return Diags; } 186 const LangOptions &getLangOptions() const { return Features; } 187 TargetInfo &getTargetInfo() const { return Target; } 188 FileManager &getFileManager() const { return FileMgr; } 189 SourceManager &getSourceManager() const { return SourceMgr; } 190 HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; } 191 192 IdentifierTable &getIdentifierTable() { return Identifiers; } 193 SelectorTable &getSelectorTable() { return Selectors; } 194 195 inline FullSourceLoc getFullLoc(SourceLocation Loc) const { 196 return FullSourceLoc(Loc, getSourceManager()); 197 } 198 199 /// SetCommentRetentionState - Control whether or not the preprocessor retains 200 /// comments in output. 201 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) { 202 this->KeepComments = KeepComments | KeepMacroComments; 203 this->KeepMacroComments = KeepMacroComments; 204 } 205 206 bool getCommentRetentionState() const { return KeepComments; } 207 208 /// isCurrentLexer - Return true if we are lexing directly from the specified 209 /// lexer. 210 bool isCurrentLexer(const Lexer *L) const { 211 return CurLexer.get() == L; 212 } 213 214 /// getCurrentLexer - Return the current file lexer being lexed from. Note 215 /// that this ignores any potentially active macro expansions and _Pragma 216 /// expansions going on at the time. 217 Lexer *getCurrentFileLexer() const; 218 219 /// getPPCallbacks/setPPCallbacks - Accessors for preprocessor callbacks. 220 /// Note that this class takes ownership of any PPCallbacks object given to 221 /// it. 222 PPCallbacks *getPPCallbacks() const { return Callbacks; } 223 void setPPCallbacks(PPCallbacks *C) { 224 delete Callbacks; 225 Callbacks = C; 226 } 227 228 /// getMacroInfo - Given an identifier, return the MacroInfo it is #defined to 229 /// or null if it isn't #define'd. 230 MacroInfo *getMacroInfo(IdentifierInfo *II) const { 231 return II->hasMacroDefinition() ? Macros.find(II)->second : 0; 232 } 233 234 /// setMacroInfo - Specify a macro for this identifier. 235 /// 236 void setMacroInfo(IdentifierInfo *II, MacroInfo *MI); 237 238 const std::string &getPredefines() const { return Predefines; } 239 /// setPredefines - Set the predefines for this Preprocessor. These 240 /// predefines are automatically injected when parsing the main file. 241 void setPredefines(const char *P) { Predefines = P; } 242 void setPredefines(const std::string &P) { Predefines = P; } 243 244 /// getIdentifierInfo - Return information about the specified preprocessor 245 /// identifier token. The version of this method that takes two character 246 /// pointers is preferred unless the identifier is already available as a 247 /// string (this avoids allocation and copying of memory to construct an 248 /// std::string). 249 IdentifierInfo *getIdentifierInfo(const char *NameStart, 250 const char *NameEnd) { 251 return &Identifiers.get(NameStart, NameEnd); 252 } 253 IdentifierInfo *getIdentifierInfo(const char *NameStr) { 254 return getIdentifierInfo(NameStr, NameStr+strlen(NameStr)); 255 } 256 257 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 258 /// If 'Namespace' is non-null, then it is a token required to exist on the 259 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 260 void AddPragmaHandler(const char *Namespace, PragmaHandler *Handler); 261 262 /// RemovePragmaHandler - Remove the specific pragma handler from 263 /// the preprocessor. If \arg Namespace is non-null, then it should 264 /// be the namespace that \arg Handler was added to. It is an error 265 /// to remove a handler that has not been registered. 266 void RemovePragmaHandler(const char *Namespace, PragmaHandler *Handler); 267 268 /// EnterMainSourceFile - Enter the specified FileID as the main source file, 269 /// which implicitly adds the builtin defines etc. 270 void EnterMainSourceFile(); 271 272 /// EnterSourceFile - Add a source file to the top of the include stack and 273 /// start lexing tokens from it instead of the current buffer. If isMainFile 274 /// is true, this is the main file for the translation unit. 275 void EnterSourceFile(unsigned CurFileID, const DirectoryLookup *Dir); 276 277 /// EnterMacro - Add a Macro to the top of the include stack and start lexing 278 /// tokens from it instead of the current buffer. Args specifies the 279 /// tokens input to a function-like macro. 280 void EnterMacro(Token &Identifier, MacroArgs *Args); 281 282 /// EnterTokenStream - Add a "macro" context to the top of the include stack, 283 /// which will cause the lexer to start returning the specified tokens. 284 /// 285 /// If DisableMacroExpansion is true, tokens lexed from the token stream will 286 /// not be subject to further macro expansion. Otherwise, these tokens will 287 /// be re-macro-expanded when/if expansion is enabled. 288 /// 289 /// If OwnsTokens is false, this method assumes that the specified stream of 290 /// tokens has a permanent owner somewhere, so they do not need to be copied. 291 /// If it is true, it assumes the array of tokens is allocated with new[] and 292 /// must be freed. 293 /// 294 void EnterTokenStream(const Token *Toks, unsigned NumToks, 295 bool DisableMacroExpansion, bool OwnsTokens); 296 297 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the 298 /// lexer stack. This should only be used in situations where the current 299 /// state of the top-of-stack lexer is known. 300 void RemoveTopOfLexerStack(); 301 302 /// EnableBacktrackAtThisPos - From the point that this method is called, and 303 /// until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor 304 /// keeps track of the lexed tokens so that a subsequent Backtrack() call will 305 /// make the Preprocessor re-lex the same tokens. 306 /// 307 /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can 308 /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will 309 /// be combined with the EnableBacktrackAtThisPos calls in reverse order. 310 /// 311 /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack 312 /// at some point after EnableBacktrackAtThisPos. If you don't, caching of 313 /// tokens will continue indefinitely. 314 /// 315 void EnableBacktrackAtThisPos(); 316 317 /// CommitBacktrackedTokens - Disable the last EnableBacktrackAtThisPos call. 318 void CommitBacktrackedTokens(); 319 320 /// Backtrack - Make Preprocessor re-lex the tokens that were lexed since 321 /// EnableBacktrackAtThisPos() was previously called. 322 void Backtrack(); 323 324 /// isBacktrackEnabled - True if EnableBacktrackAtThisPos() was called and 325 /// caching of tokens is on. 326 bool isBacktrackEnabled() const { return CacheTokens; } 327 328 /// Lex - To lex a token from the preprocessor, just pull a token from the 329 /// current lexer or macro object. 330 void Lex(Token &Result) { 331 if (CurLexer) 332 CurLexer->Lex(Result); 333 else if (CurPTHLexer) 334 CurPTHLexer->Lex(Result); 335 else if (CurTokenLexer) 336 CurTokenLexer->Lex(Result); 337 else 338 CachingLex(Result); 339 } 340 341 /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get 342 /// something not a comment. This is useful in -E -C mode where comments 343 /// would foul up preprocessor directive handling. 344 void LexNonComment(Token &Result) { 345 do 346 Lex(Result); 347 while (Result.getKind() == tok::comment); 348 } 349 350 /// LexUnexpandedToken - This is just like Lex, but this disables macro 351 /// expansion of identifier tokens. 352 void LexUnexpandedToken(Token &Result) { 353 // Disable macro expansion. 354 bool OldVal = DisableMacroExpansion; 355 DisableMacroExpansion = true; 356 // Lex the token. 357 Lex(Result); 358 359 // Reenable it. 360 DisableMacroExpansion = OldVal; 361 } 362 363 /// LookAhead - This peeks ahead N tokens and returns that token without 364 /// consuming any tokens. LookAhead(0) returns the next token that would be 365 /// returned by Lex(), LookAhead(1) returns the token after it, etc. This 366 /// returns normal tokens after phase 5. As such, it is equivalent to using 367 /// 'Lex', not 'LexUnexpandedToken'. 368 const Token &LookAhead(unsigned N) { 369 if (CachedLexPos + N < CachedTokens.size()) 370 return CachedTokens[CachedLexPos+N]; 371 else 372 return PeekAhead(N+1); 373 } 374 375 /// EnterToken - Enters a token in the token stream to be lexed next. If 376 /// BackTrack() is called afterwards, the token will remain at the insertion 377 /// point. 378 void EnterToken(const Token &Tok) { 379 EnterCachingLexMode(); 380 CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok); 381 } 382 383 /// AnnotateCachedTokens - We notify the Preprocessor that if it is caching 384 /// tokens (because backtrack is enabled) it should replace the most recent 385 /// cached tokens with the given annotation token. This function has no effect 386 /// if backtracking is not enabled. 387 /// 388 /// Note that the use of this function is just for optimization; so that the 389 /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is 390 /// invoked. 391 void AnnotateCachedTokens(const Token &Tok) { 392 assert(Tok.isAnnotationToken() && "Expected annotation token"); 393 if (CachedLexPos != 0 && InCachingLexMode()) 394 AnnotatePreviousCachedTokens(Tok); 395 } 396 397 /// Diag - Forwarding function for diagnostics. This emits a diagnostic at 398 /// the specified Token's location, translating the token's start 399 /// position in the current buffer into a SourcePosition object for rendering. 400 void Diag(SourceLocation Loc, unsigned DiagID); 401 void Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg); 402 void Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg, 403 const SourceRange &R1, const SourceRange &R2); 404 void Diag(SourceLocation Loc, unsigned DiagID, const SourceRange &R); 405 void Diag(SourceLocation Loc, unsigned DiagID, const SourceRange &R1, 406 const SourceRange &R2); 407 void Diag(const Token &Tok, unsigned DiagID) { 408 Diag(Tok.getLocation(), DiagID); 409 } 410 void Diag(const Token &Tok, unsigned DiagID, const std::string &Msg) { 411 Diag(Tok.getLocation(), DiagID, Msg); 412 } 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 } 512 513 void PopIncludeMacroStack() { 514 CurLexer.reset(IncludeMacroStack.back().TheLexer); 515 CurPTHLexer.reset(IncludeMacroStack.back().ThePTHLexer); 516 CurPPLexer = IncludeMacroStack.back().ThePPLexer; 517 CurTokenLexer.reset(IncludeMacroStack.back().TheTokenLexer); 518 CurDirLookup = IncludeMacroStack.back().TheDirLookup; 519 IncludeMacroStack.pop_back(); 520 } 521 522 /// isInPrimaryFile - Return true if we're in the top-level file, not in a 523 /// #include. 524 bool isInPrimaryFile() const; 525 526 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the 527 /// current line until the tok::eom token is found. 528 void DiscardUntilEndOfDirective(); 529 530 /// ReadMacroName - Lex and validate a macro name, which occurs after a 531 /// #define or #undef. This emits a diagnostic, sets the token kind to eom, 532 /// and discards the rest of the macro line if the macro name is invalid. 533 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0); 534 535 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 536 /// definition has just been read. Lex the rest of the arguments and the 537 /// closing ), updating MI with what we learn. Return true if an error occurs 538 /// parsing the arg list. 539 bool ReadMacroDefinitionArgList(MacroInfo *MI); 540 541 /// SkipExcludedConditionalBlock - We just read a #if or related directive and 542 /// decided that the subsequent tokens are in the #if'd out portion of the 543 /// file. Lex the rest of the file, until we see an #endif. If 544 /// FoundNonSkipPortion is true, then we have already emitted code for part of 545 /// this #if directive, so #else/#elif blocks should never be entered. If 546 /// FoundElse is false, then #else directives are ok, if not, then we have 547 /// already seen one so a #else directive is a duplicate. When this returns, 548 /// the caller can lex the first valid token. 549 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 550 bool FoundNonSkipPortion, bool FoundElse); 551 552 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that 553 /// may occur after a #if or #elif directive and return it as a bool. If the 554 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro. 555 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); 556 557 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 558 /// #pragma GCC poison/system_header/dependency and #pragma once. 559 void RegisterBuiltinPragmas(); 560 561 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 562 /// identifier table. 563 void RegisterBuiltinMacros(); 564 IdentifierInfo *RegisterBuiltinMacro(const char *Name); 565 566 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to 567 /// be expanded as a macro, handle it and return the next token as 'Tok'. If 568 /// the macro should not be expanded return true, otherwise return false. 569 bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI); 570 571 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 572 /// lexed is a '('. If so, consume the token and return true, if not, this 573 /// method should have no observable side-effect on the lexed tokens. 574 bool isNextPPTokenLParen(); 575 576 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is 577 /// invoked to read all of the formal arguments specified for the macro 578 /// invocation. This returns null on error. 579 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI); 580 581 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 582 /// as a builtin macro, handle it and return the next token as 'Tok'. 583 void ExpandBuiltinMacro(Token &Tok); 584 585 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 586 /// return the first token after the directive. The _Pragma token has just 587 /// been read into 'Tok'. 588 void Handle_Pragma(Token &Tok); 589 590 591 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and 592 /// start lexing tokens from it instead of the current buffer. 593 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); 594 595 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 596 /// checked and spelled filename, e.g. as an operand of #include. This returns 597 /// true if the input filename was in <>'s or false if it were in ""'s. The 598 /// caller is expected to provide a buffer that is large enough to hold the 599 /// spelling of the filename, but is also expected to handle the case when 600 /// this method decides to use a different buffer. 601 bool GetIncludeFilenameSpelling(SourceLocation Loc, 602 const char *&BufStart, const char *&BufEnd); 603 604 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 605 /// return null on failure. isAngled indicates whether the file reference is 606 /// for system #include's or not (i.e. using <> instead of ""). 607 const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd, 608 bool isAngled, const DirectoryLookup *FromDir, 609 const DirectoryLookup *&CurDir); 610 611 //===--------------------------------------------------------------------===// 612 // Caching stuff. 613 void CachingLex(Token &Result); 614 bool InCachingLexMode() const { return CurLexer == 0 && CurTokenLexer == 0; } 615 void EnterCachingLexMode(); 616 void ExitCachingLexMode() { 617 if (InCachingLexMode()) 618 RemoveTopOfLexerStack(); 619 } 620 const Token &PeekAhead(unsigned N); 621 void AnnotatePreviousCachedTokens(const Token &Tok); 622 623 //===--------------------------------------------------------------------===// 624 /// Handle*Directive - implement the various preprocessor directives. These 625 /// should side-effect the current preprocessor object so that the next call 626 /// to Lex() will return the appropriate token next. 627 628 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); 629 void HandleIdentSCCSDirective(Token &Tok); 630 631 // File inclusion. 632 void HandleIncludeDirective(Token &Tok, 633 const DirectoryLookup *LookupFrom = 0, 634 bool isImport = false); 635 void HandleIncludeNextDirective(Token &Tok); 636 void HandleImportDirective(Token &Tok); 637 638 // Macro handling. 639 void HandleDefineDirective(Token &Tok); 640 void HandleUndefDirective(Token &Tok); 641 // HandleAssertDirective(Token &Tok); 642 // HandleUnassertDirective(Token &Tok); 643 644 // Conditional Inclusion. 645 void HandleIfdefDirective(Token &Tok, bool isIfndef, 646 bool ReadAnyTokensBeforeDirective); 647 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective); 648 void HandleEndifDirective(Token &Tok); 649 void HandleElseDirective(Token &Tok); 650 void HandleElifDirective(Token &Tok); 651 652 // Pragmas. 653 void HandlePragmaDirective(); 654public: 655 void HandlePragmaOnce(Token &OnceTok); 656 void HandlePragmaMark(); 657 void HandlePragmaPoison(Token &PoisonTok); 658 void HandlePragmaSystemHeader(Token &SysHeaderTok); 659 void HandlePragmaDependency(Token &DependencyTok); 660}; 661 662/// PreprocessorFactory - A generic factory interface for lazily creating 663/// Preprocessor objects on-demand when they are needed. 664class PreprocessorFactory { 665public: 666 virtual ~PreprocessorFactory(); 667 virtual Preprocessor* CreatePreprocessor() = 0; 668}; 669 670} // end namespace clang 671 672#endif 673