module scheme import io import os // InputOptions controls read-ahead from a host Reader. A reader that waits for // its entire requested buffer should use read_size: 1 for interactive input. @[params] pub struct InputOptions { pub: read_size int = 4096 binary bool fold_case bool = true } @[params] pub struct OutputOptions { pub: binary bool } @[heap] struct InputPort { owner &Owner read_size int mut: source io.Reader file &os.File = unsafe { nil } stream &PortFileStream = unsafe { nil } file_backed bool // source classification survives closing and transcoding owns_file bool closed bool busy bool ended bool binary bool no_fold bool memory_input bool transcoder_code u8 buffer []u8 position int mark int = -1 location &InputLocation = unsafe { nil } } @[heap] struct OutputPort { owner &Owner mut: sink io.Writer file &os.File = unsafe { nil } stream &PortFileStream = unsafe { nil } file_backed bool // source classification survives closing and transcoding owns_file bool closed bool busy bool binary bool transcoder_code u8 buffer_mode PortBufferMode = .none memory_output &MemoryPortOutput = unsafe { nil } } @[heap] struct PortState { mut: bindings &PortBinding = unsafe { nil } transcoder_symbols &TranscoderSymbols = unsafe { nil } } // Keep stdio's V descriptor in an explicit heap object. An interface and the // close/flush path refer to the same descriptor throughout the port's lifetime. @[heap] struct PortFileStream { mut: file os.File file_budget &FileResourceBudget = unsafe { nil } bounded_link &BoundedFileLink = unsafe { nil } raw bool descriptor_only bool buffer_mode PortBufferMode = .block pending []u8 } fn (mut stream PortFileStream) read(mut bytes []u8) !int { if !stream.raw { return stream.file.read(mut bytes) } return file_read_bytes(stream.file.fd, mut bytes) } fn (mut stream PortFileStream) write(bytes []u8) !int { if !stream.raw { return stream.file.write(bytes) } if stream.buffer_mode == .none { return file_write_bytes(stream.file.fd, bytes) } if stream.pending.len == 0 && bytes.len >= 4096 { return file_write_bytes(stream.file.fd, bytes) } if bytes.len > 4096 - stream.pending.len { stream.flush_pending()! } if bytes.len >= 4096 { return file_write_bytes(stream.file.fd, bytes) } if stream.pending.cap == 0 { stream.pending = []u8{cap: 4096} unsafe { stream.pending.flags.set(.noslices) } } stream.pending << bytes return bytes.len } // input_port borrows a host Reader, keeping its interface object alive. Closing // this port does not close the host resource. Readers must not retain the // borrowed destination buffer, resize it, or reenter an operation on the same port. pub fn (mut vm VM) input_port(source io.Reader, options InputOptions) !Value { vm.ready()! if options.read_size <= 0 { return failure('input read size must be positive') } mut port := &InputPort{ owner: vm.owner, source: source, file_backed: source is PortFileStream || source is os.File, read_size: options.read_size, binary: options.binary, no_fold: !options.fold_case } // Buffer borrows exist only during Reader.read or completed datum decoding. // Neither can overlap growth or compaction of this privately owned storage. unsafe { port.buffer.flags.set(.noslices) } return payload_value(.input_port, port) } // output_port borrows a host Writer. Each write must consume its byte slice // before returning; short writes are retried. Closing does not close the host. pub fn (mut vm VM) output_port(sink io.Writer, options OutputOptions) !Value { vm.ready()! return payload_value(.output_port, &OutputPort{ owner: vm.owner, sink: sink, file_backed: sink is PortFileStream || sink is os.File, binary: options.binary }) } fn (mut vm VM) port_state() &PortState { if isnil(vm.ports) { vm.ports = &vm.port_storage } return vm.ports } pub fn (mut vm VM) current_input_port() !Value { vm.ready()! return vm.current_input_value() } fn (mut vm VM) current_input_value() !Value { return vm.current_port_value(0) } pub fn (mut vm VM) current_output_port() !Value { vm.ready()! return vm.current_output_value() } fn (mut vm VM) current_output_value() !Value { return vm.current_port_value(1) } pub fn (mut vm VM) set_input_port(value Value) ! { vm.ready()! vm.input_owner(value)! vm.set_port_value(0, value) } pub fn (mut vm VM) set_output_port(value Value) ! { vm.ready()! vm.output_owner(value)! vm.set_port_value(1, value) } fn (value Value) input_pointer() &InputPort { return unsafe { &InputPort(value.pointer()) } } fn (value Value) output_pointer() &OutputPort { if value.tag == .input_output_port { port := unsafe { &InputOutputPort(value.pointer()) } return &port.output } return unsafe { &OutputPort(value.pointer()) } } fn (vm &VM) input_owner(value Value) !&InputPort { if value.tag !in [.input_port, .input_output_port] { return failure('expected an input port') } port := value.input_pointer() if voidptr(port.owner) != voidptr(vm.owner) { return failure('input port belongs to another VM') } return port } fn (vm &VM) output_owner(value Value) !&OutputPort { if value.tag !in [.output_port, .input_output_port] { return failure('expected an output port') } port := value.output_pointer() if voidptr(port.owner) != voidptr(vm.owner) { return failure('output port belongs to another VM') } return port } fn (vm &VM) checked_input(value Value) !&InputPort { port := vm.input_owner(value)! check_combined_busy(value)! if port.closed { return failure('input port is closed') } if port.busy { return failure('input port operation is already active') } return port } fn (vm &VM) checked_output(value Value) !&OutputPort { port := vm.output_owner(value)! check_combined_busy(value)! if port.closed { return failure('output port is closed') } if port.busy { return failure('output port operation is already active') } return port } fn (vm &VM) checked_text_input(value Value) !&InputPort { port := vm.checked_input(value)! if port.binary { return failure('expected a textual input port') } return port } fn (vm &VM) checked_text_output(value Value) !&OutputPort { port := vm.checked_output(value)! if port.binary { return failure('expected a textual output port') } return port } pub fn (mut vm VM) close_input_port(value Value) ! { vm.ready()! mut port := vm.input_owner(value)! check_combined_busy(value)! if port.busy { return failure('input port operation is already active') } if port.closed { return } if !isnil(custom_input_resource(value)) { vm.custom_input_host_operation(.close_input, value, unspecified(), 0, 0, unspecified())! return } port.closed = true defer { port.buffer = []u8{} port.source = &closed_port } mut group := combined_transcoded_resource(value) mut file := combined_file_resource(value) if !isnil(group) { group.close_half(true)! } else if !isnil(file) { file.close_half(true)! } else if port.transcoder_code != 0 { if mut port.source is TranscodedResourceCloser { mut source := port.source source.close_original()! } } else if port.owns_file { port.stream.close()! } } pub fn (mut vm VM) close_output_port(value Value) ! { vm.ready()! mut port := vm.output_owner(value)! check_combined_busy(value)! if port.busy { return failure('output port operation is already active') } if port.closed { return } if !isnil(custom_output_resource(value)) { vm.custom_output_host_operation(.close_output, value, unspecified(), 0, 0, unspecified())! return } port.closed = true port.busy = true defer { port.busy = false port.sink = &closed_port } mut group := combined_transcoded_resource(value) mut file := combined_file_resource(value) if !isnil(group) { group.close_half(false)! } else if !isnil(file) { file.close_half(false)! } else if port.transcoder_code != 0 { if mut port.sink is TranscodedResourceCloser { mut sink := port.sink sink.close_original()! } } else if port.owns_file { port.stream.close()! } else if mut port.sink is OutputFlusher { mut sink := port.sink sink.flush()! } } fn (mut port InputPort) refill() ! { port.fill_buffer(false)! } fn (mut port InputPort) fill_buffer(nonblocking bool) !bool { if port.mark < 0 && port.position > 0 { port.checkpoint_input() remaining := port.buffer.len - port.position if remaining > 0 { unsafe { vmemmove(port.buffer.data, &u8(port.buffer.data) + port.position, remaining) } } unsafe { port.buffer.len = remaining } port.position = 0 } start := port.buffer.len if port.read_size > max_int - start { return failure('input buffer exceeds supported range') } port.buffer.ensure_cap(start + port.read_size) // Only bytes live in this private range. Publish just the actual read count, // including on EOF/error; the source callback cannot reenter this port. unsafe { port.buffer.len = start + port.read_size } mut published := start defer { unsafe { port.buffer.len = published } } mut destination := unsafe { port.buffer[start..] } count := (if nonblocking { if mut port.source is ReadyReader { mut capable := port.source capable.read_ready(mut destination) } else { return failure('host reader does not support nonblocking input') } } else { port.source.read(mut destination) }) or { if err is io.Eof || err is os.Eof { port.ended = true return true } return err } if nonblocking && count == -1 { return false } if count < 0 || count > port.read_size { return failure('reader returned an invalid byte count') } published = start + count if count == 0 { port.ended = true } return true } fn (mut port InputPort) ensure_bytes(count int) !bool { for port.buffer.len - port.position < count { if port.ended { return false } port.refill()! } return true } // Each cursor access follows ensure_bytes; a marked datum prevents relocation. @[direct_array_access] fn (mut port InputPort) peek_character() !(rune, int) { if !port.ensure_bytes(1)! { return rune(0), 0 } first := port.buffer[port.position] if first < 0x80 { return rune(first), 1 } width := if first >= 0xc2 && first <= 0xdf { 2 } else if first >= 0xe0 && first <= 0xef { 3 } else if first >= 0xf0 && first <= 0xf4 { 4 } else { return port.input_error(port.position, 'input is not valid UTF-8') } if !port.ensure_bytes(width)! { return port.input_error(port.position, 'incomplete UTF-8 character at end of input') } mut scalar := u32(first & u8((1 << (7 - width)) - 1)) for i in 1 .. width { next := port.buffer[port.position + i] if next & 0xc0 != 0x80 { return port.input_error(port.position, 'input is not valid UTF-8') } scalar = (scalar << 6) | u32(next & 0x3f) } if (width == 3 && scalar < 0x800) || (width == 4 && scalar < 0x10000) || scalar > 0x10ffff || (scalar >= 0xd800 && scalar <= 0xdfff) { return port.input_error(port.position, 'input is not valid UTF-8') } return rune(scalar), width } fn eof_value() Value { return Value{ tag: .eof } } pub fn (mut vm VM) peek_char(value Value) !Value { vm.ready()! return vm.port_character(value, false) } pub fn (mut vm VM) read_char(value Value) !Value { vm.ready()! return vm.port_character(value, true) } fn (mut vm VM) port_character(value Value, advance bool) !Value { mut port := vm.checked_text_input(value)! if !isnil(custom_input_resource(value)) { return vm.custom_text_input_host_operation(if advance { PortIoOperation.read_char } else { PortIoOperation.peek_char }, value, unspecified(), 0, 0, unspecified()) } port.busy = true defer { port.busy = false } c, width := port.peek_character()! if width == 0 { return eof_value() } if advance { port.position += width } // The decoder already validated this scalar at the stream boundary. return Value{ tag: .character, bits: ValueBits{ whole: i64(c) } } } fn (mut port OutputPort) write_text(text string) ! { port.write_bytes(unsafe { text.str.vbytes(text.len) })! } fn (mut port OutputPort) write_bytes(bytes []u8) ! { port.busy = true defer { port.busy = false } mut offset := 0 for offset < bytes.len { remaining := bytes.len - offset count := port.sink.write(unsafe { bytes[offset..] })! if count <= 0 || count > remaining { return failure('writer returned an invalid byte count') } offset += count } // Flush after the Writer has acknowledged its bytes. A flush failure must // not cause a transcoder to save an already-accepted batch for write retry. if port.buffer_mode == .line && bytes.index(u8(`\n`)) >= 0 { if mut port.sink is OutputFlusher { mut sink := port.sink sink.flush()! } } } // A closed wrapper keeps no potentially large host Reader or Writer graph alive. struct ClosedPort {} // closed_port drops a host I/O graph without allocating an interface box. const closed_port = ClosedPort{} fn (_ ClosedPort) read(mut _bytes []u8) !int { return failure('input port is closed') } fn (_ ClosedPort) write(_bytes []u8) !int { return failure('output port is closed') }