vile / scheme / comparison_search.v
75 lines · 71 sloc · 2.29 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3fn (mut vm VM) comparison_search(association bool) Value {
4 index := int(association)
5 if vm.comparison_searches[index].tag == .unspecified {
6 function := if association { &assoc_comparison_bridge } else { &member_comparison_bridge }
7 value := procedure_value(&Procedure{
8 mode: .closure
9 owner: vm.owner
10 name: if association { 'assoc' } else { 'member' }
11 function: function
12 })
13 if v_arena_current() == vm.allocation_owner { vm.comparison_searches[index] = value }
14 return value
15 }
16 return vm.comparison_searches[index]
17}
18
19@[direct_array_access]
20fn (mut m Machine) start_comparison_search(_association bool) ! {
21 if !m.env.slots[2].is_callable() { return failure('search comparator must be a procedure') }
22 m.env.slots[3] = integer(0)
23 m.env.slots[4] = m.env.slots[1]
24}
25
26@[direct_array_access]
27fn (mut m Machine) step_comparison_search(mut vm VM, association bool) ! {
28 current := m.env.slots[1]
29 if current.tag == .nil {
30 m.finish_call(boolean(false))
31 return
32 }
33 if current.tag != .pair { return failure('expected a proper list') }
34 item := current.pair_pointer().car
35 candidate := if association {
36 first, _ := item.pair_parts()!
37 first
38 } else {
39 item
40 }
41 m.env.slots[5] = current.pair_pointer().cdr
42 m.push(m.env.slots[2])
43 m.push(m.env.slots[0])
44 m.push(candidate)
45 m.apply(mut vm, 2, false)!
46}
47
48@[direct_array_access]
49fn (mut m Machine) collect_comparison_search(association bool) ! {
50 result := m.pop_value()
51 if result.tag == .multiple { return failure('search comparator must return one value') }
52 current := m.env.slots[1]
53 if !eqv(current.pair_pointer().cdr, m.env.slots[5]) {
54 return failure('search input was modified during iteration')
55 }
56 if result.is_true() {
57 m.finish_call(if association { current.pair_pointer().car } else { current })
58 return
59 }
60 if m.env.escaped { m.detach_bridge() }
61 steps := m.env.slots[3].whole() + 1
62 next := m.env.slots[5]
63 if steps % 2 == 0 {
64 slow := m.env.slots[4]
65 if slow.tag != .pair { return failure('search input was modified during iteration') }
66 next_slow := slow.pair_pointer().cdr
67 if next.tag == .pair && next.pointer() == next_slow.pointer() {
68 return failure('expected a proper list, got a circular list')
69 }
70 m.env.slots[4] = next_slow
71 }
72 m.env.slots[1] = next
73 m.env.slots[3] = integer(steps)
74 m.env.slots[5] = unspecified()
75}
76