module scheme import encoding.utf8 struct TextCursor { mut: offset int revision u64 } @[heap] struct IndexedIteration { callback Value strings bool collect bool length int inputs []Value mut: index int cursors []TextCursor values []Value chars []rune persistent bool prefix_count int suffix Value = nil_value() } fn (mut vm VM) install_indexed_iteration_primitives() { for name in ['vector-map', 'vector-for-each', 'string-map', 'string-for-each'] { function := &Function{ code: unsafe { nil } params: 2 rest: true slot_count: 4 instructions: [ bridge_instruction(.indexed_init, int(name[0] == `s`), int(name.ends_with('-map'))), bridge_instruction(.indexed_step, 0, 0), bridge_instruction(.indexed_collect, 0, 0), bridge_instruction(.jump, 1, 0), ] } vm.bind_global(name, procedure_value(&Procedure{ mode: .closure, name: name, owner: vm.owner, function: function })) } } fn indexed_iteration(value Value) &IndexedIteration { return unsafe { &IndexedIteration(value.pointer()) } } @[direct_array_access] fn (mut m Machine) start_indexed_iteration(strings bool, collect bool) ! { callback := m.env.slots[0] if !callback.is_callable() { return failure('sequence iteration needs a procedure') } mut rest := m.env.slots[2] mut count := 1 for rest.tag == .pair { count++ rest = rest.pair_pointer().cdr } mut inputs := value_storage(count) container_store_validated(mut inputs, 0, m.env.slots[1]) rest = m.env.slots[2] for i in 1 .. count { pair := rest.pair_pointer() container_store_validated(mut inputs, i, pair.car) rest = pair.cdr } mut length := max_int mut cursors := if strings { filled_storage(count, TextCursor{}) } else { []TextCursor{} } for i, value in inputs { mut size := 0 if strings { _ := string_data(value)! text := value.string_pointer() size = text.length cursors[i].revision = text.revision } else { size = vector_data(value)!.items.len } if size < length { length = size } } state := &IndexedIteration{ callback: callback strings: strings collect: collect length: length inputs: inputs cursors: cursors values: if collect && !strings { value_storage(length) } else { []Value{} } chars: if collect && strings { []rune{len: length} } else { []rune{} } } m.env.slots[3] = payload_value(.indexed_iteration, state) for i in 0 .. 3 { m.env.slots[i] = unspecified() } } @[direct_array_access] fn (mut m Machine) step_indexed_iteration(mut vm VM) ! { mut state := indexed_iteration(m.env.slots[3]) if state.index == state.length { m.finish_call(if state.collect { state.indexed_result()! } else { unspecified() }) return } m.push(state.callback) for i, value in state.inputs { if state.strings { text := value.string_pointer() if state.cursors[i].revision != text.revision { // Mutations preserve character count but can change byte offsets, // including when a continuation resumes after an external edit. state.cursors[i].offset = text_offset(text, state.index)! state.cursors[i].revision = text.revision } ch, width := utf8.decode_rune_at(text.value, state.cursors[i].offset) state.cursors[i].offset += width m.push(character(ch)!) } else { m.push(value.vector_pointer().items[state.index]) } } state.index++ m.apply(mut vm, state.inputs.len, false)! } @[direct_array_access] fn (mut m Machine) collect_indexed_iteration() ! { result := m.pop_value() mut state := indexed_iteration(m.env.slots[3]) mut ch := rune(0) if state.collect { if state.strings { ch = result.as_character()! } else if result.tag == .multiple { return failure('vector-map callback must return one value') } } if m.env.escaped { mut scope := m.detach_bridge() state = &IndexedIteration{ callback: state.callback strings: state.strings collect: state.collect length: state.length inputs: state.inputs index: state.index cursors: state.cursors.clone() // After capture, the existing arrays become a frozen prefix. // Later results use immutable list nodes rather than cloning the // whole output array on every captured callback return. values: unsafe { state.values } chars: unsafe { state.chars } persistent: true prefix_count: if state.persistent { state.prefix_count } else { state.index - 1 } suffix: state.suffix } scope.slots[3] = payload_value(.indexed_iteration, state) } if !state.collect { return } if state.persistent { state.suffix = cons(result, state.suffix) } else if state.strings { container_store_validated(mut state.chars, state.index - 1, ch) } else { container_store_validated(mut state.values, state.index - 1, result) } } @[direct_array_access] fn (state &IndexedIteration) indexed_result() !Value { if !state.persistent { return if state.strings { encode_characters(state.chars)! } else { payload_value(.vector, &Vector{ items: state.values }) } } mut chars := if state.strings { []rune{len: state.length} } else { []rune{} } mut items := if !state.strings { value_storage(state.length) } else { []Value{} } for i in 0 .. state.prefix_count { if state.strings { container_store_validated(mut chars, i, state.chars[i]) } else { container_store_validated(mut items, i, state.values[i]) } } mut suffix := state.suffix mut index := state.length - 1 for suffix.tag == .pair { pair := suffix.pair_pointer() if state.strings { container_store_validated(mut chars, index, rune(pair.car.whole())) } else { container_store_validated(mut items, index, pair.car) } index-- suffix = pair.cdr } return if state.strings { encode_characters(chars)! } else { payload_value(.vector, &Vector{ items: items }) } } // A circular input is unbounded; another finite input must limit the traversal. fn list_iteration_limit(value Value) !int { if value.read_only && !value.datum_graph { return value.list_length() } mut count := 0 mut current := value mut slow := value for current.tag == .pair { count++ current = current.pair_pointer().cdr if count % 2 == 0 { slow = slow.pair_pointer().cdr if current.tag == .pair && current.pointer() == slow.pointer() { return -1 } } } if current.tag != .nil { return failure('expected a proper list') } return count }