# \[Pre-RFC\] Multiple if-let guards (not chaining)

**URL:** <https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818>\
**Category:** Uncategorized\
**Created:** [January 12, 2021, 12:23pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818 "2021-01-12T12:23:39Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![Soni](https://avatars.discourse-cdn.com/v4/letter/s/a3d4f5/32.png) [@Soni](https://internals.rust-lang.org/u/Soni)\
**Post date:** [January 12, 2021, 12:23pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/1 "2021-01-12T12:23:40Z")

</div>

## Summary

if-let-guard in match should be expanded to allow different if-let-guards in or patterns.

```rust
// Existing if-let-guard
match foo {
    _ if let x = bar => {}
}

// Proposed if-let-guard-in-or-patterns
match foo {
    (A if let x = bar) | (B if let x = baz) => {}
}

```

Note the use of `(...)` for compatibility with existing programs/patterns.

## Motivation

Given:

```rust
/// A pattern element.
pub(crate) enum PatternElement<T: PatternTypes> {
    Arrow,

    Identifier(usize),

    StringKey(usize),
    RegexKey(usize),
    ParameterKey(usize),
    KeySubtree(usize),
    ValueSubtree(usize),
    ApplyPredicate(usize, PhantomData<fn(&PatternConstants<T>) -> &Predicate<T>>),

    SkipStringKey(usize),
    SkipRegexKey(usize),
    SkipParameterKey(usize),
    SkipKeySubtree(usize),
    SkipValueSubtree(usize),
    SkipApplyPredicate(usize, PhantomData<fn(&PatternConstants<T>) -> &Predicate<T>>),

    End
}

// These use more memory than the above. They're easier to work with tho.
// TODO replace with (StringKey(x) if let skip = false) | (SkipStringKey(x) if let skip = true)
// (if those ever become a thing)
enum PatternElementHelper {
    Arrow,

    Identifier(usize),

    StringKey(usize, bool),
    RegexKey(usize, bool),
    ParameterKey(usize, bool),
    KeySubtree(usize, bool),
    ValueSubtree(usize, bool),
    ApplyPredicate(usize, bool),

    End
}

impl<T: PatternTypes> From<PatternElement<T>> for PatternElementHelper {
    fn from(a: PatternElement<T>) -> PatternElementHelper {
        match a {
            PatternElement::Arrow => PatternElementHelper::Arrow,

            PatternElement::Identifier(x) => PatternElementHelper::Identifier(x),

            PatternElement::StringKey(x) => PatternElementHelper::StringKey(x, false),
            PatternElement::SkipStringKey(x) => PatternElementHelper::StringKey(x, true),
            PatternElement::RegexKey(x) => PatternElementHelper::RegexKey(x, false),
            PatternElement::SkipRegexKey(x) => PatternElementHelper::RegexKey(x, true),
            PatternElement::ParameterKey(x) => PatternElementHelper::ParameterKey(x, false),
            PatternElement::SkipParameterKey(x) => PatternElementHelper::ParameterKey(x, true),
            PatternElement::KeySubtree(x) => PatternElementHelper::KeySubtree(x, false),
            PatternElement::SkipKeySubtree(x) => PatternElementHelper::KeySubtree(x, true),
            PatternElement::ValueSubtree(x) => PatternElementHelper::ValueSubtree(x, false),
            PatternElement::SkipValueSubtree(x) => PatternElementHelper::ValueSubtree(x, true),
            PatternElement::ApplyPredicate(x, _) => PatternElementHelper::ApplyPredicate(x, false),
            PatternElement::SkipApplyPredicate(x, _) => PatternElementHelper::ApplyPredicate(x, true),

            PatternElement::End => PatternElementHelper::End,
        }
    }
}

```

Allowing the syntax in that TODO comment would allow getting rid of `PatternElementHelper` entirely, with no additional runtime cost (either processing or memory). This feature would be an adaptation of explicit fallthrough for use with pattern matching.

Instead, replacing `PatternElement` with `PatternElementHelper` would cause a 33% increase in memory usage for the structs that contain `PatternElement`s.

## Guide-level explanation

[TODO]

## Reference-level explanation

[TODO]

## Drawbacks

This proposal introduces new syntax. It also requires look-ahead, as the proposed syntax is somewhat ambiguous with tuples.

## Rationale and alternatives

This is seems to be the simplest adaptation of fallthrough for use with pattern matching, with a good cost/benefit tradeoff. It expands on existing syntax instead of introducing completely novel syntax, avoids the pitfalls of implicit fallthrough, avoids introducing non-lexical flow control (such as goto, etc), and correctly fulfills the need it is meant to fulfill.

A possible alternative could have been unreferenceablefolded fields. However, being able to fold bools into the enum variant would be problematic for the same reason we don't support packed structs anymore. More importantly, there is no good way to support mutating folded fields through `&mut Enum`. For example,

```rust
enum Foo {
  A(fold bool, Mutex<()>),
  B(fold bool, Mutex<()>),
}
fn bar(&mut Foo) {
  // how would you change A(false, mutex) into A(true, mutex), without unsafe code?
}
let mut x = Foo::A(false, Mutex::new(())); // so far so good
bar(&mut x);

```

## Prior art

- C and C++ have implicit fallthrough. It's such an issue that gcc and clang have a flag `-Wimplicit-fallthrough` to warn on implicit fallthrough, such that the programmer is required to add a `// fall through` comment where fallthrough is desired.
- [TODO]

## Unresolved questions

- Are there _other_ alternatives to this?
- [TODO]

## Future possibilities

Chaining if-let and/or allowing `(...)` around arbitrary parts of patterns is out of scope for this proposal.

---

<div class="post-metadata">

**Author:** ![H2CO3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/h2co3/32/2849_2.png) [@H2CO3](https://internals.rust-lang.org/u/H2CO3)\
**Post date:** [January 12, 2021, 1:31pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/2 "2021-01-12T13:31:58Z")

</div>

> [@Soni](#):
>
> This feature would be an adaptation of explicit fallthrough for use with pattern matching.

Rust's `match` is not really the same as C's `switch`. Especially not in philosophy. Fallthrough has been proven to cause so much pain with little benefit that I really don't think it should be in Rust (or any modern programming language, really.)

> [@Soni](#):
>
> Allowing the syntax in that TODO comment would allow getting rid of `PatternElementHelper` entirely

It's not clear what goal `PatternElementHelper` achieves. What are you actually trying to do, and what goes wrong? Perhaps there is a simpler, already doable approach for achieving what you want – provided that the above piece of code is a real-life example.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 12, 2021, 1:39pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/3 "2021-01-12T13:39:22Z")

</div>

> [@H2CO3](#):
>
> It's not clear what goal `PatternElementHelper` achieves. What are you actually trying to do, and what goes wrong?

Note that the comment/thread linked below is where this thread’s proposal came from, it helps to explain the context a bit more

> [@The Fall-Through Proposal](https://internals.rust-lang.org/t/the-fall-through-proposal/13792/3):
>
> I believe that if let guards are planned, but they always apply to the entire match arm. This restriction could be removed by requiring parentheses in some cases: match foo { A | B if bar =\> {} // is equivalent to (A | B) if bar =\> {} // This could be allowed too: (A if bar) | (B if !bar) =\> {} (A if let x = true) | (B if let x = false) =\> {} }

---

<div class="post-metadata">

**Author:** ![Soni](https://avatars.discourse-cdn.com/v4/letter/s/a3d4f5/32.png) [@Soni](https://internals.rust-lang.org/u/Soni)\
**Post date:** [January 12, 2021, 1:50pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/4 "2021-01-12T13:50:41Z")

</div>

> [@H2CO3](#):
>
> Rust's `match` is not really the same as C's `switch` . Especially not in philosophy. Fallthrough has been proven to cause so much pain with little benefit that I really don't think it should be in Rust (or any modern programming language, really.)

We don't know how to address this clearer in the rationale. It is precisely for those issues that we're not proposing fallthrough, but a "philosophical alternative" (to borrow your words) to it.

> [@H2CO3](#):
>
> It's not clear what goal `PatternElementHelper` achieves. What are you actually trying to do, and what goes wrong? Perhaps there is a simpler, already doable approach for achieving what you want – provided that the above piece of code is a real-life example.

This thing is part of a VM/interpreter. The goal is to keep the function objects small (by keeping the opcodes small), while being able to inherit behaviour across opcodes.

The original code looks something like this:

```python
class StringKey(PatternElement):
    """The 'literal' token."""

    def __init__ (self, toks):
        self.key = toks[0]
        self.skippable = toks[1] == '?'

    def on_in_key(self, frame, path, defs):
        return self.on_not_in_key(frame, path, defs)

    def on_not_in_key(self, frame, path, defs):
        path[-1].iterator = self._extract(path[-1].parent)
        path[-1].empty = False
        return True

    def _extract(self, obj):
        try:
            yield (self.key, obj[self.key])
        except (TypeError, IndexError, KeyError):
            if not self.skippable:
                raise exceptions.ValidationError

```

For memory usage reasons we're converting it to use enums + a constant pool. This means matching the whole thing. It's less than ideal having to duplicate the code between the Skip\* and the non-Skip\* variants.

---

<div class="post-metadata">

**Author:** ![mbrubeck](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mbrubeck/32/174_2.png) [@mbrubeck](https://internals.rust-lang.org/u/mbrubeck)\
**Post date:** [January 12, 2021, 1:53pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/5 "2021-01-12T13:53:04Z")

</div>

> [@Soni](#):
>
> Instead, replacing `PatternElement` with `PatternElementHelper` would cause a 33% increase in memory usage for the structs that contain `PatternElement` s.

This doesn't appear to be the case, at least in your particular example. Both enums have the same size:

```rust
size_of::<PatternElement>() = 16
size_of::<PatternElementHelper>() = 16

```

---

<div class="post-metadata">

**Author:** ![Soni](https://avatars.discourse-cdn.com/v4/letter/s/a3d4f5/32.png) [@Soni](https://internals.rust-lang.org/u/Soni)\
**Post date:** [January 12, 2021, 1:59pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/6 "2021-01-12T13:59:28Z")

</div>

Wait, bools aren't usize?

---

<div class="post-metadata">

**Author:** ![mbrubeck](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mbrubeck/32/174_2.png) [@mbrubeck](https://internals.rust-lang.org/u/mbrubeck)\
**Post date:** [January 12, 2021, 2:07pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/7 "2021-01-12T14:07:23Z")

</div>

No, `bool` has one-byte width and alignment.

---

<div class="post-metadata">

**Author:** ![Nemo157](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nemo157/32/11585_2.png) [@Nemo157](https://internals.rust-lang.org/u/Nemo157)\
**Post date:** [January 12, 2021, 2:11pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/8 "2021-01-12T14:11:22Z")

</div>

This feels like just a logical combination of RFC 2535 + RFC 2294 and moving guards from being something `match` specific to being part of general patterns.

---

<div class="post-metadata">

**Author:** ![Soni](https://avatars.discourse-cdn.com/v4/letter/s/a3d4f5/32.png) [@Soni](https://internals.rust-lang.org/u/Soni)\
**Post date:** [January 12, 2021, 3:38pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/9 "2021-01-12T15:38:09Z")

</div>

And enum tags aren't usize?

---

<div class="post-metadata">

**Author:** ![mbrubeck](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mbrubeck/32/174_2.png) [@mbrubeck](https://internals.rust-lang.org/u/mbrubeck)\
**Post date:** [January 12, 2021, 4:04pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/10 "2021-01-12T16:04:26Z")

</div>

By default, an enum is tagged with the smallest-sized integer that is large enough to represent every variant. (For example, `u8` if there are fewer than 256 variants.)

The compiler can also pack the enum tag into unused bit patterns in types like `char` or `bool` or `&T`, in some cases, though this doesn't affect the types in your example.

---

<div class="post-metadata">

**Author:** ![camelid](https://avatars.discourse-cdn.com/v4/letter/c/c67d28/32.png) [@camelid](https://internals.rust-lang.org/u/camelid)\
**Post date:** [January 13, 2021, 12:27am UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/11 "2021-01-13T00:27:59Z")

</div>

> [@mbrubeck](#):
>
> The compiler can also pack the enum tag into unused bit patterns in types like `char` or `bool` or `&T` , in some cases, though this doesn't affect the types in your example.

As an example of this optimization, this code:

```rust
enum EnumRef<'a, T> {
    Foo,
    Bar(&'a T),
}

enum EnumOwned<T> {
    Foo,
    Bar(T),
}

fn main() {
    println!("usize: {}", core::mem::size_of::<usize>());
    println!("EnumRef<usize>: {}", core::mem::size_of::<EnumRef<usize>>());
    println!("EnumOwned<usize>: {}", core::mem::size_of::<EnumOwned<usize>>());
}

```

prints this:

```plaintext
usize: 8
EnumRef<usize>: 8
EnumOwned<usize>: 16

```

As you can see, even though `EnumRef<usize>` has two variants and thus is conceptually "bigger" than `usize`, it actually takes up the same amount of space in memory. That's because Rust references are known to never be NULL – the compiler knows that and can use 8 bytes of zeros to represent the `EnumRef::Foo` variant and all other memory states to represent `EnumRef::Bar(some_val)`.

On the other hand, `EnumOwned<usize>` can't be optimized this way because then you wouldn't be able to represent values like `EnumOwned::Bar(0)`.

---

<div class="post-metadata">

**Author:** ![Soni](https://avatars.discourse-cdn.com/v4/letter/s/a3d4f5/32.png) [@Soni](https://internals.rust-lang.org/u/Soni)\
**Post date:** [January 13, 2021, 4:42pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/12 "2021-01-13T16:42:09Z")

</div>

If anyone wants to close this or if anyone has another use-case for this and wants to take it over, feel free.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [April 13, 2021, 4:42pm UTC](https://internals.rust-lang.org/t/pre-rfc-multiple-if-let-guards-not-chaining/13818/13 "2021-04-13T16:42:14Z")

</div>

Closed on April 13, 2021, 4:42pm UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
