Debian Codegraph @

%3a166/write.scm

raw symbols SCIP
1 ;; write.scm - written formatting, the default displayed for non-string/chars
2 ;; Copyright (c) 2006-2019 Alex Shinn. All rights reserved.
3 ;; BSD-style license: http://synthcode.com/license.txt
4
5 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
6
7 ;;> \section{String utilities}
8
9 (define (write-to-string x)
10 (call-with-output-string (lambda (out) (write x out))))
11
12 (define (string-replace-all str ch1 ch2)
13 (let ((out (open-output-string)))
14 (string-for-each
15 (lambda (ch) (display (if (eqv? ch ch1) ch2 ch) out))
16 str)
17 (get-output-string out)))
18
19 (define (string-intersperse-right str sep rule)
20 (let ((start (string-cursor-start str)))
21 (let lp ((i (string-cursor-end str))
22 (rule rule)
23 (res '()))
24 (let* ((offset (if (pair? rule) (car rule) rule))
25 (i2 (if offset (string-cursor-back str i offset) start)))
26 (if (string-cursor<=? i2 start)
27 (apply string-append (cons (substring/cursors str start i) res))
28 (lp i2
29 (if (and (pair? rule) (not (null? (cdr rule)))) (cdr rule) rule)
30 (cons sep (cons (substring/cursors str i2 i) res))))))))
31
32 ;;> Outputs the string str, escaping any quote or escape characters.
33 ;;> If esc-ch, which defaults to #\\, is #f, escapes only the
34 ;;> quote-ch, which defaults to #\", by doubling it, as in SQL strings
35 ;;> and CSV values. If renamer is provided, it should be a procedure
36 ;;> of one character which maps that character to its escape value,
37 ;;> e.g. #\newline => #\n, or #f if there is no escape value.
38
39 (define (escaped fmt . o)
40 (let-optionals* o ((quot #\")
41 (esc #\\)
42 (rename (lambda (x) #f)))
43 (let ((esc-str (cond ((char? esc) (string esc))
44 ((not esc) (string quot))
45 (else esc))))
46 (fn ((orig-output output))
47 (define (output* str)
48 (let ((start (string-cursor-start str))
49 (end (string-cursor-end str)))
50 (let lp ((i start) (j start))
51 (define (collect)
52 (if (eq? i j) "" (substring/cursors str i j)))
53 (if (string-cursor>=? j end)
54 (orig-output (collect))
55 (let ((c (string-ref/cursor str j))
56 (j2 (string-cursor-next str j)))
57 (cond
58 ((or (eqv? c quot) (eqv? c esc))
59 (each (orig-output (collect))
60 (orig-output esc-str)
61 (fn () (lp j j2))))
62 ((rename c)
63 => (lambda (c2)
64 (each (orig-output (collect))
65 (orig-output esc-str)
66 (orig-output (if (char? c2) (string c2) c2))
67 (fn () (lp j2 j2)))))
68 (else
69 (lp i j2))))))))
70 (with ((output output*))
71 fmt)))))
72
73 ;;> Only escape if there are special characters, in which case also
74 ;;> wrap in quotes. For writing symbols in |...| escapes, or CSV
75 ;;> fields, etc. The predicate indicates which characters cause
76 ;;> slashification - this is in addition to automatic slashifying when
77 ;;> either the quote or escape char is present.
78
79 (define (maybe-escaped fmt pred . o)
80 (let-optionals* o ((quot #\")
81 (esc #\\)
82 (rename (lambda (x) #f)))
83 (define (esc? c) (or (eqv? c quot) (eqv? c esc) (rename c) (pred c)))
84 (call-with-output
85 fmt
86 (lambda (str)
87 (if (string-cursor<? (string-index str esc?) (string-cursor-end str))
88 (each quot (escaped str quot esc rename) quot)
89 (displayed str))))))
90
91 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
92 ;; numeric formatting
93
94 (define (char-mirror c)
95 (case c ((#\() #\)) ((#\[) #\]) ((#\{) #\}) ((#\<) #\>) (else c)))
96
97 (define (integer-log a base)
98 (if (zero? a)
99 0
100 ;; (exact (ceiling (/ (log (+ a 1)) (log base))))
101 (do ((ndigits 1 (+ ndigits 1))
102 (p base (* p base)))
103 ((> p a) ndigits))))
104
105 ;; The original fmt algorithm was based on "Printing Floating-Point
106 ;; Numbers Quickly and Accurately" by Burger and Dybvig
107 ;; (FP-Printing-PLDI96.pdf). It had grown unwieldy with formatting
108 ;; special cases, so the below is a simplification which tries to rely
109 ;; on number->string for common cases.
110
111 (define unspec (list 'unspecified))
112
113 (define-syntax default
114 (syntax-rules ()
115 ((default var dflt) (if (eq? var unspec) dflt var))))
116
117 (define (numeric n . o)
118 (let-optionals* o ((rad unspec) (prec unspec) (sgn unspec)
119 (comma unspec) (commasep unspec) (decsep unspec))
120 (fn (radix precision sign-rule
121 comma-rule comma-sep decimal-sep decimal-align)
122 (let* ((radix (default rad radix))
123 (precision (default prec precision))
124 (sign-rule (default sgn sign-rule))
125 (comma-rule (default comma comma-rule))
126 (comma-sep (default commasep comma-sep))
127 (dec-sep (default decsep
128 (or decimal-sep (if (eqv? comma-sep #\.) #\, #\.))))
129 (dec-ls (if (char? dec-sep)
130 (list dec-sep)
131 (reverse (string->list dec-sep)))))
132 ;; General formatting utilities.
133 (define (get-scale q)
134 (expt radix (- (integer-log q radix) 1)))
135 (define (char-digit d)
136 (cond ((char? d) d)
137 ((< d 10) (integer->char (+ d (char->integer #\0))))
138 (else (integer->char (+ (- d 10) (char->integer #\a))))))
139 (define (digit-value ch)
140 (let ((res (- (char->integer ch) (char->integer #\0))))
141 (if (<= 0 res 9)
142 res
143 ch)))
144 (define (round-up ls)
145 (let lp ((ls ls) (res '()))
146 (cond
147 ((null? ls)
148 (append (reverse res) '(1)))
149 ((not (number? (car ls)))
150 (lp (cdr ls) (cons (car ls) res)))
151 ((= (car ls) (- radix 1))
152 (lp (cdr ls) (cons 0 res)))
153 (else
154 (append (reverse res) (cons (+ 1 (car ls)) (cdr ls)))))))
155 (define (maybe-round n d ls)
156 (let* ((q (quotient n d))
157 (digit (* 2 (if (>= q radix) (quotient q (get-scale q)) q))))
158 (if (or (> digit radix)
159 (and (= digit radix)
160 (let ((prev (find integer? ls)))
161 (and prev (odd? prev)))))
162 (round-up ls)
163 ls)))
164 (define (maybe-trim-zeros i res inexact?)
165 (if (and (not precision) (positive? i))
166 (let lp ((res res))
167 (cond
168 ((and (pair? res) (eqv? 0 (car res))) (lp (cdr res)))
169 ((and (pair? res)
170 (eqv? (car dec-ls) (car res))
171 (null? (cdr dec-ls)))
172 (if inexact?
173 (cons 0 res) ; "1.0"
174 (cdr res))) ; "1"
175 (else res)))
176 res))
177 ;; General slow loop to generate digits one at a time, for
178 ;; non-standard radixes or writing rationals with a fixed
179 ;; precision.
180 (define (gen-general n-orig)
181 (let* ((p (exact n-orig))
182 (n (numerator p))
183 (d (denominator p)))
184 (let lp ((n n)
185 (i (if (zero? p) -1 (- (integer-log p radix))))
186 (res '()))
187 (cond
188 ;; Use a fixed precision if specified, otherwise generate
189 ;; 15 decimals.
190 ((if precision (< i precision) (< i 16))
191 (let ((res (if (zero? i)
192 (append dec-ls (if (null? res) (cons 0 res) res))
193 res))
194 (q (quotient n d)))
195 (cond
196 ((< i -1)
197 (let* ((scale (expt radix (- -1 i)))
198 (digit (quotient q scale))
199 (n2 (- n (* d digit scale))))
200 (lp n2 (+ i 1) (cons digit res))))
201 (else
202 (lp (* (remainder n d) radix)
203 (+ i 1)
204 (cons q res))))))
205 (else
206 (reverse-list->string
207 (map char-digit
208 (maybe-trim-zeros i (maybe-round n d res) (inexact? n-orig)))))))))
209 ;; Generate a fixed precision decimal result by post-editing the
210 ;; result of string->number.
211 (define (gen-fixed n)
212 (cond
213 ((and (eqv? radix 10) (zero? precision) (inexact? n))
214 (number->string (exact (round n))))
215 ((and (eqv? radix 10) (or (integer? n) (inexact? n)))
216 (let* ((s (number->string n))
217 (end (string-cursor-end s))
218 (dec (string-index s #\.))
219 (digits (- (string-cursor->index s end)
220 (string-cursor->index s dec))))
221 (cond
222 ((string-cursor<? (string-index s #\e) end)
223 (gen-general n))
224 ((string-cursor=? dec end)
225 (string-append s (if (char? dec-sep) (string dec-sep) dec-sep)
226 (make-string precision #\0)))
227 ((<= digits precision)
228 (string-append s (make-string (- precision digits -1) #\0)))
229 (else
230 (let* ((last
231 (string-cursor-back s end (- digits precision 1)))
232 (res (substring/cursors s (string-cursor-start s) last)))
233 (if (and
234 (string-cursor<? last end)
235 (let ((next (digit-value (string-ref/cursor s last))))
236 (or (> next 5)
237 (and (= next 5)
238 (string-cursor>? last (string-cursor-start s))
239 (memv (digit-value
240 (string-ref/cursor
241 s (string-cursor-prev s last)))
242 '(1 3 5 7 9))))))
243 (reverse-list->string
244 (map char-digit
245 (round-up
246 (reverse
247 (map digit-value (string->list res))))))
248 res))))))
249 (else
250 (gen-general n))))
251 ;; Generate any unsigned real number.
252 (define (gen-positive-real n)
253 (cond
254 (precision
255 (gen-fixed n))
256 ((memv radix (if (exact? n) '(2 8 10 16) '(10)))
257 (number->string n radix))
258 (else
259 (gen-general n))))
260 ;; Insert commas according to the current comma-rule.
261 (define (insert-commas str)
262 (let* ((dec-pos (if (string? dec-sep)
263 (or (string-contains str dec-sep)
264 (string-cursor-end str))
265 (string-index str dec-sep)))
266 (left (substring/cursors str (string-cursor-start str) dec-pos))
267 (right (string-copy/cursors str dec-pos))
268 (sep (cond ((char? comma-sep) (string comma-sep))
269 ((string? comma-sep) comma-sep)
270 ((eqv? #\, dec-sep) ".")
271 (else ","))))
272 (string-append
273 (string-intersperse-right left sep comma-rule)
274 right)))
275 ;; Post-process a positive real number with decimal char fixup
276 ;; and commas as needed.
277 (define (wrap-comma n)
278 (if (and (not precision) (exact? n) (not (integer? n)))
279 (string-append (wrap-comma (numerator n))
280 "/"
281 (wrap-comma (denominator n)))
282 (let* ((s0 (gen-positive-real n))
283 (s1 (if (or (eqv? #\. dec-sep)
284 (equal? "." dec-sep))
285 s0
286 (string-replace-all s0 #\. dec-sep))))
287 (if comma-rule (insert-commas s1) s1))))
288 ;; Wrap the sign of a real number, forcing a + prefix or using
289 ;; parentheses (n) for negatives according to sign-rule.
290
291 (define-syntax is-neg-zero?
292 (syntax-rules ()
293 ((_ n)
294 (is-neg-zero? (-0.0) n))
295 ((_ (0.0) n) ; -0.0 is not distinguished?
296 #f)
297 ((_ (-0.0) n)
298 (eqv? -0.0 n))))
299 (define (negative?* n)
300 (or (negative? n)
301 (is-neg-zero? n)))
302 (define (wrap-sign n sign-rule)
303 (cond
304 ((negative?* n)
305 (cond
306 ((char? sign-rule)
307 (string-append (string sign-rule)
308 (wrap-comma (- n))
309 (string (char-mirror sign-rule))))
310 ((pair? sign-rule)
311 (string-append (car sign-rule)
312 (wrap-comma (- n))
313 (cdr sign-rule)))
314 (else
315 (string-append "-" (wrap-comma (- n))))))
316 ((eq? #t sign-rule)
317 (string-append "+" (wrap-comma n)))
318 (else
319 (wrap-comma n))))
320 ;; Format a single real number with padding as necessary.
321 (define (format n sign-rule)
322 (cond
323 ((finite? n)
324 (let* ((s (wrap-sign n sign-rule))
325 (dec-pos (if decimal-align
326 (string-cursor->index
327 s
328 (if (char? dec-sep)
329 (string-index s dec-sep)
330 (or (string-contains s dec-sep)
331 (string-cursor-end s))))
332 0))
333 (diff (- (or decimal-align 0) dec-pos 1)))
334 (if (positive? diff)
335 (string-append (make-string diff #\space) s)
336 s)))
337 (else
338 (number->string n))))
339 ;; Write any number.
340 (define (write-complex n)
341 (cond
342 ((and radix (not (and (integer? radix) (<= 2 radix 36))))
343 (error "invalid radix for numeric formatting" radix))
344 ((zero? (imag-part n))
345 (displayed (format (real-part n) sign-rule)))
346 (else
347 (each (format (real-part n) sign-rule)
348 (format (imag-part n) #t)
349 "i"))))
350 (write-complex n)))))
351
352 (define numeric/si
353 (let* ((names10 '#("" "k" "M" "G" "T" "E" "P" "Z" "Y"))
354 (names-10 '#("" "m" "ยต" "n" "p" "f" "a" "z" "y"))
355 (names2 (list->vector
356 (cons ""
357 (cons "Ki" (map (lambda (s) (string-append s "i"))
358 (cddr (vector->list names10)))))))
359 (names-2 (list->vector
360 (cons ""
361 (map (lambda (s) (string-append s "i"))
362 (cdr (vector->list names-10)))))))
363 (define (round-to n k)
364 (/ (round (* n k)) k))
365 (lambda (n . o)
366 (let-optionals* o ((base 1000)
367 (separator ""))
368 (if (zero? n)
369 "0"
370 (let* ((log-n (log (abs n)))
371 (names (if (negative? log-n)
372 (if (= base 1024) names-2 names-10)
373 (if (= base 1024) names2 names10)))
374 (k (min (exact ((if (negative? log-n) ceiling floor)
375 (/ (abs log-n) (log base))))
376 (- (vector-length names) 1)))
377 (n2 (round-to (/ (abs n)
378 (expt base (if (negative? log-n) (- k) k)))
379 10)))
380 (each (if (negative? n) "-" "")
381 (if (integer? n2)
382 (number->string (exact n2))
383 (inexact n2))
384 ;; (if (zero? k) "" separator)
385 separator
386 (vector-ref names k))))))))
387
388 ;; Force a number into a fixed width, print as #'s if doesn't fit.
389 ;; Needs to be wrapped in PADDED if you want to expand to the width.
390
391 (define (numeric/fitted width n . args)
392 (call-with-output
393 (apply numeric n args)
394 (lambda (str)
395 (if (> (string-length str) width)
396 (fn (precision decimal-sep comma-sep)
397 (let ((prec (if (and (pair? args) (pair? (cdr args)))
398 (cadr args)
399 precision)))
400 (if (and prec (not (zero? prec)))
401 (let* ((dec-sep
402 (or decimal-sep
403 (if (eqv? #\. comma-sep) #\, #\.)))
404 (diff (- width (+ prec
405 (if (char? dec-sep)
406 1
407 (string-length dec-sep))))))
408 (each (if (positive? diff) (make-string diff #\#) "")
409 dec-sep (make-string prec #\#)))
410 (displayed (make-string width #\#)))))
411 (displayed str)))))
412
413 (define (numeric/comma n . o)
414 (fn ((orig-comma-rule comma-rule))
415 (with ((comma-rule (if (pair? o) (car o) (or orig-comma-rule 3))))
416 (apply numeric n (if (pair? o) (cdr o) '())))))
417
418 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
419 ;; written
420
421 (define (write-with-shares obj shares)
422 (fn ((orig-radix radix) precision)
423 (let ((write-number
424 ;; Shortcut for numeric values. Try to rely on
425 ;; number->string for standard radixes and no precision,
426 ;; otherwise fall back on numeric but resetting to a usable
427 ;; radix.
428 (cond
429 ((and (not precision)
430 (assv orig-radix
431 '((16 . "#x") (10 . "") (8 . "#o") (2 . "#b"))))
432 => (lambda (cell)
433 (lambda (n)
434 (cond
435 ((eqv? orig-radix 10)
436 (displayed (number->string n (car cell))))
437 ((exact? n)
438 (each (cdr cell) (number->string n (car cell))))
439 (else
440 (with ((radix 10)) (numeric n)))))))
441 (else (lambda (n) (with ((radix 10)) (numeric n)))))))
442 ;; `wr' is the recursive writer closing over the shares.
443 (let wr ((obj obj))
444 (call-with-shared-ref
445 obj shares each
446 (fn ()
447 (cond
448 ((pair? obj)
449 (each "("
450 (fn ()
451 (let lp ((ls obj))
452 (let ((rest (cdr ls)))
453 (each (wr (car ls))
454 (cond
455 ((null? rest)
456 nothing)
457 ((pair? rest)
458 (each
459 " "
460 (call-with-shared-ref/cdr
461 rest shares each
462 (fn () (lp rest)))))
463 (else
464 (each " . " (wr rest))))))))
465 ")"))
466 ((vector? obj)
467 (let ((len (vector-length obj)))
468 (if (zero? len)
469 (displayed "#()")
470 (each "#("
471 (wr (vector-ref obj 0))
472 (fn ()
473 (let lp ((i 1))
474 (if (>= i len)
475 nothing
476 (each " " (wr (vector-ref obj i))
477 (fn () (lp (+ i 1)))))))
478 ")"))))
479 ((number? obj)
480 (write-number obj))
481 (else
482 (displayed (write-to-string obj))))))))))
483
484 ;; The default formatter for `written', overriden with the `writer'
485 ;; variable. Intended to be equivalent to `write', using datum labels
486 ;; for shared notation iff there are cycles in the object.
487
488 (define (written-default obj)
489 (fn ()
490 (write-with-shares obj (extract-shared-objects obj #t))))
491
492 ;; Writes the object showing the full shared structure.
493
494 (define (written-shared obj)
495 (fn ()
496 (write-with-shares obj (extract-shared-objects obj #f))))
497
498 ;; The only expensive part, in both time and memory, of handling
499 ;; shared structures when writing is building the initial table, so
500 ;; for the efficient version we just skip that and re-use the writing
501 ;; code.
502
503 (define (written-simply obj)
504 (fn ()
505 (write-with-shares obj (extract-shared-objects #f #f))))
506
507 ;; Local variables:
508 ;; eval: (put 'fn 'scheme-indent-function 1)
509 ;; End: