Skip to content

[Typed throws] Handle function conversions involving different thrown errors #68995

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
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
3 changes: 3 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,9 @@ ERROR(throws_functiontype_mismatch,none,
"invalid conversion from throwing function of type %0 to "
"non-throwing function type %1", (Type, Type))

ERROR(thrown_error_type_mismatch,none,
"invalid conversion of thrown error type %0 to %1", (Type, Type))

ERROR(async_functiontype_mismatch,none,
"invalid conversion from 'async' function of type %0 to "
"synchronous function type %1", (Type, Type))
Expand Down
28 changes: 27 additions & 1 deletion include/swift/Sema/CSFix.h
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,9 @@ enum class FixKind : uint8_t {
/// `throws` attribute from the source function.
DropThrowsAttribute,

/// Ignore a mismatch in the thrown error type.
IgnoreThrownErrorMismatch,

/// Fix conversion from async to sync function by removing explicit
/// `async` attribute from the source function.
DropAsyncAttribute,
Expand Down Expand Up @@ -1005,7 +1008,6 @@ class DropThrowsAttribute final : public ContextualMismatch {
FunctionType *toType, ConstraintLocator *locator)
: ContextualMismatch(cs, FixKind::DropThrowsAttribute, fromType, toType,
locator) {
assert(fromType->isThrowing() != toType->isThrowing());
}

public:
Expand All @@ -1023,6 +1025,30 @@ class DropThrowsAttribute final : public ContextualMismatch {
}
};

/// This is a contextual mismatch between the thrown error types of two
/// function types, which could be repaired by fixing one of the types.
class IgnoreThrownErrorMismatch final : public ContextualMismatch {
IgnoreThrownErrorMismatch(ConstraintSystem &cs, Type fromErrorType,
Type toErrorType, ConstraintLocator *locator)
: ContextualMismatch(cs, FixKind::IgnoreThrownErrorMismatch,
fromErrorType, toErrorType, locator) {
assert(!fromErrorType->isEqual(toErrorType));
}

public:
std::string getName() const override { return "drop 'throws' attribute"; }

bool diagnose(const Solution &solution, bool asNote = false) const override;

static IgnoreThrownErrorMismatch *create(ConstraintSystem &cs,
Type fromErrorType,
Type toErrorType,
ConstraintLocator *locator);

static bool classof(const ConstraintFix *fix) {
return fix->getKind() == FixKind::IgnoreThrownErrorMismatch;
}
};
/// This is a contextual mismatch between async and non-async
/// function types, repair it by dropping `async` attribute.
class DropAsyncAttribute final : public ContextualMismatch {
Expand Down
3 changes: 3 additions & 0 deletions include/swift/Sema/ConstraintLocatorPathElts.def
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@ ABSTRACT_LOCATOR_PATH_ELT(PatternDecl)
/// A function type global actor.
SIMPLE_LOCATOR_PATH_ELT(GlobalActorType)

/// The thrown error of a function type.
SIMPLE_LOCATOR_PATH_ELT(ThrownErrorType)

/// A type coercion operand.
SIMPLE_LOCATOR_PATH_ELT(CoercionOperand)

Expand Down
5 changes: 5 additions & 0 deletions lib/AST/TypeWalker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@ class Traversal : public TypeVisitor<Traversal, bool>
return true;
}

if (Type thrownError = ty->getThrownError()) {
if (doIt(thrownError))
return true;
}

return doIt(ty->getResult());
}

Expand Down
6 changes: 6 additions & 0 deletions lib/Sema/CSDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7096,6 +7096,12 @@ bool ThrowingFunctionConversionFailure::diagnoseAsError() {
return true;
}

bool ThrownErrorTypeConversionFailure::diagnoseAsError() {
emitDiagnostic(diag::thrown_error_type_mismatch, getFromType(),
getToType());
return true;
}

