cel-go icon indicating copy to clipboard operation
cel-go copied to clipboard

proto enum type and string conversion

Open mindbergh opened this issue 1 year ago • 3 comments

Feature request checklist

  • [x] There are no issues that match the desired change
  • [x] The change is large enough it can't be addressed with a simple Pull Request
  • [x] If this is a bug, please file a Bug Report.

Change I read from the language spec that "enum as int" is a legacy behavior. And there are build-in conversions from int/string to the corresponding enum type. When I test with cel-go, it looks like the enum is still represented as int.

I wonder if there is a way to convert string both to and from a proto enum.

Example type(google.protobuf.Field{}.kind) # this is int

Alternatives considered If the enum is of its corresponding fully-qualified enumeration E, I can probably write a function to convert it to a string.

mindbergh avatar Aug 18 '23 23:08 mindbergh

Hi @mindbergh, thanks for reaching out. The cel-go stack does not yet implement the new behavior, in part because we will need to support backwards compatibility with existing customers using cel-go in their control planes. We can enable a new type-checker option to support it, but it's been a low priority.

What you're looking for seems simpler: string to enum value and back.

If you know the enum name, you could expose a type conversion function that better supports string enum names to numeric enum values: fully.qualified.EnumName(<string>) Going the other direction isn't so easy, so it's still on the backburner at the moment.

Happy to talk more about this though to figure out if there's something simpler that would work.

-Tristan

TristonianJones avatar Aug 18 '23 23:08 TristonianJones

@TristonianJones thanks for your quick reply.

Ideally, I would like to have something like string(google.protobuf.Field{}.kind) == "TYPE_UNKNOWN". Is there a way to know the type of the enum at runtime? If so, maybe we can expose one function that does some protoreflection to convert the int to string.

Otherwise, maybe we have to expose a function for each enum type to do the conversion, which seems pretty hard to maintain and less usable. e.g. kind_string(google.protobuf.Field{}.kind) == "TYPE_UNKNOWN"

mindbergh avatar Aug 19 '23 00:08 mindbergh

@TristonianJones I've found a method of overriding the current type provider to enable enums to be compared directly with strings, would that reference implementation be valuable? If so I can open a pr to add it as an example or paste it here for posterity

WhiskeyJack96 avatar Mar 09 '24 23:03 WhiskeyJack96