vile / scheme / indexed_iteration.v
220 lines · 210 sloc · 6.28 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import encoding.utf8
4
5struct TextCursor {
6mut:
7 offset int
8 revision u64
9}
10
11@[heap]
12struct IndexedIteration {
13 callback Value
14 strings bool
15 collect bool
16 length int
17 inputs []Value
18mut:
19 index int
20 cursors []TextCursor
21 values []Value
22 chars []rune
23 persistent bool
24 prefix_count int
25 suffix Value = nil_value()
26}
27
28fn (mut vm VM) install_indexed_iteration_primitives() {
29 for name in ['vector-map', 'vector-for-each', 'string-map', 'string-for-each'] {
30 function := &Function{
31 code: unsafe { nil }
32 params: 2
33 rest: true
34 slot_count: 4
35 instructions: [
36 bridge_instruction(.indexed_init, int(name[0] == `s`), int(name.ends_with('-map'))),
37 bridge_instruction(.indexed_step, 0, 0),
38 bridge_instruction(.indexed_collect, 0, 0),
39 bridge_instruction(.jump, 1, 0),
40 ]
41 }
42 vm.bind_global(name, procedure_value(&Procedure{ mode: .closure, name: name, owner: vm.owner, function: function }))
43 }
44}
45
46fn indexed_iteration(value Value) &IndexedIteration {
47 return unsafe { &IndexedIteration(value.pointer()) }
48}
49
50@[direct_array_access]
51fn (mut m Machine) start_indexed_iteration(strings bool, collect bool) ! {
52 callback := m.env.slots[0]
53 if !callback.is_callable() { return failure('sequence iteration needs a procedure') }
54 mut rest := m.env.slots[2]
55 mut count := 1
56 for rest.tag == .pair {
57 count++
58 rest = rest.pair_pointer().cdr
59 }
60 mut inputs := value_storage(count)
61 container_store_validated(mut inputs, 0, m.env.slots[1])
62 rest = m.env.slots[2]
63 for i in 1 .. count {
64 pair := rest.pair_pointer()
65 container_store_validated(mut inputs, i, pair.car)
66 rest = pair.cdr
67 }
68 mut length := max_int
69 mut cursors := if strings { filled_storage(count, TextCursor{}) } else { []TextCursor{} }
70 for i, value in inputs {
71 mut size := 0
72 if strings {
73 _ := string_data(value)!
74 text := value.string_pointer()
75 size = text.length
76 cursors[i].revision = text.revision
77 } else {
78 size = vector_data(value)!.items.len
79 }
80 if size < length { length = size }
81 }
82 state := &IndexedIteration{
83 callback: callback
84 strings: strings
85 collect: collect
86 length: length
87 inputs: inputs
88 cursors: cursors
89 values: if collect && !strings { value_storage(length) } else { []Value{} }
90 chars: if collect && strings { []rune{len: length} } else { []rune{} }
91 }
92 m.env.slots[3] = payload_value(.indexed_iteration, state)
93 for i in 0 .. 3 { m.env.slots[i] = unspecified() }
94}
95
96@[direct_array_access]
97fn (mut m Machine) step_indexed_iteration(mut vm VM) ! {
98 mut state := indexed_iteration(m.env.slots[3])
99 if state.index == state.length {
100 m.finish_call(if state.collect { state.indexed_result()! } else { unspecified() })
101 return
102 }
103 m.push(state.callback)
104 for i, value in state.inputs {
105 if state.strings {
106 text := value.string_pointer()
107 if state.cursors[i].revision != text.revision {
108 // Mutations preserve character count but can change byte offsets,
109 // including when a continuation resumes after an external edit.
110 state.cursors[i].offset = text_offset(text, state.index)!
111 state.cursors[i].revision = text.revision
112 }
113 ch, width := utf8.decode_rune_at(text.value, state.cursors[i].offset)
114 state.cursors[i].offset += width
115 m.push(character(ch)!)
116 } else {
117 m.push(value.vector_pointer().items[state.index])
118 }
119 }
120 state.index++
121 m.apply(mut vm, state.inputs.len, false)!
122}
123
124@[direct_array_access]
125fn (mut m Machine) collect_indexed_iteration() ! {
126 result := m.pop_value()
127 mut state := indexed_iteration(m.env.slots[3])
128 mut ch := rune(0)
129 if state.collect {
130 if state.strings {
131 ch = result.as_character()!
132 } else if result.tag == .multiple {
133 return failure('vector-map callback must return one value')
134 }
135 }
136 if m.env.escaped {
137 mut scope := m.detach_bridge()
138 state = &IndexedIteration{
139 callback: state.callback
140 strings: state.strings
141 collect: state.collect
142 length: state.length
143 inputs: state.inputs
144 index: state.index
145 cursors: state.cursors.clone()
146 // After capture, the existing arrays become a frozen prefix.
147 // Later results use immutable list nodes rather than cloning the
148 // whole output array on every captured callback return.
149 values: unsafe { state.values }
150 chars: unsafe { state.chars }
151 persistent: true
152 prefix_count: if state.persistent { state.prefix_count } else { state.index - 1 }
153 suffix: state.suffix
154 }
155 scope.slots[3] = payload_value(.indexed_iteration, state)
156 }
157 if !state.collect { return }
158 if state.persistent {
159 state.suffix = cons(result, state.suffix)
160 } else if state.strings {
161 container_store_validated(mut state.chars, state.index - 1, ch)
162 } else {
163 container_store_validated(mut state.values, state.index - 1, result)
164 }
165}
166
167@[direct_array_access]
168fn (state &IndexedIteration) indexed_result() !Value {
169 if !state.persistent {
170 return if state.strings {
171 encode_characters(state.chars)!
172 } else {
173 payload_value(.vector, &Vector{ items: state.values })
174 }
175 }
176 mut chars := if state.strings { []rune{len: state.length} } else { []rune{} }
177 mut items := if !state.strings { value_storage(state.length) } else { []Value{} }
178 for i in 0 .. state.prefix_count {
179 if state.strings {
180 container_store_validated(mut chars, i, state.chars[i])
181 } else {
182 container_store_validated(mut items, i, state.values[i])
183 }
184 }
185 mut suffix := state.suffix
186 mut index := state.length - 1
187 for suffix.tag == .pair {
188 pair := suffix.pair_pointer()
189 if state.strings {
190 container_store_validated(mut chars, index, rune(pair.car.whole()))
191 } else {
192 container_store_validated(mut items, index, pair.car)
193 }
194 index--
195 suffix = pair.cdr
196 }
197 return if state.strings {
198 encode_characters(chars)!
199 } else {
200 payload_value(.vector, &Vector{ items: items })
201 }
202}
203
204// A circular input is unbounded; another finite input must limit the traversal.
205fn list_iteration_limit(value Value) !int {
206 if value.read_only && !value.datum_graph { return value.list_length() }
207 mut count := 0
208 mut current := value
209 mut slow := value
210 for current.tag == .pair {
211 count++
212 current = current.pair_pointer().cdr
213 if count % 2 == 0 {
214 slow = slow.pair_pointer().cdr
215 if current.tag == .pair && current.pointer() == slow.pointer() { return -1 }
216 }
217 }
218 if current.tag != .nil { return failure('expected a proper list') }
219 return count
220}
221