Skip to content

Commit e3b403a

Browse files
Include a quick getting started snippet licensed under MIT-0
1 parent 08178b0 commit e3b403a

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

README.md

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,32 @@ Dump runtime values to typed Hack source code.
77
Run code during build-time, codegen the values you were interested in back to
88
Hack code, write it to a Hack source file, and you have build-time compute.
99

10-
You have data you need in your program that will not change between releases.
11-
All data that enters your program has the type `mixed`, therefore you must cast
12-
it to a typed value in order to process it. If you do this safely, this incurs
13-
runtime costs. Doing it using an unsafe mechanism, such as `HH\FIXME\UNSAFE_CAST`
14-
or `HH_FIXME[4110]` is trading correctness for performance. But what if the
15-
data was already part of your program, fully typed and ready to use?
1610

11+
The following snippet[^1] embodies the essence of this library perfectly.
1712
```HACK
18-
const TheTypeYouNeed THE_DATA_YOU_NEED = /* embed the data here */;
13+
function burn_a_value_to_constant<reify T>(
14+
string $constant_name,
15+
T $value,
16+
ExprDump\DumpOptions $dumper_options = shape(),
17+
)[]: string {
18+
$type_name = TypeVisitor\visit<T, _, _>(new TypeVisitor\TypenameVisitor());
19+
$serialized_value = ExprDump\dump<T>($value, $dumper_options);
20+
return Str\format(
21+
'const %s %s = %s;',
22+
$type_name,
23+
$constant_name,
24+
$serialized_value,
25+
);
26+
}
1927
```
2028

29+
All data that enters your program at runtime is typed as `mixed`, which is why
30+
you must cast it to a typed value in order to process it. If you do this safely,
31+
this incurs runtime costs. Doing it using an unsafe mechanism, such as
32+
`HH\FIXME\UNSAFE_CAST` or `HH_FIXME[4110]` is trading correctness for performance.
33+
But with `burn_a_value_to_constant`, the data doesn't enter the program at runtime.
34+
This data is already typed, so there is no need for casting.
35+
2136
## Why the existing tools can not meet this need
2237

2338
In Hack, the same runtime value can represent two different types.
@@ -107,3 +122,8 @@ In order to minimize the potential impact of a removal of these apis, you should
107122
not use this library in places where the performance of bootstrapping the dumper
108123
is critical. A far less performant variant of `TypeVisitor` could be written, even
109124
without these api affordances.
125+
126+
[^1]: This snippet `burn_a_value_to_constant` is excempt from the MIT license
127+
of this library. It is licensed to you under MIT-0 (MIT No Attribution).
128+
This excemption does not apply to the code called by this snippet. The MIT
129+
license still covers all other parts of this program.

0 commit comments

Comments
 (0)