Skip to content

Commit 26e51e0

Browse files
committed
[ConstraintSystem] Fix: Try to match argument to element type if parameter is a collection
This allows better diagnostics in cases where collection element is a generic parameter which is supposed to be inferred from argument e.g. ```swift func foo<T>(_: [T]) {} foo(1) // Missing brackets, so error should be about [Int] vs. Int ```
1 parent 587d297 commit 26e51e0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

lib/Sema/CSSimplify.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2659,6 +2659,31 @@ bool ConstraintSystem::repairFailures(
26592659
break;
26602660
}
26612661

2662+
// If parameter is a collection but argument is not, let's try
2663+
// to try and match collection element type to the argument to
2664+
// produce better diagnostics e.g.:
2665+
//
2666+
// ```
2667+
// func foo<T>(_: [T]) {}
2668+
// foo(1) // expected '[Int]', got 'Int'
2669+
// ```
2670+
if (isCollectionType(rhs)) {
2671+
std::function<Type(Type)> getArrayOrSetType = [&](Type type) -> Type {
2672+
if (auto eltTy = isArrayType(type))
2673+
return getArrayOrSetType(*eltTy);
2674+
2675+
if (auto eltTy = isSetType(type))
2676+
return getArrayOrSetType(*eltTy);
2677+
2678+
return type;
2679+
};
2680+
2681+
// Let's ignore any optional types associated with element e.g. `[T?]`
2682+
auto rhsEltTy = getArrayOrSetType(rhs)->lookThroughAllOptionalTypes();
2683+
(void)matchTypes(lhs, rhsEltTy, ConstraintKind::Equal, TMF_ApplyingFix,
2684+
locator);
2685+
}
2686+
26622687
conversionsOrFixes.push_back(
26632688
AllowArgumentMismatch::create(*this, lhs, rhs, loc));
26642689
break;

0 commit comments

Comments
 (0)