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

Add _Enum! macros to replace _ arms when matching shared enums #1376

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Commits on Oct 1, 2024

  1. Add _Enum! macros to replace _ arms when matching shared enums

    As the docs currently state about shared enums:
    > Pattern matching with match still works but will require you to write
    > wildcard arms to handle the situation of an enum value that is not
    > one of the listed variants.
    
    This is unfortunate as there is no way to check that all listed enum
    variants are actually handled. IOW this code does not even warn:
    ```
    mod ffi {
        enum Enum {
            A,
            B,
            C = 5,
        }
    }
    
    match t {
        Enum::A => {},
        Enum::B => {},
        _ => {},
    }
    ```
    
    This generates an extra _Enum! macro that matches all the ranges that
    are _not_ listed by the enum. When using that macro instead of the _
    catch-all, we get compile-time errors if we forget to match variants:
    ```
    match t {
        Enum::A => {},
        Enum::B => {},
        _Enum!() => {},
    }
    // Error Enum{ repr: 5 } case not covered
    ```
    
    The generated macro looks like:
    ```
    macro_rules! _Enum {
        () => { Enum{ repr: 4..5 | 6.. } };
        ($i:ident) => { Enum { repr: $i @ 4..5 | 6.. } };
    }
    ```
    
    It can also be used to ergonomically retrieve the inner value in the
    unlisted case:
    ```
    match t {
        Enum::A => {},
        Enum::B => {},
        Enum::C => {},
        _Enum!(value) => panic!("Unexpected Enum value {value}"),
    }
    ```
    nicolas-guichard committed Oct 1, 2024
    Configuration menu
    Copy the full SHA
    c8c12cc View commit details
    Browse the repository at this point in the history