module scheme import math import strings // write formats a runtime value as Scheme data. Procedures and unspecified // results have descriptive, non-readable representations. Flat lists iterate. pub fn write(value Value) !string { return format_value(value, false) } // display formats strings and characters without escapes, including inside // containers. Like write, this returns text rather than performing I/O. pub fn display(value Value) !string { return format_value(value, true) } // Fixed bytevector storage stays live while Buffer grows. Emit decimal digits // directly, without per-byte strings, integer boxes, or temporary value arrays. @[direct_array_access] fn write_bytevector_literal(mut out strings.Buffer, bytes []u8) { out.write_string('#u8(') for i in 0 .. bytes.len { byte := bytes[i] if i > 0 { out.write_u8(` `) } if byte >= 100 { out.write_u8(`0` + byte / 100) } if byte >= 10 { out.write_u8(`0` + (byte / 10) % 10) } out.write_u8(`0` + byte % 10) } out.write_u8(`)`) } fn format_unshared(value Value, display_mode bool) !string { mut scalar := ScalarPrintState{} return format_unshared_parts(value, display_mode, mut scalar) } fn format_unshared_parts(value Value, display_mode bool, mut scalar ScalarPrintState) !string { mut out := strings.new_buffer(64) defer { unsafe { out.free() } } mut active := map[voidptr]bool{} write_value(mut out, value, 0, mut active, mut scalar, display_mode)! return out.take_string() } fn write_value(mut out strings.Buffer, value Value, depth int, mut active map[voidptr]bool, mut scalar ScalarPrintState, display_mode bool) ! { if depth > 512 { return failure('value printing nesting limit exceeded') } if !isnil(scalar.plan) && goops_primitive_object(value) { callback := if scalar.plan.generic.tag == .procedure { scalar.plan.generic } else { scalar.plan.vm.goops_class_for(value)!.printer } if callback.is_callable() { if out.len() != 0 { scalar.plan.parts << custom_immutable_text(out.take_string()) } scalar.plan.parts << callback scalar.plan.parts << value return } } match value.goops_kind() { .unspecified { out.write_string('#') } .multiple { out.write_string('#') } .iteration { out.write_string('#') } .sorting { out.write_string('#') } .list_utility { out.write_string('#') } .hashtable { out.write_string('#') } .hashtable_operation { out.write_string('#') } .promise { out.write_string('#') } .wind_frame, .wind_plan, .file_extent { out.write_string('#') } .uninitialized { return failure('uninitialized binding') } .input_port { out.write_string(if value.input_pointer().closed { '#' } else { '#' }) } .input_output_port { out.write_string(if value.input_pointer().closed && value.output_pointer().closed { '#' } else { '#' }) } .output_port { out.write_string(if value.output_pointer().closed { '#' } else { '#' }) } .environment { out.write_string('#') } .port_position { out.write_string('#') } .port_operation { out.write_string('#') } .custom_port_position { out.write_string('#') } .eof { out.write_string('#') } .nil { out.write_string('()') } .boolean { out.write_string(if value.whole() == 0 { '#f' } else { '#t' }) } .integer { out.write_string(value.whole().str()) } .real { x := value.floating() out.write_string(if math.is_nan(x) || math.is_inf(x, 0) { nonfinite_notation(x) } else { x.str() }) } .big_integer, .big_rational, .exact_complex, .inexact_complex { out.write_string(number_notation(value, 10)!) } .rational { r := value.rational_pointer() out.write_string('${r.numerator}/${r.denominator}') } .character { print_character(mut out, rune(value.whole()), display_mode) } .symbol { print_symbol(mut out, value.text(), mut scalar, display_mode) } .keyword { print_keyword(mut out, value.text(), mut scalar) } .record { out.write_string('#') } .goops_class { out.write_string('#') } .goops_instance { out.write_string('#') } .goops_method { out.write_string('#') } .goops_slot { out.write_string('#') } .goops_generic_data { return failure('cannot print private generic data') } .goops_next_data { return failure('cannot print private next-method data') } .parameter_context, .indexed_iteration, .port_default, .library_declaration, .library_imports, .library_instance, .library_import_state, .goops_migration { return failure('cannot print private machine state') } .goops_equal_cursor { return failure('cannot print private comparison cursor') } .record_constructor_descriptor { out.write_string('#') } .record_uid { return failure('cannot print private record UID token') } .scope_function { return failure('cannot print private scope function') } .syntax { out.write_string('#') } .syntax_captures { return failure('cannot print private syntax capture frame') } .record_type { out.write_string('#') } .codec { out.write_string('#`) } .transcoder { codec, eol, mode := value.as_transcoder()! out.write_string('#`) } .enumeration { out.write_string('#') } .record_spec { out.write_string('#') } .global_reference { out.write_string('#') } .bytevector { write_bytevector_literal(mut out, value.bytevector_pointer().bytes) } .string { if display_mode { out.write_string(value.text()) return } print_quoted_text(mut out, value.text(), false) } .procedure { p := value.procedure_pointer() out.write_string(if p.mode == .goops_generic { '#' } else if p.name == '' { '#' } else { '#' }) } .vector { if !value.read_only || value.datum_graph { if value.pointer() in active { return CircularPrint{} } active[value.pointer()] = true } out.write_string('#(') for index, element in value.vector_pointer().items { if index > 0 { out.write_u8(` `) } write_value(mut out, element, depth + 1, mut active, mut scalar, display_mode)! } out.write_u8(`)`) if !value.read_only || value.datum_graph { active.delete(value.pointer()) } } .pair { out.write_u8(`(`) mut current := value for { if !current.read_only || current.datum_graph { if current.pointer() in active { return CircularPrint{} } active[current.pointer()] = true } p := current.pair_pointer() write_value(mut out, p.car, depth + 1, mut active, mut scalar, display_mode)! if p.cdr.tag == .nil { break } if p.cdr.tag != .pair { out.write_string(' . ') write_value(mut out, p.cdr, depth + 1, mut active, mut scalar, display_mode)! break } out.write_u8(` `) current = p.cdr } out.write_u8(`)`) if !value.read_only || value.datum_graph { // Remove only this flat cdr chain. Nested paths have already been removed, // so shared acyclic tails remain printable when visited again elsewhere. mut release := value for { if !release.read_only || release.datum_graph { active.delete(release.pointer()) } if release.pointer() == current.pointer() { break } release = release.pair_pointer().cdr } } } } } // Signal a retry only for cyclic structure, never for unrelated formatting errors. struct CircularPrint { Error } fn (_ &CircularPrint) msg() string { return 'cannot print circular data' } fn format_value(value Value, display_mode bool) !string { return format_unshared(value, display_mode) or { if err is CircularPrint { return format_shared(value, display_mode) } return err } } // write_simple never emits datum labels. Cycles are rejected rather than // looping indefinitely in an embedding process. pub fn write_simple(value Value) !string { return format_unshared(value, false) or { if err is CircularPrint { return failure(err.msg()) } return err } } // write_shared preserves shared pairs and vectors, including acyclic sharing. pub fn write_shared(value Value) !string { if value.tag !in [.pair, .vector] { return write_simple(value) } return format_shared(value, false) } struct PrintSerial { mut: value int } struct PrintNode { mut: repeated bool label int = -1 } // Iterate along flat list tails; recursive calls only follow nested values. // An already visited container is counted but its children are not revisited: // the printer will emit a reference instead of expanding it a second time. fn scan_print_graph(value Value, depth int, mut nodes map[voidptr]PrintNode) ! { if depth > 512 { return failure('value printing nesting limit exceeded') } mut current := value for current.tag in [.pair, .vector, .string, .bytevector] { pointer := current.pointer() if mut node := nodes[pointer] { node.repeated = true nodes[pointer] = node return } nodes[pointer] = PrintNode{} if current.tag == .pair { pair := current.pair_pointer() scan_print_graph(pair.car, depth + 1, mut nodes)! current = pair.cdr } else if current.tag == .vector { for element in current.vector_pointer().items { scan_print_graph(element, depth + 1, mut nodes)! } return } else { return } } } fn format_shared(value Value, display_mode bool) !string { mut scalar := ScalarPrintState{} return format_shared_parts(value, display_mode, mut scalar) } fn format_shared_parts(value Value, display_mode bool, mut scalar ScalarPrintState) !string { mut nodes := map[voidptr]PrintNode{} scan_print_graph(value, 0, mut nodes)! mut out := strings.new_buffer(64) mut serial := PrintSerial{} // Scalar formatting shares the existing writer; it does not use this map. mut unused := map[voidptr]bool{} write_labeled(mut out, value, 0, mut nodes, mut serial, mut unused, mut scalar, display_mode)! return out.take_string() } fn write_labeled(mut out strings.Buffer, value Value, depth int, mut nodes map[voidptr]PrintNode, mut serial PrintSerial, mut unused map[voidptr]bool, mut scalar ScalarPrintState, display_mode bool) ! { if depth > 512 { return failure('value printing nesting limit exceeded') } if value.tag !in [.pair, .vector, .string, .bytevector] { write_value(mut out, value, depth, mut unused, mut scalar, display_mode)! return } mut node := nodes[value.pointer()] if node.repeated { out.write_u8(`#`) if node.label >= 0 { out.write_string(node.label.str()) out.write_u8(`#`) return } node.label = serial.value serial.value++ nodes[value.pointer()] = node out.write_string(node.label.str()) out.write_u8(`=`) } if value.tag in [.string, .bytevector] { write_value(mut out, value, depth, mut unused, mut scalar, display_mode)! return } if value.tag == .vector { out.write_string('#(') for i, item in value.vector_pointer().items { if i > 0 { out.write_u8(` `) } write_labeled(mut out, item, depth + 1, mut nodes, mut serial, mut unused, mut scalar, display_mode)! } out.write_u8(`)`) return } out.write_u8(`(`) mut current := value for { pair := current.pair_pointer() write_labeled(mut out, pair.car, depth + 1, mut nodes, mut serial, mut unused, mut scalar, display_mode)! if pair.cdr.tag == .nil { break } if pair.cdr.tag != .pair || nodes[pair.cdr.pointer()].repeated { out.write_string(' . ') write_labeled(mut out, pair.cdr, depth + 1, mut nodes, mut serial, mut unused, mut scalar, display_mode)! break } out.write_u8(` `) current = pair.cdr } out.write_u8(`)`) }