Skip to content

[Typed throws] Implement conformance checking for typed throws #69087

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 3 commits into from
Oct 11, 2023
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
2 changes: 1 addition & 1 deletion include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -7123,7 +7123,7 @@ class AbstractFunctionDecl : public GenericContext, public ValueDecl {
///
/// Functions with untyped throws will produce "any Error", functions that
/// cannot throw or are specified to throw "Never" will return llvm::None.
llvm::Optional<Type> getEffectiveThrownInterfaceType() const;
llvm::Optional<Type> getEffectiveThrownErrorType() const;

/// Returns if the function throws or is async.
bool hasEffect(EffectKind kind) const;
Expand Down
13 changes: 13 additions & 0 deletions include/swift/AST/TypeMatcher.h
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,15 @@ class TypeMatcher {
return false;
}

// If requested, compare the thrown error types.
Type thrownError1 = firstFunc->getEffectiveThrownErrorTypeOrNever();
Type thrownError2 = secondFunc->getEffectiveThrownErrorTypeOrNever();
if (Matcher.asDerived().considerThrownErrorTypes(thrownError1,
thrownError2) &&
!this->visit(thrownError1->getCanonicalType(),
thrownError2, thrownError1))
return false;

return this->visit(firstFunc.getResult(), secondFunc->getResult(),
sugaredFirstFunc->getResult());
}
Expand Down Expand Up @@ -558,6 +567,10 @@ class TypeMatcher {
return MatchVisitor(*this).visit(first->getCanonicalType(), second,
first);
}

