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