Debian Codegraph @

lib/srfi-159/internal/write.scm

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