Skip to content

[CS] Avoid solver-allocated inputs with typesSatisfyConstraint #82147

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 5 commits into from
Jun 13, 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
6 changes: 6 additions & 0 deletions include/swift/AST/Types.h
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,12 @@ class alignas(1 << TypeAlignInBits) TypeBase
return getRecursiveProperties().hasTypeVariable();
}

// Convenience for checking whether the given type either has a type
// variable or placeholder.
bool hasTypeVariableOrPlaceholder() const {
return hasTypeVariable() || hasPlaceholder();
}

/// Determine where this type is a type variable or a dependent
/// member root in a type variable.
bool isTypeVariableOrMember();
Expand Down
4 changes: 1 addition & 3 deletions include/swift/Sema/ConstraintSystem.h
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,7 @@ enum class FreeTypeVariableBinding {
/// Disallow any binding of such free type variables.
Disallow,
/// Allow the free type variables to persist in the solution.
Allow,
/// Bind the type variables to UnresolvedType to represent the ambiguity.
UnresolvedType
Allow
};

/// Describes whether or not a result builder method is supported.
Expand Down
18 changes: 9 additions & 9 deletions lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3577,7 +3577,13 @@ void LocatableType::Profile(llvm::FoldingSetNodeID &id, SourceLoc loc,
Type ErrorType::get(const ASTContext &C) { return C.TheErrorType; }

Type ErrorType::get(Type originalType) {
assert(originalType);
ASSERT(originalType);
// We don't currently support solver-allocated error types, if we want
// this in the future we'll need to adjust `Solution::simplifyType` to fold
// them into regular ErrorTypes. Additionally, any clients of
// `typesSatisfyConstraint` will need to be taught not to pass such types.
ASSERT(!originalType->getRecursiveProperties().isSolverAllocated() &&
"Solver-allocated error types not supported");

auto originalProperties = originalType->getRecursiveProperties();
auto arena = getArena(originalProperties);
Expand All @@ -3588,14 +3594,8 @@ Type ErrorType::get(Type originalType) {

void *mem = ctx.Allocate(sizeof(ErrorType) + sizeof(Type),
alignof(ErrorType), arena);
RecursiveTypeProperties properties = RecursiveTypeProperties::HasError;

// We need to preserve the solver allocated bit, to ensure any wrapping
// types are solver allocated too.
if (originalProperties.isSolverAllocated())
properties |= RecursiveTypeProperties::SolverAllocated;

return entry = new (mem) ErrorType(ctx, originalType, properties);
return entry = new (mem) ErrorType(ctx, originalType,
RecursiveTypeProperties::HasError);
}

void ErrorUnionType::Profile(llvm::FoldingSetNodeID &id, ArrayRef<Type> terms) {
Expand Down
9 changes: 7 additions & 2 deletions lib/AST/TypeSubstitution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -446,8 +446,13 @@ Type TypeSubstituter::transformDependentMemberType(DependentMemberType *dependen

auto result = conformance.getTypeWitness(assocType, IFS.getOptions());
if (result->is<ErrorType>()) {
// Substitute the base type for the original ErrorType for type printing.
// Avoid doing this if the substitutions introduce type variables or
// placeholders since ErrorTypes can't be solver-allocated currently (and
// type variables aren't helpful when printing anyway).
auto substBase = origBase.subst(IFS);
return DependentMemberType::get(ErrorType::get(substBase), assocType);
if (!substBase->hasTypeVariableOrPlaceholder())
return DependentMemberType::get(ErrorType::get(substBase), assocType);
}
return result;
}
Expand Down Expand Up @@ -1242,4 +1247,4 @@ ProtocolConformanceRef ReplaceExistentialArchetypesWithConcreteTypes::operator()

return subs.lookupConformance(
getInterfaceType(existentialArchetype)->getCanonicalType(), proto);
}
}
7 changes: 5 additions & 2 deletions lib/Sema/CSFix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,12 @@ CoerceToCheckedCast *CoerceToCheckedCast::attempt(ConstraintSystem &cs,
Type fromType, Type toType,
bool useConditionalCast,
ConstraintLocator *locator) {
// If any of the types has a type variable, don't add the fix.
if (fromType->hasTypeVariable() || toType->hasTypeVariable())
// If any of the types have type variables or placeholders, don't add the fix.
// `typeCheckCheckedCast` doesn't support checking such types.
if (fromType->hasTypeVariableOrPlaceholder() ||
toType->hasTypeVariableOrPlaceholder()) {
return nullptr;
}

auto anchor = locator->getAnchor();
if (auto *assignExpr = getAsExpr<AssignExpr>(anchor))
Expand Down
33 changes: 10 additions & 23 deletions lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4872,29 +4872,16 @@ bool ConstraintSystem::generateConstraints(
return convertTypeLocator;
};

// Substitute type variables in for placeholder types (and unresolved
// types, if allowed).
if (allowFreeTypeVariables == FreeTypeVariableBinding::UnresolvedType) {
convertType = convertType.transformRec([&](Type type) -> std::optional<Type> {
if (type->is<UnresolvedType>() || type->is<PlaceholderType>()) {
return Type(createTypeVariable(getLocator(type),
TVO_CanBindToNoEscape |
TVO_PrefersSubtypeBinding |
TVO_CanBindToHole));
}
return std::nullopt;
});
} else {
convertType = convertType.transformRec([&](Type type) -> std::optional<Type> {
if (type->is<PlaceholderType>()) {
return Type(createTypeVariable(getLocator(type),
TVO_CanBindToNoEscape |
TVO_PrefersSubtypeBinding |
TVO_CanBindToHole));
}
return std::nullopt;
});
}
// Substitute type variables in for placeholder types.
convertType = convertType.transformRec([&](Type type) -> std::optional<Type> {
if (type->is<PlaceholderType>()) {
return Type(createTypeVariable(getLocator(type),
TVO_CanBindToNoEscape |
TVO_PrefersSubtypeBinding |
TVO_CanBindToHole));
}
return std::nullopt;
});

addContextualConversionConstraint(expr, convertType, ctp,
convertTypeLocator);
Expand Down
33 changes: 7 additions & 26 deletions lib/Sema/CSRanking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1413,26 +1413,10 @@ SolutionCompareResult ConstraintSystem::compareSolutions(
auto type1 = types.Type1;
auto type2 = types.Type2;

// If either of the types still contains type variables, we can't
// compare them.
// FIXME: This is really unfortunate. More type variable sharing
// (when it's sound) would help us do much better here.
if (type1->hasTypeVariable() || type2->hasTypeVariable()) {
identical = false;
continue;
}

// With introduction of holes it's currently possible to form solutions
// with UnresolvedType bindings, we need to account for that in
// ranking. If one solution has a hole for a given type variable
// it's always worse than any non-hole type other solution might have.
if (type1->is<UnresolvedType>() || type2->is<UnresolvedType>()) {
if (type1->is<UnresolvedType>()) {
++score2;
} else {
++score1;
}

// If either of the types have holes or unresolved type variables, we can't
// compare them. `isSubtypeOf` cannot be used with solver-allocated types.
if (type1->hasTypeVariableOrPlaceholder() ||
type2->hasTypeVariableOrPlaceholder()) {
identical = false;
continue;
}
Expand Down Expand Up @@ -1469,15 +1453,12 @@ SolutionCompareResult ConstraintSystem::compareSolutions(
// The systems are not considered equivalent.
identical = false;

// Archetypes are worse than concrete types (i.e. non-placeholder and
// non-archetype)
// Archetypes are worse than concrete types
// FIXME: Total hack.
if (type1->is<ArchetypeType>() && !type2->is<ArchetypeType>() &&
!type2->is<PlaceholderType>()) {
if (type1->is<ArchetypeType>() && !type2->is<ArchetypeType>()) {
++score2;
continue;
} else if (type2->is<ArchetypeType>() && !type1->is<ArchetypeType>() &&
!type1->is<PlaceholderType>()) {
} else if (type2->is<ArchetypeType>() && !type1->is<ArchetypeType>()) {
++score1;
continue;
}
Expand Down
14 changes: 10 additions & 4 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4909,8 +4909,12 @@ static bool
repairViaBridgingCast(ConstraintSystem &cs, Type fromType, Type toType,
SmallVectorImpl<RestrictionOrFix> &conversionsOrFixes,
ConstraintLocatorBuilder locator) {
if (fromType->hasTypeVariable() || toType->hasTypeVariable())
// Don't check if any of the types have type variables or placeholders,
// `typeCheckCheckedCast` doesn't support checking solver-allocated types.
if (fromType->hasTypeVariableOrPlaceholder() ||
toType->hasTypeVariableOrPlaceholder()) {
return false;
}

auto objectType1 = fromType->getOptionalObjectType();
auto objectType2 = toType->getOptionalObjectType();
Expand Down Expand Up @@ -9375,10 +9379,12 @@ static ConstraintFix *maybeWarnAboutExtraneousCast(
if (locator.endsWith<LocatorPathElt::GenericArgument>())
return nullptr;

// Both types have to be fixed.
if (fromType->hasTypeVariable() || toType->hasTypeVariable() ||
fromType->hasPlaceholder() || toType->hasPlaceholder())
// Both types have to be resolved, `typeCheckCheckedCast` doesn't support
// checking solver-allocated types.
if (fromType->hasTypeVariableOrPlaceholder() ||
toType->hasTypeVariableOrPlaceholder()) {
return nullptr;
}

SmallVector<LocatorPathElt, 4> path;
auto anchor = locator.getLocatorParts(path);
Expand Down
4 changes: 0 additions & 4 deletions lib/Sema/CSSolver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,6 @@ Solution ConstraintSystem::finalize() {

case FreeTypeVariableBinding::Allow:
break;

case FreeTypeVariableBinding::UnresolvedType:
assignFixedType(tv, ctx.TheUnresolvedType);
break;
}
}

Expand Down
10 changes: 8 additions & 2 deletions lib/Sema/TypeCheckConstraints.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1080,8 +1080,14 @@ bool TypeChecker::typesSatisfyConstraint(Type type1, Type type2,
bool openArchetypes,
ConstraintKind kind, DeclContext *dc,
bool *unwrappedIUO) {
assert(!type1->hasTypeVariable() && !type2->hasTypeVariable() &&
"Unexpected type variable in constraint satisfaction testing");
// Don't allow any type variables to leak into the nested ConstraintSystem
// (including as originator types for placeholders). This also ensure that we
// avoid lifetime issues for e.g cases where we lazily populate the
// `ContextSubMap` on `NominalOrBoundGenericNominalType` in the nested arena,
// since it will be destroyed on leaving.
ASSERT(!type1->getRecursiveProperties().isSolverAllocated() &&
!type2->getRecursiveProperties().isSolverAllocated() &&
"Cannot escape solver-allocated types into a nested ConstraintSystem");

ConstraintSystem cs(dc, ConstraintSystemOptions());
if (openArchetypes) {
Expand Down
3 changes: 1 addition & 2 deletions lib/Sema/TypeOfReference.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1134,8 +1134,7 @@ static void bindArchetypesFromContext(
if (parentDC->isTypeContext()) {
if (parentDC != outerDC && parentDC->getSelfProtocolDecl()) {
auto selfTy = parentDC->getSelfInterfaceType();
auto contextTy = cs.getASTContext().TheUnresolvedType;
bindPrimaryArchetype(selfTy, contextTy);
bindPrimaryArchetype(selfTy, ErrorType::get(cs.getASTContext()));
}
continue;
}
Expand Down
20 changes: 20 additions & 0 deletions validation-test/IDE/crashers_2_fixed/pr-82147.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// RUN: %target-swift-ide-test -code-completion -code-completion-token=COMPLETE -source-filename=%s

// https://github.com/swiftlang/swift/pull/82147

protocol P {
associatedtype X
}

struct S<T> {
init<U, V>() where T == (U, V) {}
}
extension S : P where T : P {
typealias X = T.X
}

func foo<T: P, U>(_: () -> T) where U == T.X {}

foo {
S(#^COMPLETE^#)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// {"signature":"bool llvm::function_ref<bool (swift::ProtocolConformanceRef)>::callback_fn<(anonymous namespace)::MismatchedIsolatedConformances>(long, swift::ProtocolConformanceRef)"}
// RUN: not %target-swift-frontend -typecheck %s
func a {
{ print("\(\ " ")\n"
}
"\()\n"
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// {"signature":"swift::ProtocolConformanceRef::forEachMissingConformance(llvm::function_ref<bool (swift::BuiltinProtocolConformance*)>) const"}
// RUN: not --crash %target-swift-frontend -typecheck %s
// REQUIRES: rdar152763265
// RUN: not %target-swift-frontend -typecheck %s
.a == .! == b / c
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// {"signature":"swift::GenericParamKey::findIndexIn(llvm::ArrayRef<swift::GenericTypeParamType*>) const"}
// RUN: not --crash %target-swift-frontend -typecheck %s
// REQUIRES: rdar152763265
// RUN: not %target-swift-frontend -typecheck %s
a[[[[ a a?[[a a?
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// {"signature":"swift::ProtocolConformanceRef::forAbstract(swift::Type, swift::ProtocolDecl*)"}
// RUN: not --crash %target-swift-frontend -typecheck %s
// REQUIRES: rdar152763265
// RUN: not %target-swift-frontend -typecheck %s
@resultBuilder struct a {
static buildBlock<b, c, d, e>(b, c, d, e) func f<h>(_ : Bool @a Bool->h) { f(true {
cond in var g : Int g 2 30\ g
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// {"signature":"(anonymous namespace)::ApplyClassifier::classifyApply(swift::ApplyExpr*, llvm::DenseSet<swift::Expr const*, llvm::DenseMapInfo<swift::Expr const*, void>>*)"}
// RUN: not %target-swift-frontend -typecheck %s
let a = switch \0 {
case 0.0