module scheme // A lease is a dynamic resource identity. Continuations share its identity and // the physical port, while private acknowledgment/progress state is detached. @[heap] struct CustomPortLease { port Value resource &CustomPortResource closing bool input_cursor bool mut: close_attempted bool close_started bool both bool } fn custom_port_lease(value Value) &CustomPortLease { return unsafe { &CustomPortLease(value.pointer()) } } fn (lease &CustomPortLease) enter(context u64) ! { mut resource := lease.resource // A transferred binary alias cannot regain ownership through an escaped // closing continuation. Its lease must not clear the new facade's buffers. if !isnil(resource.duplex) { current := if lease.port.tag == .input_port { voidptr(&resource.duplex.input) } else { voidptr(&resource.duplex.output) } leased := if lease.port.tag == .input_port { voidptr(lease.port.input_pointer()) } else { voidptr(lease.port.output_pointer()) } if leased != current { return failure('port resource belongs to a transferred facade') } } if !isnil(resource.active) { return failure('port operation is already active') } if lease.port.tag == .input_port { mut port := lease.port.input_pointer() if port.busy { return failure('input port operation is already active') } if !lease.closing && (port.closed || resource.closed) { return failure('input port is closed') } port.busy = true if lease.input_cursor && voidptr(resource.cursor_lease) != voidptr(lease) { resource.cursor_lease = lease resource.cursor_epoch++ } } else { mut port := lease.port.output_pointer() if port.busy { return failure('output port operation is already active') } if !lease.closing && (port.closed || resource.closed) { return failure('output port is closed') } port.busy = true } resource.active = lease resource.active_context = context if (positioned_custom_binary(resource) || (positioned_custom_text(resource) && (lease.input_cursor || lease.closing)) || (positioned_custom_attached(resource) && (lease.closing || (lease.port.tag == .input_port && lease.input_cursor)))) && voidptr(resource.io_lease) != voidptr(lease) { resource.io_lease = lease resource.io_epoch++ } if lease.closing && !defer_custom_binary_close(lease) && !defer_custom_text_close(lease) && !defer_custom_attached_close(lease) { lease.begin_close() } } // Reconciliation can fail before a half-close changes the public open state. // All other closes still publish their closed facets on lease entry. fn (lease &CustomPortLease) begin_close() { mut current := unsafe { &CustomPortLease(lease) } current.close_started = true mut resource := lease.resource if lease.port.tag == .input_port { mut port := lease.port.input_pointer() port.closed = true } else { mut port := lease.port.output_pointer() port.closed = true } if isnil(resource.duplex) { resource.closed = true } else { mut duplex := resource.duplex if lease.both { duplex.input.closed = true duplex.output.closed = true } resource.closed = duplex.input.closed && duplex.output.closed } } fn (lease &CustomPortLease) release(context u64) { mut resource := lease.resource if voidptr(resource.active) != voidptr(lease) || resource.active_context != context { return } if lease.port.tag == .input_port && !lease.port.input_pointer().binary { commit_custom_text_cursor(lease.port) } resource.active = unsafe { nil } resource.active_context = 0 if lease.port.tag == .input_port { mut port := lease.port.input_pointer() port.busy = false if lease.close_started { port.source = &closed_port port.buffer = []u8{} port.location = unsafe { nil } resource.read_buffer = unspecified() resource.text_view = unspecified() resource.replay_active = false resource.replay_tail = []u8{} resource.cursor_lease = unsafe { nil } clear_custom_text_coordinates(resource) resource.release_transcoded_input_storage() } } else { mut port := lease.port.output_pointer() port.busy = false if lease.close_started { port.sink = &closed_port } } if lease.close_started && lease.both { mut duplex := resource.duplex duplex.input.busy = false duplex.input.source = &closed_port duplex.input.buffer = []u8{} duplex.input.location = unsafe { nil } duplex.output.busy = false duplex.output.sink = &closed_port resource.read_buffer = unspecified() resource.text_view = unspecified() resource.replay_active = false resource.replay_tail = []u8{} resource.cursor_lease = unsafe { nil } clear_custom_text_coordinates(resource) resource.release_transcoded_input_storage() } } fn (mut m Machine) cleanup_custom_port_leases() { mut cursor := WindRef{m.wind} for !isnil(cursor.value) { frame := cursor.value if frame.after.tag == .port_operation { custom_port_lease(frame.after).release(m.context) } cursor = WindRef{frame.parent} } } @[heap] struct CustomPortOperation { operation PortIoOperation target Value resource &CustomPortResource source Value end int position Value lease &CustomPortLease mut: frame &CustomDatumFrame = unsafe { nil } encoded &CustomEncodedState = unsafe { nil } characters int line_done bool line_cr bool snapshot string revision u64 first_byte int start int offset int bytes []u8 chunks &CustomInputChunk = unsafe { nil } pending Value request_start int request_count int wind &WindFrame = unsafe { nil } position_cursor voidptr } fn custom_port_operation(value Value) &CustomPortOperation { return unsafe { &CustomPortOperation(value.pointer()) } } fn (mut m Machine) enter_custom_port_operation() ! { mut state := custom_port_operation(m.env.slots[0]) state.lease.enter(m.context)! marker := payload_value(.port_operation, state.lease) state.wind = &WindFrame{ parent: m.wind depth: if isnil(m.wind) { 1 } else { m.wind.depth + 1 } before: marker after: marker } m.wind = state.wind } fn (mut m Machine) finish_custom_port_operation(value Value) { state := custom_port_operation(m.env.slots[0]) state.lease.release(m.context) m.wind = state.wind.parent m.finish_call(value) } fn (mut m Machine) step_custom_port_operation(mut vm VM) ! { if m.step_custom_binary_duplex(mut vm)! { return } state := custom_port_operation(m.env.slots[0]) if positioned_custom_attached(state.resource) { if m.step_custom_attached_position(mut vm)! { return } } // Keep the resumable text-position driver cold for ordinary custom I/O. // Clang leaves this larger helper out of line in the production binary. if positioned_custom_text(state.resource) { if m.step_custom_text_duplex(mut vm)! { return } } if state.target.tag == .input_port && state.operation in [.close_input, .close_any] && state.resource.closed && !isnil(state.resource.output_adapter) { // A failed TX half-close can leave an encoded suffix. Final RX close // drains it on this same machine before claiming the shared closer. m.step_custom_encoded_output(mut vm)! return } if custom_port_operation(m.env.slots[0]).target.tag == .input_port { if !custom_port_operation(m.env.slots[0]).target.input_pointer().binary { m.step_custom_text_input(mut vm)! return } m.step_custom_input_operation(mut vm)! return } if !state.target.output_pointer().binary { m.step_custom_text_output(mut vm)! return } match state.operation { .write_u8, .put_u8, .write_bytes, .put_bytes { if state.offset == state.end { m.finish_custom_port_operation(unspecified()) return } begin_custom_binary_callback(state, true) m.push(state.resource.write) m.push(state.source) m.push(integer(state.offset)) m.push(integer(state.end - state.offset)) m.apply(mut vm, 3, false)! } .close_output, .close_any, .close_input { if !claim_custom_combined_close(state.lease) { m.finish_custom_port_operation(unspecified()) return } m.push(state.resource.close) m.apply(mut vm, 0, false)! } .get_position { begin_custom_binary_callback(state, false) m.push(state.resource.get_position) m.apply(mut vm, 0, false)! } .flush_output { m.finish_custom_port_operation(unspecified()) } .set_position { begin_custom_binary_callback(state, true) m.push(state.resource.set_position) m.push(state.position) m.apply(mut vm, 1, false)! } else { return failure('invalid output port operation') } } } fn (mut m Machine) collect_custom_port_operation() ! { result := m.pop_value() initial_state := custom_port_operation(m.env.slots[0]) if positioned_custom_attached(initial_state.resource) { if m.collect_custom_attached_position(result)! { return } } if m.collect_custom_binary_duplex(result)! { return } if m.collect_custom_text_duplex(result)! { return } input_state := custom_port_operation(m.env.slots[0]) if input_state.target.tag == .input_port && !isnil(input_state.encoded) { m.collect_custom_encoded_output(result)! return } if custom_port_operation(m.env.slots[0]).target.tag == .input_port { if !custom_port_operation(m.env.slots[0]).target.input_pointer().binary { m.collect_custom_text_input(result)! return } m.collect_custom_input_operation(result)! return } mut state := custom_port_operation(m.env.slots[0]) if !state.target.output_pointer().binary { m.collect_custom_text_output(result)! return } match state.operation { .write_u8, .put_u8, .write_bytes, .put_bytes { count := custom_port_single_result(result)!.as_integer()! if count < 0 || count > state.end - state.offset { return failure('custom writer returned an invalid count') } if m.env.escaped { state = m.detach_custom_port_state() } // Zero is permitted; retry on the same machine, so instruction and // cancellation budgets still bound a callback that makes no progress. state.offset += int(count) } .get_position { value := custom_port_single_result(result)! check_custom_binary_position(value)! m.finish_custom_port_operation(value) } else { m.finish_custom_port_operation(unspecified()) } } } // Explicit V entry is a host boundary. Scheme primitives take the hybrid branch // in Machine.apply, preserving their existing Scheme continuation instead. fn (mut vm VM) custom_output_host_operation(operation PortIoOperation, target Value, source Value, start int, end int, position Value) !Value { if target.tag == .input_output_port { return vm.custom_output_host_operation(operation, custom_combined_facet(operation, target), source, start, end, position) } resource := custom_output_resource(target) if !isnil(resource.output_adapter) && operation in [.get_position, .set_position] { return failure('transcoded output port does not support positions') } if operation in [.write_u8, .put_u8, .write_bytes, .put_bytes] && start == end { return unspecified() } if operation == .get_position && !resource.get_position.is_callable() { return failure('output port does not support positions') } if operation == .set_position { if target.output_pointer().binary { check_custom_binary_position(position)! } else { checked_custom_text_position(target, position)! } if !resource.set_position.is_callable() { return failure('output port does not support setting positions') } } state := &CustomPortOperation{ operation: operation target: target resource: resource source: source offset: start end: end position: position lease: &CustomPortLease{ port: target resource: resource input_cursor: operation !in [.get_position, .flush_output, .close_any, .close_output] closing: operation in [ .close_output, .close_any, ] } } return vm.call(procedure_value(&Procedure{ mode: .closure, name: 'custom port operation', owner: vm.owner, function: &custom_port_io_bridges[int(operation)] }), [payload_value(.port_operation, state)]) } fn (mut m Machine) tail_custom_port_close(mut vm VM, target Value) ! { state := vm.prepare_custom_port_operation(.close_any, target, [target])! m.push(procedure_value(&Procedure{ mode: .closure, name: 'close-port', owner: vm.owner, function: &custom_port_io_bridges[int(PortIoOperation.close_any)] })) m.push(payload_value(.port_operation, state)) m.apply(mut vm, 1, true)! } fn custom_port_single_result(value Value) !Value { if value.tag == .multiple { return failure('custom port callback must return one value') } return value } // Enter this private one-argument bridge directly. Its public procedure is // already owned/checked by apply; allocating a replacement closure is needless. // Ordinary Scheme closure application keeps its existing hot path. fn (mut m Machine) call_custom_port_bridge(mut vm VM, function &Function, state &CustomPortOperation, call_base int, tail bool) ! { if !tail && vm.options.max_frames > 0 && m.frames.len >= vm.options.max_frames { return failure('continuation frame limit exceeded') } if !tail { m.reserve_frame_slot(vm)! } m.enter_bridge(vm, tail)! mut scope := m.checked_activation_for(vm, function, unsafe { nil }, tail)! scope.slots[0] = payload_value(.port_operation, state) if !tail { m.frames << CallFrame{ function: m.function, env: m.env, ip: m.ip, base: m.base } m.base = call_base } m.truncate(if tail { m.base } else { call_base }) m.function = function m.env = scope m.ip = 0 }