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