PPMacroExpansion.cpp revision 205408
1//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===// 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 implements the top level handling of macro expasion for the 11// preprocessor. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Lex/Preprocessor.h" 16#include "MacroArgs.h" 17#include "clang/Lex/MacroInfo.h" 18#include "clang/Basic/SourceManager.h" 19#include "clang/Basic/FileManager.h" 20#include "clang/Lex/LexDiagnostic.h" 21#include "llvm/ADT/StringSwitch.h" 22#include "llvm/Support/raw_ostream.h" 23#include <cstdio> 24#include <ctime> 25using namespace clang; 26 27/// setMacroInfo - Specify a macro for this identifier. 28/// 29void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) { 30 if (MI) { 31 Macros[II] = MI; 32 II->setHasMacroDefinition(true); 33 } else if (II->hasMacroDefinition()) { 34 Macros.erase(II); 35 II->setHasMacroDefinition(false); 36 } 37} 38 39/// RegisterBuiltinMacro - Register the specified identifier in the identifier 40/// table and mark it as a builtin macro to be expanded. 41static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ 42 // Get the identifier. 43 IdentifierInfo *Id = PP.getIdentifierInfo(Name); 44 45 // Mark it as being a macro that is builtin. 46 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); 47 MI->setIsBuiltinMacro(); 48 PP.setMacroInfo(Id, MI); 49 return Id; 50} 51 52 53/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 54/// identifier table. 55void Preprocessor::RegisterBuiltinMacros() { 56 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__"); 57 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__"); 58 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__"); 59 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__"); 60 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__"); 61 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma"); 62 63 // GCC Extensions. 64 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__"); 65 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__"); 66 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__"); 67 68 // Clang Extensions. 69 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature"); 70 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin"); 71 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include"); 72 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next"); 73} 74 75/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token 76/// in its expansion, currently expands to that token literally. 77static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, 78 const IdentifierInfo *MacroIdent, 79 Preprocessor &PP) { 80 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo(); 81 82 // If the token isn't an identifier, it's always literally expanded. 83 if (II == 0) return true; 84 85 // If the identifier is a macro, and if that macro is enabled, it may be 86 // expanded so it's not a trivial expansion. 87 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() && 88 // Fast expanding "#define X X" is ok, because X would be disabled. 89 II != MacroIdent) 90 return false; 91 92 // If this is an object-like macro invocation, it is safe to trivially expand 93 // it. 94 if (MI->isObjectLike()) return true; 95 96 // If this is a function-like macro invocation, it's safe to trivially expand 97 // as long as the identifier is not a macro argument. 98 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 99 I != E; ++I) 100 if (*I == II) 101 return false; // Identifier is a macro argument. 102 103 return true; 104} 105 106 107/// isNextPPTokenLParen - Determine whether the next preprocessor token to be 108/// lexed is a '('. If so, consume the token and return true, if not, this 109/// method should have no observable side-effect on the lexed tokens. 110bool Preprocessor::isNextPPTokenLParen() { 111 // Do some quick tests for rejection cases. 112 unsigned Val; 113 if (CurLexer) 114 Val = CurLexer->isNextPPTokenLParen(); 115 else if (CurPTHLexer) 116 Val = CurPTHLexer->isNextPPTokenLParen(); 117 else 118 Val = CurTokenLexer->isNextTokenLParen(); 119 120 if (Val == 2) { 121 // We have run off the end. If it's a source file we don't 122 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the 123 // macro stack. 124 if (CurPPLexer) 125 return false; 126 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { 127 IncludeStackInfo &Entry = IncludeMacroStack[i-1]; 128 if (Entry.TheLexer) 129 Val = Entry.TheLexer->isNextPPTokenLParen(); 130 else if (Entry.ThePTHLexer) 131 Val = Entry.ThePTHLexer->isNextPPTokenLParen(); 132 else 133 Val = Entry.TheTokenLexer->isNextTokenLParen(); 134 135 if (Val != 2) 136 break; 137 138 // Ran off the end of a source file? 139 if (Entry.ThePPLexer) 140 return false; 141 } 142 } 143 144 // Okay, if we know that the token is a '(', lex it and return. Otherwise we 145 // have found something that isn't a '(' or we found the end of the 146 // translation unit. In either case, return false. 147 return Val == 1; 148} 149 150/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be 151/// expanded as a macro, handle it and return the next token as 'Identifier'. 152bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, 153 MacroInfo *MI) { 154 if (Callbacks) Callbacks->MacroExpands(Identifier, MI); 155 156 // If this is a macro expansion in the "#if !defined(x)" line for the file, 157 // then the macro could expand to different things in other contexts, we need 158 // to disable the optimization in this case. 159 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro(); 160 161 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially. 162 if (MI->isBuiltinMacro()) { 163 ExpandBuiltinMacro(Identifier); 164 return false; 165 } 166 167 /// Args - If this is a function-like macro expansion, this contains, 168 /// for each macro argument, the list of tokens that were provided to the 169 /// invocation. 170 MacroArgs *Args = 0; 171 172 // Remember where the end of the instantiation occurred. For an object-like 173 // macro, this is the identifier. For a function-like macro, this is the ')'. 174 SourceLocation InstantiationEnd = Identifier.getLocation(); 175 176 // If this is a function-like macro, read the arguments. 177 if (MI->isFunctionLike()) { 178 // C99 6.10.3p10: If the preprocessing token immediately after the the macro 179 // name isn't a '(', this macro should not be expanded. 180 if (!isNextPPTokenLParen()) 181 return true; 182 183 // Remember that we are now parsing the arguments to a macro invocation. 184 // Preprocessor directives used inside macro arguments are not portable, and 185 // this enables the warning. 186 InMacroArgs = true; 187 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd); 188 189 // Finished parsing args. 190 InMacroArgs = false; 191 192 // If there was an error parsing the arguments, bail out. 193 if (Args == 0) return false; 194 195 ++NumFnMacroExpanded; 196 } else { 197 ++NumMacroExpanded; 198 } 199 200 // Notice that this macro has been used. 201 MI->setIsUsed(true); 202 203 // If we started lexing a macro, enter the macro expansion body. 204 205 // If this macro expands to no tokens, don't bother to push it onto the 206 // expansion stack, only to take it right back off. 207 if (MI->getNumTokens() == 0) { 208 // No need for arg info. 209 if (Args) Args->destroy(*this); 210 211 // Ignore this macro use, just return the next token in the current 212 // buffer. 213 bool HadLeadingSpace = Identifier.hasLeadingSpace(); 214 bool IsAtStartOfLine = Identifier.isAtStartOfLine(); 215 216 Lex(Identifier); 217 218 // If the identifier isn't on some OTHER line, inherit the leading 219 // whitespace/first-on-a-line property of this token. This handles 220 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is 221 // empty. 222 if (!Identifier.isAtStartOfLine()) { 223 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine); 224 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace); 225 } 226 ++NumFastMacroExpanded; 227 return false; 228 229 } else if (MI->getNumTokens() == 1 && 230 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(), 231 *this)) { 232 // Otherwise, if this macro expands into a single trivially-expanded 233 // token: expand it now. This handles common cases like 234 // "#define VAL 42". 235 236 // No need for arg info. 237 if (Args) Args->destroy(*this); 238 239 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro 240 // identifier to the expanded token. 241 bool isAtStartOfLine = Identifier.isAtStartOfLine(); 242 bool hasLeadingSpace = Identifier.hasLeadingSpace(); 243 244 // Remember where the token is instantiated. 245 SourceLocation InstantiateLoc = Identifier.getLocation(); 246 247 // Replace the result token. 248 Identifier = MI->getReplacementToken(0); 249 250 // Restore the StartOfLine/LeadingSpace markers. 251 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine); 252 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace); 253 254 // Update the tokens location to include both its instantiation and physical 255 // locations. 256 SourceLocation Loc = 257 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc, 258 InstantiationEnd,Identifier.getLength()); 259 Identifier.setLocation(Loc); 260 261 // If this is #define X X, we must mark the result as unexpandible. 262 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) 263 if (getMacroInfo(NewII) == MI) 264 Identifier.setFlag(Token::DisableExpand); 265 266 // Since this is not an identifier token, it can't be macro expanded, so 267 // we're done. 268 ++NumFastMacroExpanded; 269 return false; 270 } 271 272 // Start expanding the macro. 273 EnterMacro(Identifier, InstantiationEnd, Args); 274 275 // Now that the macro is at the top of the include stack, ask the 276 // preprocessor to read the next token from it. 277 Lex(Identifier); 278 return false; 279} 280 281/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next 282/// token is the '(' of the macro, this method is invoked to read all of the 283/// actual arguments specified for the macro invocation. This returns null on 284/// error. 285MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, 286 MacroInfo *MI, 287 SourceLocation &MacroEnd) { 288 // The number of fixed arguments to parse. 289 unsigned NumFixedArgsLeft = MI->getNumArgs(); 290 bool isVariadic = MI->isVariadic(); 291 292 // Outer loop, while there are more arguments, keep reading them. 293 Token Tok; 294 295 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 296 // an argument value in a macro could expand to ',' or '(' or ')'. 297 LexUnexpandedToken(Tok); 298 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?"); 299 300 // ArgTokens - Build up a list of tokens that make up each argument. Each 301 // argument is separated by an EOF token. Use a SmallVector so we can avoid 302 // heap allocations in the common case. 303 llvm::SmallVector<Token, 64> ArgTokens; 304 305 unsigned NumActuals = 0; 306 while (Tok.isNot(tok::r_paren)) { 307 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) && 308 "only expect argument separators here"); 309 310 unsigned ArgTokenStart = ArgTokens.size(); 311 SourceLocation ArgStartLoc = Tok.getLocation(); 312 313 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note 314 // that we already consumed the first one. 315 unsigned NumParens = 0; 316 317 while (1) { 318 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 319 // an argument value in a macro could expand to ',' or '(' or ')'. 320 LexUnexpandedToken(Tok); 321 322 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n" 323 Diag(MacroName, diag::err_unterm_macro_invoc); 324 // Do not lose the EOF/EOM. Return it to the client. 325 MacroName = Tok; 326 return 0; 327 } else if (Tok.is(tok::r_paren)) { 328 // If we found the ) token, the macro arg list is done. 329 if (NumParens-- == 0) { 330 MacroEnd = Tok.getLocation(); 331 break; 332 } 333 } else if (Tok.is(tok::l_paren)) { 334 ++NumParens; 335 } else if (Tok.is(tok::comma) && NumParens == 0) { 336 // Comma ends this argument if there are more fixed arguments expected. 337 // However, if this is a variadic macro, and this is part of the 338 // variadic part, then the comma is just an argument token. 339 if (!isVariadic) break; 340 if (NumFixedArgsLeft > 1) 341 break; 342 } else if (Tok.is(tok::comment) && !KeepMacroComments) { 343 // If this is a comment token in the argument list and we're just in 344 // -C mode (not -CC mode), discard the comment. 345 continue; 346 } else if (Tok.getIdentifierInfo() != 0) { 347 // Reading macro arguments can cause macros that we are currently 348 // expanding from to be popped off the expansion stack. Doing so causes 349 // them to be reenabled for expansion. Here we record whether any 350 // identifiers we lex as macro arguments correspond to disabled macros. 351 // If so, we mark the token as noexpand. This is a subtle aspect of 352 // C99 6.10.3.4p2. 353 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo())) 354 if (!MI->isEnabled()) 355 Tok.setFlag(Token::DisableExpand); 356 } 357 ArgTokens.push_back(Tok); 358 } 359 360 // If this was an empty argument list foo(), don't add this as an empty 361 // argument. 362 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren) 363 break; 364 365 // If this is not a variadic macro, and too many args were specified, emit 366 // an error. 367 if (!isVariadic && NumFixedArgsLeft == 0) { 368 if (ArgTokens.size() != ArgTokenStart) 369 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation(); 370 371 // Emit the diagnostic at the macro name in case there is a missing ). 372 // Emitting it at the , could be far away from the macro name. 373 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc); 374 return 0; 375 } 376 377 // Empty arguments are standard in C99 and supported as an extension in 378 // other modes. 379 if (ArgTokens.size() == ArgTokenStart && !Features.C99) 380 Diag(Tok, diag::ext_empty_fnmacro_arg); 381 382 // Add a marker EOF token to the end of the token list for this argument. 383 Token EOFTok; 384 EOFTok.startToken(); 385 EOFTok.setKind(tok::eof); 386 EOFTok.setLocation(Tok.getLocation()); 387 EOFTok.setLength(0); 388 ArgTokens.push_back(EOFTok); 389 ++NumActuals; 390 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed"); 391 --NumFixedArgsLeft; 392 } 393 394 // Okay, we either found the r_paren. Check to see if we parsed too few 395 // arguments. 396 unsigned MinArgsExpected = MI->getNumArgs(); 397 398 // See MacroArgs instance var for description of this. 399 bool isVarargsElided = false; 400 401 if (NumActuals < MinArgsExpected) { 402 // There are several cases where too few arguments is ok, handle them now. 403 if (NumActuals == 0 && MinArgsExpected == 1) { 404 // #define A(X) or #define A(...) ---> A() 405 406 // If there is exactly one argument, and that argument is missing, 407 // then we have an empty "()" argument empty list. This is fine, even if 408 // the macro expects one argument (the argument is just empty). 409 isVarargsElided = MI->isVariadic(); 410 } else if (MI->isVariadic() && 411 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X) 412 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A() 413 // Varargs where the named vararg parameter is missing: ok as extension. 414 // #define A(x, ...) 415 // A("blah") 416 Diag(Tok, diag::ext_missing_varargs_arg); 417 418 // Remember this occurred, allowing us to elide the comma when used for 419 // cases like: 420 // #define A(x, foo...) blah(a, ## foo) 421 // #define B(x, ...) blah(a, ## __VA_ARGS__) 422 // #define C(...) blah(a, ## __VA_ARGS__) 423 // A(x) B(x) C() 424 isVarargsElided = true; 425 } else { 426 // Otherwise, emit the error. 427 Diag(Tok, diag::err_too_few_args_in_macro_invoc); 428 return 0; 429 } 430 431 // Add a marker EOF token to the end of the token list for this argument. 432 SourceLocation EndLoc = Tok.getLocation(); 433 Tok.startToken(); 434 Tok.setKind(tok::eof); 435 Tok.setLocation(EndLoc); 436 Tok.setLength(0); 437 ArgTokens.push_back(Tok); 438 439 // If we expect two arguments, add both as empty. 440 if (NumActuals == 0 && MinArgsExpected == 2) 441 ArgTokens.push_back(Tok); 442 443 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) { 444 // Emit the diagnostic at the macro name in case there is a missing ). 445 // Emitting it at the , could be far away from the macro name. 446 Diag(MacroName, diag::err_too_many_args_in_macro_invoc); 447 return 0; 448 } 449 450 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(), 451 isVarargsElided, *this); 452} 453 454/// ComputeDATE_TIME - Compute the current time, enter it into the specified 455/// scratch buffer, then return DATELoc/TIMELoc locations with the position of 456/// the identifier tokens inserted. 457static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, 458 Preprocessor &PP) { 459 time_t TT = time(0); 460 struct tm *TM = localtime(&TT); 461 462 static const char * const Months[] = { 463 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" 464 }; 465 466 char TmpBuffer[100]; 467 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday, 468 TM->tm_year+1900); 469 470 Token TmpTok; 471 TmpTok.startToken(); 472 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok); 473 DATELoc = TmpTok.getLocation(); 474 475 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec); 476 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok); 477 TIMELoc = TmpTok.getLocation(); 478} 479 480 481/// HasFeature - Return true if we recognize and implement the specified feature 482/// specified by the identifier. 483static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) { 484 const LangOptions &LangOpts = PP.getLangOptions(); 485 486 return llvm::StringSwitch<bool>(II->getName()) 487 .Case("blocks", LangOpts.Blocks) 488 .Case("cxx_rtti", LangOpts.RTTI) 489 //.Case("cxx_lambdas", false) 490 //.Case("cxx_nullptr", false) 491 //.Case("cxx_concepts", false) 492 .Case("cxx_decltype", LangOpts.CPlusPlus0x) 493 .Case("cxx_auto_type", LangOpts.CPlusPlus0x) 494 .Case("cxx_exceptions", LangOpts.Exceptions) 495 .Case("cxx_attributes", LangOpts.CPlusPlus0x) 496 .Case("cxx_static_assert", LangOpts.CPlusPlus0x) 497 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI) 498 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x) 499 //.Case("cxx_rvalue_references", false) 500 .Case("attribute_overloadable", true) 501 //.Case("cxx_variadic_templates", false) 502 .Case("attribute_ext_vector_type", true) 503 .Case("attribute_analyzer_noreturn", true) 504 .Case("attribute_cf_returns_not_retained", true) 505 .Case("attribute_cf_returns_retained", true) 506 .Case("attribute_ns_returns_not_retained", true) 507 .Case("attribute_ns_returns_retained", true) 508 .Case("attribute_objc_ivar_unused", true) 509 .Default(false); 510} 511 512/// EvaluateHasIncludeCommon - Process a '__has_include("path")' 513/// or '__has_include_next("path")' expression. 514/// Returns true if successful. 515static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok, 516 IdentifierInfo *II, Preprocessor &PP, 517 const DirectoryLookup *LookupFrom) { 518 SourceLocation LParenLoc; 519 520 // Get '('. 521 PP.LexNonComment(Tok); 522 523 // Ensure we have a '('. 524 if (Tok.isNot(tok::l_paren)) { 525 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName(); 526 return false; 527 } 528 529 // Save '(' location for possible missing ')' message. 530 LParenLoc = Tok.getLocation(); 531 532 // Get the file name. 533 PP.getCurrentLexer()->LexIncludeFilename(Tok); 534 535 // Reserve a buffer to get the spelling. 536 llvm::SmallString<128> FilenameBuffer; 537 llvm::StringRef Filename; 538 539 switch (Tok.getKind()) { 540 case tok::eom: 541 // If the token kind is EOM, the error has already been diagnosed. 542 return false; 543 544 case tok::angle_string_literal: 545 case tok::string_literal: { 546 bool Invalid = false; 547 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid); 548 if (Invalid) 549 return false; 550 break; 551 } 552 553 case tok::less: 554 // This could be a <foo/bar.h> file coming from a macro expansion. In this 555 // case, glue the tokens together into FilenameBuffer and interpret those. 556 FilenameBuffer.push_back('<'); 557 if (PP.ConcatenateIncludeName(FilenameBuffer)) 558 return false; // Found <eom> but no ">"? Diagnostic already emitted. 559 Filename = FilenameBuffer.str(); 560 break; 561 default: 562 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename); 563 return false; 564 } 565 566 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename); 567 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 568 // error. 569 if (Filename.empty()) 570 return false; 571 572 // Search include directories. 573 const DirectoryLookup *CurDir; 574 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir); 575 576 // Get the result value. Result = true means the file exists. 577 Result = File != 0; 578 579 // Get ')'. 580 PP.LexNonComment(Tok); 581 582 // Ensure we have a trailing ). 583 if (Tok.isNot(tok::r_paren)) { 584 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName(); 585 PP.Diag(LParenLoc, diag::note_matching) << "("; 586 return false; 587 } 588 589 return true; 590} 591 592/// EvaluateHasInclude - Process a '__has_include("path")' expression. 593/// Returns true if successful. 594static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II, 595 Preprocessor &PP) { 596 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL)); 597} 598 599/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression. 600/// Returns true if successful. 601static bool EvaluateHasIncludeNext(bool &Result, Token &Tok, 602 IdentifierInfo *II, Preprocessor &PP) { 603 // __has_include_next is like __has_include, except that we start 604 // searching after the current found directory. If we can't do this, 605 // issue a diagnostic. 606 const DirectoryLookup *Lookup = PP.GetCurDirLookup(); 607 if (PP.isInPrimaryFile()) { 608 Lookup = 0; 609 PP.Diag(Tok, diag::pp_include_next_in_primary); 610 } else if (Lookup == 0) { 611 PP.Diag(Tok, diag::pp_include_next_absolute_path); 612 } else { 613 // Start looking up in the next directory. 614 ++Lookup; 615 } 616 617 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup)); 618} 619 620/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 621/// as a builtin macro, handle it and return the next token as 'Tok'. 622void Preprocessor::ExpandBuiltinMacro(Token &Tok) { 623 // Figure out which token this is. 624 IdentifierInfo *II = Tok.getIdentifierInfo(); 625 assert(II && "Can't be a macro without id info!"); 626 627 // If this is an _Pragma directive, expand it, invoke the pragma handler, then 628 // lex the token after it. 629 if (II == Ident_Pragma) 630 return Handle_Pragma(Tok); 631 632 ++NumBuiltinMacroExpanded; 633 634 llvm::SmallString<128> TmpBuffer; 635 llvm::raw_svector_ostream OS(TmpBuffer); 636 637 // Set up the return result. 638 Tok.setIdentifierInfo(0); 639 Tok.clearFlag(Token::NeedsCleaning); 640 641 if (II == Ident__LINE__) { 642 // C99 6.10.8: "__LINE__: The presumed line number (within the current 643 // source file) of the current source line (an integer constant)". This can 644 // be affected by #line. 645 SourceLocation Loc = Tok.getLocation(); 646 647 // Advance to the location of the first _, this might not be the first byte 648 // of the token if it starts with an escaped newline. 649 Loc = AdvanceToTokenCharacter(Loc, 0); 650 651 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of 652 // a macro instantiation. This doesn't matter for object-like macros, but 653 // can matter for a function-like macro that expands to contain __LINE__. 654 // Skip down through instantiation points until we find a file loc for the 655 // end of the instantiation history. 656 Loc = SourceMgr.getInstantiationRange(Loc).second; 657 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); 658 659 // __LINE__ expands to a simple numeric value. 660 OS << PLoc.getLine(); 661 Tok.setKind(tok::numeric_constant); 662 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) { 663 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a 664 // character string literal)". This can be affected by #line. 665 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 666 667 // __BASE_FILE__ is a GNU extension that returns the top of the presumed 668 // #include stack instead of the current file. 669 if (II == Ident__BASE_FILE__) { 670 SourceLocation NextLoc = PLoc.getIncludeLoc(); 671 while (NextLoc.isValid()) { 672 PLoc = SourceMgr.getPresumedLoc(NextLoc); 673 NextLoc = PLoc.getIncludeLoc(); 674 } 675 } 676 677 // Escape this filename. Turn '\' -> '\\' '"' -> '\"' 678 llvm::SmallString<128> FN; 679 FN += PLoc.getFilename(); 680 Lexer::Stringify(FN); 681 OS << '"' << FN.str() << '"'; 682 Tok.setKind(tok::string_literal); 683 } else if (II == Ident__DATE__) { 684 if (!DATELoc.isValid()) 685 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 686 Tok.setKind(tok::string_literal); 687 Tok.setLength(strlen("\"Mmm dd yyyy\"")); 688 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(), 689 Tok.getLocation(), 690 Tok.getLength())); 691 return; 692 } else if (II == Ident__TIME__) { 693 if (!TIMELoc.isValid()) 694 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 695 Tok.setKind(tok::string_literal); 696 Tok.setLength(strlen("\"hh:mm:ss\"")); 697 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(), 698 Tok.getLocation(), 699 Tok.getLength())); 700 return; 701 } else if (II == Ident__INCLUDE_LEVEL__) { 702 // Compute the presumed include depth of this token. This can be affected 703 // by GNU line markers. 704 unsigned Depth = 0; 705 706 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 707 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 708 for (; PLoc.isValid(); ++Depth) 709 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 710 711 // __INCLUDE_LEVEL__ expands to a simple numeric value. 712 OS << Depth; 713 Tok.setKind(tok::numeric_constant); 714 } else if (II == Ident__TIMESTAMP__) { 715 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be 716 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime. 717 718 // Get the file that we are lexing out of. If we're currently lexing from 719 // a macro, dig into the include stack. 720 const FileEntry *CurFile = 0; 721 PreprocessorLexer *TheLexer = getCurrentFileLexer(); 722 723 if (TheLexer) 724 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID()); 725 726 const char *Result; 727 if (CurFile) { 728 time_t TT = CurFile->getModificationTime(); 729 struct tm *TM = localtime(&TT); 730 Result = asctime(TM); 731 } else { 732 Result = "??? ??? ?? ??:??:?? ????\n"; 733 } 734 // Surround the string with " and strip the trailing newline. 735 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"'; 736 Tok.setKind(tok::string_literal); 737 } else if (II == Ident__COUNTER__) { 738 // __COUNTER__ expands to a simple numeric value. 739 OS << CounterValue++; 740 Tok.setKind(tok::numeric_constant); 741 } else if (II == Ident__has_feature || 742 II == Ident__has_builtin) { 743 // The argument to these two builtins should be a parenthesized identifier. 744 SourceLocation StartLoc = Tok.getLocation(); 745 746 bool IsValid = false; 747 IdentifierInfo *FeatureII = 0; 748 749 // Read the '('. 750 Lex(Tok); 751 if (Tok.is(tok::l_paren)) { 752 // Read the identifier 753 Lex(Tok); 754 if (Tok.is(tok::identifier)) { 755 FeatureII = Tok.getIdentifierInfo(); 756 757 // Read the ')'. 758 Lex(Tok); 759 if (Tok.is(tok::r_paren)) 760 IsValid = true; 761 } 762 } 763 764 bool Value = false; 765 if (!IsValid) 766 Diag(StartLoc, diag::err_feature_check_malformed); 767 else if (II == Ident__has_builtin) { 768 // Check for a builtin is trivial. 769 Value = FeatureII->getBuiltinID() != 0; 770 } else { 771 assert(II == Ident__has_feature && "Must be feature check"); 772 Value = HasFeature(*this, FeatureII); 773 } 774 775 OS << (int)Value; 776 Tok.setKind(tok::numeric_constant); 777 } else if (II == Ident__has_include || 778 II == Ident__has_include_next) { 779 // The argument to these two builtins should be a parenthesized 780 // file name string literal using angle brackets (<>) or 781 // double-quotes (""). 782 bool Value = false; 783 bool IsValid; 784 if (II == Ident__has_include) 785 IsValid = EvaluateHasInclude(Value, Tok, II, *this); 786 else 787 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this); 788 OS << (int)Value; 789 Tok.setKind(tok::numeric_constant); 790 } else { 791 assert(0 && "Unknown identifier!"); 792 } 793 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation()); 794} 795