module scheme import io import math import os import reader import strconv @[heap] struct DatumPortReader { data []u8 chunk int = 4096 forbid_eof bool mut: position int calls int } fn (mut source DatumPortReader) read(mut destination []u8) !int { source.calls++ if source.position == source.data.len { if source.forbid_eof { return failure('reader was asked for input after the complete datum') } return io.Eof{} } count := int_min(destination.len, int_min(source.chunk, source.data.len - source.position)) copy(mut destination[..count], source.data[source.position..source.position + count]) source.position += count return count } fn test_read_handles_every_datum_kind_and_streams_arbitrary_input_chunk_boundaries() { for row in [ ['42 ', '42'], ['#e1.50 ', '3/2'], ['#xdead ', '57005'], ['#t', '#t'], ['#F', '#f'], ['Hello ', 'hello'], ['"位馃榾"', '"位馃榾"'], [r'"a\"b\\c"', r'"a\"b\\c"'], [r'#\space ', r'#\space'], [r'#\位 ', r'#\位'], [r'#\) ', r'#\)'], [r'#\( ', r'#\('], [r'#\; ', r'#\;'], [r'#\" ', r'#\"'], ['()', '()'], ['(1 2 . 3)', '(1 2 . 3)'], ['#()', '#()'], ['#(1 "位" (a . b))', '#(1 "位" (a . b))'], ["'(a b)", '(quote (a b))'], ['`(a ,b ,@c)', '(quasiquote (a (unquote b) (unquote-splicing c)))'], ['(a; ignored ) " #t\n b)', '(a b)'], [' ; 位馃榾 leading comment\r\n (a #t#f)', '(a #t #f)'], [r'(#\) #\; #\")', r'(#\) #\; #\")'], ] { for chunk in [1, 2, 3, 7, 4096] { mut source := &DatumPortReader{ data: row[0].bytes(), chunk: chunk } mut vm := new() input := vm.input_port(source, read_size: 5) or { panic(err) } value := vm.read(input) or { panic('${row} chunk ${chunk}: ${err}') } assert write(value) or { panic(err) } == row[1], '${row} chunk ${chunk}' assert !input.input_pointer().busy && input.input_pointer().mark == -1 assert vm.read(input) or { panic(err) }.tag == .eof } } } fn test_read_finishes_self_terminating_data_without_waiting_for_eof() { // Short booleans need lookahead: #t may still become #true. for text in ['#t ', '#F ', '()', '(1 2)', '#(1 2)', '"hello"', "'(a)", '42 ', 'name ', r'#\space '] { mut source := &DatumPortReader{ data: text.bytes(), chunk: 1, forbid_eof: true } mut vm := new() input := vm.input_port(source, read_size: 1) or { panic(err) } value := vm.read(input) or { panic('${text}: ${err}') } assert value.tag != .eof assert source.calls == text.len } } fn test_read_char_and_peek_char_share_the_same_cursor_and_leave_atom_delimiters_unread() { mut source := &DatumPortReader{ data: '12 (a)"x"#t#foo'.bytes(), chunk: 3 } mut vm := new() input := vm.input_port(source, read_size: 5) or { panic(err) } assert vm.read(input) or { panic(err) }.as_integer() or { panic(err) } == 12 assert vm.peek_char(input) or { panic(err) }.as_character() or { panic(err) } == ` ` assert vm.read_char(input) or { panic(err) }.as_character() or { panic(err) } == ` ` assert write(vm.read(input) or { panic(err) }) or { panic(err) } == '(a)' assert vm.peek_char(input) or { panic(err) }.as_character() or { panic(err) } == `"` assert vm.read(input) or { panic(err) }.as_string() or { panic(err) } == 'x' assert vm.read(input) or { panic(err) }.as_boolean() or { panic(err) } assert !(vm.read(input) or { panic(err) }.as_boolean() or { panic(err) }) assert vm.read(input) or { panic(err) }.symbol_name() or { panic(err) } == 'oo' assert vm.read_char(input) or { panic(err) }.tag == .eof } fn test_read_results_are_fresh_mutable_data_and_keep_their_storage_after_buffer_reuse() { mut source := &DatumPortReader{ data: '(a "位馃榾" #(1 "x") . tail) '.bytes(), chunk: 1 } mut vm := new() input := vm.input_port(source, read_size: 3) or { panic(err) } data := vm.read(input) or { panic(err) } vm.define('data', data) or { panic(err) } vm.eval('(set-car! data 42) (string-set! (cadr data) 0 #\\a) (vector-set! (caddr data) 0 99) (string-set! (vector-ref (caddr data) 1) 0 #\\z)') or { panic(err) } assert write(data) or { panic(err) } == '(42 "a馃榾" #(99 "z") . tail)' assert vm.read(input) or { panic(err) }.tag == .eof gc_collect() assert write(data) or { panic(err) } == '(42 "a馃榾" #(99 "z") . tail)' text := '位馃榾'.repeat(40000) mut large := &DatumPortReader{ data: ('"' + text + '" ' + '123 '.repeat(2000)).bytes(), chunk: 997 } large_port := vm.input_port(large, read_size: 4096) or { panic(err) } saved := vm.read(large_port) or { panic(err) } assert large_port.input_pointer().buffer.cap <= 65536 for _ in 0 .. 2000 { assert vm.read(large_port) or { panic(err) }.as_integer() or { panic(err) } == 123 } assert vm.read(large_port) or { panic(err) }.tag == .eof gc_collect() assert saved.as_string() or { panic(err) } == text } fn test_read_ignores_large_leading_trivia_without_retaining_it_as_datum_storage() { mut source := &DatumPortReader{ data: ('; ' + '位馃榾 '.repeat(20000) + '\n42 ').bytes(), chunk: 193 } mut vm := new() input := vm.input_port(source, read_size: 256) or { panic(err) } assert vm.read(input) or { panic(err) }.as_integer() or { panic(err) } == 42 assert input.input_pointer().buffer.cap < 4096 mut empty := &DatumPortReader{ data: (' \t; 位馃榾\r\n'.repeat(10000)).bytes(), chunk: 97 } empty_port := vm.input_port(empty, read_size: 128) or { panic(err) } assert vm.read(empty_port) or { panic(err) }.tag == .eof } fn test_flat_read_lists_and_prefix_sequences_do_not_consume_native_stack_per_element() { mut source := &DatumPortReader{ data: ('(' + "'x ".repeat(20000) + ')').bytes(), chunk: 233 } mut vm := new() input := vm.input_port(source) or { panic(err) } data := vm.read(input) or { panic(err) } assert data.list_length() or { panic(err) } == 20000 assert write(data.pair_pointer().car) or { panic(err) } == '(quote x)' assert vm.read(input) or { panic(err) }.tag == .eof } fn test_read_nesting_is_bounded_including_quote_prefixes_but_allows_the_reader_boundary() { mut vm := new() for text in ['('.repeat(reader.max_depth + 1) + ')'.repeat(reader.max_depth + 1), "'".repeat(reader.max_depth) + '()'] { mut source := &DatumPortReader{ data: text.bytes(), chunk: 1 } input := vm.input_port(source, read_size: 1) or { panic(err) } assert vm.read(input) or { panic(err) }.tag == .pair } for text in ['('.repeat(reader.max_depth + 2), "'".repeat(reader.max_depth + 2)] { mut source := &DatumPortReader{ data: text.bytes(), forbid_eof: true } input := vm.input_port(source) or { panic(err) } if _ := vm.read(input) { assert false } else { assert err.msg().contains('nesting limit'), err.msg() } } } fn test_invalid_input_never_becomes_eof_or_an_unfinished_eval_source_error() { for text in ['(', '"unterminated', "'", '#\\', '#', ')', '(1 . 2 3)', '(1 .)', '#(1 . 2)', "a'x ", '1#t ', r'#\a#t ', r'#\(foo ', r'#\ x ', '1/0 ', '"bad\\q"'] { mut vm := new() mut source := &DatumPortReader{ data: text.bytes(), chunk: 1 } input := vm.input_port(source) or { panic(err) } vm.set_input_port(input) or { panic(err) } if _ := vm.eval('(read)') { assert false, text } else { assert err is EvalError, '${text}: ${err}' } assert !input.input_pointer().busy && input.input_pointer().mark == -1 } } fn test_read_is_available_through_the_embedding_vm_with_explicit_and_current_ports() { mut vm := new() mut source := &DatumPortReader{ data: '1 2 '.bytes() } input := vm.input_port(source) or { panic(err) } vm.define('input', input) or { panic(err) } vm.set_input_port(input) or { panic(err) } assert write(vm.eval('(list (read input) (read) (eof-object? (read)))') or { panic(err) }) or { panic(err) } == '(1 2 #t)' for code in ['(read 1)', '(read 1 2)'] { if _ := vm.eval(code) { assert false } else { assert err is EvalError } } } fn test_chunked_string_framing_keeps_backslash_parity_across_every_split() { mut vm := new() for left in 0 .. 12 { for right in 0 .. 9 { text := '\\'.repeat(left) + '"位馃榾\x00\n' + '\\'.repeat(right) encoded := write(string_value(text)) or { panic(err) } for chunk in [1, 2, 3, 5, 17] { mut source := &DatumPortReader{ data: (encoded + '#t').bytes(), chunk: chunk } input := vm.input_port(source, read_size: 11) or { panic(err) } assert vm.read(input) or { panic(err) }.as_string() or { panic(err) } == text assert vm.read(input) or { panic(err) }.as_boolean() or { panic(err) } assert vm.read(input) or { panic(err) }.tag == .eof } } } } fn test_bounded_framing_scans_find_only_delimiters_inside_the_requested_suffix() { for length in 0 .. 81 { mut bytes := []u8{len: length} for i in 0 .. length { bytes[i] = [u8(0), 255, 128, `a`, `#`, `\\`, `'`, `,`, 0x60][i % 9] } for start in 0 .. length + 1 { assert input_word_end(bytes, start) == length assert input_quote(bytes, start) == length } } for delimiter in [u8(9), 10, 11, 12, 13, 32, 40, 41, 34, 59] { for position in 0 .. 80 { mut bytes := []u8{len: 80, init: `a`} bytes[position] = delimiter for start in 0 .. 81 { expected := if start <= position { position } else { 80 } assert input_word_end(bytes, start) == expected assert input_quote(bytes, start) == if delimiter == `"` { expected } else { 80 } } } } } fn test_numeric_port_reading_matches_independent_rounding_fixtures_without_owned_token_copies() { fixture := os.read_file(@VMODROOT + '/scheme/testdata/numeric_io.tsv') or { panic(err) } mut text := '' mut expected := []u64{} for row in fixture.split_into_lines() { if row.len == 0 || row[0] == `#` { continue } fields := row.split('\t') radix := fields[0].int() mut spelling := fields[1] mut explicit := false for prefix in ['#b', '#B', '#o', '#O', '#d', '#D', '#x', '#X'] { if spelling.contains(prefix) { explicit = true } } if radix != 10 && !explicit { spelling = match radix { 2 { '#b' } 8 { '#o' } else { '#x' } } + spelling } text += spelling + ' ' expected << strconv.parse_uint(fields[2], 16, 64) or { panic(err) } } assert expected.len == 1585 mut vm := new() mut source := &DatumPortReader{ data: text.bytes(), chunk: 17 } input := vm.input_port(source, read_size: 31) or { panic(err) } for i, bits in expected { value := vm.read(input) or { panic('fixture ${i}: ${err}') } assert math.f64_bits(value.as_real() or { panic(err) }) == bits, 'fixture ${i}' } assert vm.read(input) or { panic(err) }.tag == .eof }