|
| 1 | +The goal of this document is to be a reasonably complete reference to the mode system in |
| 2 | +OCaml. |
| 3 | + |
| 4 | +<!-- CR zqian: For a gentler introduction, see [the introduction](intro.md). --> |
| 5 | + |
| 6 | +The mode system in the compiler tracks various properties of values, so that certain |
| 7 | +performance-enhancing operations can be performed safely. For example: |
| 8 | +- Locality tracks escaping. See [the local allocations reference](../local/reference.md) |
| 9 | +- Uniqueness and linearity tracks aliasing. See [the uniqueness reference](../uniqueness/reference.md) |
| 10 | +- Portability and contention tracks inter-thread sharing. |
| 11 | + <!-- CR zqian: reference for portability and contention --> |
| 12 | + |
| 13 | +# Lazy |
| 14 | +`lazy e` contains a thunk that evaluates `e`, as well as a mutable cell to store the |
| 15 | +result of `e`. Upon construction, the mode of `lazy e` cannot be stronger than `e`. For |
| 16 | +example, if `e` is `nonportable`, then `lazy e` cannot be `portable`. Upon destruction |
| 17 | +(forcing a lazy value), the result cannot be stronger than the mode of lazy value. For |
| 18 | +example, forcing a `nonportable` lazy value cannot give a `portable` result. Additionally, |
| 19 | +forcing a lazy value involves accessing the mutable cell and thus requires the lazy value |
| 20 | +to be `uncontended`. |
| 21 | + |
| 22 | +Currently, the above rules don't apply to the locality axis, because both the result and |
| 23 | +the lazy value are heap-allocated, so they are always `global`. |
| 24 | + |
| 25 | +Additionally, upon construction, the comonadic fragment of `lazy e` cannot be stronger |
| 26 | +than the thunk. The thunk is checked as `fun () -> e`, potentially closing over variables, |
| 27 | +which weakens its comonadic fragment. This rule doesn't apply to several axes: |
| 28 | +- The thunk is always heap-allocated so always `global`. |
| 29 | +- Since the thunk is only evaluated if the lazy value is `uncontended`, one can construct |
| 30 | +a lazy value at `portable` even if the thunk is `nonportable` (e.g., closing over |
| 31 | +`uncontended` or `nonportable` values). For example, the following is allowed: |
| 32 | +```ocaml |
| 33 | +let r = ref 0 in |
| 34 | +let l @ portable = lazy (r := 42) in |
| 35 | +``` |
| 36 | +- Since the thunk runs at most once even if the lazy value is forced multiple times, one |
| 37 | +can construct the lazy value at `many` even if the thunk is `once` (e.g., closing over |
| 38 | +`unique` or `once` values). For example, the following is allowed: |
| 39 | +```ocaml |
| 40 | +let r = { x = 0 } in |
| 41 | +let l @ many = lazy (overwrite_ r with { x = 42 }) |
| 42 | +``` |
0 commit comments