Skip to content
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

impl ops::Try for Ordering #76041

Closed

Conversation

calebsander
Copy link
Contributor

@calebsander calebsander commented Aug 28, 2020

Implements Try for Ordering, mirroring the behavior of Ordering::then(). (Applying ? to Less or Greater causes it to be returned immediately, while Equal? results in ().) This is useful for implementing lexicographic orderings, where comparisons are chained until the first one that returns non-Equal. See the examples below.

I've currently gated this behind the try_trait feature, but maybe a separate feature should be used instead? I was surprised that the test passed without #![feature(try_trait)]; is this expected behavior?

Example 1: comparing structs as #[derive(Ord)] would do

struct Test(bool, u8, &'static str);

impl Ord for Test {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.cmp(&other.0)?;
        self.1.cmp(&other.1)?;
        self.2.cmp(&other.2)
    }
}

Example 2: comparing iterators as Iterator::cmp() would do

fn cmp<A, I1, I2>(mut iter1: I1, mut iter2: I2) -> std::cmp::Ordering
where
    A: Ord,
    I1: Iterator<Item = A>,
    I2: Iterator<Item = A>,
{
    loop {
        match (iter1.next(), iter2.next()) {
            // If both iterators have an item available, compare them
            // and return the result if it is not `Equal`
            (Some(x), Some(y)) => x.cmp(&y)?,
            // If some iterator has finished, compare their `Option<A>` values
            // (`None < Some(_)`, so this matches the behavior of `Iterator::cmp()`)
            (x, y) => return x.cmp(&y),
        }
    }
}

@rust-highfive
Copy link
Collaborator

Thanks for the pull request, and welcome! The Rust team is excited to review your changes, and you should hear from @joshtriplett (or someone else) soon.

If any changes to this PR are deemed necessary, please add them as extra commits. This ensures that the reviewer can see what has changed since they last reviewed the code. Due to the way GitHub handles out-of-date commits, this should also make it reasonably obvious what issues have or haven't been addressed. Large or tricky changes may require several passes of review and changes.

Please see the contribution instructions for more information.

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Aug 28, 2020
library/core/src/cmp.rs Outdated Show resolved Hide resolved
@scottmcm scottmcm added needs-fcp This change is insta-stable, so needs a completed FCP to proceed. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. labels Sep 2, 2020
@scottmcm
Copy link
Member

scottmcm commented Sep 2, 2020

I was surprised that the test passed without #![feature(try_trait)]; is this expected behavior?

All trait impls are insta-stable, regardless of what attribute is put on them, sadly.

If this were able to go in unstable I'd be all for it, but the type Error = Self; here makes me think that we might not want this on stable until we're certain that the current form of the Try trait is the right one -- and right now we're pretty sure it's not, though we're also not sure how much we're stuck with it.

@calebsander calebsander force-pushed the feature/ordering-try branch 2 times, most recently from 2df8bfd to c9f756c Compare September 2, 2020 17:26
@calebsander
Copy link
Contributor Author

I agree it's awkward to use Ordering as the error type when Equal will never be returned as an error. I added a new UnequalOrdering type to use as the return value instead. (I just noticed your comment on the tracking issue proposing the same implementation.)

It's unfortunate that implementations ignore stability attributes, especially since the ? operator doesn't require the Try trait to be imported. (Have there been any attempts to address this?) However, I can't think of any other Try implementation for Ordering (aside from the particulars of the Error type) that would make sense for lexicographic comparisons. The implementation seems quite useful, so I think it merits stabilization after a thorough review, if there is no way to land it unstably.

r? @scottmcm

@calebsander calebsander force-pushed the feature/ordering-try branch 2 times, most recently from bd03146 to d65775e Compare September 2, 2020 18:36
@scottmcm
Copy link
Member

scottmcm commented Sep 2, 2020

Sorry, I should have clarified better -- we found out with impl Try for Option that the error type leaks out even though we didn't want it to. That means that if this goes in, we're somewhat stuck with being able to use ordering? in a method that returns Result, which is probably somewhat undesirable.

So my personal inclination is that -- while I think this is a good impl to have conceptually and implements the semantics I would expect -- it shouldn't happen until either:

  • it's decided that it's fine to allow mixing of types like this, or
  • the ? desugaring is changed so that such mixing doesn't compile.

But we'll see what T-libs has to say about things.

@Dylan-DPC-zz Dylan-DPC-zz added S-waiting-on-team Status: Awaiting decision from the relevant subteam (see the T-<team> label). and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Sep 4, 2020
@Dylan-DPC-zz
Copy link

Dylan-DPC-zz commented Sep 4, 2020

marked it as s-waiting-on-team because this is awaiting feedback by @rust-lang/libs . The discussion can be found here

@pickfire
Copy link
Contributor

pickfire commented Sep 6, 2020

Doesn't seemed straightforward that not equal Ordering should propagate as error, if I were to choose I would rather add Try to bool false.

