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

Allow negation of `if let` #2616

Open
mqudsi opened this Issue Dec 22, 2018 · 21 comments

Comments

Projects
None yet
@mqudsi
Copy link

mqudsi commented Dec 22, 2018

The RFC for if let was accepted with the rationale that it lowers the boilerplate and improves ergonomics over the equivalent match statement in certain cases, and I wholeheartedly agree.

However, some cases still remain exceedingly awkward; an example of which is attempting to match the "class" of a record enum variant, e.g. given the following enum:

enum Foo {
    Bar(u32),
    Baz(u32),
    Qux
}

and an instance foo: Foo, with behavior predicated on foo not being Bar and a goal of minimizing nesting/brace creep (e.g. for purposes of an early return), the only choice is to type out something like this:

    // If we are not explicitly using Bar, just return now
    if let Foo::Bar(_) = self.integrity_policy {
    } else {
        return Ok(());
    }

    // flow resumes here

or the equally awkward empty match block:

    // If we are not explicitly using Bar, just return now
    match self.integrity_policy {
        Foo::Bar(_) => return Ok(());
        _ => {}
    }

    // flow resumes here

It would be great if this were allowed:

    // If we are not explicitly using Bar, just return now
    if !let Foo::Bar(_) = self.integrity_policy {
        return Ok(());
    }

    // flow resumes here

