xref: /aosp_15_r20/external/emboss/doc/design_docs/value_of_enum_function.md (revision 99e0aae7469b87d12f0ad23e61142c2d74c1ef70)
1# Design Sketch: Integer-Value-of-Enum Function
2
3## Overview
4
5It is sometimes useful to use the integer value of an enumerated name:
6
7    enum Foo:
8      ZZ = 17
9
10    struct Bar:
11      [requires: id == Foo.ZZ]  # Type error
12      0 [+4]  UInt  id
13
14In the current Emboss expression language, there is no way to perform this
15comparison.
16
17
18## `$to_int()` Function
19
20A `$to_int()` function (name TBD), taking an `enum` value and returning the
21same numeric value with type integer, would fix this problem:
22
23    enum Foo:
24      ZZ = 17
25
26    struct Bar:
27      [requires: id == $to_int(Foo.ZZ)]
28      0 [+4]  UInt  id
29
30
31## `$from_int()` Function (Optional)
32
33The opposite function would also be useful in some circumstances, but would
34take a lot more effort: new syntax would be needed for a type-parameterized
35function.
36
37A couple of possible syntaxes:
38
39    $int_to<EnumType>(7)   # 1
40    EnumType.$from_int(7)  # 2
41    EnumType(7)            # 3
42
43The first option resembles type-parameterized functions in many languages, but
44may require some tricky modifications to Emboss's strict LR(1) grammar.
45
46The second option looks like a class method (a la Python) or a static method (a
47la C++/Java/C#), and *may* require a less-difficult change to the Emboss
48grammar... but there are some messy bits in the grammar around how `.` is
49handled, and the notation does not scale to multiple types.
50
51The third option is more C-like, *still* requires grammar updates, and does not
52provide any obvious solution for any other, future type-parameterized functions.
53
54
55## Implementation Notes
56
57`$to_int()` would require changes in a lot of places, though each change should
58be small.
59
60`$from_int()` would require changes in pretty much the same places, but a few
61of them would be significantly more complex.
62
63Basically anywhere that walks or evaluates an `ir_data.Expression` would need to
64be updated to know about the new function.  A probably-incomplete list:
65
66    compiler/back_end/header_generator.py
67    compiler/front_end/constraints.py
68    compiler/front_end/expression_bounds.py
69    compiler/front_end/type_check.py
70    compiler/util/ir_util.py
71
72Additionally, for `$to_int()`, minor tweaks would need to be made to
73`tokenizer.py` (add the new function name) and `module_ir.py` (register the new
74name as a function in the syntax).
75
76For `$from_int()`, the list is essentially the same, except that `module_ir.py`
77would need much larger updates to allow whichever new syntax, and some of the
78other changes would be more complex in order to verify that the type parameter
79was actually an `enum`.
80