@calebsander
Copy link
Contributor Author

Doesn't seemed straightforward that not equal Ordering should propagate as error, if I were to choose I would rather add Try to bool false.

I agree it's not obvious from the Ordering type that Less and Greater should be its "errors". My main rationale for this behavior is that its usage is quite natural in comparison functions. I think it makes more sense when viewing a Try type as Continue vs. Break rather than Ok vs. Error. Since you can't tell that two values are equal until you have checked all their pieces for equality, a comparison "continues" on Equal and "breaks" on non-Equal values.
impl Try for Ordering invites some analogies to impl Try for bool:

  • Short-circuiting on Less or Greater is already implemented in Ordering::then_with(), just as short-circuiting on false is already implemented (unstably) in bool::then().
  • Ord could be implemented succinctly using ? on Ordering, just like PartialEq could be implemented succinctly using ? on bool:
struct Test(bool, u8, &'static str);

impl Ord for Test {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.cmp(&other.0)?;
        self.1.cmp(&other.1)?;
        self.2.cmp(&other.2)
    }
}

impl PartialEq for Test {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq(&other.0)?;
        self.1.eq(&other.1)?;
        self.2.eq(&other.2)
    }
}

I'm not opposed to adding impl Try for bool too, but I would argue that short-circuiting on false is even less straightforward than on Less and Greater. A bool is a fundamental bit of information, so false doesn't necessarily represent failure. (For example, slice::is_empty() returns true on an empty slice, which is often an "error" case. I could see use cases for short-circuiting on true instead, i.e. ? could implement || instead of &&.) However, Ordering is explicitly meant to represent the result of a comparison, and this is the canonical way to chain comparisons.

@crlf0710 crlf0710 added the PG-error-handling Project group: Error handling (https://github.com/rust-lang/project-error-handling) label Sep 25, 2020
@camelid camelid added S-waiting-on-team Status: Awaiting decision from the relevant subteam (see the T-<team> label). and removed S-waiting-on-team Status: Awaiting decision from the relevant subteam (see the T-<team> label). labels Oct 16, 2020
@crlf0710 crlf0710 added S-waiting-on-team Status: Awaiting decision from the relevant subteam (see the T-<team> label). and removed S-waiting-on-team Status: Awaiting decision from the relevant subteam (see the T-<team> label). labels Nov 6, 2020
@m-ou-se
Copy link
Member

m-ou-se commented Nov 20, 2020

We discussed this in the libs team meeting, and agreed that—at least right now—this usage of the ? operator is too different from the ones we already have (e.g. Option and Result). Right now, ? is always used to unwrap a container while early-returning the error case. Whether ? should be used for types that do not fit this pattern is a much bigger question, which should probably be discussed (also by the lang team) as part of the whole try_trait feature. (#42327)

@m-ou-se m-ou-se added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed I-nominated S-waiting-on-team Status: Awaiting decision from the relevant subteam (see the T-<team> label). labels Nov 20, 2020
@BurntSushi
Copy link
Member

BurntSushi commented Nov 20, 2020

I wasn't at the libs meeting, but I'd like to echo my strong agreement with that position. I feel very uneasy about adding Try impls for things like bool and Ordering. I think it blows my strangeness budget personally, even if it would make some code more natural to write. For adding these impls, I personally would want to actually see the code the benefits from this and get a general idea for how common it comes up. If it's uncommon, then it seems like a "weird" use of the Try trait that anyone new to that code is going to stumble over and have to go look up and learn. At that point, I'd suggest just using a macro with a more conspicuous name.

@pickfire
Copy link
Contributor

Last time I used to be thinking that Try is good for bool but I find it weird to have Try for Ordering, but thinking of what @BurntSushi mentioned feels true.

}

// This Ord implementation should behave the same as #[derive(Ord)],
// but uses the Try operator on Ordering values
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// but uses the Try operator on Ordering values
// but uses the `?` operator on Ordering values

For clarity

}
}

// Implement Iterator::cmp() using the Try operator
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Implement Iterator::cmp() using the Try operator
// Implement Iterator::cmp() using the `?` operator

For clarity.

@scottmcm
Copy link
Member

scottmcm commented Nov 22, 2020

Thanks for the PR, @calebsander!

Given this libs team feedback I'm going to close this PR. It sounds like it might be worth keeping in mind in other try-related conversations, but that we probably need more experience with other things before we can consider it.

@scottmcm scottmcm closed this Nov 22, 2020
@scottmcm
Copy link
Member

For anyone following along, I've posted an RFC that would resolve my this would allow ordering? in a -> Result method concern: rust-lang/rfcs#3058

Note, however, that said RFC takes no position on whether implementations like this on on Ordering should happen. Anyone interested in reopening this in future would still need to resolve the unease mentioned above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-fcp This change is insta-stable, so needs a completed FCP to proceed. PG-error-handling Project group: Error handling (https://github.com/rust-lang/project-error-handling) S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.