Repository navigation
Update PartialEq/PartialOrd guarantees for comparisons to match reality - #164473
clarfonthey wants to merge 1 commit into
Conversation
|
r? @aapoalas rustbot has assigned @aapoalas. Use Why was this reviewer chosen?The reviewer was selected based on:
|
|
@rfcbot merge libs |
|
@clarfonthey has proposed to merge this. The next step is review by the rest of the tagged team members: No concerns currently listed. Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up! cc @rust-lang/libs-ping: FCP proposed for libs, please feel free to register concerns. |
| /// be consistent with `PartialEq` (see the documentation of those traits for the exact | ||
| /// requirements). It's easy to accidentally make them disagree by deriving some of the traits and | ||
| /// manually implementing others. | ||
| /// If [`PartialOrd`] is also implemented for `Self` and `Rhs`, their methods must also be |
There was a problem hiding this comment.
Removed mention of Ord here since, well, Ord can't take an Rhs, so, this is just confusing.
The |
|
Thank you, operational pedantics. I saw that, but chose to use |
|
What I find particularly funny is that all of those conversations happened after the intransitive impl was added to std… |
|
Well, maybe it's the path Eq impl that's wrong and we should run normalization? |
The |
|
Ah yeah we shouldn't have had both of |
This comment has been minimized.
This comment has been minimized.
18b25ef to
de2c91a
Compare
|
General discussion post-meeting was: this is the intersection of a bunch of compromises, and we have FCP. |
|
Does #164184 interact with this? |
|
My understanding is no @theemathas since this only changes the interaction between types, not the requirements for a single type, but I'd still like to wrap my head around what's being said regardless so we can bundle together the various changes to these traits in one FCP if we can. |
|
cc @rust-lang/libs-ping #164184 made it clear that our definition of a partial order is just wrong in subtle ways, and I've taken the liberty of updating it to match what people actually do in practice. This also explicitly declares the implementation example in #164184 to be logically incorrect. Since we're deciding to change the guarantees for these traits, I've decided that they should really all be done in one FCP so that we're certain what we're actually guaranteeing. Instead of restarting FCP, however, I've just unchecked everyone's boxes so that we can make it clear that people have actually looked at the new definition and are happy with it. I've also taken the liberty of copying the relevant sections of the docs into the PR description so they can be read more easily than the diff, since this is effectively a rewrite, and the diff just makes it look more confusing. |
PartialEq/PartialOrd guarantees for comparisons to match reality
092a05b to
3f21549
Compare
|
@rfcbot merge libs |
|
@thomcc has proposed to merge this. The next step is review by the rest of the tagged team members: No concerns currently listed. Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up! cc @rust-lang/libs-ping: FCP proposed for libs, please feel free to register concerns. |
| /* compiler built-in */ | ||
| } | ||
|
|
||
| /// Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order). |
There was a problem hiding this comment.
This should be changed - just "partial order" means the non-strict variety. With reference to discussion in #140779 (comment) I suggest saying that it's for overloading the comparison operators.
| /// * **Substitutability**: if `a == b`, then for any given logical formula containing only logical | ||
| /// operators and ordering relations (`<`, `<=`, `==`, `>=`, `>`) you can replace `a` with `b` | ||
| /// without changing its meaning, and similarly replacing `b` with `a`. |
There was a problem hiding this comment.
This is actually meant to be a new requirement, right? I don't think it follows from the conditions in the previous section since the example of #164184 still goes through if it's just them.
Also, there's no need to mention logical formulas or operators. It's enough to say that a == b implies that a can be replaced with b in every comparison.
There was a problem hiding this comment.
Pretty sure it does follow, it's not as strong of a statement as it first seems, and should pretty much already follow from everything being transitive
There was a problem hiding this comment.
The reason why I mention logical operators and comparisons is because we can't make the guarantee that it applies for all code, just specifically code that involves comparisons.
There was a problem hiding this comment.
Pretty sure it does follow, it's not as strong of a statement as it first seems, and should pretty much already follow from everything being transitive
Except, as I said, the example from the #164184 still meets the requirements of the first section in this PR. Transitivity just gives you that a < b && b < c implies a < c. You need something extra to get that a == b && b < c implies a < c, because == is not identity.
The reason why I mention logical operators and comparisons is because we can't make the guarantee that it applies for all code, just specifically code that involves comparisons.
I agree? Just we only need to talk about results of comparisons. No need to bring up logical formulas and operators, because that falls out automatically.
There was a problem hiding this comment.
If this adds new axioms it should be up above where the axioms are listed, not hidden in a later section. If not, then it should explicitly state that this follows from the other axioms.
There was a problem hiding this comment.
That breaks transitivity of <=: A1 <= A2 && A2 <= B implies A1 <= B.
But we don't have transitivity of <=. We just kinda expect it to fall out of defining a <= b as "either a < b or a == b".
You can have < really be a strict partial order and == really be a partial equivalence relation, and you can also say that you can't have both x < y and x == y, but those together still don't always give a transitive <=.
Counterexample: say we have 3 elements A, B, C:
- Define
<exactly byB < C. - Define
==exactly byA == B,B == A,A == A,B == B.
Then each of the requirements are satisfied:
<is irreflexive, asymmetric, and transitive and therefore a strict partial order.==is transitive and symmetric, and therefore a partial equivalence relation.- It is never the case that both
x < yandx == y, because we don't haveB == C.
But from the definition of <=, it comes out true in exactly these cases: B <= C, A <= B, B <= A, A <= A, B <= B.
So we have A <= B and B <= C but not A <= C.
There was a problem hiding this comment.
Transitivity of <= is explicitly added to the new requirements.
There was a problem hiding this comment.
"[...] all operators, namely
<=,==,>=, and>."
Oh, I see, maybe it's just me, but that seems a bit hidden. The transitivity of <= is actually the most important one, because you can't derive it, unlike the transitivity of <. (Proof below.)
Details
Proposition. Let < be asymmetric, let == be symmetric, and let <= be their union. If < and == are disjoint and <= is transitive, then < is transitive.
Proof. Suppose the conditions hold and suppose a < b and b < c. We have a <= c by the definition and transitivity of <=, and hence either a < c or a == c by definition. Suppose to the contrary that a == c. Then c == a by symmetry and hence c <= a by definition, so b <= a by transitivity. Therefore either b < a or b == a, but:
- Since
<is asymmetric, we cannot haveb < a. - Since
<and==are disjoint and==is symmetric, similarly we cannot haveb == a.
This is a contradiction, so we must have a < c. ∎
There was a problem hiding this comment.
Yes, I realised after this discussion that the substitutability axiom is a direct corollary of <= being transitive. It's a load-bearing requirement, so, I should clarify that more.
There was a problem hiding this comment.
You could also derive transitivity of <= from transitivity of < and == plus these substitutivity axioms (proof below):
- If
x == y, thenx < zif and only ify < z. - If
x == y, thenz < xif and only ifz < y.
Details
Proposition. Let == be transitive, let < be transitive and obey the above axioms. Let <= be the union of == and <. Then <= is transitive.
Proof. Suppose a <= b and b <= c. We have four cases:
a < bandb < c: we geta < cby transitivity of<.a == bandb == c: we geta == cby transitivity of==.a == bandb < c: sincea == b, axiom 1 givesa < cif and only ifb < c. Thereforea < c.a < bandb == c: sinceb == c, axiom 2 givesa < bif and only ifa < c. Thereforea < c.
Therefore either a == c or a < c in all cases, so a <= c. ∎
|
🔔 This is now entering its final comment period, as per the review above. 🔔 |
| /// to conflate *equality* (the `==` operator) with *identity* (literally being the same value), | ||
| /// whereas these two are not treated the same in Rust's definition. In particular, Rust satisfies | ||
| /// the rules for a *strict partial order* which is defined in terms of `<`, but not a *weak partial | ||
| /// order* which is defined in terms of `<=`. |
There was a problem hiding this comment.
This text seems to be quite confused about =. First of all, "being the same value" is not defined.
Secondly, also in math it's not uncommon to use an equivalence relation rather than the default mathematical notion of equality. Being a weak partial order wrt to an equivalence relation is an entirely reasonable notion.
So to me the old text here seems more correct and understandable than the new text, I have to say.
There was a problem hiding this comment.
It might be worth mentioning that Eq + PartialOrd actually gives us a weak partial order (wrt the equivalence relation defined by Eq)? In fact the entire story might become more understandable if we set it up around that fact:
- on its own
PartialOrddoes not make<=a weak partial order because we don't have reflexivity - but
Eq + PartialOrdmakes<=a weak partial order
There was a problem hiding this comment.
Right, to be clear part of rewriting this involved breaking my own inherent misconceptions regarding what the different types of partial orders are and what we're trying to do.
I guess that "same value" semantics are kind of muddied by the fact that PartialEq technically can use the addresses, but absolutely should not. But I do mean bit-identical values here, which is well-defined.
| /// - **Transitivity**: for all `a`, `b`, `c` of type `A`, | ||
| /// **`a < b` and `b < c` implies `a < c`**. This must also work for longer chains and | ||
| /// all operators, namely `<=`, `==`, `>=`, and `>`. |
There was a problem hiding this comment.
This can be read in two different ways:
- the other operators are transitive
- we can form chains mixing different operations
We actually do need the latter for some combination of operators, but obviously not all of them, so we probably have to be more precise here.
There was a problem hiding this comment.
Yeah, did not mean to say that it works for all combinations, just that this transitivity relation applies when you substitute a < b && b < c to replace < with any of the other four operators.
| /// Here, the strictness of `PartialOrd` has nothing to do with the actual *ordering*, so much as | ||
| /// the *definition* of ordering being based upon the `<` or `<=` operators, and the usual intuition |
There was a problem hiding this comment.
I don't know what the first sentence here is trying to say.
There was a problem hiding this comment.
Is this about this part from the PR description?
It tries to act like this is just a weak partial order instead of a strict one, but in fact, the weakness and strictness only depend on whether the axioms are defined for <= or <
That's correct but only half the story. It's also the case that the axioms for weak partial orders assume some underlying equivalence relation, which we simply don't have without Eq. Strict partial orders neatly generalize to sets without an equivalence relation, weak partial orders don't. That's why < forms a strict partial order but <= does not form a weak partial order (without Eq).
There was a problem hiding this comment.
I really should just go back and just list the axioms I'm talking about rather than walking around that. I'll do that.
There was a problem hiding this comment.
Gonna I think solve that by putting them in a <details> as I mention here.
There was a problem hiding this comment.
FWIW I currently think this paragraph should probably be cut. I have no clue what it even is trying to say, but my best guess is that you are getting hung up on a misunderstanding.
But maybe that will become more clear if you add more detail.
This comment has been minimized.
This comment has been minimized.
e99e90a to
40d4a45
Compare
|
This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed. Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers. |
| /// - **Irreflexivity**: for all `a` of type `A`, `!(a < a)` and `!(a > a)`. | ||
| /// - **Transitivity**: for all `a`, `b`, `c` of type `A`, | ||
| /// **`a < b` and `b < c` implies `a < c`**. This must also work for longer chains and | ||
| /// all operators, namely `<=`, `==`, `>=`, and `>`. |
There was a problem hiding this comment.
For == this is redundant as it is already required by PartialEq.
There was a problem hiding this comment.
Right, I included it for completeness, but I'm fine putting more text to clarify that if you think it's helpful.
There was a problem hiding this comment.
I think the best clarification is to remove it from the list. This is supposed to list the new axioms one has to prove when instantiating PartialOrd, not summarize all axioms.
There was a problem hiding this comment.
This kind of combines with our comment about how this is kind of balancing between just making these docs overbearing and making sure all the details are fully spelled out. Like, in this case, it is an axiom required by PartialOrd to be correct, it's just that PartialEq is specifically providing that requirement already, and so, you will have satisfied it by this point if you've done everything correctly.
But I think it might similarly be confusing if I omitted == from this list for that reason, and also overbearing if I spent the time to add a full sentence clarifying that PartialEq covers this. But, I also think this is more of an aesthetic choice and I'm fine deferring to what people think is best.
|
Rebased but going to try and get to the feedback this weekend. I think that I might, assuming that rustdoc doesn't complain, add a few collapsible |
|
The final comment period, with a disposition to merge, as per the review above, is now complete. As the automated representative of the governance process, I would like to thank the author for their work and everyone else who contributed. |
|
Marking as blocked since I do have some changes I want to do before merge, which are mostly just adding more information. The base guarantees shouldn't change. |
View all comments
This fixes #164470 and #164184 by making our guarantees match reality
Note that this is a guarantee change and thus requires FCP, however, we have to do something since currently the standard library conflicts with its own recommendations.
Transitivity across types
Essentially, while we had all the ingredients to understand this in 1.0.0, we kinda blew it by adding the invalid transitive impls in 1.8.0: in particular, the comparison
PartialEq<str> for Pathbreaks this condition, and this is trivial to prove by comparing"test" == Path::new("./test")andPath::new("./test") == "./test", which does not imply"test" == "./test".Considering how the
Borrowtrait kind of saw through this problem and was part of 1.0, I suggest we simply relax the guarantees to not require transitivity across different types unlessBorrowis implemented for them, in which case the transitivity is added back in. This effectively matches the intuition for what libs thinks these types do, but actually makes it a reality.Definition of partial order
Currently, Rust's definition of a partial order is subtly incorrect, due to a misconception that partial orders are consistent with partial equivalence relations. It tries to act like this is just a weak partial order instead of a strict one, but in fact, the weakness and strictness only depend on whether the axioms are defined for
<=or<. This is the issue brought up in #164184.This changes the axioms we offer to explicitly mention that: actually, what Rust offers is a strict partial ordering. The full list of changes is complicated and I would recommend just reading the new requirements in isolation and see if they're correct.
Rendering
For easy reading, here are both the new relevant docs for
Borrow,PartialEq, andPartialOrd.BorrowAdditionally, if
PartialEqandPartialOrdallow comparisons between types and their borrowed versions, those comparisons must allow the user to satisfy all the relevant transitive requirements of these traits, e.g.x.borrow() == yandy == z.borrow()should implyx == zas well.PartialEqFor any type
A: PartialEq, the equality relation==must satisfy the following condition:a,b,cof typeA,a == bandb == cimpliesa == c. This must also work for longer chains.For any given combination of
AandBwhereA: PartialEq<B>andB: PartialEq<A>, the equality relation==must additionally satisfy the following condition:aof typeAandbof typeB,a == bimpliesb == a. This also means that this case applies forA == B.Note that the for any given
A: PartialEq<B>impl, the symmetricB: PartialEq<A>impl is not forced to exist, but these requirements apply whenever they do exist.Note that transitivity for more than one type is not guaranteed. For any given combination of
A,B, andCwhereA: PartialEq<B>andB: PartialEq<C>, the following may not hold:aof typeA,bof typeB, andcof typeC,a == bandb == cdoes not implya == c.Note that types are allowed to be transitive in this method, but it is not strictly required. If you want stronger guarantees across types, you should use conversions like
Borrowto convert everything to the same type before comparing.Violating these requirements is a logic error. The behavior resulting from a logic error is not specified, but users of the trait must ensure that such logic errors do not result in undefined behavior. This means that
unsafecode must not rely on the correctness of these methods.PartialOrdFor any type
A: PartialOrd, the ordering must satisfy the following conditions:aof typeA,!(a < a)and!(a > a).a,b,cof typeA,a < bandb < cimpliesa < c. This must also work for longer chains and all operators, namely<=,==,>=, and>.There is also a third property guaranteed by the signature of
partial_cmpitself:a,bof typeA, at most one ofa < b,a == b, ora > b.For any given combination of
AandBwhereA: PartialOrd<B>andB: PartialOrd<A>, the ordering must additionally satisfy the following condition:aof typeAandbof typeB,a < bif and only ifb > a.Note that the for any given
A: PartialOrd<B>impl, the symmetricB: PartialOrd<A>impl is not forced to exist, but these requirements apply whenever they do exist.Note that transitivity for more than one type is not guaranteed. For any given combination of
A,B, andCwhereA: PartialEq<B>andB: PartialEq<C>, the following may not hold:aof typeA,bof typeB, andcof typeC,a < bandb < cdoes not implya < c. This similarly is not guaranteed for the operators<=,==,>=, and>.Note that types are allowed to be transitive in this method, but it is not strictly required. If you want stronger guarantees across types, you should use conversions like
Borrowto convert everything to the same type before comparing.Violating these requirements is a logic error. The behavior resulting from a logic error is not specified, but users of the trait must ensure that such logic errors do not result in undefined behavior. This means that
unsafecode must not rely on the correctness of these methods.Definition of partial order
In general, the definition of a partial order can be pretty confusing because of how people tend to conflate equality (the
==operator) with identity (literally being the same value), whereas these two are not treated the same in Rust's definition. In particular, Rust satisfies the rules for a strict partial order which is defined in terms of<, but not a weak partial order which is defined in terms of<=.In general, weak partial orderings will guarantee reflexivity, which Rust's
PartialOrdexplicitly does not guarantee:aof typeA,PartialOrddoes not guaranteea <= aora >= a.Here, the strictness of
PartialOrdhas nothing to do with the actual ordering, so much as the definition of ordering being based upon the<or<=operators, and the usual intuition for those operators. We match the intuition for<, but not that for<=. However, despite this, one important intuitive property ofPartialOrdholds:a == b, then for any given logical formula containing only logical operators and ordering relations (<,<=,==,>=,>) you can replaceawithbwithout changing its meaning, and similarly replacingbwitha.