or perhaps a variation on that with slightly less accurate mathematical connotation but far clearer in its intent (you can't miss the ! this time):

    // If we are not explicitly using Bar, just return now
    if let Foo::Bar(_) != self.integrity_policy {
        return Ok(());
    }

    // flow resumes here

(although perhaps it is a better idea to tackle this from an entirely different perspective with the goal of greatly increasing overall ergonomics with some form of is operator, e.g. if self.integrity_policy is Foo::Bar ..., but that is certainly a much more contentious proposition.)

@H2CO3

This comment has been minimized.

Copy link

H2CO3 commented Dec 23, 2018

or the equally awkward empty match block

I don't understand what's "awkward" in a block.

Furthermore, I don't see any good syntax for realizing this. Certainly, both proposed ones (if !let foo = … and if let foo != …) are much more awkward and a lot harder to read than a perfectly clear match. I would consider such code less ergonomic and less readable than the equivalent match expression.

@burdges

This comment has been minimized.

Copy link

burdges commented Dec 23, 2018

We've seen numerous proposals for this, so maybe review them before attempting to push any serious discussion.

If the variants contain data then you normally require said data, but you cannot bind with a non-match, so is_[property] methods are frequently best at covering the actual station. If is_[property] methods do not provide a nice abstraction, then maybe all those empty match arms actually serve some purpose, but if not then you can always use a wild card:

let x = match self.integrity_policy {
    Foo::Bar(x) => x,
    _ => return Ok(()),
}

Also, one can always do very fancy comparisons like:

use std::mem::discriminant;
let d = discriminant(self.integrity_policy);
while d != discriminant(self.integrity_policy) {  // loop until our state machine changes state
    ...
}

I believe the only "missing" syntax around bindings is tightly related to refinement types, which require a major type system extension. In my opinion, we should first understand more what design by contract and formal verification might look like in Rust because formal verification is currently the major use case for refinement types. Assuming no problems, there is a lovely syntax in which some refine keyword works vaguely like a partial match. As an example, let y = x? would be equivalent to

let Ok(y) = refine x { Err(z) => return z.into(); }  

In this let Ok(y) = .. could type checks because refine returns a refinement type, specifically an enum variant type ala #2593. I suppose refinement is actually kinda the opposite of what you suggest here, but figured I'd mention it.

@mqudsi

This comment has been minimized.

Copy link
Author

mqudsi commented Dec 23, 2018

I looked around for past proposals regarding expanding the if let syntax, starting with the original if let rfc and issues referenced in the comments before opening this.

@burdges Thanks for sharing that info, I have some reading to do. But with regards to

if is_[property] methods do not provide a nice abstraction, then maybe all those empty match arms actually serve some purpose

No, those are exactly what I would like, except they're not available for enum variants, i.e. for enum Foo { Bar(i8), Baz } there is no (automatically-created) Foo::is_bar(&self) method. It is in fact the absence of such an interface that required the use of if let or match.

One problem with the existing if let syntax is that it is a wholly unique expression masquerading as an if statement. It isn't natural to have an if statement you can't negate - the default expectation is that this is a boolean expression that may be treated the same as any other predicate in an if clause.

@H2CO3

This comment has been minimized.

Copy link

H2CO3 commented Dec 23, 2018

No, those are exactly what I would like, except they're not available for enum variants.

Oh, I think that can be fixed quite easily. They could be #[derive]d easily based on naming conventions. I'll try to write up an example implementation soon.

@burdges

This comment has been minimized.

Copy link

burdges commented Dec 23, 2018

I'd suggest #[allow(non_snake_case)] for autogenerated one, so they look like

    #[allow(non_snake_case)]
    pub fn is_A(&self) { if let MyEnum::A = self { true } else { false } }

That said, if you have more than a couple variants then is_ methods might describe meaningful variants collections, not individual variants. We're talking about situations where you do not care about the variant's data after all.

In fact, you'd often want the or/| pattern like

let x = match self.integrity_policy {
    Foo::A(x) | Foo::B(x,_) => x,
    Foo::C { .. } | Foo::D => return Ok(()),
    Foo::E(_) => panic!(),
}
@H2CO3

This comment has been minimized.

Copy link

H2CO3 commented Dec 24, 2018

I made a PoC implementation of the "generate is_XXX methods automatically" approach.

@Centril

This comment has been minimized.

Copy link
Contributor

Centril commented Dec 24, 2018

@H2CO3 This already exists on crates.io: https://crates.io/crates/derive_is_enum_variant and there's likely more complex variants too involving prisms/lenses and whatnot.

It seems to me however that generating a bunch of .is_$variant() methods is not a solution that scales well and that the need for these are due to the lack of a bool typed operation such as expr is pat (which could be let pat = expr... -- color of bikeshed...).

Fortunately, given or-patterns (rust-lang/rust#54883) let chains (rust-lang/rust#53667), and a trivial macro defined like so:

macro_rules! is { ($(x:tt)+) => { if $(x)+ { true } else { false } } }

we can write:

is!(let Some(E::Bar(x)) && x.some_condition() && let Other::Stuff = foo(x));

and the simpler version of this is:

is!(let E::Bar(..) = something)
// instead of: something.is_bar()
@H2CO3

This comment has been minimized.

Copy link

H2CO3 commented Dec 24, 2018

@Centril I'm glad it already exists in a production-ready version. Then OP can just use it without needing to wait for an implementation.

there's likely more complex variants too involving prisms/lenses and whatnot.

What do you exactly mean by this? AFAIK there aren't many kinds of enum variants in Rust. There are only unit, tuple, and struct variants. I'm unaware of special prism and/or lens support in Rust that would lead to the existence of other kinds of variants.

It seems to me however that generating a bunch of .is_$variant() methods is not a solution that scales well

I beg to differ. Since they are generated automatically, there's not much the user has to do… moreover the generated functions are trivial, there are O(number of variants) of them, and they can be annotated with #[inline] so that the binary size won't be bigger compared to manually-written matching or negated if-let.

Fortunately, given or-patterns [and] let chains

Those are very nice, and seem fairly powerful. I would be glad if we could indeed reuse these two new mechanisms plus macros in order to avoid growing the language even more.

@Centril

This comment has been minimized.

Copy link
Contributor

Centril commented Dec 24, 2018

@H2CO3

@Centril I'm glad it already exists in a production-ready version. Then OP can just use it without needing to wait for an implementation.

🎉

What do you exactly mean by this? AFAIK there aren't many kinds of enum variants in Rust. There are only unit, tuple, and struct variants. I'm unaware of special prism and/or lens support in Rust that would lead to the existence of other kinds of variants.

I found this a while back: https://docs.rs/refraction/0.1.2/refraction/ and it seemed like an interesting experiment; other solutions might be to generate .extract_Bar(): Option<TupleOfBarsFieldTypes> and then use ? + try { .. } + .and_then() pervasively. You can use .is_some() on that to get the answer to "was it of the expected variant".

I beg to differ. Since they are generated automatically, there's not much the user has to do… moreover the generated functions are trivial, there are O(number of variants) of them, and they can be annotated with #[inline] so that the binary size won't be bigger compared to manually-written matching or negated if-let.

In a small crate I don't think it would pay off to use a derive macro like this; just compiling syn and quote seems too costly to get anyone to accept it. Another problem with the deriving strategy is that when you are working on a codebase (say rustc) and you want to check whether a value is of a certain variant, then you first need to go to the type's definition and add the derive macro; that can inhibit flow.

Those are very nice, and seem fairly powerful. I would be glad if we could indeed reuse these two new mechanisms plus macros in order to avoid growing the language even more.

Sure; this is indeed nice; but imo, it seems natural and useful to think of let pat = expr as an expression typed at bool which is true iff pat matches expr and false otherwise. In that case, if !let pat = expr { ... } is merely the composition of if !expr { ... } and let pat = expr.

@alexreg

This comment has been minimized.

Copy link

alexreg commented Dec 29, 2018

I'm for this. It arguably reduces the semantic complexity of the language, and improves consistency, especially with let-chaining coming in.

Has @rust-lang/libs thought of bundling the is! macro with the language, given how common it is?

@mbrubeck

This comment has been minimized.

Copy link
Contributor

mbrubeck commented Jan 8, 2019

See also #1303.

@graydon

This comment has been minimized.

Copy link

graydon commented Jan 12, 2019

Opposed. Not a big enough use-case to warrant extension at language level. Similar to there not being both while and do while loops, it can be done via numerous user-level escape hatches provided above.

@mqudsi

This comment has been minimized.

Copy link
Author

mqudsi commented Jan 12, 2019

It is respectfully nothing like the while vs do while situation. A while loop is one thing, and do while is another. An if statement already exists in the language with clearly defined semantics and permutations. This syntax reuses the if statement in name only, masquerading as a block of code while not actually sharing any of its features apart from reusing the same if keyword, with no reason why that can’t be fixed.

@graydon

This comment has been minimized.

Copy link

graydon commented Jan 12, 2019

I regard if let the same way you do: as a random recycling of if somewhat out of context; I wouldn't have voted for its addition. But disliking it doesn't mean I think it needs to get more ways to mean something else yet again. It does not. If you dislike my analogy, you can substitute the analogy that we don't (and should not gain) a match-not expression.

(And definitely also not a guard-let or whatever Swift has. It has too many of these.)

@comex

This comment has been minimized.

Copy link

comex commented Jan 13, 2019

Which is why I think let should become an actual boolean expression, albeit with special rules around scoping. That solves the “random recycling” problem and also enables if !let.

@comex

This comment was marked as off-topic.

Copy link

comex commented Jan 13, 2019

(and while this is admittedly both rude and off topic :\, after checking your recent posts, is there anything you’re not against?)

@mikhail-krainik

This comment has been minimized.

Copy link

mikhail-krainik commented Jan 15, 2019

In Ruby exists unless operator where executes code if conditional is false. If the conditional is true, code specified in the else clause is executed.
It may be like

unless let Foo::Bar(_) = self.integrity_policy {
        return Ok(());
}
@mark-i-m

This comment has been minimized.

Copy link
Contributor

mark-i-m commented Jan 15, 2019

I’ve always disliked unless operators in languages that have them. There is some cognitive overhead for me to deal with the extra implicit negation.

@vext01

This comment has been minimized.

Copy link

vext01 commented Feb 5, 2019

Hi,

I've landed here looking for if !let. I wanted to write:

if !let Ok((Index{num_mirs: 0}, None)) = Decoder::new(&mut curs) {
    panic!();
}

Which I think today, is best expressed as:

match Decoder::new(&mut curs) {                                                                 
    Ok((Index{num_mirs: 0}, None)) => (),                                     
    _ => panic!(),                                                            
}
@scottmcm

This comment has been minimized.

Copy link
Member

scottmcm commented Mar 15, 2019

@mark-i-m I dislike them when they're just sugar for !, but if there's a difference in what they do (like the unless block must be : !), then it might be plausible. The negation, given the !-typed block, is consistent with things like assert!, so I don't think it's fundamentally confusing.

@mark-i-m

This comment has been minimized.

Copy link
Contributor

mark-i-m commented Mar 17, 2019

I feel like that would be a bit unexpected for most people. There is conceptually no reason unless foo {...} would not be a normal expression like if or match.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.