Check the mutating form* twins against their non-mutating originals

formUnion against union, formIntersection against intersection,
subtract against subtracting, and formSymmetricDifference against
symmetricDifference, in both the Self-taking and Sequence-taking
overloads.

Each runs under withHiddenCopies at both sharing states, because a
mutating operation on a shared value is where copy-on-write bugs
live, and the original is checked afterwards to confirm it was not
mutated through the copy.

This is the highest-value law in the checker. The two implementations
should agree by construction, so a divergence is a real bug rather
than a debatable one — and nothing else here would catch a form*
method that is simply wrong: a formUnion that intersects passes every
law in the preceding commit.

Verified by injecting three defects into a stand-in conformance: a
formUnion that intersects, an isStrictSubset that drops strictness,
and a subtracting that returns a stale count. All three are caught,
and an unmodified control passes. The stale-count case is caught only
because contents and count are asserted separately.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Joseph CursioandClaude Opus 5 committed 2026-09-21 21:14:59 -05:00
1 parent 79f41229ef
commit de23cb86c8
1 file changed
+41
@@ -264,4 +264,45 @@ private func _checkSetAlgebraBinaryLaws<S: SetAPIChecker & Sequence>(
expectEqual(x.isSubset(of: y), x.subtracting(y).isEmpty,
"isSubset disagrees with an empty difference",
file: file, line: line)
// The mutating twins must agree with the non-mutating originals -- including
// when the value is shared, which is where copy-on-write bugs live.
withEvery("isShared", in: [false, true]) { isShared in
func checkMutation(
_ label: String,
_ mutate: (inout S) -> Void,
_ expected: Set<S.Element>
) {
var copy = x
withHiddenCopies(if: isShared, of: &copy) { copy in
mutate(&copy)
expectEqual(Set(copy), expected, "\(label): wrong elements",
file: file, line: line)
expectEqual(copy.count, expected.count, "\(label): wrong count",
file: file, line: line)
}
// The original must be untouched.
expectEqual(Set(x), xm, "\(label): mutated the original",
file: file, line: line)
}
checkMutation("formUnion", { $0.formUnion(y) }, xm.union(ym))
checkMutation("formIntersection", { $0.formIntersection(y) },
xm.intersection(ym))
checkMutation("subtract", { $0.subtract(y) }, xm.subtracting(ym))
checkMutation("formSymmetricDifference",
{ $0.formSymmetricDifference(y) },
xm.symmetricDifference(ym))
// The Sequence-taking overloads of the same four.
checkMutation("formUnion(Sequence)", { $0.formUnion(Array(ym)) },
xm.union(ym))
checkMutation("formIntersection(Sequence)",
{ $0.formIntersection(Array(ym)) }, xm.intersection(ym))
checkMutation("subtract(Sequence)", { $0.subtract(Array(ym)) },
xm.subtracting(ym))
checkMutation("formSymmetricDifference(Sequence)",
{ $0.formSymmetricDifference(Array(ym)) },
xm.symmetricDifference(ym))
}
}