|
| 1 | +(* |
| 2 | + An overview of the implementation of dicts in ReScript: |
| 3 | + ### What is a dict? |
| 4 | + Dicts are effectively an object with unknown fields, but a single known type of the values it holds. |
| 5 | +
|
| 6 | + ### How are they implemented? |
| 7 | + Dicts in ReScript are implemented as predefined record type, with a single (magic) field that holds |
| 8 | + the type of the dict's values. This field is called `dictValuesType`, and is just an implementation |
| 9 | + detail - it's never actually exposed to the user, just used internally. |
| 10 | +
|
| 11 | + The compiler will route any label lookup on the dict record type to the magic field, which creates a |
| 12 | + record with unknown keys, but of a single type. |
| 13 | +
|
| 14 | + The reason for this seemingly convoluted implementation is that it allows us to piggyback on the |
| 15 | + existing record pattern matching mechanism, which means we get pattern matching on dicts for free. |
| 16 | +
|
| 17 | + ### Modifications to the type checker |
| 18 | + We've made a few smaller modifications to the type checker to support this implementation: |
| 19 | +
|
| 20 | + - We've added a new predefined type `dict` that is a record with a single field called `dictValuesType`. |
| 21 | + This type is used to represent the type of the values in a dict. |
| 22 | + - We've modified the type checker to recognize `dict` patterns, and route them to the predefined `dict` type. |
| 23 | + This allows us to get full inference for dicts in patterns. |
| 24 | + |
| 25 | + ### Syntax |
| 26 | + There's first class syntax support for dicts, both as expressions and as patterns. |
| 27 | + A dict pattern is treated as a record pattern in the compiler and syntax, with an attriubute `@res.dictPattern` |
| 28 | + attached to it. This attribute is used to tell the compiler that the pattern is a dict pattern, and is what |
| 29 | + triggers the compiler to treat the dict record type differently to regular record types. |
| 30 | + *) |
1 | 31 | let dict_magic_field_name = "dictValuesType"
|
2 | 32 |
|
3 | 33 | let has_dict_pattern_attribute attrs =
|
|
0 commit comments