| 1 | module scheme |
| 2 | |
| 3 | struct GoopsPrintPlan { |
| 4 | vm &VM |
| 5 | generic Value |
| 6 | mut: |
| 7 | parts []Value |
| 8 | } |
| 9 | |
| 10 | // Prepare the graph before writing the first byte. A retry with datum labels |
| 11 | // must never invoke a printer twice. The immutable plan and current index |
| 12 | // survive a continuation captured by either a printer or a custom port. |
| 13 | fn (mut m Machine) prepare_goops_print(mut vm VM, p &Procedure, operation PortIoOperation, base int, args []Value) !bool { |
| 14 | if operation !in [.display_text, .write_datum, .write_simple, .write_shared, .put_datum] { |
| 15 | return false |
| 16 | } |
| 17 | check_custom_port_arity(operation, args.len)! |
| 18 | put := operation == .put_datum |
| 19 | value := args[if put { 1 } else { 0 }] |
| 20 | if value.tag !in [.pair, .vector] && !goops_primitive_object(value) { return false } |
| 21 | if value.tag !in [.pair, .vector] && !vm.goops_class_for(value)!.printer.is_callable() { |
| 22 | return false |
| 23 | } |
| 24 | port := if put { args[0] } else if args.len == 2 { args[1] } else { vm.current_output_value()! } |
| 25 | vm.checked_text_output(port)! |
| 26 | generic := if operation in [.display_text, .write_datum] && !isnil(p.env) && value.tag in [.pair, .vector] { |
| 27 | p.env.slots[0] |
| 28 | } else { |
| 29 | unspecified() |
| 30 | } |
| 31 | mut plan := GoopsPrintPlan{ vm: vm, generic: generic } |
| 32 | mut state := ScalarPrintState{ plan: &plan } |
| 33 | displaying := operation == .display_text |
| 34 | suffix := if operation == .write_shared { |
| 35 | format_shared_parts(value, false, mut state)! |
| 36 | } else { |
| 37 | format_unshared_parts(value, displaying, mut state) or { |
| 38 | if err !is CircularPrint { return err } |
| 39 | if operation == .write_simple { return failure(err.msg()) } |
| 40 | plan.parts.clear() |
| 41 | state.preserve_case = false |
| 42 | format_shared_parts(value, displaying, mut state)! |
| 43 | } |
| 44 | } |
| 45 | m.truncate(base) |
| 46 | if plan.parts.len == 0 { |
| 47 | m.push(vm.goops.print_text) |
| 48 | m.push(custom_immutable_text(suffix)) |
| 49 | } else { |
| 50 | if suffix.len != 0 { plan.parts << custom_immutable_text(suffix) } |
| 51 | m.push(vm.goops.print_parts) |
| 52 | m.push(payload_value(.vector, &Vector{ items: unsafe { plan.parts } })) |
| 53 | } |
| 54 | m.push(port) |
| 55 | return true |
| 56 | } |
| 57 | |