bool considerThrownErrorTypes(Type errorType1, Type errorType2) const {
return false;
}
};

} // end namespace swift
Expand Down
11 changes: 9 additions & 2 deletions include/swift/AST/Types.h
Original file line number Diff line number Diff line change
Expand Up @@ -3391,8 +3391,15 @@ class AnyFunctionType : public TypeBase {
///
/// Functions with untyped throws will produce "any Error", functions that
/// cannot throw or are specified to throw "Never" will return llvm::None.
llvm::Optional<Type> getEffectiveThrownInterfaceType() const;

llvm::Optional<Type> getEffectiveThrownErrorType() const;

/// Retrieve the "effective" thrown interface type, or `Never` if
/// this function cannot throw.
///
/// Functions with untyped throws will produce `any Error`, functions that
/// cannot throw or are specified to throw `Never` will return `Never`.
Type getEffectiveThrownErrorTypeOrNever() const;

/// Returns true if the function type stores a Clang type that cannot
/// be derived from its Swift type. Returns false otherwise, including if
/// the function type is not @convention(c) or @convention(block).
Expand Down
4 changes: 2 additions & 2 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -951,15 +951,15 @@ Type AbstractFunctionDecl::getThrownInterfaceType() const {
}

llvm::Optional<Type>
AbstractFunctionDecl::getEffectiveThrownInterfaceType() const {
AbstractFunctionDecl::getEffectiveThrownErrorType() const {
Type interfaceType = getInterfaceType();
if (hasImplicitSelfDecl()) {
if (auto fnType = interfaceType->getAs<AnyFunctionType>())
interfaceType = fnType->getResult();
}

return interfaceType->castTo<AnyFunctionType>()
->getEffectiveThrownInterfaceType();
->getEffectiveThrownErrorType();
}

Expr *AbstractFunctionDecl::getSingleExpressionBody() const {
Expand Down
2 changes: 1 addition & 1 deletion lib/AST/Expr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1937,7 +1937,7 @@ Type AbstractClosureExpr::getResultType(

llvm::Optional<Type> AbstractClosureExpr::getEffectiveThrownType() const {
return getType()->castTo<AnyFunctionType>()
->getEffectiveThrownInterfaceType();
->getEffectiveThrownErrorType();
}

bool AbstractClosureExpr::isBodyThrowing() const {
Expand Down
9 changes: 8 additions & 1 deletion lib/AST/Type.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5419,7 +5419,7 @@ AnyFunctionType *AnyFunctionType::getWithoutThrowing() const {
return withExtInfo(info);
}

llvm::Optional<Type> AnyFunctionType::getEffectiveThrownInterfaceType() const {
llvm::Optional<Type> AnyFunctionType::getEffectiveThrownErrorType() const {
// A non-throwing function... has no thrown interface type.
if (!isThrowing())
return llvm::None;
Expand All @@ -5437,6 +5437,13 @@ llvm::Optional<Type> AnyFunctionType::getEffectiveThrownInterfaceType() const {
return thrownError;
}

Type AnyFunctionType::getEffectiveThrownErrorTypeOrNever() const {
if (auto thrown = getEffectiveThrownErrorType())
return *thrown;

return getASTContext().getNeverType();
}

llvm::Optional<TangentSpace>
TypeBase::getAutoDiffTangentSpace(LookupConformanceFn lookupConformance) {
assert(lookupConformance);
Expand Down
2 changes: 1 addition & 1 deletion lib/SILGen/SILGenBackDeploy.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ void SILGenFunction::emitBackDeploymentThunk(SILDeclRef thunk) {
}

prepareEpilog(getResultInterfaceType(AFD),
AFD->getEffectiveThrownInterfaceType(),
AFD->getEffectiveThrownErrorType(),
CleanupLocation(AFD));

SILBasicBlock *availableBB = createBasicBlock("availableBB");
Expand Down
6 changes: 3 additions & 3 deletions lib/SILGen/SILGenConstructor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ void SILGenFunction::emitValueConstructor(ConstructorDecl *ctor) {
// Create a basic block to jump to for the implicit 'self' return.
// We won't emit this until after we've emitted the body.
// The epilog takes a void return because the return of 'self' is implicit.
prepareEpilog(llvm::None, ctor->getEffectiveThrownInterfaceType(),
prepareEpilog(llvm::None, ctor->getEffectiveThrownErrorType(),
CleanupLocation(ctor));

// If the constructor can fail, set up an alternative epilog for constructor
Expand Down Expand Up @@ -1185,7 +1185,7 @@ void SILGenFunction::emitClassConstructorInitializer(ConstructorDecl *ctor) {

// Create a basic block to jump to for the implicit 'self' return.
// We won't emit the block until after we've emitted the body.
prepareEpilog(llvm::None, ctor->getEffectiveThrownInterfaceType(),
prepareEpilog(llvm::None, ctor->getEffectiveThrownErrorType(),
CleanupLocation(endOfInitLoc));

auto resultType = ctor->mapTypeIntoContext(ctor->getResultInterfaceType());
Expand Down Expand Up @@ -1751,7 +1751,7 @@ void SILGenFunction::emitInitAccessor(AccessorDecl *accessor) {
}

prepareEpilog(accessor->getResultInterfaceType(),
accessor->getEffectiveThrownInterfaceType(),
accessor->getEffectiveThrownErrorType(),
CleanupLocation(accessor));

emitProfilerIncrement(accessor->getTypecheckedBody());
Expand Down
2 changes: 1 addition & 1 deletion lib/SILGen/SILGenFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1051,7 +1051,7 @@ void SILGenFunction::emitFunction(FuncDecl *fd) {
emitDistributedActorFactory(fd);
} else {
prepareEpilog(fd->getResultInterfaceType(),
fd->getEffectiveThrownInterfaceType(), CleanupLocation(fd));
fd->getEffectiveThrownErrorType(), CleanupLocation(fd));

if (fd->requiresUnavailableDeclABICompatibilityStubs())
emitApplyOfUnavailableCodeReached();
Expand Down
133 changes: 45 additions & 88 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

#include "CSDiagnostics.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckEffects.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
Expand Down Expand Up @@ -2945,28 +2946,6 @@ 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,
Expand All @@ -2978,82 +2957,45 @@ matchFunctionThrowing(ConstraintSystem &cs,
// 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))
Type thrownError1 = func1->getEffectiveThrownErrorTypeOrNever();
Type thrownError2 = func2->getEffectiveThrownErrorTypeOrNever();
if (!thrownError1 || !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) {
switch (compareThrownErrorsForSubtyping(thrownError1, thrownError2, cs.DC)) {
case ThrownErrorSubtyping::DropsThrows: {
// We need to drop 'throws' to make this work.
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);

return cs.getTypeMatchSuccess();
}

// If we need to unify the thrown error types, do so now.
if (mustUnify) {
case ThrownErrorSubtyping::ExactMatch:
return cs.getTypeMatchSuccess();

case ThrownErrorSubtyping::Subtype:
// We know this is going to work, but we might still need to generate a
// constraint if one of the error types involves type variables.
if (thrownError1->hasTypeVariable() || thrownError2->hasTypeVariable()) {
// Fall through to the dependent case.
} else if (kind < ConstraintKind::Subtype) {
// We aren't allowed to have a subtype, so fail here.
return cs.getTypeMatchFailure(locator);
} else {
// We have a subtype. All set!
return cs.getTypeMatchSuccess();
}
LLVM_FALLTHROUGH;

case ThrownErrorSubtyping::Dependent: {
// The presence of type variables in the thrown error types require that
// we generate a constraint to unify the thrown error types, so do so now.
ConstraintKind subKind = (kind < ConstraintKind::Subtype)
? ConstraintKind::Equal
: ConstraintKind::Subtype;
Expand All @@ -3064,9 +3006,24 @@ matchFunctionThrowing(ConstraintSystem &cs,
locator.withPathElement(LocatorPathElt::ThrownErrorType()));
if (result == ConstraintSystem::SolutionKind::Error)
return cs.getTypeMatchFailure(locator);

return cs.getTypeMatchSuccess();
}

return cs.getTypeMatchSuccess();
case ThrownErrorSubtyping::Mismatch: {
auto thrownErrorLocator = cs.getConstraintLocator(
locator.withPathElement(LocatorPathElt::ThrownErrorType()));
if (!cs.shouldAttemptFixes())
return cs.getTypeMatchFailure(thrownErrorLocator);

auto *fix = IgnoreThrownErrorMismatch::create(
cs, thrownError1, thrownError2, thrownErrorLocator);
if (cs.recordFix(fix))
return cs.getTypeMatchFailure(thrownErrorLocator);

return cs.getTypeMatchSuccess();
}
}
}

ConstraintSystem::TypeMatchResult
Expand Down
Loading