1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
|
//===------ SemaSwift.cpp ------ Swift language-specific routines ---------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis functions specific to Swift.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaSwift.h"
#include "clang/AST/DeclBase.h"
#include "clang/Basic/AttributeCommonInfo.h"
#include "clang/Basic/DiagnosticSema.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Sema/Attr.h"
#include "clang/Sema/ParsedAttr.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaObjC.h"
namespace clang {
SemaSwift::SemaSwift(Sema &S) : SemaBase(S) {}
SwiftNameAttr *SemaSwift::mergeNameAttr(Decl *D, const SwiftNameAttr &SNA,
StringRef Name) {
if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
<< PrevSNA << &SNA
<< (PrevSNA->isRegularKeywordAttribute() ||
SNA.isRegularKeywordAttribute());
Diag(SNA.getLoc(), diag::note_conflicting_attribute);
}
D->dropAttr<SwiftNameAttr>();
}
return ::new (getASTContext()) SwiftNameAttr(getASTContext(), SNA, Name);
}
/// Pointer-like types in the default address space.
static bool isValidSwiftContextType(QualType Ty) {
if (!Ty->hasPointerRepresentation())
return Ty->isDependentType();
return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
}
/// Pointers and references in the default address space.
static bool isValidSwiftIndirectResultType(QualType Ty) {
if (const auto *PtrType = Ty->getAs<PointerType>()) {
Ty = PtrType->getPointeeType();
} else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
Ty = RefType->getPointeeType();
} else {
return Ty->isDependentType();
}
return Ty.getAddressSpace() == LangAS::Default;
}
/// Pointers and references to pointers in the default address space.
static bool isValidSwiftErrorResultType(QualType Ty) {
if (const auto *PtrType = Ty->getAs<PointerType>()) {
Ty = PtrType->getPointeeType();
} else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
Ty = RefType->getPointeeType();
} else {
return Ty->isDependentType();
}
if (!Ty.getQualifiers().empty())
return false;
return isValidSwiftContextType(Ty);
}
void SemaSwift::handleAttrAttr(Decl *D, const ParsedAttr &AL) {
if (AL.isInvalid() || AL.isUsedAsTypeAttr())
return;
// Make sure that there is a string literal as the annotation's single
// argument.
StringRef Str;
if (!SemaRef.checkStringLiteralArgumentAttr(AL, 0, Str)) {
AL.setInvalid();
return;
}
D->addAttr(::new (getASTContext()) SwiftAttrAttr(getASTContext(), AL, Str));
}
void SemaSwift::handleBridge(Decl *D, const ParsedAttr &AL) {
// Make sure that there is a string literal as the annotation's single
// argument.
StringRef BT;
if (!SemaRef.checkStringLiteralArgumentAttr(AL, 0, BT))
return;
// Warn about duplicate attributes if they have different arguments, but drop
// any duplicate attributes regardless.
if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) {
if (Other->getSwiftType() != BT)
Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
return;
}
D->addAttr(::new (getASTContext()) SwiftBridgeAttr(getASTContext(), AL, BT));
}
static bool isErrorParameter(Sema &S, QualType QT) {
const auto *PT = QT->getAs<PointerType>();
if (!PT)
return false;
QualType Pointee = PT->getPointeeType();
// Check for NSError**.
if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>())
if (const auto *ID = OPT->getInterfaceDecl())
if (ID->getIdentifier() == S.ObjC().getNSErrorIdent())
return true;
// Check for CFError**.
if (const auto *PT = Pointee->getAs<PointerType>())
if (const auto *RT = PT->getPointeeType()->getAs<RecordType>())
if (S.ObjC().isCFError(RT->getDecl()))
return true;
return false;
}
void SemaSwift::handleError(Decl *D, const ParsedAttr &AL) {
auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
if (isErrorParameter(S, getFunctionOrMethodParamType(D, I)))
return true;
}
S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter)
<< AL << isa<ObjCMethodDecl>(D);
return false;
};
auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
// - C, ObjC, and block pointers are definitely okay.
// - References are definitely not okay.
// - nullptr_t is weird, but acceptable.
QualType RT = getFunctionOrMethodResultType(D);
if (RT->hasPointerRepresentation() && !RT->isReferenceType())
return true;
S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
<< AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
<< /*pointer*/ 1;
return false;
};
auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
QualType RT = getFunctionOrMethodResultType(D);
if (RT->isIntegralType(S.Context))
return true;
S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
<< AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
<< /*integral*/ 0;
return false;
};
if (D->isInvalidDecl())
return;
IdentifierLoc *Loc = AL.getArgAsIdent(0);
SwiftErrorAttr::ConventionKind Convention;
if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(),
Convention)) {
Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
<< AL << Loc->Ident;
return;
}
switch (Convention) {
case SwiftErrorAttr::None:
// No additional validation required.
break;
case SwiftErrorAttr::NonNullError:
if (!hasErrorParameter(SemaRef, D, AL))
return;
break;
case SwiftErrorAttr::NullResult:
if (!hasErrorParameter(SemaRef, D, AL) || !hasPointerResult(SemaRef, D, AL))
return;
break;
case SwiftErrorAttr::NonZeroResult:
case SwiftErrorAttr::ZeroResult:
if (!hasErrorParameter(SemaRef, D, AL) || !hasIntegerResult(SemaRef, D, AL))
return;
break;
}
D->addAttr(::new (getASTContext())
SwiftErrorAttr(getASTContext(), AL, Convention));
}
static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D,
const SwiftAsyncErrorAttr *ErrorAttr,
const SwiftAsyncAttr *AsyncAttr) {
if (AsyncAttr->getKind() == SwiftAsyncAttr::None) {
if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) {
S.Diag(AsyncAttr->getLocation(),
diag::err_swift_async_error_without_swift_async)
<< AsyncAttr << isa<ObjCMethodDecl>(D);
}
return;
}
const ParmVarDecl *HandlerParam = getFunctionOrMethodParam(
D, AsyncAttr->getCompletionHandlerIndex().getASTIndex());
// handleSwiftAsyncAttr already verified the type is correct, so no need to
// double-check it here.
const auto *FuncTy = HandlerParam->getType()
->castAs<BlockPointerType>()
->getPointeeType()
->getAs<FunctionProtoType>();
ArrayRef<QualType> BlockParams;
if (FuncTy)
BlockParams = FuncTy->getParamTypes();
switch (ErrorAttr->getConvention()) {
case SwiftAsyncErrorAttr::ZeroArgument:
case SwiftAsyncErrorAttr::NonZeroArgument: {
uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx();
if (ParamIdx == 0 || ParamIdx > BlockParams.size()) {
S.Diag(ErrorAttr->getLocation(),
diag::err_attribute_argument_out_of_bounds)
<< ErrorAttr << 2;
return;
}
QualType ErrorParam = BlockParams[ParamIdx - 1];
if (!ErrorParam->isIntegralType(S.Context)) {
StringRef ConvStr =
ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument
? "zero_argument"
: "nonzero_argument";
S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral)
<< ErrorAttr << ConvStr << ParamIdx << ErrorParam;
return;
}
break;
}
case SwiftAsyncErrorAttr::NonNullError: {
bool AnyErrorParams = false;
for (QualType Param : BlockParams) {
// Check for NSError *.
if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) {
if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) {
if (ID->getIdentifier() == S.ObjC().getNSErrorIdent()) {
AnyErrorParams = true;
break;
}
}
}
// Check for CFError *.
if (const auto *PtrTy = Param->getAs<PointerType>()) {
if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) {
if (S.ObjC().isCFError(RT->getDecl())) {
AnyErrorParams = true;
break;
}
}
}
}
if (!AnyErrorParams) {
S.Diag(ErrorAttr->getLocation(),
diag::err_swift_async_error_no_error_parameter)
<< ErrorAttr << isa<ObjCMethodDecl>(D);
return;
}
break;
}
case SwiftAsyncErrorAttr::None:
break;
}
}
void SemaSwift::handleAsyncError(Decl *D, const ParsedAttr &AL) {
IdentifierLoc *IDLoc = AL.getArgAsIdent(0);
SwiftAsyncErrorAttr::ConventionKind ConvKind;
if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(),
ConvKind)) {
Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
<< AL << IDLoc->Ident;
return;
}
uint32_t ParamIdx = 0;
switch (ConvKind) {
case SwiftAsyncErrorAttr::ZeroArgument:
case SwiftAsyncErrorAttr::NonZeroArgument: {
if (!AL.checkExactlyNumArgs(SemaRef, 2))
return;
Expr *IdxExpr = AL.getArgAsExpr(1);
if (!SemaRef.checkUInt32Argument(AL, IdxExpr, ParamIdx))
return;
break;
}
case SwiftAsyncErrorAttr::NonNullError:
case SwiftAsyncErrorAttr::None: {
if (!AL.checkExactlyNumArgs(SemaRef, 1))
return;
break;
}
}
auto *ErrorAttr = ::new (getASTContext())
SwiftAsyncErrorAttr(getASTContext(), AL, ConvKind, ParamIdx);
D->addAttr(ErrorAttr);
if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>())
checkSwiftAsyncErrorBlock(SemaRef, D, ErrorAttr, AsyncAttr);
}
// For a function, this will validate a compound Swift name, e.g.
// <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
// the function will output the number of parameter names, and whether this is a
// single-arg initializer.
//
// For a type, enum constant, property, or variable declaration, this will
// validate either a simple identifier, or a qualified
// <code>context.identifier</code> name.
static bool validateSwiftFunctionName(Sema &S, const ParsedAttr &AL,
SourceLocation Loc, StringRef Name,
unsigned &SwiftParamCount,
bool &IsSingleParamInit) {
SwiftParamCount = 0;
IsSingleParamInit = false;
// Check whether this will be mapped to a getter or setter of a property.
bool IsGetter = false, IsSetter = false;
if (Name.consume_front("getter:"))
IsGetter = true;
else if (Name.consume_front("setter:"))
IsSetter = true;
if (Name.back() != ')') {
S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
return false;
}
bool IsMember = false;
StringRef ContextName, BaseName, Parameters;
std::tie(BaseName, Parameters) = Name.split('(');
// Split at the first '.', if it exists, which separates the context name
// from the base name.
std::tie(ContextName, BaseName) = BaseName.split('.');
if (BaseName.empty()) {
BaseName = ContextName;
ContextName = StringRef();
} else if (ContextName.empty() || !isValidAsciiIdentifier(ContextName)) {
S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
<< AL << /*context*/ 1;
return false;
} else {
IsMember = true;
}
if (!isValidAsciiIdentifier(BaseName) || BaseName == "_") {
S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
<< AL << /*basename*/ 0;
return false;
}
bool IsSubscript = BaseName == "subscript";
// A subscript accessor must be a getter or setter.
if (IsSubscript && !IsGetter && !IsSetter) {
S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
<< AL << /* getter or setter */ 0;
return false;
}
if (Parameters.empty()) {
S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL;
return false;
}
assert(Parameters.back() == ')' && "expected ')'");
Parameters = Parameters.drop_back(); // ')'
if (Parameters.empty()) {
// Setters and subscripts must have at least one parameter.
if (IsSubscript) {
S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
<< AL << /* have at least one parameter */ 1;
return false;
}
if (IsSetter) {
S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL;
return false;
}
return true;
}
if (Parameters.back() != ':') {
S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
return false;
}
StringRef CurrentParam;
std::optional<unsigned> SelfLocation;
unsigned NewValueCount = 0;
std::optional<unsigned> NewValueLocation;
do {
std::tie(CurrentParam, Parameters) = Parameters.split(':');
if (!isValidAsciiIdentifier(CurrentParam)) {
S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
<< AL << /*parameter*/ 2;
return false;
}
if (IsMember && CurrentParam == "self") {
// "self" indicates the "self" argument for a member.
// More than one "self"?
if (SelfLocation) {
S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL;
return false;
}
// The "self" location is the current parameter.
SelfLocation = SwiftParamCount;
} else if (CurrentParam == "newValue") {
// "newValue" indicates the "newValue" argument for a setter.
// There should only be one 'newValue', but it's only significant for
// subscript accessors, so don't error right away.
++NewValueCount;
NewValueLocation = SwiftParamCount;
}
++SwiftParamCount;
} while (!Parameters.empty());
// Only instance subscripts are currently supported.
if (IsSubscript && !SelfLocation) {
S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
<< AL << /*have a 'self:' parameter*/ 2;
return false;
}
IsSingleParamInit =
SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_";
// Check the number of parameters for a getter/setter.
if (IsGetter || IsSetter) {
// Setters have one parameter for the new value.
unsigned NumExpectedParams = IsGetter ? 0 : 1;
unsigned ParamDiag = IsGetter
? diag::warn_attr_swift_name_getter_parameters
: diag::warn_attr_swift_name_setter_parameters;
// Instance methods have one parameter for "self".
if (SelfLocation)
++NumExpectedParams;
// Subscripts may have additional parameters beyond the expected params for
// the index.
if (IsSubscript) {
if (SwiftParamCount < NumExpectedParams) {
S.Diag(Loc, ParamDiag) << AL;
return false;
}
// A subscript setter must explicitly label its newValue parameter to
// distinguish it from index parameters.
if (IsSetter) {
if (!NewValueLocation) {
S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue)
<< AL;
return false;
}
if (NewValueCount > 1) {
S.Diag(Loc,
diag::warn_attr_swift_name_subscript_setter_multiple_newValues)
<< AL;
return false;
}
} else {
// Subscript getters should have no 'newValue:' parameter.
if (NewValueLocation) {
S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue)
<< AL;
return false;
}
}
} else {
// Property accessors must have exactly the number of expected params.
if (SwiftParamCount != NumExpectedParams) {
S.Diag(Loc, ParamDiag) << AL;
return false;
}
}
}
return true;
}
bool SemaSwift::DiagnoseName(Decl *D, StringRef Name, SourceLocation Loc,
const ParsedAttr &AL, bool IsAsync) {
if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
ArrayRef<ParmVarDecl *> Params;
unsigned ParamCount;
if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) {
ParamCount = Method->getSelector().getNumArgs();
Params = Method->parameters().slice(0, ParamCount);
} else {
const auto *F = cast<FunctionDecl>(D);
ParamCount = F->getNumParams();
Params = F->parameters();
if (!F->hasWrittenPrototype()) {
Diag(Loc, diag::warn_attribute_wrong_decl_type)
<< AL << AL.isRegularKeywordAttribute()
<< ExpectedFunctionWithProtoType;
return false;
}
}
// The async name drops the last callback parameter.
if (IsAsync) {
if (ParamCount == 0) {
Diag(Loc, diag::warn_attr_swift_name_decl_missing_params)
<< AL << isa<ObjCMethodDecl>(D);
return false;
}
ParamCount -= 1;
}
unsigned SwiftParamCount;
bool IsSingleParamInit;
if (!validateSwiftFunctionName(SemaRef, AL, Loc, Name, SwiftParamCount,
IsSingleParamInit))
return false;
bool ParamCountValid;
if (SwiftParamCount == ParamCount) {
ParamCountValid = true;
} else if (SwiftParamCount > ParamCount) {
ParamCountValid = IsSingleParamInit && ParamCount == 0;
} else {
// We have fewer Swift parameters than Objective-C parameters, but that
// might be because we've transformed some of them. Check for potential
// "out" parameters and err on the side of not warning.
unsigned MaybeOutParamCount =
llvm::count_if(Params, [](const ParmVarDecl *Param) -> bool {
QualType ParamTy = Param->getType();
if (ParamTy->isReferenceType() || ParamTy->isPointerType())
return !ParamTy->getPointeeType().isConstQualified();
return false;
});
ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount;
}
if (!ParamCountValid) {
Diag(Loc, diag::warn_attr_swift_name_num_params)
<< (SwiftParamCount > ParamCount) << AL << ParamCount
<< SwiftParamCount;
return false;
}
} else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) ||
isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) ||
isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) ||
isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) &&
!IsAsync) {
StringRef ContextName, BaseName;
std::tie(ContextName, BaseName) = Name.split('.');
if (BaseName.empty()) {
BaseName = ContextName;
ContextName = StringRef();
} else if (!isValidAsciiIdentifier(ContextName)) {
Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
<< AL << /*context*/ 1;
return false;
}
if (!isValidAsciiIdentifier(BaseName)) {
Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
<< AL << /*basename*/ 0;
return false;
}
} else {
Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL;
return false;
}
return true;
}
void SemaSwift::handleName(Decl *D, const ParsedAttr &AL) {
StringRef Name;
SourceLocation Loc;
if (!SemaRef.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
return;
if (!DiagnoseName(D, Name, Loc, AL, /*IsAsync=*/false))
return;
D->addAttr(::new (getASTContext()) SwiftNameAttr(getASTContext(), AL, Name));
}
void SemaSwift::handleAsyncName(Decl *D, const ParsedAttr &AL) {
StringRef Name;
SourceLocation Loc;
if (!SemaRef.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
return;
if (!DiagnoseName(D, Name, Loc, AL, /*IsAsync=*/true))
return;
D->addAttr(::new (getASTContext())
SwiftAsyncNameAttr(getASTContext(), AL, Name));
}
void SemaSwift::handleNewType(Decl *D, const ParsedAttr &AL) {
// Make sure that there is an identifier as the annotation's single argument.
if (!AL.checkExactlyNumArgs(SemaRef, 1))
return;
if (!AL.isArgIdent(0)) {
Diag(AL.getLoc(), diag::err_attribute_argument_type)
<< AL << AANT_ArgumentIdentifier;
return;
}
SwiftNewTypeAttr::NewtypeKind Kind;
IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) {
Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
return;
}
if (!isa<TypedefNameDecl>(D)) {
Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
<< AL << AL.isRegularKeywordAttribute() << ExpectedTypedef;
return;
}
D->addAttr(::new (getASTContext())
SwiftNewTypeAttr(getASTContext(), AL, Kind));
}
void SemaSwift::handleAsyncAttr(Decl *D, const ParsedAttr &AL) {
if (!AL.isArgIdent(0)) {
Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
<< AL << 1 << AANT_ArgumentIdentifier;
return;
}
SwiftAsyncAttr::Kind Kind;
IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) {
Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II;
return;
}
ParamIdx Idx;
if (Kind == SwiftAsyncAttr::None) {
// If this is 'none', then there shouldn't be any additional arguments.
if (!AL.checkExactlyNumArgs(SemaRef, 1))
return;
} else {
// Non-none swift_async requires a completion handler index argument.
if (!AL.checkExactlyNumArgs(SemaRef, 2))
return;
Expr *HandlerIdx = AL.getArgAsExpr(1);
if (!SemaRef.checkFunctionOrMethodParameterIndex(D, AL, 2, HandlerIdx, Idx))
return;
const ParmVarDecl *CompletionBlock =
getFunctionOrMethodParam(D, Idx.getASTIndex());
QualType CompletionBlockType = CompletionBlock->getType();
if (!CompletionBlockType->isBlockPointerType()) {
Diag(CompletionBlock->getLocation(), diag::err_swift_async_bad_block_type)
<< CompletionBlock->getType();
return;
}
QualType BlockTy =
CompletionBlockType->castAs<BlockPointerType>()->getPointeeType();
if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) {
Diag(CompletionBlock->getLocation(), diag::err_swift_async_bad_block_type)
<< CompletionBlock->getType();
return;
}
}
auto *AsyncAttr =
::new (getASTContext()) SwiftAsyncAttr(getASTContext(), AL, Kind, Idx);
D->addAttr(AsyncAttr);
if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>())
checkSwiftAsyncErrorBlock(SemaRef, D, ErrorAttr, AsyncAttr);
}
void SemaSwift::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
ParameterABI abi) {
ASTContext &Context = getASTContext();
QualType type = cast<ParmVarDecl>(D)->getType();
if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
if (existingAttr->getABI() != abi) {
Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
<< getParameterABISpelling(abi) << existingAttr
<< (CI.isRegularKeywordAttribute() ||
existingAttr->isRegularKeywordAttribute());
Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
return;
}
}
switch (abi) {
case ParameterABI::HLSLOut:
case ParameterABI::HLSLInOut:
llvm_unreachable("explicit attribute for non-swift parameter ABI?");
case ParameterABI::Ordinary:
llvm_unreachable("explicit attribute for ordinary parameter ABI?");
case ParameterABI::SwiftContext:
if (!isValidSwiftContextType(type)) {
Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
<< getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
}
D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
return;
case ParameterABI::SwiftAsyncContext:
if (!isValidSwiftContextType(type)) {
Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
<< getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
}
D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI));
return;
case ParameterABI::SwiftErrorResult:
if (!isValidSwiftErrorResultType(type)) {
Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
<< getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
}
D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
return;
case ParameterABI::SwiftIndirectResult:
if (!isValidSwiftIndirectResultType(type)) {
Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
<< getParameterABISpelling(abi) << /*pointer*/ 0 << type;
}
D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
return;
}
llvm_unreachable("bad parameter ABI attribute");
}
} // namespace clang
|