vile / scheme / write.v
363 lines · 345 sloc · 12.06 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import math
4import strings
5
6// write formats a runtime value as Scheme data. Procedures and unspecified
7// results have descriptive, non-readable representations. Flat lists iterate.
8pub fn write(value Value) !string {
9 return format_value(value, false)
10}
11
12// display formats strings and characters without escapes, including inside
13// containers. Like write, this returns text rather than performing I/O.
14pub fn display(value Value) !string {
15 return format_value(value, true)
16}
17
18// Fixed bytevector storage stays live while Buffer grows. Emit decimal digits
19// directly, without per-byte strings, integer boxes, or temporary value arrays.
20@[direct_array_access]
21fn write_bytevector_literal(mut out strings.Buffer, bytes []u8) {
22 out.write_string('#u8(')
23 for i in 0 .. bytes.len {
24 byte := bytes[i]
25 if i > 0 { out.write_u8(` `) }
26 if byte >= 100 { out.write_u8(`0` + byte / 100) }
27 if byte >= 10 { out.write_u8(`0` + (byte / 10) % 10) }
28 out.write_u8(`0` + byte % 10)
29 }
30 out.write_u8(`)`)
31}
32
33fn format_unshared(value Value, display_mode bool) !string {
34 mut scalar := ScalarPrintState{}
35 return format_unshared_parts(value, display_mode, mut scalar)
36}
37
38fn format_unshared_parts(value Value, display_mode bool, mut scalar ScalarPrintState) !string {
39 mut out := strings.new_buffer(64)
40 defer { unsafe { out.free() } }
41 mut active := map[voidptr]bool{}
42 write_value(mut out, value, 0, mut active, mut scalar, display_mode)!
43 return out.take_string()
44}
45
46fn write_value(mut out strings.Buffer, value Value, depth int, mut active map[voidptr]bool, mut scalar ScalarPrintState, display_mode bool) ! {
47 if depth > 512 { return failure('value printing nesting limit exceeded') }
48 if !isnil(scalar.plan) && goops_primitive_object(value) {
49 callback := if scalar.plan.generic.tag == .procedure {
50 scalar.plan.generic
51 } else {
52 scalar.plan.vm.goops_class_for(value)!.printer
53 }
54 if callback.is_callable() {
55 if out.len() != 0 { scalar.plan.parts << custom_immutable_text(out.take_string()) }
56 scalar.plan.parts << callback
57 scalar.plan.parts << value
58 return
59 }
60 }
61 match value.goops_kind() {
62 .unspecified { out.write_string('#<unspecified>') }
63 .multiple { out.write_string('#<values>') }
64 .iteration { out.write_string('#<iteration>') }
65 .sorting { out.write_string('#<sorting>') }
66 .list_utility { out.write_string('#<list-utility>') }
67 .hashtable { out.write_string('#<hashtable>') }
68 .hashtable_operation { out.write_string('#<hashtable-state>') }
69 .promise { out.write_string('#<promise>') }
70 .wind_frame, .wind_plan, .file_extent { out.write_string('#<wind-state>') }
71 .uninitialized { return failure('uninitialized binding') }
72 .input_port {
73 out.write_string(if value.input_pointer().closed {
74 '#<closed-input-port>'
75 } else {
76 '#<input-port>'
77 })
78 }
79 .input_output_port {
80 out.write_string(if value.input_pointer().closed && value.output_pointer().closed {
81 '#<closed-input/output-port>'
82 } else {
83 '#<input/output-port>'
84 })
85 }
86 .output_port {
87 out.write_string(if value.output_pointer().closed {
88 '#<closed-output-port>'
89 } else {
90 '#<output-port>'
91 })
92 }
93 .environment { out.write_string('#<environment>') }
94 .port_position { out.write_string('#<port-position>') }
95 .port_operation { out.write_string('#<port-operation>') }
96 .custom_port_position { out.write_string('#<port-position>') }
97 .eof { out.write_string('#<eof>') }
98 .nil { out.write_string('()') }
99 .boolean { out.write_string(if value.whole() == 0 { '#f' } else { '#t' }) }
100 .integer { out.write_string(value.whole().str()) }
101 .real {
102 x := value.floating()
103 out.write_string(if math.is_nan(x) || math.is_inf(x, 0) {
104 nonfinite_notation(x)
105 } else {
106 x.str()
107 })
108 }
109 .big_integer, .big_rational, .exact_complex, .inexact_complex {
110 out.write_string(number_notation(value, 10)!)
111 }
112 .rational {
113 r := value.rational_pointer()
114 out.write_string('${r.numerator}/${r.denominator}')
115 }
116 .character { print_character(mut out, rune(value.whole()), display_mode) }
117 .symbol { print_symbol(mut out, value.text(), mut scalar, display_mode) }
118 .keyword { print_keyword(mut out, value.text(), mut scalar) }
119 .record {
120 out.write_string('#<record ' + value.record_pointer().record_type.spec.name + '>')
121 }
122 .goops_class {
123 out.write_string('#<class ' + value.goops_class_pointer().name + '>')
124 }
125 .goops_instance {
126 out.write_string('#<instance ' + value.goops_instance_pointer().class.name + '>')
127 }
128 .goops_method { out.write_string('#<method>') }
129 .goops_slot { out.write_string('#<slot ' + value.goops_slot_pointer().slot.name + '>') }
130 .goops_generic_data { return failure('cannot print private generic data') }
131 .goops_next_data { return failure('cannot print private next-method data') }
132 .parameter_context, .indexed_iteration, .port_default, .library_declaration,
133 .library_imports, .library_instance, .library_import_state, .goops_migration {
134 return failure('cannot print private machine state')
135 }
136 .goops_equal_cursor { return failure('cannot print private comparison cursor') }
137 .record_constructor_descriptor { out.write_string('#<record-constructor-descriptor>') }
138 .record_uid { return failure('cannot print private record UID token') }
139 .scope_function { return failure('cannot print private scope function') }
140 .syntax { out.write_string('#<syntax>') }
141 .syntax_captures { return failure('cannot print private syntax capture frame') }
142 .record_type {
143 out.write_string('#<record-type ' + value.record_type_pointer().spec.name + '>')
144 }
145 .codec {
146 out.write_string('#<codec ')
147 out.write_string(codec_name(value.as_codec()!))
148 out.write_u8(`>`)
149 }
150 .transcoder {
151 codec, eol, mode := value.as_transcoder()!
152 out.write_string('#<transcoder ')
153 out.write_string(codec_name(codec))
154 out.write_u8(` `)
155 out.write_string(eol_name(eol))
156 out.write_u8(` `)
157 out.write_string(error_mode_name(mode))
158 out.write_u8(`>`)
159 }
160 .enumeration { out.write_string('#<enum-set>') }
161 .record_spec { out.write_string('#<record-definition>') }
162 .global_reference { out.write_string('#<global-reference>') }
163 .bytevector { write_bytevector_literal(mut out, value.bytevector_pointer().bytes) }
164 .string {
165 if display_mode {
166 out.write_string(value.text())
167 return
168 }
169 print_quoted_text(mut out, value.text(), false)
170 }
171 .procedure {
172 p := value.procedure_pointer()
173 out.write_string(if p.mode == .goops_generic {
174 '#<generic ${p.name}>'
175 } else if p.name == '' {
176 '#<procedure>'
177 } else {
178 '#<procedure ${p.name}>'
179 })
180 }
181 .vector {
182 if !value.read_only || value.datum_graph {
183 if value.pointer() in active { return CircularPrint{} }
184 active[value.pointer()] = true
185 }
186 out.write_string('#(')
187 for index, element in value.vector_pointer().items {
188 if index > 0 { out.write_u8(` `) }
189 write_value(mut out, element, depth + 1, mut active, mut scalar, display_mode)!
190 }
191 out.write_u8(`)`)
192 if !value.read_only || value.datum_graph { active.delete(value.pointer()) }
193 }
194 .pair {
195 out.write_u8(`(`)
196 mut current := value
197 for {
198 if !current.read_only || current.datum_graph {
199 if current.pointer() in active { return CircularPrint{} }
200 active[current.pointer()] = true
201 }
202 p := current.pair_pointer()
203 write_value(mut out, p.car, depth + 1, mut active, mut scalar, display_mode)!
204 if p.cdr.tag == .nil { break }
205 if p.cdr.tag != .pair {
206 out.write_string(' . ')
207 write_value(mut out, p.cdr, depth + 1, mut active, mut scalar, display_mode)!
208 break
209 }
210 out.write_u8(` `)
211 current = p.cdr
212 }
213 out.write_u8(`)`)
214 if !value.read_only || value.datum_graph {
215 // Remove only this flat cdr chain. Nested paths have already been removed,
216 // so shared acyclic tails remain printable when visited again elsewhere.
217 mut release := value
218 for {
219 if !release.read_only || release.datum_graph {
220 active.delete(release.pointer())
221 }
222 if release.pointer() == current.pointer() { break }
223 release = release.pair_pointer().cdr
224 }
225 }
226 }
227 }
228}
229
230// Signal a retry only for cyclic structure, never for unrelated formatting errors.
231struct CircularPrint {
232 Error
233}
234
235fn (_ &CircularPrint) msg() string { return 'cannot print circular data' }
236
237fn format_value(value Value, display_mode bool) !string {
238 return format_unshared(value, display_mode) or {
239 if err is CircularPrint { return format_shared(value, display_mode) }
240 return err
241 }
242}
243
244// write_simple never emits datum labels. Cycles are rejected rather than
245// looping indefinitely in an embedding process.
246pub fn write_simple(value Value) !string {
247 return format_unshared(value, false) or {
248 if err is CircularPrint { return failure(err.msg()) }
249 return err
250 }
251}
252
253// write_shared preserves shared pairs and vectors, including acyclic sharing.
254pub fn write_shared(value Value) !string {
255 if value.tag !in [.pair, .vector] { return write_simple(value) }
256 return format_shared(value, false)
257}
258
259struct PrintSerial {
260mut:
261 value int
262}
263
264struct PrintNode {
265mut:
266 repeated bool
267 label int = -1
268}
269
270// Iterate along flat list tails; recursive calls only follow nested values.
271// An already visited container is counted but its children are not revisited:
272// the printer will emit a reference instead of expanding it a second time.
273fn scan_print_graph(value Value, depth int, mut nodes map[voidptr]PrintNode) ! {
274 if depth > 512 { return failure('value printing nesting limit exceeded') }
275 mut current := value
276 for current.tag in [.pair, .vector, .string, .bytevector] {
277 pointer := current.pointer()
278 if mut node := nodes[pointer] {
279 node.repeated = true
280 nodes[pointer] = node
281 return
282 }
283 nodes[pointer] = PrintNode{}
284 if current.tag == .pair {
285 pair := current.pair_pointer()
286 scan_print_graph(pair.car, depth + 1, mut nodes)!
287 current = pair.cdr
288 } else if current.tag == .vector {
289 for element in current.vector_pointer().items {
290 scan_print_graph(element, depth + 1, mut nodes)!
291 }
292 return
293 } else {
294 return
295 }
296 }
297}
298
299fn format_shared(value Value, display_mode bool) !string {
300 mut scalar := ScalarPrintState{}
301 return format_shared_parts(value, display_mode, mut scalar)
302}
303
304fn format_shared_parts(value Value, display_mode bool, mut scalar ScalarPrintState) !string {
305 mut nodes := map[voidptr]PrintNode{}
306 scan_print_graph(value, 0, mut nodes)!
307 mut out := strings.new_buffer(64)
308 mut serial := PrintSerial{}
309 // Scalar formatting shares the existing writer; it does not use this map.
310 mut unused := map[voidptr]bool{}
311 write_labeled(mut out, value, 0, mut nodes, mut serial, mut unused, mut scalar, display_mode)!
312 return out.take_string()
313}
314
315fn 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) ! {
316 if depth > 512 { return failure('value printing nesting limit exceeded') }
317 if value.tag !in [.pair, .vector, .string, .bytevector] {
318 write_value(mut out, value, depth, mut unused, mut scalar, display_mode)!
319 return
320 }
321 mut node := nodes[value.pointer()]
322 if node.repeated {
323 out.write_u8(`#`)
324 if node.label >= 0 {
325 out.write_string(node.label.str())
326 out.write_u8(`#`)
327 return
328 }
329 node.label = serial.value
330 serial.value++
331 nodes[value.pointer()] = node
332 out.write_string(node.label.str())
333 out.write_u8(`=`)
334 }
335 if value.tag in [.string, .bytevector] {
336 write_value(mut out, value, depth, mut unused, mut scalar, display_mode)!
337 return
338 }
339 if value.tag == .vector {
340 out.write_string('#(')
341 for i, item in value.vector_pointer().items {
342 if i > 0 { out.write_u8(` `) }
343 write_labeled(mut out, item, depth + 1, mut nodes, mut serial, mut unused, mut scalar, display_mode)!
344 }
345 out.write_u8(`)`)
346 return
347 }
348 out.write_u8(`(`)
349 mut current := value
350 for {
351 pair := current.pair_pointer()
352 write_labeled(mut out, pair.car, depth + 1, mut nodes, mut serial, mut unused, mut scalar, display_mode)!
353 if pair.cdr.tag == .nil { break }
354 if pair.cdr.tag != .pair || nodes[pair.cdr.pointer()].repeated {
355 out.write_string(' . ')
356 write_labeled(mut out, pair.cdr, depth + 1, mut nodes, mut serial, mut unused, mut scalar, display_mode)!
357 break
358 }
359 out.write_u8(` `)
360 current = pair.cdr
361 }
362 out.write_u8(`)`)
363}
364