Check coherence between enum or struct fields

Did you know if it's possible with macro (or another system) to check coherence between enum or struct fields?

Example with a hypothetical macro shape:

    enum A {
        Kind1,
        Kind2
    }

    #[shape(A)] //Should compile without error
    enum B {
        Kind1,
        Kind2
    }

    #[shape(A)] //Should not compile: error, "Kind2" missing 
    enum B {
        Kind1
    }

I couldn't find a macro to do this. I may not have the right keyword to search for that.

Macros can't look up the definition of other things, so its not possible for a macro to do this.

1 Like

You could have the macro create a function like

fn _shape_check(a: A) {
    match a {
        A::Kind1 => {}
    }
}

where it generates an A::Variant => {} match arm for each variant of B, and that would fail to compile if B's variants weren't the same as A's. The error message wouldn't be great, but at least for the example you posted in the OP, it's possible.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.