protobuf
protobuf copied to clipboard
[C#] Ensure enum members are preserved with trimming
Note: I haven't seen anything broken by this issue. These are my thoughts in the area in case it does become a problem in the future.
AOT and trimming will remove unused members. That can include enum fields. I have tested places that use enum fields with reflection (e.g. JSON parser with enum values) and it appears to work, but I don't think that is a guarantee it will work forever.
The typical fix to this problem is to use DynamicallyAccessedMembersAttribute
(DAM) to explicitly preserve values. However, that isn't possible when enum descriptors are registered because GeneratedClrTypeInfo accepts enum types in an array, and an array can't be annotated.
I see two ways to fix this:
One way is generate a dummy method that has a Type
parameter and returns Type
. The method parameter would have the DAM attribute on it:
private Type EnsureEnumMembers([DynamicallyAccessedMembers(PublicFields)] Type t) => t;
And then call it when values are passed to GeneratedClrTypeInfo
. e.g.
new pbr::GeneratedClrTypeInfo(
new[] { EnsureEnumMembers(typeof(global::Conformance.WireFormat)), EnsureEnumMembers(typeof(global::Conformance.TestCategory)) },
...);
That would signal to the linker that public fields for these enum types should never be trimmed.
Or have an AddEnumType
method on GeneratedClrTypeInfo
used to add enum types. That method can be annotated with the DAM attribute. The downside here is GeneratedClrTypeInfo
is designed to be immutable (mostly, the arrays can be set, but they're not intended to be.
We triage inactive PRs and issues in order to make it easier to find active work. If this issue should remain active or becomes active again, please add a comment.
This issue is labeled inactive
because the last activity was over 90 days ago.
I still need to get back to this.
We triage inactive PRs and issues in order to make it easier to find active work. If this issue should remain active or becomes active again, please add a comment.
This issue is labeled inactive
because the last activity was over 90 days ago.
We triage inactive PRs and issues in order to make it easier to find active work. If this issue should remain active or becomes active again, please reopen it.
This issue was closed and archived because there has been no new activity in the 14 days since the inactive
label was added.