vile / scheme / sort.v
197 lines · 187 sloc · 5.15 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3enum SortKind as u8 {
4 list
5 vector
6 in_place
7}
8
9@[heap]
10struct SortState {
11 callback Value
12 kind SortKind
13 target Value
14mut:
15 input []Value
16 output []Value
17 width int = 1
18 left int
19 middle int
20 end int
21 i int
22 j int
23 written int
24 persistent bool
25 prefix_count int
26 suffix Value = nil_value()
27}
28
29fn sort_state(value Value) &SortState {
30 return unsafe { &SortState(value.pointer()) }
31}
32
33fn (mut vm VM) install_sort_primitives() {
34 for i, name in ['list-sort', 'vector-sort', 'vector-sort!'] {
35 function := &Function{
36 code: unsafe { nil }
37 params: 2
38 slot_count: 3
39 instructions: [bridge_instruction(.sort_init, i, 0), bridge_instruction(.sort_step, 0, 0),
40 bridge_instruction(.sort_collect, 0, 0), bridge_instruction(.jump, 1, 0)]
41 }
42 vm.bind_global(name, procedure_value(&Procedure{ owner: vm.owner, mode: .closure, name: name, function: function }))
43 }
44}
45
46@[direct_array_access]
47fn (mut m Machine) start_sort(kind SortKind) ! {
48 callback := m.env.slots[0]
49 if !callback.is_callable() { return failure('sort comparator must be a procedure') }
50 target := m.env.slots[1]
51 if kind == .in_place { target.require_mutable(.vector)! }
52 if kind == .list {
53 if target.tag == .nil || (target.tag == .pair && target.pair_pointer().cdr.tag == .nil) {
54 m.finish_call(target)
55 return
56 }
57 } else {
58 data := vector_data(target)!
59 if data.items.len < 2 {
60 m.finish_call(if kind == .in_place {
61 unspecified()
62 } else {
63 payload_value(.vector, &Vector{ items: data.items.clone() })
64 })
65 return
66 }
67 }
68 items := if kind == .list { target.list_items()! } else { target.vector_items()! }
69 state := &SortState{
70 callback: callback
71 kind: kind
72 target: if kind == .in_place { target } else { unspecified() }
73 input: items
74 output: value_storage(items.len)
75 }
76 m.env.slots[2] = payload_value(.sorting, state)
77 m.env.slots[0] = unspecified()
78 m.env.slots[1] = unspecified()
79}
80
81// Only the output prefix changes during a merge pass. After capture it becomes
82// immutable; later writes use persistent list nodes until pass materialization.
83// No full sort-array clone is needed on each captured comparator return.
84@[direct_array_access]
85fn (mut state SortState) append_sorted(value Value) {
86 if state.persistent {
87 state.suffix = cons(value, state.suffix)
88 } else {
89 container_store_validated(mut state.output, state.written, value)
90 }
91 state.written++
92}
93
94@[direct_array_access]
95fn (state &SortState) materialize_sorted_pass() []Value {
96 mut output := value_storage(state.input.len)
97 for i in 0 .. state.prefix_count { container_store_validated(mut output, i, state.output[i]) }
98 mut tail := state.suffix
99 mut index := output.len - 1
100 for tail.tag == .pair {
101 pair := tail.pair_pointer()
102 container_store_validated(mut output, index, pair.car)
103 index--
104 tail = pair.cdr
105 }
106 return output
107}
108
109@[direct_array_access]
110fn (mut m Machine) step_sort(mut vm VM) ! {
111 mut state := sort_state(m.env.slots[2])
112 length := state.input.len
113 if length < 2 {
114 m.finish_sort(state)
115 return
116 }
117 for {
118 if state.end == 0 {
119 state.middle = int_min(state.left + state.width, length)
120 state.end = int_min(state.middle + state.width, length)
121 state.i = state.left
122 state.j = state.middle
123 }
124 if state.i < state.middle && state.j < state.end {
125 // Strictly-smaller right element wins; ties retain the left element.
126 m.push(state.callback)
127 m.push(state.input[state.j])
128 m.push(state.input[state.i])
129 m.apply(mut vm, 2, false)!
130 return
131 }
132 for state.i < state.middle {
133 state.append_sorted(state.input[state.i])
134 state.i++
135 }
136 for state.j < state.end {
137 state.append_sorted(state.input[state.j])
138 state.j++
139 }
140 state.left = state.end
141 state.end = 0
142 if state.left < length { continue }
143 if state.persistent {
144 state.input = state.materialize_sorted_pass()
145 state.output = []Value{}
146 state.prefix_count = 0
147 state.suffix = nil_value()
148 } else {
149 previous := state.input
150 state.input = state.output
151 state.output = previous
152 }
153 if state.width >= (length + 1) / 2 {
154 m.finish_sort(state)
155 return
156 }
157 state.width *= 2
158 state.left = 0
159 state.written = 0
160 }
161}
162
163@[direct_array_access]
164fn (mut m Machine) collect_sort() ! {
165 result := m.pop_value()
166 if result.tag == .multiple { return failure('sort comparator must return one value') }
167 mut state := sort_state(m.env.slots[2])
168 if m.env.escaped {
169 mut scope := m.detach_bridge()
170 state = &SortState{
171 ...state
172 persistent: true
173 prefix_count: if state.persistent { state.prefix_count } else { state.written }
174 }
175 scope.slots[2] = payload_value(.sorting, state)
176 }
177 if result.is_true() {
178 state.append_sorted(state.input[state.j])
179 state.j++
180 } else {
181 state.append_sorted(state.input[state.i])
182 state.i++
183 }
184}
185
186@[direct_array_access]
187fn (mut m Machine) finish_sort(state &SortState) {
188 match state.kind {
189 .list { m.finish_call(list(state.input)) }
190 .vector { m.finish_call(payload_value(.vector, &Vector{ items: state.input })) }
191 .in_place {
192 mut target := state.target.vector_pointer()
193 for i, value in state.input { container_store_validated(mut target.items, i, value) }
194 m.finish_call(unspecified())
195 }
196 }
197}
198