Fix vm-global-get in native OCaml VM + transpiled VM ref

The previous commit fixed lib/vm.sx (SX spec) but the server uses
sx_vm.ml (hand-maintained native OCaml) and sx_vm_ref.ml (transpiled).
Both had the same globals-first lookup bug. Now all three implementations
check closure env before vm.globals, matching vm-global-set.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-06 12:14:30 +00:00
parent 3a9d113537
commit 577d09f443
3 changed files with 34 additions and 33 deletions

View File

@@ -410,21 +410,23 @@ and run vm =
| 20 (* OP_GLOBAL_GET *) ->
let idx = read_u16 frame in
let name = match consts.(idx) with String s -> s | _ -> "" in
let v = try Hashtbl.find vm.globals name with Not_found ->
(* Walk the closure env chain for inner functions *)
let id = Sx_types.intern name in
let rec env_lookup e =
try Hashtbl.find e.bindings id
with Not_found ->
match e.parent with Some p -> env_lookup p | None ->
try Sx_primitives.get_primitive name
with _ -> raise (Eval_error ("VM undefined: " ^ name))
in
match frame.closure.vm_closure_env with
| Some env -> env_lookup env
(* Check closure env first (matches OP_GLOBAL_SET priority) *)
let id = Sx_types.intern name in
let found_in_env = match frame.closure.vm_closure_env with
| Some env ->
let rec env_lookup e =
try Some (Hashtbl.find e.bindings id)
with Not_found ->
match e.parent with Some p -> env_lookup p | None -> None
in env_lookup env
| None -> None
in
let v = match found_in_env with
| Some v -> v
| None ->
try Sx_primitives.get_primitive name
with _ -> raise (Eval_error ("VM undefined: " ^ name))
try Hashtbl.find vm.globals name with Not_found ->
try Sx_primitives.get_primitive name
with _ -> raise (Eval_error ("VM undefined: " ^ name))
in
push vm v
| 21 (* OP_GLOBAL_SET *) ->