feat: add Valid() method to generated enum types#2227
Conversation
Generate a Valid() bool method on each enum type that returns true when the receiver matches one of the defined enum constants and false otherwise. This lets callers validate enum values at runtime with a simple method call instead of hand-writing switch statements. This is default-on because it only adds a new method to an already generated type -- existing code that does not call Valid() is completely unaffected, so this should be very unlikely to break anything. Co-Authored-By: Claude Opus 4.6 <[email protected]>
58e61de to
2615c6e
Compare
jamietanna
left a comment
There was a problem hiding this comment.
From #2181 I do wonder if it'd be useful to be able to get the list of valid enum names, though, i.e. as a slice
But maybe we can see if this solves the underlying need folks have
It turns out we don't need a sorted map of names, since we have the same thing already present on the template context in a different way. Co-Authored-By: Claude Opus 4.6 <[email protected]>
I think it does, because you can always validate in your own code with something like |
If this is default-on, how can we turn it off explicitly? |
|
Ha! You are right, @rkosegi , I forgot to add the flag. I will do so in a subsequent commit. Whenever I add something I think is useful, it inevitably clashes with someone's code. |
Add an `output-options.skip-enum-validate` flag that suppresses the `Valid()` method generated on enum types. The method is still emitted by default; users whose code defines its own `Valid()` on the same type can now opt out instead of seeing a compile-time conflict. Relates to PR #2227, which introduced the `Valid()` method. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Generate a Valid() bool method on each enum type that returns true when the receiver matches one of the defined enum constants and false otherwise. This lets callers validate enum values at runtime with a simple method call instead of hand-writing switch statements.
This is default-on because it only adds a new method to an already generated type -- existing code that does not call Valid() is completely unaffected, so this should be very unlikely to break anything.