Skip to content

Resilient re-ordering of associated types #15806

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
Apr 6, 2018
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
8 changes: 8 additions & 0 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -2510,6 +2510,14 @@ class TypeDecl : public ValueDecl {

/// Compute an ordering between two type declarations that is ABI-stable.
static int compare(const TypeDecl *type1, const TypeDecl *type2);

/// Compute an ordering between two type declarations that is ABI-stable.
/// This version takes a pointer-to-a-pointer for use with
/// llvm::array_pod_sort() and similar.
template<typename T>
static int compare(T * const* type1, T * const* type2) {
return compare(*type1, *type2);
}
};

/// A type declaration that can have generic parameters attached to it. Because
Expand Down
5 changes: 0 additions & 5 deletions include/swift/AST/Types.h
Original file line number Diff line number Diff line change
Expand Up @@ -4288,11 +4288,6 @@ class ProtocolType : public NominalType, public llvm::FoldingSetNode {
static bool visitAllProtocols(ArrayRef<ProtocolDecl *> protocols,
llvm::function_ref<bool(ProtocolDecl *)> fn);

/// Compare two protocols to provide them with a stable ordering for
/// use in sorting.
static int compareProtocols(ProtocolDecl * const* PP1,
ProtocolDecl * const* PP2);

void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getDecl(), getParent());
}
Expand Down
13 changes: 11 additions & 2 deletions include/swift/SIL/SILWitnessVisitor.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,21 @@ template <class T> class SILWitnessVisitor : public ASTVisitor<T> {
if (haveAddedAssociatedTypes) return;
haveAddedAssociatedTypes = true;

SmallVector<AssociatedTypeDecl *, 2> associatedTypes;
for (Decl *member : protocol->getMembers()) {
if (auto associatedType = dyn_cast<AssociatedTypeDecl>(member)) {
// TODO: only add associated types when they're new?
asDerived().addAssociatedType(AssociatedType(associatedType));
associatedTypes.push_back(associatedType);
}
}

// Sort associated types by name, for resilience.
llvm::array_pod_sort(associatedTypes.begin(), associatedTypes.end(),
TypeDecl::compare);

for (auto *associatedType : associatedTypes) {
// TODO: only add associated types when they're new?
asDerived().addAssociatedType(AssociatedType(associatedType));
}
};

