Skip to content

Fix @_implements type resolution diagnostics #81421

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions lib/Sema/TypeCheckAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4281,8 +4281,25 @@ void AttributeChecker::visitImplementsAttr(ImplementsAttr *attr) {
ProtocolDecl *PD = attr->getProtocol(DC);

if (!PD) {
diagnose(attr->getLocation(), diag::implements_attr_non_protocol_type)
.highlight(attr->getProtocolTypeRepr()->getSourceRange());
// `ImplementsAttr::getProtocol()` returns `nullptr` both when a type fails
// to resolve, and when it resolves to something other than a protocol.
// Due to layering concerns, it doesn't resolve in a way that emits
// diagnostics.
//
// Distinguish between these situations by trying to resolve the type again.
// If it doesn't resolve, TypeResolution will have diagnosed the problem; if
// it does, it must have resolved to a non-protocol, so emit a diagnostic to
// that effect.
TypeResolutionOptions options(TypeResolverContext::None);
auto resolvedType = TypeResolution::resolveContextualType(
attr->getProtocolTypeRepr(), DC, options,
// Unbound generics and placeholders are not allowed within this attr.
/*unboundTyOpener*/ nullptr, /*placeholderHandler*/ nullptr,
/*packElementOpener*/ nullptr);

if (resolvedType && !resolvedType->hasError())
diagnose(attr->getLocation(), diag::implements_attr_non_protocol_type)
.highlight(attr->getProtocolTypeRepr()->getSourceRange());
return;
}

Expand Down
4 changes: 4 additions & 0 deletions test/attr/attr_implements_bad_types.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,9 @@ struct S0 : NeedsF0 { // expected-error {{type 'S0' does not conform to protoco
@_implements(Equatable, ==(_:_:)) // expected-error {{containing type 'S0' does not conform to protocol 'Equatable'}}
static func gg2(x:S0, y:S0) -> Bool {
}

@_implements(NonexistentType, ff3()) // expected-error {{cannot find type 'NonexistentType' in scope}}
func gg3() {
}
}