|
| 1 | +// SPDX-License-Identifier: PMPL-1.0-or-later |
| 2 | += Codegen Environment Rules — Top-Level Bindings |
| 3 | +:toc: macro |
| 4 | +:toclevels: 2 |
| 5 | +:source-highlighter: rouge |
| 6 | + |
| 7 | +This spec clarifies how top-level declarations — `fn`, `const`, `type`, `effect`, `trait`, `impl` — are threaded through the codegen environment, with particular attention to the two declarations that emit runtime artefacts: `fn` and `const`. |
| 8 | + |
| 9 | +This is the doc-companion to https://github.com/hyperpolymath/affinescript/issues/89[#89]; the implementation reference for the WASM target is the `gen_decl` cases in `lib/codegen.ml`. The intra-module `const`-referenced-by-`fn` failure mode is tracked in https://github.com/hyperpolymath/affinescript/issues/73[#73]. |
| 10 | + |
| 11 | +toc::[] |
| 12 | + |
| 13 | +== Overview |
| 14 | + |
| 15 | +The codegen environment is a `ctx` record threaded through `gen_decl` for each top-level declaration in source order. The two fields that hold name → index bindings are: |
| 16 | + |
| 17 | +[cols="1,3", options="header"] |
| 18 | +|=== |
| 19 | +| Field | Purpose |
| 20 | +| `func_indices` | Maps both function names AND constant names to a signed integer. *Positive* indices point into `funcs` (a function); *negative* indices encode `-(global_idx + 1)` to point into `globals` (a constant). |
| 21 | +| `globals` | The WASM globals table — one entry per `TopConst`, holding type + mutability + initialiser expression. |
| 22 | +|=== |
| 23 | + |
| 24 | +The signed-int sentinel trick is **internal**: every `ExprVar` lookup in fn bodies must consult `func_indices` and dispatch on the sign to emit either a `call` or a `global.get`. |
| 25 | + |
| 26 | +== TopFn (top-level function) |
| 27 | + |
| 28 | +Mechanism in `lib/codegen.ml`: |
| 29 | + |
| 30 | +. The function body is generated against a fresh context derived from `ctx` (`gen_fn_body`), producing a list of WASM instructions and any lambda-funcs created during generation. |
| 31 | +. A new entry is appended to `ctx.funcs` with a fresh index `func_idx = List.length ctx.funcs`. |
| 32 | +. `func_indices` gains `(fd.fd_name.name, func_idx)`. |
| 33 | +. If `Public` or matches a game-hook export name (`init`, `update`, `draw`, ...), an `ExportFunc` export is added. |
| 34 | + |
| 35 | +ExprVar lookup against a TopFn: `List.assoc name func_indices` returns a non-negative `func_idx`; the call site emits `Call func_idx`. |
| 36 | + |
| 37 | +== TopConst (top-level constant) |
| 38 | + |
| 39 | +Mechanism in `lib/codegen.ml` (see the `| TopConst tc ->` case in `gen_decl`): |
| 40 | + |
| 41 | +. The initialiser expression is compiled against the current ctx via `gen_expr`. The result must be a constant expression — a single `I32Const` (or analogue). Non-constant initialisers are not yet supported and will fail at WASM validation. |
| 42 | +. A new entry is appended to `ctx.globals`: |
| 43 | ++ |
| 44 | +[source] |
| 45 | +---- |
| 46 | +{ g_type = I32; g_mutable = false; g_init = init_code } |
| 47 | +---- |
| 48 | +. The const's name is registered in `func_indices` with a *negative* index: `(tc.tc_name.name, -(global_idx + 1))`. This sentinel encoding lets ExprVar lookup dispatch on the sign without a separate `const_indices` table. |
| 49 | + |
| 50 | +ExprVar lookup against a TopConst: `List.assoc name func_indices` returns a negative index `i`; the call site decodes `global_idx = -i - 1` and emits `GlobalGet global_idx`. |
| 51 | + |
| 52 | +== Order matters |
| 53 | + |
| 54 | +Top-level declarations are processed in source order. A `fn` body that references a `const` defined *later* in the file currently fails at codegen with `Codegen.UnboundVariable`, because `func_indices` only contains entries for declarations already processed. This forward-reference limitation is a known constraint. |
| 55 | + |
| 56 | +Recommended source ordering: |
| 57 | + |
| 58 | +. Top-level types (`type`) |
| 59 | +. Top-level effects (`effect`) |
| 60 | +. Top-level constants (`const`) |
| 61 | +. Top-level traits / impls |
| 62 | +. Top-level functions |
| 63 | + |
| 64 | +This ordering matches how the typechecker resolves dependencies and avoids forward-reference failures in codegen. |
| 65 | + |
| 66 | +== Cross-module: imported top-level bindings |
| 67 | + |
| 68 | +Cross-module imports (`use OtherModule::{thing}`) are handled by two passes: |
| 69 | + |
| 70 | +* **WASM and WasmGC targets** — `Codegen.gen_imports` walks `prog.prog_imports`, loads each referenced module via `Module_loader`, and emits one `(import "<modpath>" "<fn>" (func ...))` entry per imported function. The imported name lands in `func_indices` with a positive index pointing into the imports section. |
| 71 | +* **All other codegens** (Rust, JS, Lua, OCaml, Julia, C, WGSL, Faust, ONNX, Bash, Nickel, ReScript, LLVM, Verilog, Gleam, CUDA, Metal, OpenCL, MLIR, Why3, Lean, SPIR-V) — `Module_loader.flatten_imports` prepends imported public `TopFn` declarations into the importer's `prog_decls` (deduplicating against local fn names). The non-WASM codegens then see the imports as if they were locally-defined and emit them inline. |
| 72 | + |
| 73 | +Imported `TopConst`s are **not** currently threaded by either path. This is a known gap; only `TopFn` flows across module boundaries today. |
| 74 | + |
| 75 | +== Non-WASM targets |
| 76 | + |
| 77 | +Each non-WASM codegen has its own `gen_decl` (or equivalent) and may or may not implement `TopConst`. The expected behaviour, target-by-target: |
| 78 | + |
| 79 | +[cols="1,2", options="header"] |
| 80 | +|=== |
| 81 | +| Target | TopConst handling |
| 82 | +| `js_codegen.ml` | Emits `const <name> = <init>;` at module top-level. Same-file fn bodies reference it directly. |
| 83 | +| `rust_codegen.ml` | Emits `pub const <name>: <ty> = <init>;` at module top-level (or `static` for non-`Copy` types). |
| 84 | +| `ocaml_codegen.ml` | Emits `let <name> = <init>` at module top-level. |
| 85 | +| Other backends | If unimplemented, `gen_decl` may silently skip `TopConst`, producing a successful build whose runtime then fails with an unbound-name error. Codegens that explicitly do not support `TopConst` should raise `CodegenError UnsupportedFeature` per the loud-fail policy. |
| 86 | +|=== |
| 87 | + |
| 88 | +When auditing or adding a backend, the env-population rule is the same: **register the name and emit a target-appropriate definition before any fn body that might reference it**. |
| 89 | + |
| 90 | +== Known issues |
| 91 | + |
| 92 | +* https://github.com/hyperpolymath/affinescript/issues/73[#73] — `Codegen.UnboundVariable` for top-level `const` bindings: typechecker accepts the reference, codegen ExprVar lookup fails. Implementation status varies by target; verify against the current `gen_decl` for the target in question. |
| 93 | + |
| 94 | +== References |
| 95 | + |
| 96 | +* `lib/codegen.ml` — WASM `gen_decl`, especially the `TopFn`, `TopConst`, and `gen_imports` cases. |
| 97 | +* `lib/module_loader.ml` — `flatten_imports` for non-WASM cross-module threading. |
| 98 | +* `bin/main.ml` — pipeline wiring (parse → resolve → typecheck → codegen with loader threading). |
0 commit comments