for (const auto &reqt : protocol->getRequirementSignature()) {
Expand Down
2 changes: 1 addition & 1 deletion lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1613,7 +1613,7 @@ static int compareSimilarAssociatedTypes(AssociatedTypeDecl *const *lhs,
AssociatedTypeDecl *const *rhs) {
auto lhsProto = (*lhs)->getProtocol();
auto rhsProto = (*rhs)->getProtocol();
return ProtocolType::compareProtocols(&lhsProto, &rhsProto);
return TypeDecl::compare(lhsProto, rhsProto);
}

ArrayRef<AssociatedTypeDecl *> AssociatedTypeDecl::getOverriddenDecls() const {
Expand Down
2 changes: 1 addition & 1 deletion lib/AST/ConformanceLookupTable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1110,7 +1110,7 @@ int ConformanceLookupTable::compareProtocolConformances(
// Otherwise, sort by protocol.
ProtocolDecl *lhsProto = lhs->getProtocol();
ProtocolDecl *rhsProto = rhs->getProtocol();
return ProtocolType::compareProtocols(&lhsProto, &rhsProto);
return TypeDecl::compare(lhsProto, rhsProto);
}

void ConformanceLookupTable::getAllConformances(
Expand Down
2 changes: 1 addition & 1 deletion lib/AST/GenericSignature.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ GenericSignature::getCanonical(TypeArrayView<GenericTypeParamType> params,
auto prevProto =
prevReqt.getSecondType()->castTo<ProtocolType>()->getDecl();
auto proto = reqt.getSecondType()->castTo<ProtocolType>()->getDecl();
assert(ProtocolType::compareProtocols(&prevProto, &proto) < 0 &&
assert(TypeDecl::compare(prevProto, proto) < 0 &&
"Out-of-order conformance requirements");
}
#endif
Expand Down
4 changes: 2 additions & 2 deletions lib/AST/GenericSignatureBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2073,7 +2073,7 @@ static int compareAssociatedTypes(AssociatedTypeDecl *assocType1,
// - by protocol, so t_n_m.`P.T` < t_n_m.`Q.T` (given P < Q)
auto proto1 = assocType1->getProtocol();
auto proto2 = assocType2->getProtocol();
if (int compareProtocols = ProtocolType::compareProtocols(&proto1, &proto2))
if (int compareProtocols = TypeDecl::compare(proto1, proto2))
return compareProtocols;

// Error case: if we have two associated types with the same name in the
Expand Down Expand Up @@ -7286,7 +7286,7 @@ void GenericSignatureBuilder::enumerateRequirements(

// Sort the protocols in canonical order.
llvm::array_pod_sort(protocols.begin(), protocols.end(),
ProtocolType::compareProtocols);
TypeDecl::compare);

// Enumerate the conformance requirements.
for (auto proto : protocols) {
Expand Down
3 changes: 1 addition & 2 deletions lib/AST/ProtocolConformance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1188,8 +1188,7 @@ DeclContext::getLocalProtocols(

// Sort if required.
if (sorted) {
llvm::array_pod_sort(result.begin(), result.end(),
&ProtocolType::compareProtocols);
llvm::array_pod_sort(result.begin(), result.end(), TypeDecl::compare);
}

return result;
Expand Down
8 changes: 1 addition & 7 deletions lib/AST/Type.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -971,12 +971,6 @@ static void addMinimumProtocols(Type T,
}
}

/// \brief Compare two protocols to establish an ordering between them.
int ProtocolType::compareProtocols(ProtocolDecl * const* PP1,
ProtocolDecl * const* PP2) {
return TypeDecl::compare(*PP1, *PP2);
}

bool ProtocolType::visitAllProtocols(
ArrayRef<ProtocolDecl *> protocols,
llvm::function_ref<bool(ProtocolDecl *)> fn) {
Expand Down Expand Up @@ -1052,7 +1046,7 @@ void ProtocolType::canonicalizeProtocols(

// Sort the set of protocols by module + name, to give a stable
// ordering.
llvm::array_pod_sort(protocols.begin(), protocols.end(), compareProtocols);
llvm::array_pod_sort(protocols.begin(), protocols.end(), TypeDecl::compare);
}

static Type
Expand Down
3 changes: 1 addition & 2 deletions lib/Sema/TypeCheckProtocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4890,8 +4890,7 @@ TypeChecker::findWitnessedObjCRequirements(const ValueDecl *witness,
= cast<ProtocolDecl>(lhs->getDeclContext());
ProtocolDecl *rhsProto
= cast<ProtocolDecl>(rhs->getDeclContext());
return ProtocolType::compareProtocols(&lhsProto,
&rhsProto) < 0;
return TypeDecl::compare(lhsProto, rhsProto) < 0;
});
}
return result;
Expand Down
2 changes: 1 addition & 1 deletion test/IRGen/associated_type_witness.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ protocol Assocked {

struct Universal : P, Q {}

// CHECK: [[ASSOC_TYPE_NAMES:@.*]] = private constant [29 x i8] c"OneAssoc TwoAssoc ThreeAssoc\00"
// CHECK: [[ASSOC_TYPE_NAMES:@.*]] = private constant [29 x i8] c"OneAssoc ThreeAssoc TwoAssoc\00"
// CHECK: @"$S23associated_type_witness18HasThreeAssocTypesMp" =
// CHECK-SAME: [[ASSOC_TYPE_NAMES]] to i64

Expand Down
2 changes: 1 addition & 1 deletion test/IRGen/associated_types.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func testFastRuncible<T: Runcible, U: FastRuncible>(_ t: T, u: U)
// 1. Get the type metadata for U.RuncerType.Runcee.
// 1a. Get the type metadata for U.RuncerType.
// Note that we actually look things up in T, which is going to prove unfortunate.
// CHECK: [[T0_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.Runcible, i32 1
// CHECK: [[T0_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.Runcible, i32 2
// CHECK: [[T0:%.*]] = load i8*, i8** [[T0_GEP]]
// CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to %swift.metadata_response ([[INT]], %swift.type*, i8**)*
// CHECK-NEXT: [[T2:%.*]] = call swiftcc %swift.metadata_response [[T1]]([[INT]] 0, %swift.type* %T, i8** %T.Runcible)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
public protocol Bed {
func squiggle()
}

public protocol Outfit {
var size: Int { get }
}

public protocol Eater {
#if BEFORE
func eat()
func poop()
#else
func poop()
func eat()
#endif
}

public protocol Wiggler {
#if BEFORE
func wiggle()
func cry()
#else
func cry()
func wiggle()
#endif
}

#if BEFORE

public protocol Baby : Eater, Wiggler {
associatedtype Bassinet : Bed
associatedtype Onesie : Outfit

var outfitSize: Int { get }

func sleep(in: Bassinet)
func wear(outfit: Onesie)
}

#else

public protocol Baby : Wiggler, Eater {
associatedtype Onesie : Outfit
associatedtype Bassinet : Bed

var outfitSize: Int { get }

func wear(outfit: Onesie)
func sleep(in: Bassinet)
}

#endif

public func goodDay<B : Baby>(for baby: B,
sleepingIn bed: B.Bassinet,
wearing outfit: B.Onesie) {
if baby.outfitSize != outfit.size {
fatalError("I grew too much!")
}

baby.wear(outfit: outfit)
baby.sleep(in: bed)
baby.poop()
baby.sleep(in: bed)
baby.eat()
baby.sleep(in: bed)
baby.wiggle()
}
94 changes: 94 additions & 0 deletions validation-test/Evolution/test_protocol_reorder_requirements.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// RUN: %target-resilience-test --no-backward-deployment
// REQUIRES: executable_test

import StdlibUnittest
import protocol_reorder_requirements


var ProtocolReorderRequirementsTest = TestSuite("ProtocolReorderRequirements")

var log = [String]()

struct MyBassinet : Bed {
func squiggle() {
log.append("nap time")
}
}

struct MyOnesie : Outfit {
let size = 3
}

struct SillyBaby : Baby {
func eat() {
log.append("hangry!")
}

func sleep(in bassinet: MyBassinet) {
bassinet.squiggle()
}

func wear(outfit: MyOnesie) {
log.append("wearing outfit size \(outfit.size)")
}

func poop() {
log.append("change the diaper")
}

func cry() {
log.append("waaaaah!")
}

func wiggle() {
log.append("time to wiggle!")
}

let outfitSize = 3
}

func typicalDay<B : Baby>(for baby: B,
sleepingIn bed: B.Bassinet,
wearing outfit: B.Onesie) {
baby.wear(outfit: outfit)
baby.sleep(in: bed)
baby.cry()
baby.poop()
baby.cry()
baby.sleep(in: bed)
baby.eat()
baby.cry()
}

ProtocolReorderRequirementsTest.test("ReorderProtocolRequirements") {
let baby = SillyBaby()
let bed = MyBassinet()
let outfit = MyOnesie()

typicalDay(for: baby, sleepingIn: bed, wearing: outfit)
expectEqual(log, [
"wearing outfit size 3",
"nap time",
"waaaaah!",
"change the diaper",
"waaaaah!",
"nap time",
"hangry!",
"waaaaah!"
])
log = []

goodDay(for: baby, sleepingIn: bed, wearing: outfit)
expectEqual(log, [
"wearing outfit size 3",
"nap time",
"change the diaper",
"nap time",
"hangry!",
"nap time",
"time to wiggle!"
])
}

runAllTests()