module scheme // Binding helpers have fresh VM locations on every call. Flatten only helpers // whose values cannot escape their creating activation; no closure or location // from this private IR is ever published to the VM or another native graph. struct NativeBindingLowering { mut: function &Function prepared map[u64]&Function loop_roots map[u64]bool active []NativeBindingLoop transformed int allow_named_loops bool } struct NativeBindingCall { constructor int = -1 producer int = -1 consumer int = -1 wind_before int = -1 wind_body int = -1 wind_after int = -1 values bool } struct NativeValuesDestination { base int arity int = -1 } // These negative tokens are private to the nonescape proof. A guard-only // global load is emitted as an inert marker only after every use is checked. const native_values_operator = -1 const native_cwv_operator = -2 const native_wind_operator = -3 const native_control_guard = -365 fn native_control_operator(p &Procedure) int { if !isnil(p.env) { return 0 } if p.mode == .values { return native_values_operator } if p.mode != .closure || isnil(p.function) { return 0 } f := p.function if !isnil(f.code) || f.rest || !isnil(f.star) || f.goops_next_slot >= 0 || f.goops_needs_next || f.capture_depth != 0 || f.children.len != 0 || f.constants.len != 0 || f.names.len != 0 || f.global_slots.len != 0 || f.failures.len != 0 || f.instructions.len != 5 { return 0 } x := f.instructions if f.params == 3 && f.slot_count == 5 && x[0].op == .wind_init && x[1].op == .wind_enter && x[2].op == .wind_leave && x[3].op == .wind_finish && x[4].op == .ret { for ins in x { if ins.a != 0 || ins.b != 0 { return 0 } } return native_wind_operator } if f.params != 2 || f.slot_count != 2 { return 0 } if x[0].op != .local || x[0].a != 0 || x[0].b != 1 || x[1].op != .local || x[1].a != 0 || x[1].b != 0 || x[2].op != .call || x[3].op != .call_values_tail || x[4].op != .ret { return 0 } for ins in x[2..] { if ins.a != 0 || ins.b != 0 { return 0 } } return native_cwv_operator } fn native_binding_operator(mut vm VM, f &Function, ins Instruction) !int { slot := native_global_slot(mut vm, f, ins)! value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) } if value.tag != .procedure { return 0 } vm.check_callable_owner(value)! return native_control_operator(value.procedure_pointer()) } fn native_binding_calls(mut vm VM, f &Function, destination NativeValuesDestination) ![]NativeBindingCall { depths := native_stack_depths(f)! mut states := [][]int{len: f.instructions.len} mut visited := []bool{len: f.instructions.len} mut calls := []NativeBindingCall{len: f.instructions.len} mut queue := [0] visited[0] = true for qi := 0; qi < queue.len; qi++ { if queue.len > 16384 { return error('binding control flow too complex') } pc := queue[qi] ins := f.instructions[pc] a := int(ins.a) mut after := states[pc].clone() match ins.op { .closure, .scope_function { after << pc + 1 } .constant, .local { after << 0 } .global, .global_reference { after << native_binding_operator(mut vm, f, ins)! } .drop { after.delete_last() } .duplicate { after << after.last() } .swap { n := after.len t := after[n - 1] after[n - 1] = after[n - 2] after[n - 2] = t } .define_local, .assign_local, .jump_false, .and_jump, .or_jump { if after.last() != 0 { return error('binding helper escapes as data') } if ins.op == .jump_false { after.delete_last() } } .implicit_call { if after.last() < 0 { return error('implicit control operator') } if after.last() > 0 { calls[pc] = NativeBindingCall{constructor: after.last() - 1} if a != 0 { if after.len != 1 { return error('binding implicit tail stack') } continue } after[after.len - 1] = 0 } } .call, .tail_call, .scope_call, .scope_tail { argc := a base := after.len - argc - 1 operator := after[base] if operator == native_wind_operator { if argc != 3 || after[base + 1] <= 0 || after[base + 2] <= 0 || after[base + 3] <= 0 { return error('wind callbacks are not private') } calls[pc] = NativeBindingCall{wind_before: after[base + 1] - 1, wind_body: after[base + 2] - 1, wind_after: after[base + 3] - 1} } else if operator == native_cwv_operator { if argc != 2 || after[base + 1] <= 0 || after[base + 2] <= 0 { return error('values callbacks are not private') } calls[pc] = NativeBindingCall{producer: after[base + 1] - 1, consumer: after[base + 2] - 1} } else { for value in after[base + 1..] { if value != 0 { return error('binding helper passed as an argument') } } if operator == native_values_operator { if ins.op != .tail_call || destination.arity != argc { return error('values escape private producer') } calls[pc] = NativeBindingCall{values: true} } else if operator > 0 { calls[pc] = NativeBindingCall{constructor: operator - 1} } } if ins.op in [.scope_call, .scope_tail] && calls[pc].constructor < 0 { return error('unknown scope helper') } if ins.op in [.tail_call, .scope_tail] { if depths[pc] != argc + 1 { return error('binding tail stack') } continue } after.trim(base + 1) after[base] = 0 } .ret { if after.len != 1 || after[0] != 0 { return error('binding helper returned') } continue } .jump {} else { return error('unsupported binding instruction ${ins.op}') } } mut nexts := []int{} match ins.op { .jump { nexts << a } .jump_false, .and_jump, .or_jump { nexts << [a, pc + 1] } else { nexts << pc + 1 } } for branch, next in nexts { mut outgoing := after.clone() if ins.op in [.and_jump, .or_jump] && branch == 1 { outgoing.delete_last() } if !visited[next] { states[next] = outgoing visited[next] = true queue << next } else { for i, value in outgoing { if value != states[next][i] { return error('ambiguous binding helper identity') } } } } } return calls } fn native_lower_bindings(mut vm VM, f &Function, allow_named_loops bool) !&Function { if f.instructions.len == 0 || f.instructions.len > 4096 { return error('binding function too large') } // Flatten a named loop within its caller. When the compiler wrapper itself // is the entry, its existing loop-body closure has the smaller native IR. if native_named_wrapper(f) { return error('prefer native loop-body entry') } mut needed := false for ins in f.instructions { if ins.op in [.closure, .scope_function] { needed = true; break } } if !needed { return f } mut lowering := NativeBindingLowering{allow_named_loops: allow_named_loops, function: &Function{ code: f.code, params: f.params, slot_count: f.slot_count }} prepared := lowering.prepare(f)! lowering.function.slot_count = prepared.slot_count _ := lowering.body(mut vm, prepared, [0], true, 0, NativeValuesDestination{})! return lowering.function } fn (mut b NativeBindingLowering) append(ins Instruction) !int { if b.function.instructions.len >= 4096 { return error('expanded binding graph too large') } pc := b.function.instructions.len b.function.instructions << ins return pc } fn (mut b NativeBindingLowering) body(mut vm VM, f &Function, frames []int, root_return bool, barrier int, destination NativeValuesDestination) ![]int { if frames.len > 64 || f.instructions.len == 0 || f.instructions.len > 4096 || f.rest || !isnil(f.star) || f.goops_next_slot >= 0 || voidptr(f.code) != voidptr(b.function.code) || f.slot_count > 64 || f.params > 8 { return error('unsupported binding helper') } calls := native_binding_calls(mut vm, f, destination)! depths := native_stack_depths(f)! constants := b.function.constants.len names := b.function.names.len b.function.constants << f.constants b.function.names << f.names for slot in f.global_slots { b.function.global_slots << if slot < -1 { slot - constants } else { slot } } // Constructors become an inert private stack marker. It is proved to be // consumed only as a call operator or dropped before entering this emitter. marker := b.function.constants.len b.function.constants << unspecified() uninit := b.function.constants.len b.function.constants << Value{tag: .uninitialized} active_count := b.active.len defer { b.active.trim(active_count) } if u64(f) in b.loop_roots { b.active << NativeBindingLoop{function: f, base: frames.last(), entry: b.function.instructions.len, barrier: barrier} b.reset_locals(f, frames.last(), uninit)! } mut mapping := []int{len: f.instructions.len, init: -1} mut jumps := []int{} mut targets := []int{} mut exits := []int{} for pc, original in f.instructions { if depths[pc] < 0 { continue } mapping[pc] = b.function.instructions.len mut ins := original match ins.op { .closure, .scope_function { ins = Instruction{...ins, op: .constant, a: i32(marker), b: 0} } .constant { ins = Instruction{...ins, a: i32(constants + ins.a)} } .global, .global_reference { guard := native_binding_operator(mut vm, f, ins)! != 0 ins = Instruction{...ins, a: i32(names + ins.a), b: if guard { native_control_guard } else { ins.b }} } .local, .define_local, .assign_local { depth := int(ins.a) if depth < frames.len { ins = Instruction{...ins, a: 0, b: i32(frames[frames.len - 1 - depth] + ins.b)} } else { ins = Instruction{...ins, a: i32(depth - frames.len + 1)} } } .jump, .jump_false, .and_jump, .or_jump { jumps << b.function.instructions.len targets << int(ins.a) } .call, .tail_call, .scope_call, .scope_tail, .implicit_call { tail := ins.op in [.tail_call, .scope_tail] || (ins.op == .implicit_call && ins.a != 0) if calls[pc].values { b.move_arguments(ins, int(ins.a), destination.base)! exits << b.append(Instruction{...ins, op: .jump, a: -1, b: 0})! continue } if calls[pc].wind_before >= 0 { // These private callbacks cannot capture, reenter or otherwise // observe the extent: unsupported effects decline the whole graph. // All speculative mutations retain the native transaction path. callbacks := [b.prepare(f.children[int(f.instructions[calls[pc].wind_before].a)])!, b.prepare(f.children[int(f.instructions[calls[pc].wind_body].a)])!, b.prepare(f.children[int(f.instructions[calls[pc].wind_after].a)])!] mut bases := []int{} for callback in callbacks { if callback.params != 0 || b.function.slot_count + callback.slot_count + 1 > 64 { return error('wind callback arity or width') } bases << b.function.slot_count b.function.slot_count += callback.slot_count } result_slot := b.function.slot_count b.function.slot_count++ for _ in 0 .. 4 { _ := b.append(Instruction{...ins, op: .drop, a: 0, b: 0})! } for i, callback in callbacks { b.reset_locals(callback, bases[i], uninit)! mut nested := frames.clone() nested << bases[i] callback_exits := b.body(mut vm, callback, nested, false, barrier + 1, if i == 1 { NativeValuesDestination{base: result_slot, arity: 1} } else { NativeValuesDestination{} })! for exit in callback_exits { b.function.instructions[exit] = Instruction{...b.function.instructions[exit], a: i32(b.function.instructions.len)} } if i != 1 { _ := b.append(Instruction{...ins, op: .drop, a: 0, b: 0})! } } _ := b.append(Instruction{...ins, op: .local, a: 0, b: i32(result_slot)})! if tail { if root_return { _ := b.append(Instruction{...ins, op: .ret, a: 0, b: 0})! } else { b.scalar_destination(ins, destination)! exits << b.append(Instruction{...ins, op: .jump, a: -1, b: 0})! } } continue } if calls[pc].producer >= 0 { producer := b.prepare(f.children[int(f.instructions[calls[pc].producer].a)])! consumer := b.prepare(f.children[int(f.instructions[calls[pc].consumer].a)])! if producer.params != 0 || consumer.params > 8 || b.function.slot_count + producer.slot_count + consumer.slot_count > 64 { return error('values callback width') } producer_base := b.function.slot_count consumer_base := producer_base + producer.slot_count b.function.slot_count += producer.slot_count + consumer.slot_count for _ in 0 .. 3 { _ := b.append(Instruction{...ins, op: .drop, a: 0, b: 0})! } b.reset_locals(producer, producer_base, uninit)! mut producer_frames := frames.clone() producer_frames << producer_base producer_exits := b.body(mut vm, producer, producer_frames, false, barrier + 1, NativeValuesDestination{base: consumer_base, arity: consumer.params})! for exit in producer_exits { b.function.instructions[exit] = Instruction{...b.function.instructions[exit], a: i32(b.function.instructions.len)} } b.reset_locals(consumer, consumer_base, uninit)! mut consumer_frames := frames.clone() consumer_frames << consumer_base consumer_exits := b.body(mut vm, consumer, consumer_frames, tail && root_return, if tail { barrier } else { barrier + 1 }, if tail { destination } else { NativeValuesDestination{} })! if tail { exits << consumer_exits } else { for exit in consumer_exits { b.function.instructions[exit] = Instruction{...b.function.instructions[exit], a: i32(b.function.instructions.len)} } } continue } if calls[pc].constructor >= 0 { constructor := f.instructions[calls[pc].constructor] child := b.prepare(f.children[int(constructor.a)])! argc := if ins.op == .implicit_call { 0 } else { int(ins.a) } if child.params != argc { return error('binding arity') } mut recursive := -1 for i, active in b.active { if voidptr(active.function) == voidptr(child) { recursive = i; break } } if recursive >= 0 { active := b.active[recursive] if !tail || barrier != active.barrier { return error('non-tail private recursion') } b.move_arguments(ins, argc, active.base)! _ := b.append(Instruction{...ins, op: .jump, a: i32(active.entry), b: 0})! continue } if b.function.slot_count + child.slot_count > 64 { return error('binding arity or width') } base := b.function.slot_count b.function.slot_count += child.slot_count // Move evaluated arguments before resetting only this activation. b.move_arguments(ins, argc, base)! if u64(child) !in b.loop_roots { b.reset_locals(child, base, uninit)! } mut nested := frames.clone() nested << base child_exits := b.body(mut vm, child, nested, tail && root_return, if tail { barrier } else { barrier + 1 }, if tail { destination } else { NativeValuesDestination{} })! if tail { exits << child_exits } else { for exit in child_exits { b.function.instructions[exit] = Instruction{...b.function.instructions[exit], a: i32(b.function.instructions.len)} } } continue } if ins.op == .implicit_call { if !root_return { ins = Instruction{...ins, a: 0} } } else if tail && !root_return { _ := b.append(Instruction{...ins, op: .call})! b.scalar_destination(ins, destination)! exits << b.append(Instruction{...ins, op: .jump, a: -1, b: 0})! continue } } .ret { if !root_return { b.scalar_destination(ins, destination)! exits << b.append(Instruction{...ins, op: .jump, a: -1, b: 0})! continue } } else {} } _ := b.append(ins)! } for i, pc in jumps { if mapping[targets[i]] < 0 { return error('unreachable binding target') } b.function.instructions[pc] = Instruction{...b.function.instructions[pc], a: i32(mapping[targets[i]])} } return exits } fn (mut b NativeBindingLowering) scalar_destination(ins Instruction, destination NativeValuesDestination) ! { if destination.arity < 0 { return } if destination.arity != 1 { return error('scalar producer arity') } _ := b.append(Instruction{...ins, op: .define_local, a: 0, b: i32(destination.base)})! _ := b.append(Instruction{...ins, op: .drop, a: 0, b: 0})! } // Called with the metadata arena active. Original bytecode remains immutable; // only lowered tables needed to re-resolve guarded bindings outlive scratch. fn native_retain_resolver(lowered &Function, original &Function) &Function { if voidptr(lowered) == voidptr(original) { return original } return &Function{ code: original.code params: original.params slot_count: lowered.slot_count instructions: lowered.instructions.clone() constants: lowered.constants.clone() names: lowered.names.clone() global_slots: lowered.global_slots.clone() } }