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 expansion for the 11 // preprocessor. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Lex/Preprocessor.h" 16 #include "clang/Basic/Attributes.h" 17 #include "clang/Basic/FileManager.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "clang/Lex/CodeCompletionHandler.h" 21 #include "clang/Lex/ExternalPreprocessorSource.h" 22 #include "clang/Lex/LexDiagnostic.h" 23 #include "clang/Lex/MacroArgs.h" 24 #include "clang/Lex/MacroInfo.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallString.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/Config/llvm-config.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/Format.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <cstdio> 33 #include <ctime> 34 using namespace clang; 35 36 MacroDirective * 37 Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const { 38 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!"); 39 40 macro_iterator Pos = Macros.find(II); 41 assert(Pos != Macros.end() && "Identifier macro info is missing!"); 42 return Pos->second; 43 } 44 45 void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){ 46 assert(MD && "MacroDirective should be non-zero!"); 47 assert(!MD->getPrevious() && "Already attached to a MacroDirective history."); 48 49 MacroDirective *&StoredMD = Macros[II]; 50 MD->setPrevious(StoredMD); 51 StoredMD = MD; 52 II->setHasMacroDefinition(MD->isDefined()); 53 bool isImportedMacro = isa<DefMacroDirective>(MD) && 54 cast<DefMacroDirective>(MD)->isImported(); 55 if (II->isFromAST() && !isImportedMacro) 56 II->setChangedSinceDeserialization(); 57 } 58 59 void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II, 60 MacroDirective *MD) { 61 assert(II && MD); 62 MacroDirective *&StoredMD = Macros[II]; 63 assert(!StoredMD && 64 "the macro history was modified before initializing it from a pch"); 65 StoredMD = MD; 66 // Setup the identifier as having associated macro history. 67 II->setHasMacroDefinition(true); 68 if (!MD->isDefined()) 69 II->setHasMacroDefinition(false); 70 } 71 72 /// RegisterBuiltinMacro - Register the specified identifier in the identifier 73 /// table and mark it as a builtin macro to be expanded. 74 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ 75 // Get the identifier. 76 IdentifierInfo *Id = PP.getIdentifierInfo(Name); 77 78 // Mark it as being a macro that is builtin. 79 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); 80 MI->setIsBuiltinMacro(); 81 PP.appendDefMacroDirective(Id, MI); 82 return Id; 83 } 84 85 86 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 87 /// identifier table. 88 void Preprocessor::RegisterBuiltinMacros() { 89 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__"); 90 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__"); 91 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__"); 92 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__"); 93 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__"); 94 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma"); 95 96 // GCC Extensions. 97 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__"); 98 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__"); 99 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__"); 100 101 // Microsoft Extensions. 102 if (LangOpts.MicrosoftExt) { 103 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier"); 104 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma"); 105 } else { 106 Ident__identifier = 0; 107 Ident__pragma = 0; 108 } 109 110 // Clang Extensions. 111 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature"); 112 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension"); 113 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin"); 114 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute"); 115 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include"); 116 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next"); 117 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning"); 118 119 // Modules. 120 if (LangOpts.Modules) { 121 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module"); 122 123 // __MODULE__ 124 if (!LangOpts.CurrentModule.empty()) 125 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__"); 126 else 127 Ident__MODULE__ = 0; 128 } else { 129 Ident__building_module = 0; 130 Ident__MODULE__ = 0; 131 } 132 } 133 134 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token 135 /// in its expansion, currently expands to that token literally. 136 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, 137 const IdentifierInfo *MacroIdent, 138 Preprocessor &PP) { 139 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo(); 140 141 // If the token isn't an identifier, it's always literally expanded. 142 if (II == 0) return true; 143 144 // If the information about this identifier is out of date, update it from 145 // the external source. 146 if (II->isOutOfDate()) 147 PP.getExternalSource()->updateOutOfDateIdentifier(*II); 148 149 // If the identifier is a macro, and if that macro is enabled, it may be 150 // expanded so it's not a trivial expansion. 151 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() && 152 // Fast expanding "#define X X" is ok, because X would be disabled. 153 II != MacroIdent) 154 return false; 155 156 // If this is an object-like macro invocation, it is safe to trivially expand 157 // it. 158 if (MI->isObjectLike()) return true; 159 160 // If this is a function-like macro invocation, it's safe to trivially expand 161 // as long as the identifier is not a macro argument. 162 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 163 I != E; ++I) 164 if (*I == II) 165 return false; // Identifier is a macro argument. 166 167 return true; 168 } 169 170 171 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 172 /// lexed is a '('. If so, consume the token and return true, if not, this 173 /// method should have no observable side-effect on the lexed tokens. 174 bool Preprocessor::isNextPPTokenLParen() { 175 // Do some quick tests for rejection cases. 176 unsigned Val; 177 if (CurLexer) 178 Val = CurLexer->isNextPPTokenLParen(); 179 else if (CurPTHLexer) 180 Val = CurPTHLexer->isNextPPTokenLParen(); 181 else 182 Val = CurTokenLexer->isNextTokenLParen(); 183 184 if (Val == 2) { 185 // We have run off the end. If it's a source file we don't 186 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the 187 // macro stack. 188 if (CurPPLexer) 189 return false; 190 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { 191 IncludeStackInfo &Entry = IncludeMacroStack[i-1]; 192 if (Entry.TheLexer) 193 Val = Entry.TheLexer->isNextPPTokenLParen(); 194 else if (Entry.ThePTHLexer) 195 Val = Entry.ThePTHLexer->isNextPPTokenLParen(); 196 else 197 Val = Entry.TheTokenLexer->isNextTokenLParen(); 198 199 if (Val != 2) 200 break; 201 202 // Ran off the end of a source file? 203 if (Entry.ThePPLexer) 204 return false; 205 } 206 } 207 208 // Okay, if we know that the token is a '(', lex it and return. Otherwise we 209 // have found something that isn't a '(' or we found the end of the 210 // translation unit. In either case, return false. 211 return Val == 1; 212 } 213 214 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be 215 /// expanded as a macro, handle it and return the next token as 'Identifier'. 216 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, 217 MacroDirective *MD) { 218 MacroDirective::DefInfo Def = MD->getDefinition(); 219 assert(Def.isValid()); 220 MacroInfo *MI = Def.getMacroInfo(); 221 222 // If this is a macro expansion in the "#if !defined(x)" line for the file, 223 // then the macro could expand to different things in other contexts, we need 224 // to disable the optimization in this case. 225 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro(); 226 227 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially. 228 if (MI->isBuiltinMacro()) { 229 if (Callbacks) Callbacks->MacroExpands(Identifier, MD, 230 Identifier.getLocation(),/*Args=*/0); 231 ExpandBuiltinMacro(Identifier); 232 return true; 233 } 234 235 /// Args - If this is a function-like macro expansion, this contains, 236 /// for each macro argument, the list of tokens that were provided to the 237 /// invocation. 238 MacroArgs *Args = 0; 239 240 // Remember where the end of the expansion occurred. For an object-like 241 // macro, this is the identifier. For a function-like macro, this is the ')'. 242 SourceLocation ExpansionEnd = Identifier.getLocation(); 243 244 // If this is a function-like macro, read the arguments. 245 if (MI->isFunctionLike()) { 246 // Remember that we are now parsing the arguments to a macro invocation. 247 // Preprocessor directives used inside macro arguments are not portable, and 248 // this enables the warning. 249 InMacroArgs = true; 250 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd); 251 252 // Finished parsing args. 253 InMacroArgs = false; 254 255 // If there was an error parsing the arguments, bail out. 256 if (Args == 0) return true; 257 258 ++NumFnMacroExpanded; 259 } else { 260 ++NumMacroExpanded; 261 } 262 263 // Notice that this macro has been used. 264 markMacroAsUsed(MI); 265 266 // Remember where the token is expanded. 267 SourceLocation ExpandLoc = Identifier.getLocation(); 268 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd); 269 270 if (Callbacks) { 271 if (InMacroArgs) { 272 // We can have macro expansion inside a conditional directive while 273 // reading the function macro arguments. To ensure, in that case, that 274 // MacroExpands callbacks still happen in source order, queue this 275 // callback to have it happen after the function macro callback. 276 DelayedMacroExpandsCallbacks.push_back( 277 MacroExpandsInfo(Identifier, MD, ExpansionRange)); 278 } else { 279 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args); 280 if (!DelayedMacroExpandsCallbacks.empty()) { 281 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) { 282 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i]; 283 // FIXME: We lose macro args info with delayed callback. 284 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range, /*Args=*/0); 285 } 286 DelayedMacroExpandsCallbacks.clear(); 287 } 288 } 289 } 290 291 // If the macro definition is ambiguous, complain. 292 if (Def.getDirective()->isAmbiguous()) { 293 Diag(Identifier, diag::warn_pp_ambiguous_macro) 294 << Identifier.getIdentifierInfo(); 295 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen) 296 << Identifier.getIdentifierInfo(); 297 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition(); 298 PrevDef && !PrevDef.isUndefined(); 299 PrevDef = PrevDef.getPreviousDefinition()) { 300 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(), 301 diag::note_pp_ambiguous_macro_other) 302 << Identifier.getIdentifierInfo(); 303 if (!PrevDef.getDirective()->isAmbiguous()) 304 break; 305 } 306 } 307 308 // If we started lexing a macro, enter the macro expansion body. 309 310 // If this macro expands to no tokens, don't bother to push it onto the 311 // expansion stack, only to take it right back off. 312 if (MI->getNumTokens() == 0) { 313 // No need for arg info. 314 if (Args) Args->destroy(*this); 315 316 // Propagate whitespace info as if we had pushed, then popped, 317 // a macro context. 318 Identifier.setFlag(Token::LeadingEmptyMacro); 319 PropagateLineStartLeadingSpaceInfo(Identifier); 320 ++NumFastMacroExpanded; 321 return false; 322 } else if (MI->getNumTokens() == 1 && 323 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(), 324 *this)) { 325 // Otherwise, if this macro expands into a single trivially-expanded 326 // token: expand it now. This handles common cases like 327 // "#define VAL 42". 328 329 // No need for arg info. 330 if (Args) Args->destroy(*this); 331 332 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro 333 // identifier to the expanded token. 334 bool isAtStartOfLine = Identifier.isAtStartOfLine(); 335 bool hasLeadingSpace = Identifier.hasLeadingSpace(); 336 337 // Replace the result token. 338 Identifier = MI->getReplacementToken(0); 339 340 // Restore the StartOfLine/LeadingSpace markers. 341 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine); 342 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace); 343 344 // Update the tokens location to include both its expansion and physical 345 // locations. 346 SourceLocation Loc = 347 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc, 348 ExpansionEnd,Identifier.getLength()); 349 Identifier.setLocation(Loc); 350 351 // If this is a disabled macro or #define X X, we must mark the result as 352 // unexpandable. 353 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) { 354 if (MacroInfo *NewMI = getMacroInfo(NewII)) 355 if (!NewMI->isEnabled() || NewMI == MI) { 356 Identifier.setFlag(Token::DisableExpand); 357 // Don't warn for "#define X X" like "#define bool bool" from 358 // stdbool.h. 359 if (NewMI != MI || MI->isFunctionLike()) 360 Diag(Identifier, diag::pp_disabled_macro_expansion); 361 } 362 } 363 364 // Since this is not an identifier token, it can't be macro expanded, so 365 // we're done. 366 ++NumFastMacroExpanded; 367 return true; 368 } 369 370 // Start expanding the macro. 371 EnterMacro(Identifier, ExpansionEnd, MI, Args); 372 return false; 373 } 374 375 enum Bracket { 376 Brace, 377 Paren 378 }; 379 380 /// CheckMatchedBrackets - Returns true if the braces and parentheses in the 381 /// token vector are properly nested. 382 static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) { 383 SmallVector<Bracket, 8> Brackets; 384 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(), 385 E = Tokens.end(); 386 I != E; ++I) { 387 if (I->is(tok::l_paren)) { 388 Brackets.push_back(Paren); 389 } else if (I->is(tok::r_paren)) { 390 if (Brackets.empty() || Brackets.back() == Brace) 391 return false; 392 Brackets.pop_back(); 393 } else if (I->is(tok::l_brace)) { 394 Brackets.push_back(Brace); 395 } else if (I->is(tok::r_brace)) { 396 if (Brackets.empty() || Brackets.back() == Paren) 397 return false; 398 Brackets.pop_back(); 399 } 400 } 401 if (!Brackets.empty()) 402 return false; 403 return true; 404 } 405 406 /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new 407 /// vector of tokens in NewTokens. The new number of arguments will be placed 408 /// in NumArgs and the ranges which need to surrounded in parentheses will be 409 /// in ParenHints. 410 /// Returns false if the token stream cannot be changed. If this is because 411 /// of an initializer list starting a macro argument, the range of those 412 /// initializer lists will be place in InitLists. 413 static bool GenerateNewArgTokens(Preprocessor &PP, 414 SmallVectorImpl<Token> &OldTokens, 415 SmallVectorImpl<Token> &NewTokens, 416 unsigned &NumArgs, 417 SmallVectorImpl<SourceRange> &ParenHints, 418 SmallVectorImpl<SourceRange> &InitLists) { 419 if (!CheckMatchedBrackets(OldTokens)) 420 return false; 421 422 // Once it is known that the brackets are matched, only a simple count of the 423 // braces is needed. 424 unsigned Braces = 0; 425 426 // First token of a new macro argument. 427 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin(); 428 429 // First closing brace in a new macro argument. Used to generate 430 // SourceRanges for InitLists. 431 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end(); 432 NumArgs = 0; 433 Token TempToken; 434 // Set to true when a macro separator token is found inside a braced list. 435 // If true, the fixed argument spans multiple old arguments and ParenHints 436 // will be updated. 437 bool FoundSeparatorToken = false; 438 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(), 439 E = OldTokens.end(); 440 I != E; ++I) { 441 if (I->is(tok::l_brace)) { 442 ++Braces; 443 } else if (I->is(tok::r_brace)) { 444 --Braces; 445 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken) 446 ClosingBrace = I; 447 } else if (I->is(tok::eof)) { 448 // EOF token is used to separate macro arguments 449 if (Braces != 0) { 450 // Assume comma separator is actually braced list separator and change 451 // it back to a comma. 452 FoundSeparatorToken = true; 453 I->setKind(tok::comma); 454 I->setLength(1); 455 } else { // Braces == 0 456 // Separator token still separates arguments. 457 ++NumArgs; 458 459 // If the argument starts with a brace, it can't be fixed with 460 // parentheses. A different diagnostic will be given. 461 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) { 462 InitLists.push_back( 463 SourceRange(ArgStartIterator->getLocation(), 464 PP.getLocForEndOfToken(ClosingBrace->getLocation()))); 465 ClosingBrace = E; 466 } 467 468 // Add left paren 469 if (FoundSeparatorToken) { 470 TempToken.startToken(); 471 TempToken.setKind(tok::l_paren); 472 TempToken.setLocation(ArgStartIterator->getLocation()); 473 TempToken.setLength(0); 474 NewTokens.push_back(TempToken); 475 } 476 477 // Copy over argument tokens 478 NewTokens.insert(NewTokens.end(), ArgStartIterator, I); 479 480 // Add right paren and store the paren locations in ParenHints 481 if (FoundSeparatorToken) { 482 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation()); 483 TempToken.startToken(); 484 TempToken.setKind(tok::r_paren); 485 TempToken.setLocation(Loc); 486 TempToken.setLength(0); 487 NewTokens.push_back(TempToken); 488 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(), 489 Loc)); 490 } 491 492 // Copy separator token 493 NewTokens.push_back(*I); 494 495 // Reset values 496 ArgStartIterator = I + 1; 497 FoundSeparatorToken = false; 498 } 499 } 500 } 501 502 return !ParenHints.empty() && InitLists.empty(); 503 } 504 505 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next 506 /// token is the '(' of the macro, this method is invoked to read all of the 507 /// actual arguments specified for the macro invocation. This returns null on 508 /// error. 509 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, 510 MacroInfo *MI, 511 SourceLocation &MacroEnd) { 512 // The number of fixed arguments to parse. 513 unsigned NumFixedArgsLeft = MI->getNumArgs(); 514 bool isVariadic = MI->isVariadic(); 515 516 // Outer loop, while there are more arguments, keep reading them. 517 Token Tok; 518 519 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 520 // an argument value in a macro could expand to ',' or '(' or ')'. 521 LexUnexpandedToken(Tok); 522 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?"); 523 524 // ArgTokens - Build up a list of tokens that make up each argument. Each 525 // argument is separated by an EOF token. Use a SmallVector so we can avoid 526 // heap allocations in the common case. 527 SmallVector<Token, 64> ArgTokens; 528 bool ContainsCodeCompletionTok = false; 529 530 SourceLocation TooManyArgsLoc; 531 532 unsigned NumActuals = 0; 533 while (Tok.isNot(tok::r_paren)) { 534 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod))) 535 break; 536 537 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) && 538 "only expect argument separators here"); 539 540 unsigned ArgTokenStart = ArgTokens.size(); 541 SourceLocation ArgStartLoc = Tok.getLocation(); 542 543 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note 544 // that we already consumed the first one. 545 unsigned NumParens = 0; 546 547 while (1) { 548 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 549 // an argument value in a macro could expand to ',' or '(' or ')'. 550 LexUnexpandedToken(Tok); 551 552 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n" 553 if (!ContainsCodeCompletionTok) { 554 Diag(MacroName, diag::err_unterm_macro_invoc); 555 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 556 << MacroName.getIdentifierInfo(); 557 // Do not lose the EOF/EOD. Return it to the client. 558 MacroName = Tok; 559 return 0; 560 } else { 561 // Do not lose the EOF/EOD. 562 Token *Toks = new Token[1]; 563 Toks[0] = Tok; 564 EnterTokenStream(Toks, 1, true, true); 565 break; 566 } 567 } else if (Tok.is(tok::r_paren)) { 568 // If we found the ) token, the macro arg list is done. 569 if (NumParens-- == 0) { 570 MacroEnd = Tok.getLocation(); 571 break; 572 } 573 } else if (Tok.is(tok::l_paren)) { 574 ++NumParens; 575 } else if (Tok.is(tok::comma) && NumParens == 0 && 576 !(Tok.getFlags() & Token::IgnoredComma)) { 577 // In Microsoft-compatibility mode, single commas from nested macro 578 // expansions should not be considered as argument separators. We test 579 // for this with the IgnoredComma token flag above. 580 581 // Comma ends this argument if there are more fixed arguments expected. 582 // However, if this is a variadic macro, and this is part of the 583 // variadic part, then the comma is just an argument token. 584 if (!isVariadic) break; 585 if (NumFixedArgsLeft > 1) 586 break; 587 } else if (Tok.is(tok::comment) && !KeepMacroComments) { 588 // If this is a comment token in the argument list and we're just in 589 // -C mode (not -CC mode), discard the comment. 590 continue; 591 } else if (Tok.getIdentifierInfo() != 0) { 592 // Reading macro arguments can cause macros that we are currently 593 // expanding from to be popped off the expansion stack. Doing so causes 594 // them to be reenabled for expansion. Here we record whether any 595 // identifiers we lex as macro arguments correspond to disabled macros. 596 // If so, we mark the token as noexpand. This is a subtle aspect of 597 // C99 6.10.3.4p2. 598 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo())) 599 if (!MI->isEnabled()) 600 Tok.setFlag(Token::DisableExpand); 601 } else if (Tok.is(tok::code_completion)) { 602 ContainsCodeCompletionTok = true; 603 if (CodeComplete) 604 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(), 605 MI, NumActuals); 606 // Don't mark that we reached the code-completion point because the 607 // parser is going to handle the token and there will be another 608 // code-completion callback. 609 } 610 611 ArgTokens.push_back(Tok); 612 } 613 614 // If this was an empty argument list foo(), don't add this as an empty 615 // argument. 616 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren) 617 break; 618 619 // If this is not a variadic macro, and too many args were specified, emit 620 // an error. 621 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) { 622 if (ArgTokens.size() != ArgTokenStart) 623 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation(); 624 else 625 TooManyArgsLoc = ArgStartLoc; 626 } 627 628 // Empty arguments are standard in C99 and C++0x, and are supported as an 629 // extension in other modes. 630 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99) 631 Diag(Tok, LangOpts.CPlusPlus11 ? 632 diag::warn_cxx98_compat_empty_fnmacro_arg : 633 diag::ext_empty_fnmacro_arg); 634 635 // Add a marker EOF token to the end of the token list for this argument. 636 Token EOFTok; 637 EOFTok.startToken(); 638 EOFTok.setKind(tok::eof); 639 EOFTok.setLocation(Tok.getLocation()); 640 EOFTok.setLength(0); 641 ArgTokens.push_back(EOFTok); 642 ++NumActuals; 643 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0) 644 --NumFixedArgsLeft; 645 } 646 647 // Okay, we either found the r_paren. Check to see if we parsed too few 648 // arguments. 649 unsigned MinArgsExpected = MI->getNumArgs(); 650 651 // If this is not a variadic macro, and too many args were specified, emit 652 // an error. 653 if (!isVariadic && NumActuals > MinArgsExpected && 654 !ContainsCodeCompletionTok) { 655 // Emit the diagnostic at the macro name in case there is a missing ). 656 // Emitting it at the , could be far away from the macro name. 657 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc); 658 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 659 << MacroName.getIdentifierInfo(); 660 661 // Commas from braced initializer lists will be treated as argument 662 // separators inside macros. Attempt to correct for this with parentheses. 663 // TODO: See if this can be generalized to angle brackets for templates 664 // inside macro arguments. 665 666 SmallVector<Token, 4> FixedArgTokens; 667 unsigned FixedNumArgs = 0; 668 SmallVector<SourceRange, 4> ParenHints, InitLists; 669 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs, 670 ParenHints, InitLists)) { 671 if (!InitLists.empty()) { 672 DiagnosticBuilder DB = 673 Diag(MacroName, 674 diag::note_init_list_at_beginning_of_macro_argument); 675 for (SmallVector<SourceRange, 4>::iterator 676 Range = InitLists.begin(), RangeEnd = InitLists.end(); 677 Range != RangeEnd; ++Range) { 678 if (DB.hasMaxRanges()) 679 break; 680 DB << *Range; 681 } 682 } 683 return 0; 684 } 685 if (FixedNumArgs != MinArgsExpected) 686 return 0; 687 688 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro); 689 for (SmallVector<SourceRange, 4>::iterator 690 ParenLocation = ParenHints.begin(), ParenEnd = ParenHints.end(); 691 ParenLocation != ParenEnd; ++ParenLocation) { 692 if (DB.hasMaxFixItHints()) 693 break; 694 DB << FixItHint::CreateInsertion(ParenLocation->getBegin(), "("); 695 if (DB.hasMaxFixItHints()) 696 break; 697 DB << FixItHint::CreateInsertion(ParenLocation->getEnd(), ")"); 698 } 699 ArgTokens.swap(FixedArgTokens); 700 NumActuals = FixedNumArgs; 701 } 702 703 // See MacroArgs instance var for description of this. 704 bool isVarargsElided = false; 705 706 if (ContainsCodeCompletionTok) { 707 // Recover from not-fully-formed macro invocation during code-completion. 708 Token EOFTok; 709 EOFTok.startToken(); 710 EOFTok.setKind(tok::eof); 711 EOFTok.setLocation(Tok.getLocation()); 712 EOFTok.setLength(0); 713 for (; NumActuals < MinArgsExpected; ++NumActuals) 714 ArgTokens.push_back(EOFTok); 715 } 716 717 if (NumActuals < MinArgsExpected) { 718 // There are several cases where too few arguments is ok, handle them now. 719 if (NumActuals == 0 && MinArgsExpected == 1) { 720 // #define A(X) or #define A(...) ---> A() 721 722 // If there is exactly one argument, and that argument is missing, 723 // then we have an empty "()" argument empty list. This is fine, even if 724 // the macro expects one argument (the argument is just empty). 725 isVarargsElided = MI->isVariadic(); 726 } else if (MI->isVariadic() && 727 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X) 728 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A() 729 // Varargs where the named vararg parameter is missing: OK as extension. 730 // #define A(x, ...) 731 // A("blah") 732 // 733 // If the macro contains the comma pasting extension, the diagnostic 734 // is suppressed; we know we'll get another diagnostic later. 735 if (!MI->hasCommaPasting()) { 736 Diag(Tok, diag::ext_missing_varargs_arg); 737 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 738 << MacroName.getIdentifierInfo(); 739 } 740 741 // Remember this occurred, allowing us to elide the comma when used for 742 // cases like: 743 // #define A(x, foo...) blah(a, ## foo) 744 // #define B(x, ...) blah(a, ## __VA_ARGS__) 745 // #define C(...) blah(a, ## __VA_ARGS__) 746 // A(x) B(x) C() 747 isVarargsElided = true; 748 } else if (!ContainsCodeCompletionTok) { 749 // Otherwise, emit the error. 750 Diag(Tok, diag::err_too_few_args_in_macro_invoc); 751 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 752 << MacroName.getIdentifierInfo(); 753 return 0; 754 } 755 756 // Add a marker EOF token to the end of the token list for this argument. 757 SourceLocation EndLoc = Tok.getLocation(); 758 Tok.startToken(); 759 Tok.setKind(tok::eof); 760 Tok.setLocation(EndLoc); 761 Tok.setLength(0); 762 ArgTokens.push_back(Tok); 763 764 // If we expect two arguments, add both as empty. 765 if (NumActuals == 0 && MinArgsExpected == 2) 766 ArgTokens.push_back(Tok); 767 768 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() && 769 !ContainsCodeCompletionTok) { 770 // Emit the diagnostic at the macro name in case there is a missing ). 771 // Emitting it at the , could be far away from the macro name. 772 Diag(MacroName, diag::err_too_many_args_in_macro_invoc); 773 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 774 << MacroName.getIdentifierInfo(); 775 return 0; 776 } 777 778 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this); 779 } 780 781 /// \brief Keeps macro expanded tokens for TokenLexers. 782 // 783 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is 784 /// going to lex in the cache and when it finishes the tokens are removed 785 /// from the end of the cache. 786 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer, 787 ArrayRef<Token> tokens) { 788 assert(tokLexer); 789 if (tokens.empty()) 790 return 0; 791 792 size_t newIndex = MacroExpandedTokens.size(); 793 bool cacheNeedsToGrow = tokens.size() > 794 MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); 795 MacroExpandedTokens.append(tokens.begin(), tokens.end()); 796 797 if (cacheNeedsToGrow) { 798 // Go through all the TokenLexers whose 'Tokens' pointer points in the 799 // buffer and update the pointers to the (potential) new buffer array. 800 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) { 801 TokenLexer *prevLexer; 802 size_t tokIndex; 803 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i]; 804 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex; 805 } 806 } 807 808 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex)); 809 return MacroExpandedTokens.data() + newIndex; 810 } 811 812 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() { 813 assert(!MacroExpandingLexersStack.empty()); 814 size_t tokIndex = MacroExpandingLexersStack.back().second; 815 assert(tokIndex < MacroExpandedTokens.size()); 816 // Pop the cached macro expanded tokens from the end. 817 MacroExpandedTokens.resize(tokIndex); 818 MacroExpandingLexersStack.pop_back(); 819 } 820 821 /// ComputeDATE_TIME - Compute the current time, enter it into the specified 822 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of 823 /// the identifier tokens inserted. 824 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, 825 Preprocessor &PP) { 826 time_t TT = time(0); 827 struct tm *TM = localtime(&TT); 828 829 static const char * const Months[] = { 830 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" 831 }; 832 833 { 834 SmallString<32> TmpBuffer; 835 llvm::raw_svector_ostream TmpStream(TmpBuffer); 836 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon], 837 TM->tm_mday, TM->tm_year + 1900); 838 Token TmpTok; 839 TmpTok.startToken(); 840 PP.CreateString(TmpStream.str(), TmpTok); 841 DATELoc = TmpTok.getLocation(); 842 } 843 844 { 845 SmallString<32> TmpBuffer; 846 llvm::raw_svector_ostream TmpStream(TmpBuffer); 847 TmpStream << llvm::format("\"%02d:%02d:%02d\"", 848 TM->tm_hour, TM->tm_min, TM->tm_sec); 849 Token TmpTok; 850 TmpTok.startToken(); 851 PP.CreateString(TmpStream.str(), TmpTok); 852 TIMELoc = TmpTok.getLocation(); 853 } 854 } 855 856 857 /// HasFeature - Return true if we recognize and implement the feature 858 /// specified by the identifier as a standard language feature. 859 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) { 860 const LangOptions &LangOpts = PP.getLangOpts(); 861 StringRef Feature = II->getName(); 862 863 // Normalize the feature name, __foo__ becomes foo. 864 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4) 865 Feature = Feature.substr(2, Feature.size() - 4); 866 867 return llvm::StringSwitch<bool>(Feature) 868 .Case("address_sanitizer", LangOpts.Sanitize.Address) 869 .Case("attribute_analyzer_noreturn", true) 870 .Case("attribute_availability", true) 871 .Case("attribute_availability_with_message", true) 872 .Case("attribute_cf_returns_not_retained", true) 873 .Case("attribute_cf_returns_retained", true) 874 .Case("attribute_deprecated_with_message", true) 875 .Case("attribute_ext_vector_type", true) 876 .Case("attribute_ns_returns_not_retained", true) 877 .Case("attribute_ns_returns_retained", true) 878 .Case("attribute_ns_consumes_self", true) 879 .Case("attribute_ns_consumed", true) 880 .Case("attribute_cf_consumed", true) 881 .Case("attribute_objc_ivar_unused", true) 882 .Case("attribute_objc_method_family", true) 883 .Case("attribute_overloadable", true) 884 .Case("attribute_unavailable_with_message", true) 885 .Case("attribute_unused_on_fields", true) 886 .Case("blocks", LangOpts.Blocks) 887 .Case("c_thread_safety_attributes", true) 888 .Case("cxx_exceptions", LangOpts.Exceptions) 889 .Case("cxx_rtti", LangOpts.RTTI) 890 .Case("enumerator_attributes", true) 891 .Case("memory_sanitizer", LangOpts.Sanitize.Memory) 892 .Case("thread_sanitizer", LangOpts.Sanitize.Thread) 893 .Case("dataflow_sanitizer", LangOpts.Sanitize.DataFlow) 894 // Objective-C features 895 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE? 896 .Case("objc_arc", LangOpts.ObjCAutoRefCount) 897 .Case("objc_arc_weak", LangOpts.ObjCARCWeak) 898 .Case("objc_default_synthesize_properties", LangOpts.ObjC2) 899 .Case("objc_fixed_enum", LangOpts.ObjC2) 900 .Case("objc_instancetype", LangOpts.ObjC2) 901 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules) 902 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile()) 903 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword? 904 .Case("objc_protocol_qualifier_mangling", true) 905 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport()) 906 .Case("ownership_holds", true) 907 .Case("ownership_returns", true) 908 .Case("ownership_takes", true) 909 .Case("objc_bool", true) 910 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile()) 911 .Case("objc_array_literals", LangOpts.ObjC2) 912 .Case("objc_dictionary_literals", LangOpts.ObjC2) 913 .Case("objc_boxed_expressions", LangOpts.ObjC2) 914 .Case("arc_cf_code_audited", true) 915 // C11 features 916 .Case("c_alignas", LangOpts.C11) 917 .Case("c_atomic", LangOpts.C11) 918 .Case("c_generic_selections", LangOpts.C11) 919 .Case("c_static_assert", LangOpts.C11) 920 .Case("c_thread_local", 921 LangOpts.C11 && PP.getTargetInfo().isTLSSupported()) 922 // C++11 features 923 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11) 924 .Case("cxx_alias_templates", LangOpts.CPlusPlus11) 925 .Case("cxx_alignas", LangOpts.CPlusPlus11) 926 .Case("cxx_atomic", LangOpts.CPlusPlus11) 927 .Case("cxx_attributes", LangOpts.CPlusPlus11) 928 .Case("cxx_auto_type", LangOpts.CPlusPlus11) 929 .Case("cxx_constexpr", LangOpts.CPlusPlus11) 930 .Case("cxx_decltype", LangOpts.CPlusPlus11) 931 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11) 932 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11) 933 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11) 934 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11) 935 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11) 936 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11) 937 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11) 938 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11) 939 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11) 940 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11) 941 .Case("cxx_lambdas", LangOpts.CPlusPlus11) 942 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11) 943 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11) 944 .Case("cxx_noexcept", LangOpts.CPlusPlus11) 945 .Case("cxx_nullptr", LangOpts.CPlusPlus11) 946 .Case("cxx_override_control", LangOpts.CPlusPlus11) 947 .Case("cxx_range_for", LangOpts.CPlusPlus11) 948 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11) 949 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11) 950 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11) 951 .Case("cxx_strong_enums", LangOpts.CPlusPlus11) 952 .Case("cxx_static_assert", LangOpts.CPlusPlus11) 953 .Case("cxx_thread_local", 954 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported()) 955 .Case("cxx_trailing_return", LangOpts.CPlusPlus11) 956 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11) 957 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11) 958 .Case("cxx_user_literals", LangOpts.CPlusPlus11) 959 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11) 960 // C++1y features 961 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus1y) 962 .Case("cxx_binary_literals", LangOpts.CPlusPlus1y) 963 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus1y) 964 //.Case("cxx_generic_lambdas", LangOpts.CPlusPlus1y) 965 .Case("cxx_init_captures", LangOpts.CPlusPlus1y) 966 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus1y) 967 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus1y) 968 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlus1y) 969 .Case("cxx_variable_templates", LangOpts.CPlusPlus1y) 970 // Type traits 971 .Case("has_nothrow_assign", LangOpts.CPlusPlus) 972 .Case("has_nothrow_copy", LangOpts.CPlusPlus) 973 .Case("has_nothrow_constructor", LangOpts.CPlusPlus) 974 .Case("has_trivial_assign", LangOpts.CPlusPlus) 975 .Case("has_trivial_copy", LangOpts.CPlusPlus) 976 .Case("has_trivial_constructor", LangOpts.CPlusPlus) 977 .Case("has_trivial_destructor", LangOpts.CPlusPlus) 978 .Case("has_virtual_destructor", LangOpts.CPlusPlus) 979 .Case("is_abstract", LangOpts.CPlusPlus) 980 .Case("is_base_of", LangOpts.CPlusPlus) 981 .Case("is_class", LangOpts.CPlusPlus) 982 .Case("is_constructible", LangOpts.CPlusPlus) 983 .Case("is_convertible_to", LangOpts.CPlusPlus) 984 .Case("is_empty", LangOpts.CPlusPlus) 985 .Case("is_enum", LangOpts.CPlusPlus) 986 .Case("is_final", LangOpts.CPlusPlus) 987 .Case("is_literal", LangOpts.CPlusPlus) 988 .Case("is_standard_layout", LangOpts.CPlusPlus) 989 .Case("is_pod", LangOpts.CPlusPlus) 990 .Case("is_polymorphic", LangOpts.CPlusPlus) 991 .Case("is_sealed", LangOpts.MicrosoftExt) 992 .Case("is_trivial", LangOpts.CPlusPlus) 993 .Case("is_trivially_assignable", LangOpts.CPlusPlus) 994 .Case("is_trivially_constructible", LangOpts.CPlusPlus) 995 .Case("is_trivially_copyable", LangOpts.CPlusPlus) 996 .Case("is_union", LangOpts.CPlusPlus) 997 .Case("modules", LangOpts.Modules) 998 .Case("tls", PP.getTargetInfo().isTLSSupported()) 999 .Case("underlying_type", LangOpts.CPlusPlus) 1000 .Default(false); 1001 } 1002 1003 /// HasExtension - Return true if we recognize and implement the feature 1004 /// specified by the identifier, either as an extension or a standard language 1005 /// feature. 1006 static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) { 1007 if (HasFeature(PP, II)) 1008 return true; 1009 1010 // If the use of an extension results in an error diagnostic, extensions are 1011 // effectively unavailable, so just return false here. 1012 if (PP.getDiagnostics().getExtensionHandlingBehavior() == 1013 DiagnosticsEngine::Ext_Error) 1014 return false; 1015 1016 const LangOptions &LangOpts = PP.getLangOpts(); 1017 StringRef Extension = II->getName(); 1018 1019 // Normalize the extension name, __foo__ becomes foo. 1020 if (Extension.startswith("__") && Extension.endswith("__") && 1021 Extension.size() >= 4) 1022 Extension = Extension.substr(2, Extension.size() - 4); 1023 1024 // Because we inherit the feature list from HasFeature, this string switch 1025 // must be less restrictive than HasFeature's. 1026 return llvm::StringSwitch<bool>(Extension) 1027 // C11 features supported by other languages as extensions. 1028 .Case("c_alignas", true) 1029 .Case("c_atomic", true) 1030 .Case("c_generic_selections", true) 1031 .Case("c_static_assert", true) 1032 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported()) 1033 // C++11 features supported by other languages as extensions. 1034 .Case("cxx_atomic", LangOpts.CPlusPlus) 1035 .Case("cxx_deleted_functions", LangOpts.CPlusPlus) 1036 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus) 1037 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus) 1038 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus) 1039 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus) 1040 .Case("cxx_override_control", LangOpts.CPlusPlus) 1041 .Case("cxx_range_for", LangOpts.CPlusPlus) 1042 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus) 1043 .Case("cxx_rvalue_references", LangOpts.CPlusPlus) 1044 // C++1y features supported by other languages as extensions. 1045 .Case("cxx_binary_literals", true) 1046 .Case("cxx_init_captures", LangOpts.CPlusPlus11) 1047 .Case("cxx_variable_templates", LangOpts.CPlusPlus) 1048 .Default(false); 1049 } 1050 1051 /// EvaluateHasIncludeCommon - Process a '__has_include("path")' 1052 /// or '__has_include_next("path")' expression. 1053 /// Returns true if successful. 1054 static bool EvaluateHasIncludeCommon(Token &Tok, 1055 IdentifierInfo *II, Preprocessor &PP, 1056 const DirectoryLookup *LookupFrom) { 1057 // Save the location of the current token. If a '(' is later found, use 1058 // that location. If not, use the end of this location instead. 1059 SourceLocation LParenLoc = Tok.getLocation(); 1060 1061 // These expressions are only allowed within a preprocessor directive. 1062 if (!PP.isParsingIfOrElifDirective()) { 1063 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName(); 1064 return false; 1065 } 1066 1067 // Get '('. 1068 PP.LexNonComment(Tok); 1069 1070 // Ensure we have a '('. 1071 if (Tok.isNot(tok::l_paren)) { 1072 // No '(', use end of last token. 1073 LParenLoc = PP.getLocForEndOfToken(LParenLoc); 1074 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren; 1075 // If the next token looks like a filename or the start of one, 1076 // assume it is and process it as such. 1077 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) && 1078 !Tok.is(tok::less)) 1079 return false; 1080 } else { 1081 // Save '(' location for possible missing ')' message. 1082 LParenLoc = Tok.getLocation(); 1083 1084 if (PP.getCurrentLexer()) { 1085 // Get the file name. 1086 PP.getCurrentLexer()->LexIncludeFilename(Tok); 1087 } else { 1088 // We're in a macro, so we can't use LexIncludeFilename; just 1089 // grab the next token. 1090 PP.Lex(Tok); 1091 } 1092 } 1093 1094 // Reserve a buffer to get the spelling. 1095 SmallString<128> FilenameBuffer; 1096 StringRef Filename; 1097 SourceLocation EndLoc; 1098 1099 switch (Tok.getKind()) { 1100 case tok::eod: 1101 // If the token kind is EOD, the error has already been diagnosed. 1102 return false; 1103 1104 case tok::angle_string_literal: 1105 case tok::string_literal: { 1106 bool Invalid = false; 1107 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid); 1108 if (Invalid) 1109 return false; 1110 break; 1111 } 1112 1113 case tok::less: 1114 // This could be a <foo/bar.h> file coming from a macro expansion. In this 1115 // case, glue the tokens together into FilenameBuffer and interpret those. 1116 FilenameBuffer.push_back('<'); 1117 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) { 1118 // Let the caller know a <eod> was found by changing the Token kind. 1119 Tok.setKind(tok::eod); 1120 return false; // Found <eod> but no ">"? Diagnostic already emitted. 1121 } 1122 Filename = FilenameBuffer.str(); 1123 break; 1124 default: 1125 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename); 1126 return false; 1127 } 1128 1129 SourceLocation FilenameLoc = Tok.getLocation(); 1130 1131 // Get ')'. 1132 PP.LexNonComment(Tok); 1133 1134 // Ensure we have a trailing ). 1135 if (Tok.isNot(tok::r_paren)) { 1136 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after) 1137 << II << tok::r_paren; 1138 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; 1139 return false; 1140 } 1141 1142 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename); 1143 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 1144 // error. 1145 if (Filename.empty()) 1146 return false; 1147 1148 // Search include directories. 1149 const DirectoryLookup *CurDir; 1150 const FileEntry *File = 1151 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir, NULL, 1152 NULL, NULL); 1153 1154 // Get the result value. A result of true means the file exists. 1155 return File != 0; 1156 } 1157 1158 /// EvaluateHasInclude - Process a '__has_include("path")' expression. 1159 /// Returns true if successful. 1160 static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II, 1161 Preprocessor &PP) { 1162 return EvaluateHasIncludeCommon(Tok, II, PP, NULL); 1163 } 1164 1165 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression. 1166 /// Returns true if successful. 1167 static bool EvaluateHasIncludeNext(Token &Tok, 1168 IdentifierInfo *II, Preprocessor &PP) { 1169 // __has_include_next is like __has_include, except that we start 1170 // searching after the current found directory. If we can't do this, 1171 // issue a diagnostic. 1172 const DirectoryLookup *Lookup = PP.GetCurDirLookup(); 1173 if (PP.isInPrimaryFile()) { 1174 Lookup = 0; 1175 PP.Diag(Tok, diag::pp_include_next_in_primary); 1176 } else if (Lookup == 0) { 1177 PP.Diag(Tok, diag::pp_include_next_absolute_path); 1178 } else { 1179 // Start looking up in the next directory. 1180 ++Lookup; 1181 } 1182 1183 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup); 1184 } 1185 1186 /// \brief Process __building_module(identifier) expression. 1187 /// \returns true if we are building the named module, false otherwise. 1188 static bool EvaluateBuildingModule(Token &Tok, 1189 IdentifierInfo *II, Preprocessor &PP) { 1190 // Get '('. 1191 PP.LexNonComment(Tok); 1192 1193 // Ensure we have a '('. 1194 if (Tok.isNot(tok::l_paren)) { 1195 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II 1196 << tok::l_paren; 1197 return false; 1198 } 1199 1200 // Save '(' location for possible missing ')' message. 1201 SourceLocation LParenLoc = Tok.getLocation(); 1202 1203 // Get the module name. 1204 PP.LexNonComment(Tok); 1205 1206 // Ensure that we have an identifier. 1207 if (Tok.isNot(tok::identifier)) { 1208 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module); 1209 return false; 1210 } 1211 1212 bool Result 1213 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule; 1214 1215 // Get ')'. 1216 PP.LexNonComment(Tok); 1217 1218 // Ensure we have a trailing ). 1219 if (Tok.isNot(tok::r_paren)) { 1220 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II 1221 << tok::r_paren; 1222 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; 1223 return false; 1224 } 1225 1226 return Result; 1227 } 1228 1229 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 1230 /// as a builtin macro, handle it and return the next token as 'Tok'. 1231 void Preprocessor::ExpandBuiltinMacro(Token &Tok) { 1232 // Figure out which token this is. 1233 IdentifierInfo *II = Tok.getIdentifierInfo(); 1234 assert(II && "Can't be a macro without id info!"); 1235 1236 // If this is an _Pragma or Microsoft __pragma directive, expand it, 1237 // invoke the pragma handler, then lex the token after it. 1238 if (II == Ident_Pragma) 1239 return Handle_Pragma(Tok); 1240 else if (II == Ident__pragma) // in non-MS mode this is null 1241 return HandleMicrosoft__pragma(Tok); 1242 1243 ++NumBuiltinMacroExpanded; 1244 1245 SmallString<128> TmpBuffer; 1246 llvm::raw_svector_ostream OS(TmpBuffer); 1247 1248 // Set up the return result. 1249 Tok.setIdentifierInfo(0); 1250 Tok.clearFlag(Token::NeedsCleaning); 1251 1252 if (II == Ident__LINE__) { 1253 // C99 6.10.8: "__LINE__: The presumed line number (within the current 1254 // source file) of the current source line (an integer constant)". This can 1255 // be affected by #line. 1256 SourceLocation Loc = Tok.getLocation(); 1257 1258 // Advance to the location of the first _, this might not be the first byte 1259 // of the token if it starts with an escaped newline. 1260 Loc = AdvanceToTokenCharacter(Loc, 0); 1261 1262 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of 1263 // a macro expansion. This doesn't matter for object-like macros, but 1264 // can matter for a function-like macro that expands to contain __LINE__. 1265 // Skip down through expansion points until we find a file loc for the 1266 // end of the expansion history. 1267 Loc = SourceMgr.getExpansionRange(Loc).second; 1268 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); 1269 1270 // __LINE__ expands to a simple numeric value. 1271 OS << (PLoc.isValid()? PLoc.getLine() : 1); 1272 Tok.setKind(tok::numeric_constant); 1273 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) { 1274 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a 1275 // character string literal)". This can be affected by #line. 1276 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 1277 1278 // __BASE_FILE__ is a GNU extension that returns the top of the presumed 1279 // #include stack instead of the current file. 1280 if (II == Ident__BASE_FILE__ && PLoc.isValid()) { 1281 SourceLocation NextLoc = PLoc.getIncludeLoc(); 1282 while (NextLoc.isValid()) { 1283 PLoc = SourceMgr.getPresumedLoc(NextLoc); 1284 if (PLoc.isInvalid()) 1285 break; 1286 1287 NextLoc = PLoc.getIncludeLoc(); 1288 } 1289 } 1290 1291 // Escape this filename. Turn '\' -> '\\' '"' -> '\"' 1292 SmallString<128> FN; 1293 if (PLoc.isValid()) { 1294 FN += PLoc.getFilename(); 1295 Lexer::Stringify(FN); 1296 OS << '"' << FN.str() << '"'; 1297 } 1298 Tok.setKind(tok::string_literal); 1299 } else if (II == Ident__DATE__) { 1300 if (!DATELoc.isValid()) 1301 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 1302 Tok.setKind(tok::string_literal); 1303 Tok.setLength(strlen("\"Mmm dd yyyy\"")); 1304 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(), 1305 Tok.getLocation(), 1306 Tok.getLength())); 1307 return; 1308 } else if (II == Ident__TIME__) { 1309 if (!TIMELoc.isValid()) 1310 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 1311 Tok.setKind(tok::string_literal); 1312 Tok.setLength(strlen("\"hh:mm:ss\"")); 1313 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(), 1314 Tok.getLocation(), 1315 Tok.getLength())); 1316 return; 1317 } else if (II == Ident__INCLUDE_LEVEL__) { 1318 // Compute the presumed include depth of this token. This can be affected 1319 // by GNU line markers. 1320 unsigned Depth = 0; 1321 1322 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 1323 if (PLoc.isValid()) { 1324 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 1325 for (; PLoc.isValid(); ++Depth) 1326 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 1327 } 1328 1329 // __INCLUDE_LEVEL__ expands to a simple numeric value. 1330 OS << Depth; 1331 Tok.setKind(tok::numeric_constant); 1332 } else if (II == Ident__TIMESTAMP__) { 1333 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be 1334 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime. 1335 1336 // Get the file that we are lexing out of. If we're currently lexing from 1337 // a macro, dig into the include stack. 1338 const FileEntry *CurFile = 0; 1339 PreprocessorLexer *TheLexer = getCurrentFileLexer(); 1340 1341 if (TheLexer) 1342 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID()); 1343 1344 const char *Result; 1345 if (CurFile) { 1346 time_t TT = CurFile->getModificationTime(); 1347 struct tm *TM = localtime(&TT); 1348 Result = asctime(TM); 1349 } else { 1350 Result = "??? ??? ?? ??:??:?? ????\n"; 1351 } 1352 // Surround the string with " and strip the trailing newline. 1353 OS << '"' << StringRef(Result, strlen(Result)-1) << '"'; 1354 Tok.setKind(tok::string_literal); 1355 } else if (II == Ident__COUNTER__) { 1356 // __COUNTER__ expands to a simple numeric value. 1357 OS << CounterValue++; 1358 Tok.setKind(tok::numeric_constant); 1359 } else if (II == Ident__has_feature || 1360 II == Ident__has_extension || 1361 II == Ident__has_builtin || 1362 II == Ident__has_attribute) { 1363 // The argument to these builtins should be a parenthesized identifier. 1364 SourceLocation StartLoc = Tok.getLocation(); 1365 1366 bool IsValid = false; 1367 IdentifierInfo *FeatureII = 0; 1368 1369 // Read the '('. 1370 LexUnexpandedToken(Tok); 1371 if (Tok.is(tok::l_paren)) { 1372 // Read the identifier 1373 LexUnexpandedToken(Tok); 1374 if ((FeatureII = Tok.getIdentifierInfo())) { 1375 // Read the ')'. 1376 LexUnexpandedToken(Tok); 1377 if (Tok.is(tok::r_paren)) 1378 IsValid = true; 1379 } 1380 } 1381 1382 bool Value = false; 1383 if (!IsValid) 1384 Diag(StartLoc, diag::err_feature_check_malformed); 1385 else if (II == Ident__has_builtin) { 1386 // Check for a builtin is trivial. 1387 Value = FeatureII->getBuiltinID() != 0; 1388 } else if (II == Ident__has_attribute) 1389 Value = hasAttribute(AttrSyntax::Generic, nullptr, FeatureII, 1390 getTargetInfo().getTriple(), getLangOpts()); 1391 else if (II == Ident__has_extension) 1392 Value = HasExtension(*this, FeatureII); 1393 else { 1394 assert(II == Ident__has_feature && "Must be feature check"); 1395 Value = HasFeature(*this, FeatureII); 1396 } 1397 1398 OS << (int)Value; 1399 if (IsValid) 1400 Tok.setKind(tok::numeric_constant); 1401 } else if (II == Ident__has_include || 1402 II == Ident__has_include_next) { 1403 // The argument to these two builtins should be a parenthesized 1404 // file name string literal using angle brackets (<>) or 1405 // double-quotes (""). 1406 bool Value; 1407 if (II == Ident__has_include) 1408 Value = EvaluateHasInclude(Tok, II, *this); 1409 else 1410 Value = EvaluateHasIncludeNext(Tok, II, *this); 1411 OS << (int)Value; 1412 if (Tok.is(tok::r_paren)) 1413 Tok.setKind(tok::numeric_constant); 1414 } else if (II == Ident__has_warning) { 1415 // The argument should be a parenthesized string literal. 1416 // The argument to these builtins should be a parenthesized identifier. 1417 SourceLocation StartLoc = Tok.getLocation(); 1418 bool IsValid = false; 1419 bool Value = false; 1420 // Read the '('. 1421 LexUnexpandedToken(Tok); 1422 do { 1423 if (Tok.isNot(tok::l_paren)) { 1424 Diag(StartLoc, diag::err_warning_check_malformed); 1425 break; 1426 } 1427 1428 LexUnexpandedToken(Tok); 1429 std::string WarningName; 1430 SourceLocation StrStartLoc = Tok.getLocation(); 1431 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'", 1432 /*MacroExpansion=*/false)) { 1433 // Eat tokens until ')'. 1434 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) && 1435 Tok.isNot(tok::eof)) 1436 LexUnexpandedToken(Tok); 1437 break; 1438 } 1439 1440 // Is the end a ')'? 1441 if (!(IsValid = Tok.is(tok::r_paren))) { 1442 Diag(StartLoc, diag::err_warning_check_malformed); 1443 break; 1444 } 1445 1446 if (WarningName.size() < 3 || WarningName[0] != '-' || 1447 WarningName[1] != 'W') { 1448 Diag(StrStartLoc, diag::warn_has_warning_invalid_option); 1449 break; 1450 } 1451 1452 // Finally, check if the warning flags maps to a diagnostic group. 1453 // We construct a SmallVector here to talk to getDiagnosticIDs(). 1454 // Although we don't use the result, this isn't a hot path, and not 1455 // worth special casing. 1456 SmallVector<diag::kind, 10> Diags; 1457 Value = !getDiagnostics().getDiagnosticIDs()-> 1458 getDiagnosticsInGroup(WarningName.substr(2), Diags); 1459 } while (false); 1460 1461 OS << (int)Value; 1462 if (IsValid) 1463 Tok.setKind(tok::numeric_constant); 1464 } else if (II == Ident__building_module) { 1465 // The argument to this builtin should be an identifier. The 1466 // builtin evaluates to 1 when that identifier names the module we are 1467 // currently building. 1468 OS << (int)EvaluateBuildingModule(Tok, II, *this); 1469 Tok.setKind(tok::numeric_constant); 1470 } else if (II == Ident__MODULE__) { 1471 // The current module as an identifier. 1472 OS << getLangOpts().CurrentModule; 1473 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule); 1474 Tok.setIdentifierInfo(ModuleII); 1475 Tok.setKind(ModuleII->getTokenID()); 1476 } else if (II == Ident__identifier) { 1477 SourceLocation Loc = Tok.getLocation(); 1478 1479 // We're expecting '__identifier' '(' identifier ')'. Try to recover 1480 // if the parens are missing. 1481 LexNonComment(Tok); 1482 if (Tok.isNot(tok::l_paren)) { 1483 // No '(', use end of last token. 1484 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after) 1485 << II << tok::l_paren; 1486 // If the next token isn't valid as our argument, we can't recover. 1487 if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) 1488 Tok.setKind(tok::identifier); 1489 return; 1490 } 1491 1492 SourceLocation LParenLoc = Tok.getLocation(); 1493 LexNonComment(Tok); 1494 1495 if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) 1496 Tok.setKind(tok::identifier); 1497 else { 1498 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier) 1499 << Tok.getKind(); 1500 // Don't walk past anything that's not a real token. 1501 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation()) 1502 return; 1503 } 1504 1505 // Discard the ')', preserving 'Tok' as our result. 1506 Token RParen; 1507 LexNonComment(RParen); 1508 if (RParen.isNot(tok::r_paren)) { 1509 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after) 1510 << Tok.getKind() << tok::r_paren; 1511 Diag(LParenLoc, diag::note_matching) << tok::l_paren; 1512 } 1513 return; 1514 } else { 1515 llvm_unreachable("Unknown identifier!"); 1516 } 1517 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation()); 1518 } 1519 1520 void Preprocessor::markMacroAsUsed(MacroInfo *MI) { 1521 // If the 'used' status changed, and the macro requires 'unused' warning, 1522 // remove its SourceLocation from the warn-for-unused-macro locations. 1523 if (MI->isWarnIfUnused() && !MI->isUsed()) 1524 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 1525 MI->setIsUsed(true); 1526 } 1527