module scheme import strings // OutputFlusher is an optional host Writer capability. A Writer without it has // no Vile-owned pending output, so flush-output-port is a successful no-op. // Like write, flush must not reenter an operation on the same port. pub interface OutputFlusher { mut: flush() ! } @[heap] struct MemoryPortOutput { mut: bytes []u8 // Negative means append: ordinary writes need no separate cursor update. position int = -1 binary bool } fn (mut sink MemoryPortOutput) write(bytes []u8) !int { if sink.position >= 0 { return sink.write_positioned(bytes) } if bytes.len > max_int - 1 - sink.bytes.len { return failure('memory port exceeds supported length') } sink.bytes << bytes return bytes.len } // open_input_string snapshots the host text. Its one owned byte array also // serves as the read buffer; no Reader callback or second input copy is needed. pub fn (mut vm VM) open_input_string(text string) !Value { return vm.memory_input_port(text.bytes(), false) } fn (mut vm VM) memory_input_port(bytes []u8, binary bool) !Value { vm.ready()! mut port := &InputPort{ owner: vm.owner, read_size: 4096, source: &closed_port, buffer: bytes, ended: true, binary: binary, memory_input: true } unsafe { port.buffer.flags.set(.noslices) } return payload_value(.input_port, port) } pub fn (mut vm VM) open_output_string() !Value { return vm.memory_output_port(false) } fn (mut vm VM) memory_output_port(binary bool) !Value { vm.ready()! mut sink := &MemoryPortOutput{ binary: binary } unsafe { sink.bytes.flags.set(.noslices) } return payload_value(.output_port, &OutputPort{ owner: vm.owner, sink: sink, memory_output: sink, binary: binary }) } // get_output_string returns an independent, mutable snapshot, including after // close. Later writes and Scheme mutations cannot change an earlier snapshot. pub fn (mut vm VM) get_output_string(value Value) !Value { vm.ready()! port := vm.output_owner(value)! if isnil(port.memory_output) || port.binary { return failure('expected a string output port') } if port.busy { return failure('output port operation is already active') } text := port.memory_output.bytes.bytestr() return owned_string(text, unicode_length(text)) } pub fn (mut vm VM) read_line(value Value) !Value { vm.ready()! return vm.read_port_text(value, -1) } // append_source_line appends through the next LF, retaining its original bytes. // The Scheme reader validates the accumulated source. Return false only at EOF // with no bytes appended. REPLs can share this cursor with read and peek-char. pub fn (mut vm VM) append_source_line(value Value, mut source strings.Builder) !bool { vm.ready()! mut port := vm.checked_text_input(value)! initial := source.len if !isnil(custom_input_resource(value)) { for { ch := vm.read_char(value)! if ch.tag == .eof { return source.len != initial } source.write_rune(rune(ch.whole())) if ch.whole() == 10 { return true } } return false } port.busy = true defer { port.busy = false port.release_large_frame() } for port.ensure_bytes(1)! { end := input_quote_end(port.buffer, port.position, 10) found := end < port.buffer.len next := if found { end + 1 } else { end } unsafe { source.write_ptr(&u8(port.buffer.data) + port.position, next - port.position) } port.position = next if found { return true } } return source.len != initial } pub fn (mut vm VM) read_string(value Value, count int) !Value { vm.ready()! if count < 0 { return failure('read-string count must be nonnegative') } return vm.read_port_text(value, count) } // Copy each decoded span directly into the result's owned buffer. Input can // compact/refill between spans, and Buffer transfers the completed allocation. // A count of -1 reads a line; a nonnegative count reads that many characters. @[direct_array_access] fn (mut vm VM) read_port_text(value Value, count int) !Value { mut port := vm.checked_text_input(value)! if !isnil(custom_input_resource(value)) { operation := if count == -1 { PortIoOperation.read_line } else if count == -2 { PortIoOperation.get_line } else { PortIoOperation.get_text } return vm.custom_text_input_host_operation(operation, value, unspecified(), 0, if count < 0 { max_int } else { count }, unspecified()) } port.busy = true defer { port.busy = false port.release_large_frame() } mut out := strings.new_buffer(0) mut length := 0 for count < 0 || length < count { ch, width := port.peek_character()! if width == 0 { if length == 0 { return eof_value() } break } if count < 0 && (ch == `\n` || (count == -1 && ch in [`\r`, rune(0x85), rune(0x2028)])) { port.position += width // CRLF and CRNEL are one ending. Inspect only their exact bytes; // malformed input belonging to the next line stays unread. if ch == `\r` && port.ensure_bytes(1)! { if port.buffer[port.position] == `\n` { port.position++ } else if port.buffer[port.position] == 0xc2 && port.ensure_bytes(2)! && port.buffer[port.position + 1] == 0x85 { port.position += 2 } } break } if width > max_int - 1 - out.len() { return failure('string length exceeds supported range') } unsafe { out.write_ptr(&u8(port.buffer.data) + port.position, width) } port.position += width length++ } return owned_string(out.take_string(), length) } pub fn (mut vm VM) flush_output_port(value Value) ! { vm.ready()! mut port := vm.checked_output(value)! if !isnil(custom_output_resource(value)) { vm.custom_output_host_operation(.flush_output, value, unspecified(), 0, 0, unspecified())! return } port.busy = true defer { port.busy = false } if mut port.sink is OutputFlusher { mut sink := port.sink sink.flush()! } } const text_port_native_descriptors = [ NativeDescriptor{'port?', NativeFn(port_anyp)} NativeDescriptor{'textual-port?', port_textualp} NativeDescriptor{'binary-port?', port_binaryp} NativeDescriptor{'input-port-open?', port_input_openp} NativeDescriptor{'output-port-open?', port_output_openp} NativeDescriptor{'close-port', port_close} NativeDescriptor{'open-input-string', port_open_input_string} NativeDescriptor{'open-output-string', port_open_output_string} NativeDescriptor{'get-output-string', port_get_output_string} NativeDescriptor{'read-line', port_read_line} NativeDescriptor{'read-string', port_read_string} NativeDescriptor{'write-string', port_write_string} NativeDescriptor{'flush-output-port', port_flush_output} NativeDescriptor{'eof-object', port_eof_object}, ]! fn (mut vm VM) install_text_port_primitives() { for index in 0 .. text_port_native_descriptors.len { entry := &text_port_native_descriptors[index] vm.bind_global(entry.name, vm.port_native_procedure(entry)) } } fn port_anyp(mut _vm VM, args []Value) !Value { check_arity('port predicate', args.len, 1, 1)! return boolean(args[0].tag in [.input_port, .output_port, .input_output_port]) } fn port_binaryp(mut _vm VM, args []Value) !Value { check_arity('binary-port?', args.len, 1, 1)! return boolean(is_binary_port(args[0])) } fn is_binary_port(value Value) bool { return match value.tag { .input_port, .input_output_port { value.input_pointer().binary } .output_port { value.output_pointer().binary } else { false } } } fn port_textualp(mut _vm VM, args []Value) !Value { check_arity('textual-port?', args.len, 1, 1)! return boolean(args[0].tag in [.input_port, .output_port, .input_output_port] && !is_binary_port(args[0])) } fn port_input_openp(mut vm VM, args []Value) !Value { check_arity('input-port-open?', args.len, 1, 1)! if args[0].tag == .output_port { vm.output_owner(args[0])! return boolean(false) } return boolean(!vm.input_owner(args[0])!.closed) } fn port_output_openp(mut vm VM, args []Value) !Value { check_arity('output-port-open?', args.len, 1, 1)! if args[0].tag == .input_port { vm.input_owner(args[0])! return boolean(false) } return boolean(!vm.output_owner(args[0])!.closed) } fn port_close(mut vm VM, args []Value) !Value { check_arity('close-port', args.len, 1, 1)! vm.close_port(args[0])! return unspecified() } fn port_open_input_string(mut vm VM, args []Value) !Value { check_arity('open-input-string', args.len, 1, 1)! return vm.open_input_string(string_data(args[0])!) } fn port_open_output_string(mut vm VM, args []Value) !Value { check_arity('open-output-string', args.len, 0, 0)! return vm.open_output_string() } fn port_get_output_string(mut vm VM, args []Value) !Value { check_arity('get-output-string', args.len, 1, 1)! return vm.get_output_string(args[0]) } fn port_read_line(mut vm VM, args []Value) !Value { check_arity('read-line', args.len, 0, 1)! return vm.read_port_text(if args.len == 0 { vm.current_input_value()! } else { args[0] }, -1) } fn port_read_string(mut vm VM, args []Value) !Value { check_arity('read-string', args.len, 1, 2)! count := args[0].as_integer()! if count < 0 || count > max_int { return failure('read-string count out of supported range') } return vm.read_port_text(if args.len == 1 { vm.current_input_value()! } else { args[1] }, int(count)) } fn port_write_string(mut vm VM, args []Value) !Value { check_arity('write-string', args.len, 1, 4)! text, first, last, _, _ := string_range(args, 0, 2)! target := if args.len == 1 { vm.current_output_value()! } else { args[1] } mut port := vm.checked_text_output(target)! port.write_text(text_view(text.value, first, last))! return unspecified() } fn port_flush_output(mut vm VM, args []Value) !Value { check_arity('flush-output-port', args.len, 0, 1)! vm.flush_output_port(if args.len == 0 { vm.current_output_value()! } else { args[0] })! return unspecified() } fn port_eof_object(mut _vm VM, args []Value) !Value { check_arity('eof-object', args.len, 0, 0)! return eof_value() }