Skip to content

Commit 91c6425

Browse files
authored
Merge pull request swiftlang#78272 from xedin/rdar-140300022-6.1
[6.1][TypeChecker/SILGen] Allow `any Sendable` to match `Any` while matching generic arguments
2 parents 99a9d61 + fde6f50 commit 91c6425

20 files changed

+725
-20
lines changed

include/swift/AST/DiagnosticsSema.def

+3
Original file line numberDiff line numberDiff line change
@@ -2789,6 +2789,9 @@ ERROR(types_not_inherited_decl,none,
27892789
ERROR(types_not_inherited_in_decl_ref,none,
27902790
"referencing %kind0 on %1 requires that %2 inherit from %3",
27912791
(const ValueDecl *, Type, Type, Type))
2792+
ERROR(cannot_reference_conditional_member_on_base_multiple_mismatches,none,
2793+
"cannot reference %kind0 on %1",
2794+
(const ValueDecl *, Type))
27922795
NOTE(where_requirement_failure_one_subst,none,
27932796
"where %0 = %1", (Type, Type))
27942797
NOTE(where_requirement_failure_both_subst,none,

include/swift/AST/Expr.h

+18
Original file line numberDiff line numberDiff line change
@@ -3615,6 +3615,24 @@ class ActorIsolationErasureExpr : public ImplicitConversionExpr {
36153615
}
36163616
};
36173617

3618+
/// UnsafeCastExpr - A special kind of conversion that performs an unsafe
3619+
/// bitcast from one type to the other.
3620+
///
3621+
/// Note that this is an unsafe operation and type-checker is allowed to
3622+
/// use this only in a limited number of cases like: `any Sendable` -> `Any`
3623+
/// conversions in some positions, covariant conversions of function and
3624+
/// function result types.
3625+
class UnsafeCastExpr : public ImplicitConversionExpr {
3626+
public:
3627+
UnsafeCastExpr(Expr *subExpr, Type type)
3628+
: ImplicitConversionExpr(ExprKind::UnsafeCast, subExpr, type) {
3629+
}
3630+
3631+
static bool classof(const Expr *E) {
3632+
return E->getKind() == ExprKind::UnsafeCast;
3633+
}
3634+
};
3635+
36183636
/// Extracts the isolation of a dynamically isolated function value.
36193637
class ExtractFunctionIsolationExpr : public Expr {
36203638
/// The function value expression from which to extract the

include/swift/AST/ExprNodes.def

+2-1
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,8 @@ ABSTRACT_EXPR(ImplicitConversion, Expr)
191191
EXPR(LinearFunctionExtractOriginal, ImplicitConversionExpr)
192192
EXPR(LinearToDifferentiableFunction, ImplicitConversionExpr)
193193
EXPR(ActorIsolationErasure, ImplicitConversionExpr)
194-
EXPR_RANGE(ImplicitConversion, Load, ActorIsolationErasure)
194+
EXPR(UnsafeCast, ImplicitConversionExpr)
195+
EXPR_RANGE(ImplicitConversion, Load, UnsafeCast)
195196
ABSTRACT_EXPR(ExplicitCast, Expr)
196197
ABSTRACT_EXPR(CheckedCast, ExplicitCastExpr)
197198
EXPR(ForcedCheckedCast, CheckedCastExpr)

include/swift/AST/Types.h

+3
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,9 @@ class alignas(1 << TypeAlignInBits) TypeBase
674674
/// Is this an existential containing only marker protocols?
675675
bool isMarkerExistential();
676676

677+
/// Is this `any Sendable` type?
678+
bool isSendableExistential();
679+
677680
bool isPlaceholder();
678681

679682
/// Returns true if this contextual type does not satisfy a conformance to

lib/AST/ASTDumper.cpp

+6
Original file line numberDiff line numberDiff line change
@@ -2727,6 +2727,12 @@ class PrintExpr : public ExprVisitor<PrintExpr, void, StringRef>,
27272727
printFoot();
27282728
}
27292729

2730+
void visitUnsafeCastExpr(UnsafeCastExpr *E, StringRef label) {
2731+
printCommon(E, "unsafe_cast_expr", label);
2732+
printRec(E->getSubExpr());
2733+
printFoot();
2734+
}
2735+
27302736
void visitExtractFunctionIsolationExpr(ExtractFunctionIsolationExpr *E,
27312737
StringRef label) {
27322738
printCommon(E, "extract_function_isolation", label);

lib/AST/ASTPrinter.cpp

+3
Original file line numberDiff line numberDiff line change
@@ -5346,6 +5346,9 @@ void PrintAST::visitLinearToDifferentiableFunctionExpr(swift::LinearToDifferenti
53465346
void PrintAST::visitActorIsolationErasureExpr(ActorIsolationErasureExpr *expr) {
53475347
}
53485348

5349+
void PrintAST::visitUnsafeCastExpr(UnsafeCastExpr *expr) {
5350+
}
5351+
53495352
void PrintAST::visitExtractFunctionIsolationExpr(ExtractFunctionIsolationExpr *expr) {
53505353
visit(expr->getFunctionExpr());
53515354
Printer << ".isolation";

lib/AST/Expr.cpp

+3
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,7 @@ ConcreteDeclRef Expr::getReferencedDecl(bool stopAtParenExpr) const {
459459
PASS_THROUGH_REFERENCE(UnderlyingToOpaque, getSubExpr);
460460
PASS_THROUGH_REFERENCE(Unreachable, getSubExpr);
461461
PASS_THROUGH_REFERENCE(ActorIsolationErasure, getSubExpr);
462+
PASS_THROUGH_REFERENCE(UnsafeCast, getSubExpr);
462463
NO_REFERENCE(Coerce);
463464
NO_REFERENCE(ForcedCheckedCast);
464465
NO_REFERENCE(ConditionalCheckedCast);
@@ -828,6 +829,7 @@ bool Expr::canAppendPostfixExpression(bool appendingPostfixOperator) const {
828829
case ExprKind::UnderlyingToOpaque:
829830
case ExprKind::Unreachable:
830831
case ExprKind::ActorIsolationErasure:
832+
case ExprKind::UnsafeCast:
831833
case ExprKind::TypeValue:
832834
// Implicit conversion nodes have no syntax of their own; defer to the
833835
// subexpression.
@@ -1058,6 +1060,7 @@ bool Expr::isValidParentOfTypeExpr(Expr *typeExpr) const {
10581060
case ExprKind::CurrentContextIsolation:
10591061
case ExprKind::ActorIsolationErasure:
10601062
case ExprKind::ExtractFunctionIsolation:
1063+
case ExprKind::UnsafeCast:
10611064
return false;
10621065
}
10631066

lib/AST/Type.cpp

+11
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,17 @@ bool TypeBase::isMarkerExistential() {
163163
return true;
164164
}
165165

166+
bool TypeBase::isSendableExistential() {
167+
Type constraint = this;
168+
if (auto existential = constraint->getAs<ExistentialType>())
169+
constraint = existential->getConstraintType();
170+
171+
if (!constraint->isConstraintType())
172+
return false;
173+
174+
return constraint->getKnownProtocol() == KnownProtocolKind::Sendable;
175+
}
176+
166177
bool TypeBase::isPlaceholder() {
167178
return is<PlaceholderType>();
168179
}

lib/SILGen/SILGenBuilder.cpp

+25
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,31 @@ ManagedValue SILGenBuilder::createUncheckedBitCast(SILLocation loc,
757757
return cloner.clone(cast);
758758
}
759759

760+
ManagedValue SILGenBuilder::createUncheckedForwardingCast(SILLocation loc,
761+
ManagedValue value,
762+
SILType type) {
763+
CleanupCloner cloner(*this, value);
764+
SILValue cast = createUncheckedForwardingCast(loc, value.getValue(), type);
765+
766+
// Currently createUncheckedBitCast only produces these
767+
// instructions. We assert here to make sure if this changes, this code is
768+
// updated.
769+
assert((isa<UncheckedTrivialBitCastInst>(cast) ||
770+
isa<UncheckedRefCastInst>(cast) ||
771+
isa<UncheckedValueCastInst>(cast) ||
772+
isa<ConvertFunctionInst>(cast)) &&
773+
"SILGenBuilder is out of sync with SILBuilder.");
774+
775+
// If we have a trivial inst, just return early.
776+
if (isa<UncheckedTrivialBitCastInst>(cast))
777+
return ManagedValue::forObjectRValueWithoutOwnership(cast);
778+
779+
// Otherwise, we forward the cleanup of the input value and place the cleanup
780+
// on the cast value since unchecked_ref_cast is "forwarding".
781+
value.forward(SGF);
782+
return cloner.clone(cast);
783+
}
784+
760785
ManagedValue SILGenBuilder::createOpenExistentialRef(SILLocation loc,
761786
ManagedValue original,
762787
SILType type) {

lib/SILGen/SILGenBuilder.h

+5
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,11 @@ class SILGenBuilder : public SILBuilder {
340340
ManagedValue createUncheckedBitCast(SILLocation loc, ManagedValue original,
341341
SILType type);
342342

343+
using SILBuilder::createUncheckedForwardingCast;
344+
ManagedValue createUncheckedForwardingCast(SILLocation loc,
345+
ManagedValue original,
346+
SILType type);
347+
343348
using SILBuilder::createOpenExistentialRef;
344349
ManagedValue createOpenExistentialRef(SILLocation loc, ManagedValue arg,
345350
SILType openedType);

lib/SILGen/SILGenExpr.cpp

+19
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,7 @@ namespace {
497497
RValue visitCovariantReturnConversionExpr(
498498
CovariantReturnConversionExpr *E,
499499
SGFContext C);
500+
RValue visitUnsafeCastExpr(UnsafeCastExpr *E, SGFContext C);
500501
RValue visitErasureExpr(ErasureExpr *E, SGFContext C);
501502
RValue visitAnyHashableErasureExpr(AnyHashableErasureExpr *E, SGFContext C);
502503
RValue visitForcedCheckedCastExpr(ForcedCheckedCastExpr *E,
@@ -2132,6 +2133,24 @@ RValue RValueEmitter::visitExtractFunctionIsolationExpr(
21322133
return RValue(SGF, E, result);
21332134
}
21342135

2136+
RValue RValueEmitter::visitUnsafeCastExpr(UnsafeCastExpr *E, SGFContext C) {
2137+
ManagedValue original = SGF.emitRValueAsSingleValue(E->getSubExpr());
2138+
SILType resultType = SGF.getLoweredType(E->getType());
2139+
2140+
if (resultType == original.getType())
2141+
return RValue(SGF, E, original);
2142+
2143+
ManagedValue result;
2144+
if (original.getType().isAddress()) {
2145+
ASSERT(resultType.isAddress());
2146+
result = SGF.B.createUncheckedAddrCast(E, original, resultType);
2147+
} else {
2148+
result = SGF.B.createUncheckedForwardingCast(E, original, resultType);
2149+
}
2150+
2151+
return RValue(SGF, E, result);
2152+
}
2153+
21352154
RValue RValueEmitter::visitErasureExpr(ErasureExpr *E, SGFContext C) {
21362155
if (auto result = tryEmitAsBridgingConversion(SGF, E, false, C)) {
21372156
return RValue(SGF, E, *result);

lib/Sema/CSApply.cpp

+12
Original file line numberDiff line numberDiff line change
@@ -7066,6 +7066,18 @@ Expr *ExprRewriter::coerceToType(Expr *expr, Type toType,
70667066
}
70677067
}
70687068

7069+
// `any Sendable` -> `Any` conversion is allowed in generic
7070+
// argument positions.
7071+
{
7072+
auto erasedFromType = fromType->stripConcurrency(
7073+
/*recursive=*/true, /*dropGlobalActor=*/false);
7074+
auto erasedToType = toType->stripConcurrency(
7075+
/*recursive=*/true, /*dropGlobalActor=*/false);
7076+
7077+
if (erasedFromType->isEqual(erasedToType))
7078+
return cs.cacheType(new (ctx) UnsafeCastExpr(expr, toType));
7079+
}
7080+
70697081
auto &err = llvm::errs();
70707082
err << "fromType->getCanonicalType() = ";
70717083
fromType->getCanonicalType()->dump(err);

lib/Sema/CSDiagnostics.cpp

+63-7
Original file line numberDiff line numberDiff line change
@@ -904,16 +904,44 @@ bool GenericArgumentsMismatchFailure::diagnoseAsError() {
904904
// before pointer types could be compared.
905905
auto locator = getLocator();
906906
auto path = locator->getPath();
907-
unsigned toDrop = 0;
908-
for (const auto &elt : llvm::reverse(path)) {
909-
if (!elt.is<LocatorPathElt::OptionalPayload>())
910-
break;
911907

912-
// Disregard optional payload element to look at its source.
913-
++toDrop;
908+
// If there are generic types involved, we need to find
909+
// the outermost generic types and report on them instead
910+
// of their arguments.
911+
// For example:
912+
//
913+
// <expr> -> contextual type
914+
// -> generic type S<[Int]>
915+
// -> generic type S<[String]>
916+
// -> generic argument #0
917+
//
918+
// Is going to have from/to types as `[Int]` and `[String]` but
919+
// the diagnostic should mention `S<[Int]>` and `S<[String]>`
920+
// because it refers to a contextual type location.
921+
if (locator->isLastElement<LocatorPathElt::GenericArgument>()) {
922+
for (unsigned i = 0; i < path.size(); ++i) {
923+
if (auto genericType = path[i].getAs<LocatorPathElt::GenericType>()) {
924+
ASSERT(i + 1 < path.size());
925+
926+
fromType = resolveType(genericType->getType());
927+
toType = resolveType(
928+
path[i + 1].castTo<LocatorPathElt::GenericType>().getType());
929+
break;
930+
}
931+
}
914932
}
915933

916-
path = path.drop_back(toDrop);
934+
while (!path.empty()) {
935+
auto last = path.back();
936+
if (last.is<LocatorPathElt::OptionalPayload>() ||
937+
last.is<LocatorPathElt::GenericType>() ||
938+
last.is<LocatorPathElt::GenericArgument>()) {
939+
path = path.drop_back();
940+
continue;
941+
}
942+
943+
break;
944+
}
917945

918946
std::optional<Diag<Type, Type>> diagnostic;
919947
if (path.empty()) {
@@ -1009,6 +1037,34 @@ bool GenericArgumentsMismatchFailure::diagnoseAsError() {
10091037
break;
10101038
}
10111039

1040+
case ConstraintLocator::Member: {
1041+
auto *memberLoc = getConstraintLocator(anchor, path);
1042+
auto selectedOverload = getOverloadChoiceIfAvailable(memberLoc);
1043+
if (!selectedOverload)
1044+
return false;
1045+
1046+
auto baseTy = selectedOverload->choice.getBaseType()->getRValueType();
1047+
auto *memberRef = selectedOverload->choice.getDecl();
1048+
1049+
if (Mismatches.size() == 1) {
1050+
auto mismatchIdx = Mismatches.front();
1051+
auto actualArgTy = getActual()->getGenericArgs()[mismatchIdx];
1052+
auto requiredArgTy = getRequired()->getGenericArgs()[mismatchIdx];
1053+
1054+
emitDiagnostic(diag::types_not_equal_in_decl_ref, memberRef, baseTy,
1055+
actualArgTy, requiredArgTy);
1056+
emitDiagnosticAt(memberRef, diag::decl_declared_here, memberRef);
1057+
return true;
1058+
}
1059+
1060+
emitDiagnostic(
1061+
diag::cannot_reference_conditional_member_on_base_multiple_mismatches,
1062+
memberRef, baseTy);
1063+
emitDiagnosticAt(memberRef, diag::decl_declared_here, memberRef);
1064+
emitNotesForMismatches();
1065+
return true;
1066+
}
1067+
10121068
default:
10131069
break;
10141070
}

0 commit comments

Comments
 (0)