module scheme enum SortKind as u8 { list vector in_place } @[heap] struct SortState { callback Value kind SortKind target Value mut: input []Value output []Value width int = 1 left int middle int end int i int j int written int persistent bool prefix_count int suffix Value = nil_value() } fn sort_state(value Value) &SortState { return unsafe { &SortState(value.pointer()) } } fn (mut vm VM) install_sort_primitives() { for i, name in ['list-sort', 'vector-sort', 'vector-sort!'] { function := &Function{ code: unsafe { nil } params: 2 slot_count: 3 instructions: [bridge_instruction(.sort_init, i, 0), bridge_instruction(.sort_step, 0, 0), bridge_instruction(.sort_collect, 0, 0), bridge_instruction(.jump, 1, 0)] } vm.bind_global(name, procedure_value(&Procedure{ owner: vm.owner, mode: .closure, name: name, function: function })) } } @[direct_array_access] fn (mut m Machine) start_sort(kind SortKind) ! { callback := m.env.slots[0] if !callback.is_callable() { return failure('sort comparator must be a procedure') } target := m.env.slots[1] if kind == .in_place { target.require_mutable(.vector)! } if kind == .list { if target.tag == .nil || (target.tag == .pair && target.pair_pointer().cdr.tag == .nil) { m.finish_call(target) return } } else { data := vector_data(target)! if data.items.len < 2 { m.finish_call(if kind == .in_place { unspecified() } else { payload_value(.vector, &Vector{ items: data.items.clone() }) }) return } } items := if kind == .list { target.list_items()! } else { target.vector_items()! } state := &SortState{ callback: callback kind: kind target: if kind == .in_place { target } else { unspecified() } input: items output: value_storage(items.len) } m.env.slots[2] = payload_value(.sorting, state) m.env.slots[0] = unspecified() m.env.slots[1] = unspecified() } // Only the output prefix changes during a merge pass. After capture it becomes // immutable; later writes use persistent list nodes until pass materialization. // No full sort-array clone is needed on each captured comparator return. @[direct_array_access] fn (mut state SortState) append_sorted(value Value) { if state.persistent { state.suffix = cons(value, state.suffix) } else { container_store_validated(mut state.output, state.written, value) } state.written++ } @[direct_array_access] fn (state &SortState) materialize_sorted_pass() []Value { mut output := value_storage(state.input.len) for i in 0 .. state.prefix_count { container_store_validated(mut output, i, state.output[i]) } mut tail := state.suffix mut index := output.len - 1 for tail.tag == .pair { pair := tail.pair_pointer() container_store_validated(mut output, index, pair.car) index-- tail = pair.cdr } return output } @[direct_array_access] fn (mut m Machine) step_sort(mut vm VM) ! { mut state := sort_state(m.env.slots[2]) length := state.input.len if length < 2 { m.finish_sort(state) return } for { if state.end == 0 { state.middle = int_min(state.left + state.width, length) state.end = int_min(state.middle + state.width, length) state.i = state.left state.j = state.middle } if state.i < state.middle && state.j < state.end { // Strictly-smaller right element wins; ties retain the left element. m.push(state.callback) m.push(state.input[state.j]) m.push(state.input[state.i]) m.apply(mut vm, 2, false)! return } for state.i < state.middle { state.append_sorted(state.input[state.i]) state.i++ } for state.j < state.end { state.append_sorted(state.input[state.j]) state.j++ } state.left = state.end state.end = 0 if state.left < length { continue } if state.persistent { state.input = state.materialize_sorted_pass() state.output = []Value{} state.prefix_count = 0 state.suffix = nil_value() } else { previous := state.input state.input = state.output state.output = previous } if state.width >= (length + 1) / 2 { m.finish_sort(state) return } state.width *= 2 state.left = 0 state.written = 0 } } @[direct_array_access] fn (mut m Machine) collect_sort() ! { result := m.pop_value() if result.tag == .multiple { return failure('sort comparator must return one value') } mut state := sort_state(m.env.slots[2]) if m.env.escaped { mut scope := m.detach_bridge() state = &SortState{ ...state persistent: true prefix_count: if state.persistent { state.prefix_count } else { state.written } } scope.slots[2] = payload_value(.sorting, state) } if result.is_true() { state.append_sorted(state.input[state.j]) state.j++ } else { state.append_sorted(state.input[state.i]) state.i++ } } @[direct_array_access] fn (mut m Machine) finish_sort(state &SortState) { match state.kind { .list { m.finish_call(list(state.input)) } .vector { m.finish_call(payload_value(.vector, &Vector{ items: state.input })) } .in_place { mut target := state.target.vector_pointer() for i, value in state.input { container_store_validated(mut target.items, i, value) } m.finish_call(unspecified()) } } }