module scheme import lexer import reader import unicode17 // Only boundary state survives suspension. The canonical reader still validates // each completed frame once. Trivia outside datums is never accumulated. enum CustomDatumMode { atmosphere line block hash comma quoted word word_escape word_hex word_hash boolean_alias vector_head label character } struct CustomDatumContext { mut: prefix bool ignored int } @[heap] struct CustomDatumFrame { mut: mode CustomDatumMode active bool done bool comments_only bool initial_fold bool opening InputLocation hash_opening InputLocation block_opening InputLocation directive_point InputLocation stack []CustomDatumContext ignored int hash_outside bool block_depth int block_previous rune delimiter u8 escaped bool word_escapes bool directive_active bool directive []u8 alias string alias_index int probe [4]u8 probe_len int probe_point InputLocation probe_epoch u64 } // Return a bounded speculative prefix before the live callback tail. The tail // is never copied; its StringData identity and revision tracking stay intact. fn unread_custom_text_probe(value Value, bytes []u8, point InputLocation, epoch u64, positions &CustomTextProbePositions, raw_positions &CustomAttachedProbePositions) { if bytes.len == 0 { return } mut port := value.input_pointer() mut resource := custom_input_resource(value) current := port.input_location(port.position) // Unresolved lookahead belongs to private scanner progress. A continuation // may return after another operation moved or sought the shared cursor. // Such an operation's committed history must never be rewound by this probe. if resource.cursor_epoch != epoch || current.offset != point.offset + bytes.len || current.line != point.line || current.column != point.column + bytes.len || current.previous_cr { return } commit_custom_text_cursor(value) remaining := if resource.replay_active { port.buffer.len } else { 0 } mut prefix := []u8{len: bytes.len + remaining} unsafe { vmemcpy(prefix.data, bytes.data, bytes.len) if remaining > 0 { vmemcpy(&u8(prefix.data) + bytes.len, port.buffer.data, remaining) } } prepend_custom_text_coordinates(resource, positions, bytes.len, remaining) prepend_custom_attached_coordinates(resource, raw_positions, bytes.len, remaining) if !resource.replay_active { resource.replay_tail = unsafe { port.buffer } } resource.replay_active = true port.buffer = prefix port.position = 0 if isnil(port.location) { port.location = &InputLocation{} } unsafe { *port.location = point } } fn custom_text_unread(value Value) ![]u8 { port := value.input_pointer() resource := custom_input_resource(value) if !resource.replay_active { return copy_byte_range(port.buffer, port.position, port.buffer.len) } mut tail := unsafe { resource.replay_tail } if resource.text_view.tag == .string { data := resource.text_view.string_pointer() first := text_offset(data, resource.view_start)! last := text_offset(data, resource.view_count)! tail = unsafe { (data.value.str + first).vbytes(last - first) } } first_length := port.buffer.len - port.position mut bytes := []u8{len: first_length + tail.len} unsafe { if first_length > 0 { vmemcpy(bytes.data, &u8(port.buffer.data) + port.position, first_length) } if tail.len > 0 { vmemcpy(&u8(bytes.data) + first_length, tail.data, tail.len) } } return bytes } fn (mut state CustomPortOperation) datum_take(length int) { mut port := state.target.input_pointer() if state.frame.active { state.bytes << unsafe { port.buffer[port.position..port.position + length] } state.offset += length } if state.frame.directive_active { state.frame.directive << unsafe { port.buffer[port.position..port.position + length] } } port.position += length } fn (mut state CustomPortOperation) datum_begin() { mut frame := state.frame if frame.active { return } port := state.target.input_pointer() frame.active = true frame.initial_fold = !port.no_fold frame.opening = port.input_location(port.position) } fn (mut state CustomPortOperation) datum_reset() { state.bytes = []u8{} unsafe { state.bytes.flags.set(.noslices) } state.offset = 0 state.chunks = unsafe { nil } mut frame := state.frame frame.active = false frame.done = false frame.comments_only = false frame.mode = .atmosphere frame.ignored = 0 frame.stack.clear() state.clear_text_probe() } fn (mut frame CustomDatumFrame) datum_token(token InputFrameToken) ! { frame.mode = .atmosphere if token in [.open, .prefix] { if frame.stack.len >= reader.max_depth + 1 { return failure('input datum nesting limit exceeded') } frame.stack << CustomDatumContext{ prefix: token == .prefix } return } if token == .close { if frame.stack.len == 0 || frame.stack.last().prefix { frame.done = true return } frame.stack.delete_last() } for { if frame.stack.len == 0 { if frame.ignored > 0 { frame.ignored-- frame.done = frame.comments_only && frame.ignored == 0 } else { frame.done = true } return } last := frame.stack.len - 1 if frame.stack[last].ignored > 0 { frame.stack[last].ignored-- return } if !frame.stack[last].prefix { return } frame.stack.delete_last() } } fn (mut state CustomPortOperation) datum_token(token InputFrameToken) ! { state.frame.datum_token(token) or { port := state.target.input_pointer() return port.input_error(port.position, err.msg()) } } fn (state &CustomPortOperation) datum_bytes() []u8 { if isnil(state.chunks) { return unsafe { state.bytes } } mut bytes := []u8{len: state.offset} state.copy_text_bytes(mut bytes, 0) return bytes } fn custom_datum_error(err IError, bytes []u8, point InputLocation) IError { // This view only maps diagnostics; it never calls a synchronous Reader. port := InputPort{ owner: unsafe { nil }, buffer: bytes, position: bytes.len, location: &point } return port.absolute_input_error(err, 0) } fn custom_datum_operation_error(operation PortIoOperation, err IError) IError { if operation != .read_datum { return err } // Match the native read primitive's REPL-safe consumed-error conversion. // get-datum and the public V read method retain typed reader errors. if err is reader.ReadError { return EvalError{ message: 'read: ' + err.message, offset: err.offset, line: err.line, column: err.column } } if err is lexer.LexError { return EvalError{ message: 'read: ' + err.message, offset: err.offset, line: err.line, column: err.column } } return err } fn (mut state CustomPortOperation) datum_directive() ! { mut frame := state.frame bytes := unsafe { frame.directive } source := unsafe { tos(bytes.data, bytes.len) } mut port := state.target.input_pointer() mut scanner := lexer.new_scanner(source, fold_case: !port.no_fold) or { return custom_datum_error(err, bytes, frame.directive_point) } scanner.next() or { return custom_datum_error(err, bytes, frame.directive_point) } port.no_fold = !scanner.fold_case() frame.directive_active = false frame.directive = []u8{} if frame.hash_outside { state.datum_reset() } else { frame.mode = .atmosphere } } fn (mut state CustomPortOperation) datum_word_end() ! { if state.frame.directive_active { state.datum_directive()! } else { state.datum_token(.atom)! } } fn (mut state CustomPortOperation) datum_eof() ! { mut frame := state.frame if frame.mode == .block { p := frame.block_opening return lexer.LexError{ message: 'unterminated block comment', offset: p.offset, line: p.line, column: p.column, incomplete: true } } if frame.mode == .boolean_alias { unread_custom_text_probe(state.target, unsafe { (&frame.probe[0]).vbytes(frame.probe_len) }, frame.probe_point, frame.probe_epoch, state.text_probe_positions(), state.attached_probe_positions()) frame.probe_len = 0 state.clear_text_probe() state.datum_token(.atom)! return } if frame.mode == .word_hash { state.bytes << u8(`#`) state.offset++ if frame.directive_active { frame.directive << u8(`#`) } } if frame.directive_active { state.datum_directive()! return } frame.done = frame.active } // Captured callbacks detach both scanner state and the mutable suffix before // resuming. Input cursor effects stay shared, as they do for ordinary ports. @[direct_array_access] fn (mut m Machine) step_custom_datum_input(mut vm VM) ! { mut state := custom_port_operation(m.env.slots[0]) mut frame := state.frame mut port := state.target.input_pointer() for { refresh_custom_text_view(state.target)! if frame.done { bytes := state.datum_bytes() source := unsafe { tos(bytes.data, bytes.len) } if frame.comments_only { doc := reader.read_all(source, fold_case: frame.initial_fold) or { return custom_datum_error(err, bytes, frame.opening) } port.no_fold = !doc.final_fold_case() state.datum_reset() continue } mut scratch := InputFrameState{ no_fold: !frame.initial_fold } result := scratch.read_frame(source, frame.initial_fold) or { return custom_datum_error(err, bytes, frame.opening) } port.no_fold = scratch.no_fold m.finish_custom_port_operation(result) return } if port.position == port.buffer.len { if !port.ended { m.request_custom_text_input(mut vm)! return } observe_custom_attached_eof(state.target) state.datum_eof()! if frame.done || port.position < port.buffer.len { continue } m.finish_custom_port_operation(eof_value()) return } c, width := port.peek_character()! match frame.mode { .atmosphere { if (c < 128 && input_space(u8(c))) || unicode17.whitespace(c) { state.datum_take(width) } else if c == `;` { state.datum_take(width) frame.mode = .line } else { outside := !frame.active state.datum_begin() if c == `#` { frame.hash_outside = outside frame.hash_opening = port.input_location(port.position) state.datum_take(1) frame.mode = .hash } else if c in [`"`, `|`] { frame.delimiter = u8(c) frame.escaped = false state.datum_take(1) frame.mode = .quoted } else if c in [`(`, `)`] { state.datum_take(1) state.datum_token(if c == `(` { .open } else { .close })! } else if c in [`'`, `\x60`, `,`] { state.datum_take(1) if c == `,` { frame.mode = .comma } else { state.datum_token(.prefix)! } } else { frame.word_escapes = true frame.mode = .word } } } .line { state.datum_take(width) if c in [`\r`, 10, 0x85, 0x2028, 0x2029] { frame.mode = .atmosphere } } .block { state.datum_take(width) if frame.block_previous == `#` && c == `|` { frame.block_depth++ frame.block_previous = 0 } else if frame.block_previous == `|` && c == `#` { frame.block_depth-- frame.block_previous = 0 if frame.block_depth == 0 { frame.mode = .atmosphere } } else { frame.block_previous = if c in [`#`, `|`] { c } else { rune(0) } } } .hash { if c == `|` { frame.block_opening = frame.hash_opening if frame.hash_outside { state.datum_reset() } state.datum_take(1) frame.block_depth = 1 frame.block_previous = 0 frame.mode = .block } else if c == `!` { state.datum_take(1) frame.directive = [u8(`#`), `!`] frame.directive_point = frame.hash_opening frame.directive_active = true frame.word_escapes = false frame.mode = .word } else if c == `;` { state.datum_take(1) if frame.hash_outside { frame.comments_only = true } if frame.stack.len == 0 { if frame.ignored == max_int { return failure('datum comment count exceeds supported range') } frame.ignored++ } else { last := frame.stack.len - 1 if frame.stack[last].ignored == max_int { return failure('datum comment count exceeds supported range') } frame.stack[last].ignored++ } frame.mode = .atmosphere } else if c == `(` { state.datum_take(1) state.datum_token(.open)! } else if c in [`'`, `\x60`, `,`, `:`] { state.datum_take(1) if c == `,` { frame.mode = .comma } else { state.datum_token(.prefix)! } } else if c in [`u`, `U`, `v`, `V`] { frame.alias = if c in [`u`, `U`] { '8(' } else { 'u8(' } frame.alias_index = 0 state.datum_take(1) frame.mode = .vector_head } else if c in [`t`, `T`, `f`, `F`] { frame.alias = if c in [`t`, `T`] { '#true' } else { '#false' } frame.alias_index = 2 state.datum_take(1) frame.probe_len = 0 state.clear_text_probe() frame.probe_point = port.input_location(port.position) frame.probe_epoch = state.resource.cursor_epoch frame.mode = .boolean_alias } else if c >= `0` && c <= `9` { state.datum_take(1) frame.mode = .label } else if c == `\\` { state.datum_take(1) frame.mode = .character } else { frame.word_escapes = true frame.mode = .word } } .comma { if c == `@` { state.datum_take(1) } state.datum_token(.prefix)! } .quoted { start := port.position quote := input_quote_end(port.buffer, start, frame.delimiter) mut slashes := quote for slashes > start && port.buffer[slashes - 1] == u8(`\\`) { slashes-- } odd := ((quote - slashes) & 1) != 0 quoted := odd != (slashes == start && frame.escaped) state.datum_take(quote - start) if quote == port.buffer.len { frame.escaped = quoted } else { state.datum_take(1) frame.escaped = false if !quoted { state.datum_token(.atom)! } } } .word { end := input_event_end(port.buffer, port.position) if end > port.position { state.datum_take(end - port.position) continue } if (c < 128 && (input_delimiter(u8(c)) || c == `|`)) || unicode17.whitespace(c) { state.datum_word_end()! } else if c == `#` { frame.probe_point = port.input_location(port.position) frame.probe_epoch = state.resource.cursor_epoch state.remember_custom_text_probe(0)! port.position++ frame.mode = .word_hash } else if frame.word_escapes && c == `\\` { state.datum_take(1) frame.mode = .word_escape } else { state.datum_take(width) } } .word_hash { if c in [`|`, `;`, `!`] { frame.probe[0] = u8(`#`) unread_custom_text_probe(state.target, unsafe { (&frame.probe[0]).vbytes(1) }, frame.probe_point, frame.probe_epoch, state.text_probe_positions(), state.attached_probe_positions()) state.clear_text_probe() state.datum_word_end()! } else { state.clear_text_probe() state.bytes << u8(`#`) state.offset++ if frame.directive_active { frame.directive << u8(`#`) } frame.mode = .word } } .word_escape { if c in [`x`, `X`] { state.datum_take(1) frame.mode = .word_hex } else { frame.mode = .word } } .word_hex { if c == `;` { state.datum_take(1) frame.mode = .word } else if c < 128 && (input_delimiter(u8(c)) || c == `|`) { frame.mode = .word } else { state.datum_take(width) } } .boolean_alias { if c < 128 && u8(c) | 0x20 == frame.alias[frame.alias_index] { state.remember_custom_text_probe(frame.probe_len)! frame.probe[frame.probe_len] = u8(c) frame.probe_len++ frame.alias_index++ port.position++ if frame.alias_index == frame.alias.len { state.bytes << unsafe { (&frame.probe[0]).vbytes(frame.probe_len) } state.offset += frame.probe_len frame.probe_len = 0 state.clear_text_probe() frame.word_escapes = false frame.mode = .word } } else { unread_custom_text_probe(state.target, unsafe { (&frame.probe[0]).vbytes(frame.probe_len) }, frame.probe_point, frame.probe_epoch, state.text_probe_positions(), state.attached_probe_positions()) frame.probe_len = 0 state.clear_text_probe() state.datum_token(.atom)! } } .vector_head { if c < 128 && (u8(c) | if c == `(` { u8(0) } else { u8(0x20) }) == frame.alias[frame.alias_index] { state.datum_take(1) frame.alias_index++ if frame.alias_index == frame.alias.len { state.datum_token(.open)! } } else { frame.word_escapes = true frame.mode = .word } } .label { if c >= `0` && c <= `9` { state.datum_take(1) } else if c in [`=`, `#`] { state.datum_take(1) state.datum_token(if c == `=` { .prefix } else { .atom })! } else { frame.word_escapes = false frame.mode = .word } } .character { state.datum_take(width) frame.word_escapes = false frame.mode = .word } } } }