bool AsyncFunctionConversionFailure::diagnoseAsError() {
auto *locator = getLocator();

Expand Down
18 changes: 18 additions & 0 deletions lib/Sema/CSDiagnostics.h
Original file line number Diff line number Diff line change
Expand Up @@ -933,6 +933,24 @@ class ThrowingFunctionConversionFailure final : public ContextualFailure {
bool diagnoseAsError() override;
};

/// Diagnose failures related to conversion between the thrown error type
/// of two function types, e.g.,
///
/// ```swift
/// func foo<T>(_ t: T) throws(MyError) -> Void {}
/// let _: (Int) throws (OtherError)-> Void = foo
/// // `MyError` can't be implicitly converted to `OtherError`
/// ```
class ThrownErrorTypeConversionFailure final : public ContextualFailure {
public:
ThrownErrorTypeConversionFailure(const Solution &solution, Type fromType,
Type toType, ConstraintLocator *locator)
: ContextualFailure(solution, fromType, toType, locator) {
}

bool diagnoseAsError() override;
};

/// Diagnose failures related to conversion between 'async' function type
/// and a synchronous one e.g.
///
Expand Down
15 changes: 15 additions & 0 deletions lib/Sema/CSFix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1627,6 +1627,21 @@ DropThrowsAttribute *DropThrowsAttribute::create(ConstraintSystem &cs,
DropThrowsAttribute(cs, fromType, toType, locator);
}

bool IgnoreThrownErrorMismatch::diagnose(const Solution &solution,
bool asNote) const {
ThrownErrorTypeConversionFailure failure(solution, getFromType(),
getToType(), getLocator());
return failure.diagnose(asNote);
}

IgnoreThrownErrorMismatch *IgnoreThrownErrorMismatch::create(ConstraintSystem &cs,
Type fromErrorType,
Type toErrorType,
ConstraintLocator *locator) {
return new (cs.getAllocator())
IgnoreThrownErrorMismatch(cs, fromErrorType, toErrorType, locator);
}

bool DropAsyncAttribute::diagnose(const Solution &solution,
bool asNote) const {
AsyncFunctionConversionFailure failure(solution, getFromType(),
Expand Down
1 change: 0 additions & 1 deletion lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2453,7 +2453,6 @@ namespace {
auto resultLocator =
CS.getConstraintLocator(closure, ConstraintLocator::ClosureResult);

// FIXME: Need a better locator.
auto thrownErrorLocator =
CS.getConstraintLocator(closure, ConstraintLocator::ClosureThrownError);

Expand Down
152 changes: 139 additions & 13 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2945,23 +2945,139 @@ bool ConstraintSystem::hasPreconcurrencyCallee(
return calleeOverload->choice.getDecl()->preconcurrency();
}

namespace {
/// Classifies a thrown error kind as Never, a specific type, or 'any Error'.
enum class ThrownErrorKind {
Never,
Specific,
AnyError,
};

ThrownErrorKind getThrownErrorKind(Type type) {
if (type->isNever())
return ThrownErrorKind::Never;

if (type->isExistentialType()) {
Type anyError = type->getASTContext().getErrorExistentialType();
if (anyError->isEqual(type))
return ThrownErrorKind::AnyError;
}

return ThrownErrorKind::Specific;
}
}

/// Match the throwing specifier of the two function types.
static ConstraintSystem::TypeMatchResult
matchFunctionThrowing(ConstraintSystem &cs,
FunctionType *func1, FunctionType *func2,
ConstraintKind kind,
ConstraintSystem::TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// A function type that throws the error type E1 is a subtype of a function
// that throws error type E2 when E1 is a subtype of E2. For the purpose
// of this comparison, a non-throwing function has thrown error type 'Never',
// and an untyped throwing function has thrown error type 'any Error'.
Type neverType = cs.getASTContext().getNeverType();
Type thrownError1 = func1->getEffectiveThrownInterfaceType().value_or(neverType);
Type thrownError2 = func2->getEffectiveThrownInterfaceType().value_or(neverType);
if (!thrownError1 || !thrownError2 || thrownError1->isEqual(thrownError2))
return cs.getTypeMatchSuccess();

auto thrownErrorKind1 = getThrownErrorKind(thrownError1);
auto thrownErrorKind2 = getThrownErrorKind(thrownError2);

bool mustUnify = false;
bool dropThrows = false;

switch (thrownErrorKind1) {
case ThrownErrorKind::Specific:
// If the specific thrown error contains no type variables and we're
// going to try to convert it to \c Never, treat this as dropping throws.
if (thrownErrorKind2 == ThrownErrorKind::Never &&
!thrownError1->hasTypeVariable()) {
dropThrows = true;
} else {
// We need to unify the thrown error types.
mustUnify = true;
}
break;

case ThrownErrorKind::Never:
switch (thrownErrorKind2) {
case ThrownErrorKind::Specific:
// We need to unify the thrown error types.
mustUnify = true;
break;

case ThrownErrorKind::Never:
llvm_unreachable("The thrown error types should have been equal");
break;

case ThrownErrorKind::AnyError:
// We have a subtype. If we're not allowed to do the subtype,
// then we need to drop "throws".
if (kind < ConstraintKind::Subtype)
dropThrows = true;
break;
}
break;

case ThrownErrorKind::AnyError:
switch (thrownErrorKind2) {
case ThrownErrorKind::Specific:
// We need to unify the thrown error types.
mustUnify = true;
break;

case ThrownErrorKind::Never:
// We're going to have to drop the "throws" entirely.
dropThrows = true;
break;

case ThrownErrorKind::AnyError:
llvm_unreachable("The thrown error types should have been equal");
}
break;
}

// If we know we need to drop 'throws', try it now.
if (dropThrows) {
if (!cs.shouldAttemptFixes())
return cs.getTypeMatchFailure(locator);

auto *fix = DropThrowsAttribute::create(cs, func1, func2,
cs.getConstraintLocator(locator));
if (cs.recordFix(fix))
return cs.getTypeMatchFailure(locator);
}

// If we need to unify the thrown error types, do so now.
if (mustUnify) {
ConstraintKind subKind = (kind < ConstraintKind::Subtype)
? ConstraintKind::Equal
: ConstraintKind::Subtype;
const auto subflags = getDefaultDecompositionOptions(flags);
auto result = cs.matchTypes(
thrownError1, thrownError2,
subKind, subflags,
locator.withPathElement(LocatorPathElt::ThrownErrorType()));
if (result == ConstraintSystem::SolutionKind::Error)
return cs.getTypeMatchFailure(locator);
}

return cs.getTypeMatchSuccess();
}

ConstraintSystem::TypeMatchResult
ConstraintSystem::matchFunctionTypes(FunctionType *func1, FunctionType *func2,
ConstraintKind kind, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// A non-throwing function can be a subtype of a throwing function.
if (func1->isThrowing() != func2->isThrowing()) {
// Cannot drop 'throws'.
if (func1->isThrowing() || kind < ConstraintKind::Subtype) {
if (!shouldAttemptFixes())
return getTypeMatchFailure(locator);

auto *fix = DropThrowsAttribute::create(*this, func1, func2,
getConstraintLocator(locator));
if (recordFix(fix))
return getTypeMatchFailure(locator);
}
}
// Match the 'throws' effect.
TypeMatchResult throwsResult =
matchFunctionThrowing(*this, func1, func2, kind, flags, locator);
if (throwsResult.isFailure())
return throwsResult;

// A synchronous function can be a subtype of an 'async' function.
if (func1->isAsync() != func2->isAsync()) {
Expand Down Expand Up @@ -5152,6 +5268,13 @@ bool ConstraintSystem::repairFailures(
getConstraintLocator(locator)))
return true;

if (locator.endsWith<LocatorPathElt::ThrownErrorType>()) {
conversionsOrFixes.push_back(
IgnoreThrownErrorMismatch::create(*this, lhs, rhs,
getConstraintLocator(locator)));
return true;
}

if (path.empty()) {
if (!anchor)
return false;
Expand Down Expand Up @@ -15002,6 +15125,9 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifyFixConstraint(
case FixKind::IgnoreGenericSpecializationArityMismatch: {
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::IgnoreThrownErrorMismatch: {
return recordFix(fix, 2) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::IgnoreInvalidASTNode: {
return recordFix(fix, 10) ? SolutionKind::Error : SolutionKind::Solved;
}
Expand Down
5 changes: 5 additions & 0 deletions lib/Sema/ConstraintLocator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ unsigned LocatorPathElt::getNewSummaryFlags() const {
case ConstraintLocator::GlobalActorType:
case ConstraintLocator::CoercionOperand:
case ConstraintLocator::PackExpansionType:
case ConstraintLocator::ThrownErrorType:
return 0;

case ConstraintLocator::FunctionArgument:
Expand Down Expand Up @@ -519,6 +520,10 @@ void LocatorPathElt::dump(raw_ostream &out) const {
<< expansionElt.getOpenedType()->getString(PO) << ")";
break;
}
case ConstraintLocator::ThrownErrorType: {
out << "thrown error type";
break;
}
}
}

Expand Down
3 changes: 3 additions & 0 deletions lib/Sema/ConstraintSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5971,6 +5971,9 @@ void constraints::simplifyLocator(ASTNode &anchor,
case ConstraintLocator::GenericParameter:
break;

case ConstraintLocator::ThrownErrorType:
break;

case ConstraintLocator::OpenedGeneric:
case ConstraintLocator::OpenedOpaqueArchetype:
break;
Expand Down
3 changes: 0 additions & 3 deletions lib/Sema/TypeCheckEffects.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1118,9 +1118,6 @@ class ApplyClassifier {
classifyFunctionBody(fnRef,
PotentialEffectReason::forApply(),
kind));
assert(result.getConditionalKind(kind)
!= ConditionalEffectKind::None &&
"body classification decided function had no effect?");
}
};

Expand Down
1 change: 1 addition & 0 deletions lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3633,6 +3633,7 @@ NeverNullType TypeResolver::resolveASTFunctionType(
if (thrownTy->hasError()) {
thrownTy = Type();
} else if (!options.contains(TypeResolutionFlags::SilenceErrors) &&
!thrownTy->hasTypeParameter() &&
!TypeChecker::conformsToProtocol(
thrownTy, ctx.getErrorDecl(),
resolution.getDeclContext()->getParentModule())) {
Expand Down
11 changes: 4 additions & 7 deletions test/attr/typed_throws_availability_osx.swift
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
// RUN: %swift -typecheck -verify -target x86_64-apple-macosx10.10 %s -enable-experimental-feature TypedThrows
// RUN: %swift -typecheck -verify -target %target-cpu-apple-macosx11 %s -enable-experimental-feature TypedThrows

// REQUIRES: OS=macosx

@available(macOS 12, *)
@available(macOS 13, *)
enum MyError: Error {
case fail
}

@available(macOS 11, *)
@available(macOS 12, *)
func throwMyErrorBadly() throws(MyError) { }
// expected-error@-1{{'MyError' is only available in macOS 12 or newer}}



// expected-error@-1{{'MyError' is only available in macOS 13 or newer}}
Loading