module scheme import lexer import reader // read consumes one external datum. The reader sees a borrowed, complete frame // once; decoded strings/symbols and every mutable container own their storage. // No compiler cache, reversed car array, or second copy of the input is needed. pub fn (mut vm VM) read(value Value) !Value { vm.ready()! if !isnil(custom_input_resource(value)) { vm.checked_text_input(value)! return vm.custom_text_input_host_operation(.get_datum, value, unspecified(), 0, 0, unspecified()) } return vm.read_input(value) } fn (mut vm VM) read_input(value Value) !Value { mut port := vm.checked_text_input(value)! port.busy = true defer { port.busy = false port.mark = -1 port.release_large_frame() } start, end, initial_fold, present := port.frame_datum()! if !present { return eof_value() } source := unsafe { tos(&u8(port.buffer.data) + start, end - start) } result := port.read_input_frame(source, initial_fold) or { return port.absolute_input_error(err, start) } return result } fn port_read(mut vm VM, args []Value) !Value { check_arity('read', args.len, 0, 1)! target := if args.len == 0 { vm.current_input_value()! } else { args[0] } return vm.read_input(target) or { // Consumed port errors must never ask a REPL to replay its eval form. 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 } } @[inline] fn input_space(byte u8) bool { return byte == ` ` || (byte >= 0x09 && byte <= 0x0d) } @[inline] fn input_delimiter(byte u8) bool { return input_space(byte) || byte in [`(`, `)`, `"`, `;`] } // Decoding a completed frame does not require an I/O resource or heap port. struct InputFrameState { mut: no_fold bool } @[inline] fn (mut port InputPort) read_input_frame(source string, initial_fold bool) !Value { mut state := InputFrameState{ no_fold: port.no_fold } defer { port.no_fold = state.no_fold } return state.read_frame(source, initial_fold) } fn (mut port InputFrameState) read_frame(source string, initial_fold bool) !Value { first := source[0] if source.len == 2 && first == `#` && source[1] in [`t`, `T`, `f`, `F`] { return boolean(source[1] in [`t`, `T`]) } if first !in [`(`, `)`, `"`, `'`, `\x60`, `,`] && !(first == `#` && source.len >= 2 && source[1] in [`(`, `\\`]) { mut scanner := lexer.new_scanner(source, fold_case: initial_fold)! token := scanner.next()! if token.start == 0 && token.end == source.len { if token.kind == .number { return parse_number(source) } if token.kind == .boolean { return boolean(source[1] in [`t`, `T`]) } if token.kind == .identifier && scanner.token_flags() & (lexer.token_identifier_escaped | lexer.token_identifier_barred | lexer.token_identifier_unicode) == 0 { return text_value(.symbol, if initial_fold { source.to_lower_ascii() } else { source.clone() }) } } } doc := reader.read_all(source, fold_case: initial_fold)! port.no_fold = !doc.final_fold_case() if doc.forms.len != 1 { return failure('input frame must contain one datum') } if doc.arena.has_labels() { mut cache := map[reader.NodeId]Value{} return materialize_datum_graph(&doc, doc.forms[0], mut cache, false) } return read_port_datum(&doc, doc.forms[0]) } fn read_port_datum(doc &reader.Document, id reader.NodeId) !Value { node := doc.arena.node(id)! return match node.kind { .empty_list { nil_value() } .reference { return failure('unresolved reader reference') } .bytevector { read_bytevector_datum(doc, id, '')! } .boolean { boolean(doc.arena.boolean_value(id)!) } .number { // The parser consumes this lexer-validated span synchronously and // retains no source view; the port buffer stays pinned throughout. canonical := doc.arena.node(doc.arena.canonical_id(id)!)! parse_number(number_view(doc.arena.source_text(), canonical.start, canonical.end)) or { return EvalError{ message: err.msg(), offset: node.start, line: node.line, column: node.column } } } .character { character(doc.arena.character_value(id)!)! } .symbol { text_value(.symbol, doc.arena.symbol_name(id)!) } .keyword { text_value(.keyword, doc.arena.keyword_name(id)!) } .string_literal { text_value(.string, doc.arena.string_value(id)!) } .vector { mut items := []Value{len: node.count} for i in 0 .. node.count { items[i] = read_port_datum(doc, doc.arena.vector_at(id, i)!)! } payload_value(.vector, &Vector{ items: items }) } .pair { mut root := nil_value() mut last := &Pair(unsafe { nil }) mut cursor := id for { pair := doc.arena.node(cursor)! if pair.kind != .pair { break } car := read_port_datum(doc, pair.car)! mut cell := &Pair{ car: car, cdr: nil_value() } value := payload_value(.pair, cell) if isnil(last) { root = value } else { last.cdr = value } last = cell cursor = pair.cdr } tail := read_port_datum(doc, cursor)! last.cdr = tail root } } } fn (mut port InputPort) release_large_frame() { // Memory ports retain their single source snapshot so positions stay seekable. if port.memory_input { return } remaining := port.buffer.len - port.position if port.buffer.cap <= 65536 || port.buffer.cap / 4 <= port.read_size || remaining > port.read_size { return } port.checkpoint_input() mut replacement := []u8{len: remaining, cap: port.read_size} // Datum conversion has finished and retains no views of the input. Move // only unread lookahead, so a long string need not pin the high-water buffer. unsafe { if remaining > 0 { vmemcpy(replacement.data, &u8(port.buffer.data) + port.position, remaining) } replacement.flags.set(.noslices) } port.buffer = replacement port.position = 0 }