Skip to content

Sema: Fix handling of getter typed throws in witness matching #80445

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 4 commits into from
Apr 2, 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
7 changes: 2 additions & 5 deletions include/swift/AST/IRGenOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#define SWIFT_AST_IRGENOPTIONS_H

#include "swift/AST/LinkLibrary.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/PathRemapper.h"
#include "swift/Basic/Sanitizers.h"
#include "swift/Basic/OptionSet.h"
Expand Down Expand Up @@ -655,11 +656,7 @@ class IRGenOptions {
TypeInfoFilter(TypeInfoDumpFilter::All),
PlatformCCallingConvention(llvm::CallingConv::C), UseCASBackend(false),
CASObjMode(llvm::CASBackendMode::Native) {
#ifndef NDEBUG
DisableRoundTripDebugTypes = false;
#else
DisableRoundTripDebugTypes = true;
#endif
DisableRoundTripDebugTypes = !CONDITIONAL_ASSERT_enabled();
}

/// Appends to \p os an arbitrary string representing all options which
Expand Down
102 changes: 72 additions & 30 deletions lib/Sema/AssociatedTypeInference.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1908,27 +1908,16 @@ static Type getWithoutProtocolTypeAliases(Type type) {
///
/// Also see simplifyCurrentTypeWitnesses().
static Type getWitnessTypeForMatching(NormalProtocolConformance *conformance,
ValueDecl *witness) {
if (witness->isRecursiveValidation()) {
LLVM_DEBUG(llvm::dbgs() << "Recursive validation\n";);
return Type();
}

if (witness->isInvalid()) {
LLVM_DEBUG(llvm::dbgs() << "Invalid witness\n";);
return Type();
}

ValueDecl *witness, Type type) {
if (!witness->getDeclContext()->isTypeContext()) {
// FIXME: Could we infer from 'Self' to make these work?
return witness->getInterfaceType();
return type;
}

// Retrieve the set of substitutions to be applied to the witness.
Type model =
conformance->getDeclContext()->mapTypeIntoContext(conformance->getType());
TypeSubstitutionMap substitutions = model->getMemberSubstitutions(witness);
Type type = witness->getInterfaceType()->getReferenceStorageReferent();

type = getWithoutProtocolTypeAliases(type);

Expand Down Expand Up @@ -2082,14 +2071,20 @@ AssociatedTypeInference::inferTypeWitnessesViaAssociatedType(
!witnessHasImplementsAttrForRequiredName(typeDecl, assocType))
continue;

// Determine the witness type.
Type witnessType = getWitnessTypeForMatching(conformance, typeDecl);
if (!witnessType) continue;
if (typeDecl->isInvalid()) {
LLVM_DEBUG(llvm::dbgs() << "Recursive validation\n";);
continue;
}

if (auto witnessMetaType = witnessType->getAs<AnyMetatypeType>())
witnessType = witnessMetaType->getInstanceType();
else
if (typeDecl->isRecursiveValidation()) {
LLVM_DEBUG(llvm::dbgs() << "Recursive validation\n";);
continue;
}

// Determine the witness type.
Type witnessType = getWitnessTypeForMatching(conformance, typeDecl,
typeDecl->getDeclaredInterfaceType());
if (!witnessType) continue;

if (result.empty()) {
// If we found at least one default candidate, we must allow for the
Expand Down Expand Up @@ -2177,21 +2172,60 @@ AssociatedTypeInference::getPotentialTypeWitnessesByMatchingTypes(ValueDecl *req
InferredAssociatedTypesByWitness inferred;
inferred.Witness = witness;

// Compute the requirement and witness types we'll use for matching.
Type fullWitnessType = getWitnessTypeForMatching(conformance, witness);
if (!fullWitnessType) {
auto reqType = removeSelfParam(req, req->getInterfaceType());
Type witnessType;

if (witness->isRecursiveValidation()) {
LLVM_DEBUG(llvm::dbgs() << "Recursive validation\n";);
return inferred;
}

LLVM_DEBUG(llvm::dbgs() << "Witness type for matching is "
<< fullWitnessType << "\n";);
if (witness->isInvalid()) {
LLVM_DEBUG(llvm::dbgs() << "Invalid witness\n";);
return inferred;
}

auto setup =
[&]() -> std::tuple<std::optional<RequirementMatch>, Type, Type> {
fullWitnessType = removeSelfParam(witness, fullWitnessType);
[&]() -> std::tuple<std::optional<RequirementMatch>, Type, Type, Type, Type> {
// Compute the requirement and witness types we'll use for matching.
witnessType = witness->getInterfaceType()->getReferenceStorageReferent();
witnessType = getWitnessTypeForMatching(conformance, witness, witnessType);

LLVM_DEBUG(llvm::dbgs() << "Witness type for matching is "
<< witnessType << "\n";);

witnessType = removeSelfParam(witness, witnessType);

Type reqThrownError;
Type witnessThrownError;

if (auto *witnessASD = dyn_cast<AbstractStorageDecl>(witness)) {
auto *reqASD = cast<AbstractStorageDecl>(req);

// Dig out the thrown error types from the getter so we can compare them
// later.
auto getThrownErrorType = [](AbstractStorageDecl *asd) -> Type {
if (auto getter = asd->getEffectfulGetAccessor()) {
if (Type thrownErrorType = getter->getThrownInterfaceType()) {
return thrownErrorType;
} else if (getter->hasThrows()) {
return asd->getASTContext().getErrorExistentialType();
}
}

return asd->getASTContext().getNeverType();
};

reqThrownError = getThrownErrorType(reqASD);

witnessThrownError = getThrownErrorType(witnessASD);
witnessThrownError = getWitnessTypeForMatching(conformance, witness,
witnessThrownError);
}

return std::make_tuple(std::nullopt,
removeSelfParam(req, req->getInterfaceType()),
fullWitnessType);
reqType, witnessType,
reqThrownError, witnessThrownError);
};

/// Visits a requirement type to match it to a potential witness for
Expand Down Expand Up @@ -2327,7 +2361,7 @@ AssociatedTypeInference::getPotentialTypeWitnessesByMatchingTypes(ValueDecl *req
Type witnessType) -> std::optional<RequirementMatch> {
if (!matchVisitor.match(reqType, witnessType)) {
return RequirementMatch(witness, MatchKind::TypeConflict,
fullWitnessType);
witnessType);
}

return std::nullopt;
Expand All @@ -2340,7 +2374,7 @@ AssociatedTypeInference::getPotentialTypeWitnessesByMatchingTypes(ValueDecl *req
return RequirementMatch(witness,
anyRenaming ? MatchKind::RenamedMatch
: MatchKind::ExactMatch,
fullWitnessType);
witnessType);

};

Expand Down Expand Up @@ -4587,5 +4621,13 @@ ReferencedAssociatedTypesRequest::evaluate(Evaluator &eval,
reqTy->getCanonicalType().walk(walker);
}

if (auto *asd = dyn_cast<AbstractStorageDecl>(req)) {
if (auto getter = asd->getEffectfulGetAccessor()) {
if (Type thrownErrorType = getter->getThrownInterfaceType()) {
thrownErrorType->getCanonicalType().walk(walker);
}
}
}

return assocTypes;
}
6 changes: 5 additions & 1 deletion lib/Sema/TypeCheckEffects.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4897,7 +4897,11 @@ static ThrownErrorClassification classifyThrownErrorType(Type type) {
return ThrownErrorClassification::AnyError;
}

if (type->hasTypeVariable() || type->hasTypeParameter())
// All three cases come up. The first one from the "real" witness matcher,
// and the other two from associated type inference.
if (type->hasTypeVariable() ||
type->hasTypeParameter() ||
type->hasPrimaryArchetype())
return ThrownErrorClassification::Dependent;

return ThrownErrorClassification::Specific;
Expand Down
88 changes: 50 additions & 38 deletions lib/Sema/TypeCheckProtocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -512,8 +512,7 @@ checkEffects(AbstractStorageDecl *witness, AbstractStorageDecl *req) {
/// to be used by `matchWitness`.
static std::optional<RequirementMatch>
matchWitnessStructureImpl(ValueDecl *req, ValueDecl *witness,
bool &decomposeFunctionType, bool &ignoreReturnType,
Type &reqThrownError, Type &witnessThrownError) {
bool &decomposeFunctionType, bool &ignoreReturnType) {
assert(!req->isInvalid() && "Cannot have an invalid requirement here");

/// Make sure the witness is of the same kind as the requirement.
Expand Down Expand Up @@ -658,23 +657,6 @@ matchWitnessStructureImpl(ValueDecl *req, ValueDecl *witness,

// Decompose the parameters for subscript declarations.
decomposeFunctionType = isa<SubscriptDecl>(req);

// Dig out the thrown error types from the getter so we can compare them
// later.
auto getThrownErrorType = [](AbstractStorageDecl *asd) -> Type {
if (auto getter = asd->getEffectfulGetAccessor()) {
if (Type thrownErrorType = getter->getThrownInterfaceType()) {
return thrownErrorType;
} else if (getter->hasThrows()) {
return asd->getASTContext().getAnyExistentialType();
}
}

return asd->getASTContext().getNeverType();
};

reqThrownError = getThrownErrorType(reqASD);
witnessThrownError = getThrownErrorType(witnessASD);
} else if (isa<ConstructorDecl>(witness)) {
decomposeFunctionType = true;
ignoreReturnType = true;
Expand Down Expand Up @@ -713,39 +695,33 @@ bool swift::TypeChecker::witnessStructureMatches(ValueDecl *req,
const ValueDecl *witness) {
bool decomposeFunctionType = false;
bool ignoreReturnType = false;
Type reqThrownError;
Type witnessThrownError;
return matchWitnessStructureImpl(req, const_cast<ValueDecl *>(witness),
decomposeFunctionType, ignoreReturnType,
reqThrownError,
witnessThrownError) == std::nullopt;
decomposeFunctionType, ignoreReturnType)
== std::nullopt;
}

RequirementMatch swift::matchWitness(
DeclContext *dc, ValueDecl *req, ValueDecl *witness,
llvm::function_ref<
std::tuple<std::optional<RequirementMatch>, Type, Type>(void)>
std::tuple<std::optional<RequirementMatch>, Type, Type, Type, Type>(void)>
setup,
llvm::function_ref<std::optional<RequirementMatch>(Type, Type)> matchTypes,
llvm::function_ref<RequirementMatch(bool, ArrayRef<OptionalAdjustment>)>
finalize) {
bool decomposeFunctionType = false;
bool ignoreReturnType = false;
Type reqThrownError;
Type witnessThrownError;

if (auto StructuralMismatch = matchWitnessStructureImpl(
req, witness, decomposeFunctionType, ignoreReturnType, reqThrownError,
witnessThrownError)) {
req, witness, decomposeFunctionType, ignoreReturnType)) {
return *StructuralMismatch;
}

// Set up the match, determining the requirement and witness types
// in the process.
Type reqType, witnessType;
Type reqType, witnessType, reqThrownError, witnessThrownError;
{
std::optional<RequirementMatch> result;
std::tie(result, reqType, witnessType) = setup();
std::tie(result, reqType, witnessType, reqThrownError, witnessThrownError) = setup();
if (result) {
return std::move(result.value());
}
Expand Down Expand Up @@ -936,7 +912,8 @@ RequirementMatch swift::matchWitness(

case ThrownErrorSubtyping::Subtype:
// If there were no type parameters, we're done.
if (!reqThrownError->hasTypeParameter())
if (!reqThrownError->hasTypeVariable() &&
!reqThrownError->hasTypeParameter())
break;

LLVM_FALLTHROUGH;
Expand Down Expand Up @@ -1186,7 +1163,7 @@ swift::matchWitness(WitnessChecker::RequirementEnvironmentCache &reqEnvCache,

// Set up the constraint system for matching.
auto setup =
[&]() -> std::tuple<std::optional<RequirementMatch>, Type, Type> {
[&]() -> std::tuple<std::optional<RequirementMatch>, Type, Type, Type, Type> {
// Construct a constraint system to use to solve the equality between
// the required type and the witness type.
cs.emplace(dc, ConstraintSystemFlags::AllowFixes);
Expand All @@ -1199,10 +1176,12 @@ swift::matchWitness(WitnessChecker::RequirementEnvironmentCache &reqEnvCache,
if (syntheticEnv)
selfTy = syntheticEnv->mapTypeIntoContext(selfTy);


// Open up the type of the requirement.
SmallVector<OpenedType, 4> reqReplacements;

reqLocator =
cs->getConstraintLocator(req, ConstraintLocator::ProtocolRequirement);
SmallVector<OpenedType, 4> reqReplacements;
reqType =
cs->getTypeOfMemberReference(selfTy, req, dc,
/*isDynamicResult=*/false,
Expand Down Expand Up @@ -1235,14 +1214,17 @@ swift::matchWitness(WitnessChecker::RequirementEnvironmentCache &reqEnvCache,
}

// Open up the witness type.
SmallVector<OpenedType, 4> witnessReplacements;

witnessType = witness->getInterfaceType();
witnessLocator =
cs->getConstraintLocator(req, LocatorPathElt::Witness(witness));
if (witness->getDeclContext()->isTypeContext()) {
openWitnessType =
cs->getTypeOfMemberReference(
selfTy, witness, dc, /*isDynamicResult=*/false,
FunctionRefInfo::doubleBaseNameApply(), witnessLocator)
cs->getTypeOfMemberReference(selfTy, witness, dc,
/*isDynamicResult=*/false,
FunctionRefInfo::doubleBaseNameApply(),
witnessLocator, &witnessReplacements)
.adjustedReferenceType;
} else {
openWitnessType =
Expand All @@ -1253,7 +1235,37 @@ swift::matchWitness(WitnessChecker::RequirementEnvironmentCache &reqEnvCache,
}
openWitnessType = openWitnessType->getRValueType();

return std::make_tuple(std::nullopt, reqType, openWitnessType);
Type reqThrownError;
Type witnessThrownError;

if (auto *witnessASD = dyn_cast<AbstractStorageDecl>(witness)) {
auto *reqASD = cast<AbstractStorageDecl>(req);

// Dig out the thrown error types from the getter so we can compare them
// later.
auto getThrownErrorType = [](AbstractStorageDecl *asd) -> Type {
if (auto getter = asd->getEffectfulGetAccessor()) {
if (Type thrownErrorType = getter->getThrownInterfaceType()) {
return thrownErrorType;
} else if (getter->hasThrows()) {
return asd->getASTContext().getErrorExistentialType();
}
}

return asd->getASTContext().getNeverType();
};

reqThrownError = getThrownErrorType(reqASD);
reqThrownError = cs->openType(reqThrownError, reqReplacements,
reqLocator);

witnessThrownError = getThrownErrorType(witnessASD);
witnessThrownError = cs->openType(witnessThrownError, witnessReplacements,
witnessLocator);
}

return std::make_tuple(std::nullopt, reqType, openWitnessType,
reqThrownError, witnessThrownError);
};

// Match a type in the requirement to a type in the witness.
Expand Down
2 changes: 1 addition & 1 deletion lib/Sema/TypeCheckProtocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ class ConformanceChecker : public WitnessChecker {
RequirementMatch matchWitness(
DeclContext *dc, ValueDecl *req, ValueDecl *witness,
llvm::function_ref<
std::tuple<std::optional<RequirementMatch>, Type, Type>(void)>
std::tuple<std::optional<RequirementMatch>, Type, Type, Type, Type>(void)>
setup,
llvm::function_ref<std::optional<RequirementMatch>(Type, Type)> matchTypes,
llvm::function_ref<RequirementMatch(bool, ArrayRef<OptionalAdjustment>)>
Expand Down
Loading