Debian Codegraph @

src/libfmt.scm

raw
1 ;;;
2 ;;; libfmt.scm - format
3 ;;;
4 ;;; Copyright (c) 2013-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 (declare) ;; a dummy form to suppress generation of "sci" file
35
36 (define-module gauche.format
37 (use util.match))
38 (select-module gauche.format)
39 (inline-stub
40 (.include "gauche/priv/configP.h"))
41
42 ;; Parsing format string
43 ;; The whole parsing business can be written much cleaner using parser.peg,
44 ;; but we need this as a built-in, so we take low-level approach.
45
46 ;; formatter-lex :: String -> [Directive]
47 ;; Directive = String
48 ;; | (S flags mincol colinc minpad padchar maxcol)
49 ;; | (A flags mincol colinc minpad padchar maxcol)
50 ;; | (C flags)
51 ;; | (W flags)
52 ;; | (D flags mincol padchar commachar interval)
53 ;; | (B flags mincol padchar commachar interval)
54 ;; | (O flags mincol padchar commachar interval)
55 ;; | (X flags mincol padchar commachar interval)
56 ;; | (x flags mincol padchar commachar interval)
57 ;; | (R flags mincol padchar commachar interval)
58 ;; | (r flags mincol padchar commachar interval)
59 ;; | (F flags width digits scale ovfchar padchar)
60 ;; | ($ flags digits pre-digits width padchar)
61 ;; | (* flags count)
62 ;; | (? flags)
63 ;; | (& flags count)
64 ;; | (P flags)
65 ;; | (char flags <char> count) ; single-character insertion
66 ;; | (bra flags) ; ~[, beginning of conditional
67 ;; | (sep flags) ; ~;, separator of conditional
68 ;; | (ket flags) ; ~], end of conditional
69 ;; flags : '() | (Cons #\@ flags) | (Cons #\: flags)
70
71 ;; NB: This procedure is written in a way that all closures can be
72 ;; lifted (by the 0.9.3.3 compiler) so that we avoid runtime closure
73 ;; allocation.
74 (define formatter-lex
75 (let ()
76 (define (fmtstr p) (port-attribute-ref p 'format-string))
77 (define (directive? c)
78 (string-scan "sSaAcCwWdDbBoOxXrR*?fF$~%&pPtT|(){}[];" c))
79 (define directive-param-spec ; (type max-#-of-params [token-id])
80 '((S 5) (A 5) (W 0) (C 0)
81 (D 4) (B 4) (O 4) (X 4) (x 4) (* 1) (R 5) (r 5) (F 5) ($ 4) (? 0)
82 (& 1) (P 0)
83 ;; single-character instertion
84 (~ 1 #\~) (% 1 #\newline) (T 1 #\tab) (|\|| 1 #\page)
85 ;; tokens for structures
86 (|(| 0 paren) (|)| 0 thesis) (|[| 1 bra) (|]| 0 ket)
87 (|{| 0 curly) (|}| 0 brace) (|\;| 0 sep)))
88 (define (flag? c) (memv c '(#\@ #\:)))
89 (define (next p)
90 (rlet1 c (read-char p)
91 (if (eof-object? c)
92 (error "Incomplete format directive in" (fmtstr p)))))
93 (define (char p c)
94 (let loop ([cs (list c)])
95 (let1 c (read-char p)
96 (cond [(eof-object? c) (list (list->string (reverse cs)))]
97 [(eqv? c #\~) (cons (list->string (reverse cs))
98 (directive p (next p)))]
99 [else (loop (cons c cs))]))))
100 ;; NB: this keeps params and flags in reverse order.
101 ;; check-param reverses them.
102 (define (directive p c)
103 (let loop ([params '()] [c c])
104 (receive (param c) (fc-param p c params)
105 (cond [param (loop (cons param params) c)]
106 [(eqv? c #\newline) ;; tilde-newline
107 (if (memq #\@ params)
108 (if (memq #\: params)
109 (error "@ and : flags can't be specified simultaneously \
110 for the ~ + newline directive: " (fmtstr p))
111 (begin (skip-ws p) (cons "\n" (init p)))) ; ~@\newline
112 (if (memq #\: params)
113 (init p) ; ~:\newline
114 (begin (skip-ws p) (init p))))] ; ~\newline
115 [(directive? c)
116 (let1 dir ($ string->symbol $ string
117 $ if (memv c '(#\x #\r)) c (char-upcase c))
118 (acons dir params (init p)))]
119 [else (errorf "Invalid format directive character `~a' in ~s"
120 c (fmtstr p))]))))
121 ;; initial state
122 (define (init p)
123 (let1 c (read-char p)
124 (cond [(eof-object? c) '()]
125 [(eqv? c #\~) (directive p (next p))]
126 [else (char p c)])))
127 ;; parse one parameter, returns it and next char.
128 ;; if we don't have param, return #f as param.
129 (define (fc-param p c params)
130 (if-let1 d (digit->integer c)
131 (and (ensure-noflag p params)
132 (digit-param p d 1))
133 (case c
134 [(#\+ #\-)
135 (ensure-noflag p params)
136 (let1 c (next p)
137 (if-let1 d (digit->integer c)
138 (digit-param p d (if (eqv? c #\+) 1 -1))
139 (errorf "Invalid format directive in ~s" (fmtstr p))))]
140 [(#\') (ensure-noflag p params)
141 (let1 c (next p)
142 (values c (ensure-param-delimiter p (next p))))]
143 [(#\,) (ensure-noflag p params)
144 (values 'empty (next p))]
145 [(#\@ #\:)
146 (when (memv c params)
147 (errorf "Duplicate ~a flag in ~s" c (fmtstr p)))
148 (values c (next p))]
149 [(#\v) (ensure-noflag p params)
150 (values 'variable (ensure-param-delimiter p (next p)))]
151 [else (values #f c)])))
152 (define (ensure-noflag p params)
153 (if (or (memv #\@ params) (memv #\: params))
154 (errorf "Invalid format directive in ~s" (fmtstr p))
155 #t))
156 (define (ensure-param-delimiter p c)
157 (cond [(eqv? c #\,) (next p)]
158 [(or (directive? c) (flag? c)) c]
159 [else(errorf "Invalid format parameter syntax in ~s" (fmtstr p))]))
160 (define (digit-param p val sign)
161 (let loop ([val val])
162 (let1 c (next p)
163 (if-let1 d (digit->integer c)
164 (loop (+ (* val 10) d))
165 (values (* val sign) (ensure-param-delimiter p c))))))
166 ;; for tilde-newline. skip following whitespaces.
167 (define (skip-ws p)
168 (let loop ([c (peek-char p)])
169 (when (char-whitespace? c)
170 (begin (read-char p) (loop (peek-char p))))))
171 ;; Check directive parameters vailidity. This also normalize
172 ;; the use of 'empty. Returns normalized directive.
173 (define (check-param directive p)
174 (if (pair? directive)
175 (receive (flags params)
176 (let outer ([ps (cdr directive)] [fs '()])
177 (cond [(null? ps) (values fs '())]
178 [(flag? (car ps)) (outer (cdr ps) (cons (car ps) fs))]
179 [(eq? (car ps) 'empty) (outer (cdr ps) fs)]
180 [else (values fs (reverse! ps))]))
181 (receive (nparams type)
182 (match (assq (car directive) directive-param-spec)
183 [(_ nparams) (values nparams (car directive))]
184 [(_ nparams dir) (values nparams dir)])
185 (unless (length<=? params nparams)
186 (errorf "Too many parameters for directive `~a' in ~s"
187 (car directive) (fmtstr p)))
188 (if (char? type)
189 (char-node flags params type)
190 (list* type flags params))))
191 directive))
192 ;; single character node optimization
193 (define (char-node flags params char)
194 (cond [(null? params) (string char)]
195 [(integer? (car params)) (make-string (car params) char)]
196 [else (list* 'char flags char params)]))
197
198 ;; Body of formatter-lex
199 (^[format-str]
200 (let1 p (open-input-string format-str)
201 (port-attribute-set! p 'format-string format-str)
202 ;; can be (map (cut check-param <> p) (init p)), but want to avoid
203 ;; closure allocation
204 (let loop ([directives (init p)] [r '()])
205 (if (null? directives)
206 (reverse! r)
207 (loop (cdr directives)
208 (cons (check-param (car directives) p) r))))))))
209
210 ;; formatter-parse :: [Directive] -> Tree
211 ;;
212 ;; Tree = String
213 ;; | (Seq Tree ...)
214 ;; | (S flags mincol colinc minpad padchar maxcol)
215 ;; | (A flags mincol colinc minpad padchar maxcol)
216 ;; | (C flags)
217 ;; | (W flags)
218 ;; | (D flags mincol padchar commachar interval)
219 ;; | (B flags mincol padchar commachar interval)
220 ;; | (O flags mincol padchar commachar interval)
221 ;; | (X flags mincol padchar commachar interval)
222 ;; | (x flags mincol padchar commachar interval)
223 ;; | (F flags width digits scale ovfchar padchar)
224 ;; | ($ flags digits pre-digits width padchar)
225 ;; | (* flags count)
226 ;; | (? flags)
227 ;; | (& flags count)
228 ;; | (P flags)
229 ;; | (char flags <char> count)
230 ;; | (case (Tree ...) Tree)
231 ;; | (if Tree Tree) ; NB: if arg is #f, the first clause is chosen
232 ;; | (maybe Tree)
233 ;;
234 (define formatter-parse
235 (let ()
236 ;; Plain string. Concatenate consecutive strings.
237 (define (string-node node ds)
238 (let loop ([ds ds] [strs (list node)])
239 (match ds
240 [() (values (list (apply string-append (reverse strs))) '())]
241 [((? string? node) . rest) (loop rest (cons node strs))]
242 [_ (receive (trees rest) (parse ds)
243 (values
244 (cons (apply string-append (reverse strs)) trees)
245 rest))])))
246 ;; Non-structured, argument consuming nodes
247 (define (simple-node node ds)
248 (receive (trees rest) (parse ds)
249 (values (cons node trees) rest)))
250 ;; Parsing ~[...~;...~]
251 (define (conditional-node node ds)
252 (receive (tree rest)
253 (match node
254 [(_ ()) (case-tree ds)]
255 [(_ (#\:)) (if-tree ds)]
256 [(_ (#\@)) (maybe-tree ds)]
257 [_ (error "Format directive ~[ may have either : or @ flag, \
258 but not both")])
259 (receive (trees rest) (parse rest)
260 (values (cons tree trees) rest))))
261 (define (case-tree ds)
262 (let loop ([ds ds] [clauses '()] [next-default? #f])
263 (receive (trees rest) (parse ds)
264 (match rest
265 [(('ket . _) . rest)
266 (values (if next-default?
267 `(case ,(reverse clauses) ,(treefy trees))
268 `(case ,(reverse (cons (treefy trees) clauses)) #f))
269 rest)]
270 [(('sep fs) . rest)
271 (when next-default?
272 (error "Extra ~; directive after ~:;"))
273 (loop rest (cons (treefy trees) clauses) (has-:? fs))]
274 [_ (unterminated "~[")]))))
275 (define (if-tree ds)
276 (receive (trees1 rest) (parse ds)
277 (match rest
278 [(('sep . _) . rest)
279 (receive (trees2 rest) (parse rest)
280 (match rest
281 [(('ket . _) . rest)
282 (values `(if ,(treefy trees1) ,(treefy trees2)) rest)]
283 [_ (unterminated "~:[")]))]
284 [_ (unterminated "~:[")])))
285 (define (maybe-tree ds)
286 (receive (trees rest) (parse ds)
287 (match rest
288 [(('ket . _) . rest) (values `(maybe ,(treefy trees)) rest)]
289 [_ (unterminated "~@[")])))
290 ;; [Tree] -> Tree
291 (define (treefy trees)
292 (match trees
293 [(tree) tree]
294 [(tree ...) `(Seq ,@tree)]))
295 (define (unterminated what) (errorf "Unterminated ~a directive" what))
296 ;; master dispatcher. returns [Tree] and the rest of ds.
297 (define (parse ds)
298 (match ds
299 [() (values ds '())]
300 [((? string? s) . rest) (string-node s rest)]
301 [(n . rest)
302 (match n
303 [('bra flags) (conditional-node n rest)]
304 [('ket . _) (values '() ds)]
305 [('sep . _) (values '() ds)]
306 [_ (simple-node n rest)])]))
307 ;; Main body of formatter-parse.
308 ;; (We don't utilize # of parameters yet).
309 (^[directives]
310 (receive (trees rest) (parse directives)
311 (unless (null? rest)
312 (errorf "Unbalanced formatter directive: ~~~a" (caar rest)))
313 (treefy trees)))))
314
315 ;; Runtime
316 ;; Formatters have canonical signature:
317 ;; (ArgPtr, Port, Control) -> ArgPtr
318 ;; ArgPtr is a structure to hold the argument list and the current position.
319
320 ;; ArgPtr
321 ;; +---+---+
322 ;; | . | .-------------------------\
323 ;; +-|-+---+ |
324 ;; | |
325 ;; v |
326 ;; +---+---+ arglist v
327 ;; | . | .------> (arg0 arg1 .... argN ...)
328 ;; +-|-+---+
329 ;; |
330 ;; v
331 ;; ooo-flag
332 ;;
333 ;; ooo-flag (out-of-order flag) indicates whether the argument list
334 ;; is accessed out-of-order, by ~* directive.
335
336 (define (fr-make-argptr args)
337 (cons (cons #f args) args))
338
339 ;; returns current arg, increment argptr.
340 (define (fr-next-arg! fmtstr argptr)
341 (if (null? (cdr argptr))
342 (errorf "Running out arguments for format string ~s" fmtstr)
343 (rlet1 arg (cadr argptr)
344 (set! (cdr argptr) (cddr argptr)))))
345
346 ;; returns the current arg, without changing pointer
347 (define (fr-peek-arg fmtstr argptr)
348 (if (null? (cdr argptr))
349 (errorf "Running out arguments for format string ~s" fmtstr)
350 (cadr argptr)))
351
352 ;; check if we used all args. if we've reordered args, this always succeeds.
353 (define (fr-args-used? argptr)
354 (or (caar argptr)
355 (null? (cdr argptr))))
356
357 (define (fr-jump-arg! argptr k)
358 (if-let1 t (list-tail (cdar argptr) k #f)
359 (begin (set! (cdr argptr) t)
360 (set! (caar argptr) #t))
361 (error "Format argument displacement out of range" k)))
362
363 (define (fr-arg-current-index argptr)
364 (let loop ([k 0] [p (cdar argptr)])
365 (if (eq? (cdr argptr) p)
366 k
367 (loop (+ k 1) (cdr p)))))
368
369 (define (fr-jump-arg-relative! argptr k)
370 (fr-jump-arg! argptr (+ k (fr-arg-current-index argptr))))
371
372 ;; Flag accessors
373 (define-inline (has-@? flags) (memv #\@ flags))
374 (define-inline (has-:? flags) (memv #\: flags))
375 (define-inline (no-flag? flags) (null? flags))
376
377 ;;
378 ;; Formatter generators
379 ;;
380
381 ;; TODO: strict check of invalid params/flags.
382
383 (define (make-format-seq fmtstr formatters)
384 (^[argptr port ctrl] (dolist [f formatters] (f argptr port ctrl))))
385
386 ;; (with-format-params ((var default [check]) ...) body ...)
387 ;; Implicitly refers 'params' and 'fmtstr'.
388 ;; Bounds 'port', 'argptr' and 'ctrl' in body.
389 (define-macro (with-format-params binds . body)
390 (define (gen-extract var default :optional (check #f))
391 `(,var (if (eq? ,var 'empty) ,default ,var)))
392 (define (gen-check var default :optional (check #f))
393 (and check
394 `(unless (and (not (eq? ,var 'variable)) (,check ,var))
395 (error "Bad type of argument for the format parameter ~a: ~s"
396 ',var ,var))))
397 (define (gen-vbind var default :optional (check #f))
398 `(,var
399 (if (eq? ,var 'variable)
400 ,(if check
401 `(rlet1 ,var (fr-next-arg! fmtstr argptr)
402 (unless (,check ,var)
403 (error "Bad type of argument for the format parameter ~a: ~s"
404 ',var ,var)))
405 '(fr-next-arg! fmtstr argptr))
406 ,var)))
407 (let ([binds1 (map (^b `(,(car b) 'empty)) binds)]
408 [binds2 (map ($ apply gen-extract $) binds)]
409 [checks (filter identity (map ($ apply gen-check $) binds))]
410 [vbinds (map ($ apply gen-vbind $) binds)])
411 `(let-optionals* params ,binds1
412 (let* ,binds2
413 ,@checks
414 (if (memq 'variable params)
415 (^[argptr port ctrl]
416 (let* ,vbinds
417 ,@body))
418 (^[argptr port ctrl] ,@body))))))
419
420 ;; ~S, ~A
421 (define (make-format-expr fmtstr params flags printer)
422 (if (null? params)
423 (^[argptr port ctrl]
424 (let1 arg (fr-next-arg! fmtstr argptr)
425 (if ctrl
426 (printer arg port ctrl)
427 (printer arg port))))
428 ($ with-format-params ([mincol 0]
429 [colinc 1]
430 [minpad 0]
431 [padchar #\space]
432 [maxcol #f])
433 ;; TODO: propagate write context from port to sport
434 (let ([sport (open-output-string)]
435 [arg (fr-next-arg! fmtstr argptr)])
436 (when (and (> minpad 0) (has-@? flags))
437 (dotimes [_ minpad] (write-char padchar sport)))
438 (if ctrl
439 (printer arg sport ctrl)
440 (printer arg sport))
441 (when (and (> minpad 0) (not (has-@? flags)))
442 (dotimes [_ minpad] (write-char padchar sport)))
443 (let* ([s (get-output-string sport)]
444 [len (string-length s)])
445 (if (and maxcol (> len maxcol))
446 (chop-and-out s maxcol flags port)
447 (let1 npad (* (ceiling (/ (max (- mincol len) 0) colinc)) colinc)
448 (when (has-@? flags)
449 (dotimes [_ npad] (write-char padchar port)))
450 (display s port)
451 (unless (has-@? flags)
452 (dotimes [_ npad] (write-char padchar port))))))))))
453
454 (define (chop-and-out str limit flags port)
455 ;; check if str chopped at limit contains terminated double-quote.
456 ;; Returns one of the tree values:
457 ;; #t - Double-quote is terminated. No special treatment needed.
458 ;; #f - Double quote is not terminated, and the last character is not
459 ;; a lone backslash. We emit an extra double-quote.
460 ;; #\\ - Double quote is not termianted, and the last character is
461 ;; a lone backslash. In this case, we need to emit extra backslash
462 ;; before the terminating double-quote. Otherwise, the program
463 ;; that interprets the result (e.g. font colorizer) mistakes the
464 ;; closing backquote as escaped.
465 (define (quote-terminated? str limit)
466 (scan-out (open-input-string str) limit))
467 (define (scan-out p limit)
468 (or (<= limit 0)
469 (let1 c (read-char p)
470 (or (eof-object? c)
471 (cond [(eqv? c #\") (scan-in p (- limit 1))]
472 [(eqv? c #\\) (read-char p) (scan-out p (- limit 2))]
473 [else (scan-out p (- limit 1))])))))
474 (define (scan-in p limit)
475 (and (> limit 0)
476 (let1 c (read-char p)
477 (and (not (eof-object? c))
478 (cond [(eqv? c #\") (scan-out p (- limit 1))]
479 [(eqv? c #\\) (read-char p)
480 (if (= limit 1)
481 #\\
482 (scan-in p (- limit 2)))]
483 [else (scan-in p (- limit 1))])))))
484
485 (if (and (has-:? flags) (>= limit 4))
486 (begin (display (substring str 0 (- limit 4)) port)
487 (case (quote-terminated? str (- limit 4))
488 [(#t) (display " ..." port)]
489 [(#f) (display "\"..." port)]
490 [(#\\) (display "\\\".." port)]))
491 (display (substring str 0 limit) port)))
492
493 ;; ~W
494 ;; Without flags, just behave like ~S.
495 ;; With ':'-flag, pretty print.
496 ;; With '@'-flag, remove level and length limits.
497 (define (make-format-pprint fmtstr flags)
498 (let1 ctrl-args
499 (cond-list [(has-:? flags) @ '(:pretty #t :width 79)]
500 [(has-@? flags) @ '(:length #f :level #f)])
501 (^[argptr port ctrl]
502 (let ([arg (fr-next-arg! fmtstr argptr)]
503 [ctrl-args (list* :indent
504 ((with-module gauche.internal port-column) port)
505 ctrl-args)])
506 (write-shared arg port
507 (if ctrl
508 (apply write-controls-copy ctrl ctrl-args)
509 (apply make-write-controls ctrl-args)))))))
510
511 ;; ~C
512 ;; The "spelling out" mode (~:C) isn't supported yet.
513 (define (make-format-char fmtstr flags)
514 (define (char-formatter writer)
515 (^[argptr port ctrl]
516 (let1 c (fr-next-arg! fmtstr argptr)
517 (unless (char? c)
518 (error "Character required for ~c format directive, but got:" c))
519 (writer c port))))
520 (char-formatter (if (has-@? flags) write display)))
521
522 ;; Common in ~X etc. and ~nR
523 (define-inline (format-num-body fmtstr argptr port ctrl radix upcase
524 flags mincol padchar comma interval point)
525 (let* ([arg (fr-next-arg! fmtstr argptr)]
526 [sarg (if (number? arg)
527 (number->string arg radix upcase)
528 (write-to-string arg display))])
529 ;; In CL, ':' and '@' are only honored for exact integers.
530 ;; We honor it on flonums as well.
531 (when (or (exact-integer? arg) (flonum? arg))
532 (when (has-:? flags)
533 (set! sarg (insert-comma-in-digits sarg comma interval point)))
534 (when (and (has-@? flags) (>= arg 0))
535 (set! sarg (string-append "+" sarg))))
536 (let1 len (string-length sarg)
537 (when (< len mincol)
538 (dotimes [_ (- mincol len)] (write-char padchar port)))
539 (display sarg port))))
540
541 ;; ~D, ~B, ~O, ~X, ~nR
542 (define (make-format-num fmtstr params flags radix upcase)
543 (if (and (null? params) (no-flag? flags))
544 (^[argptr port ctrl]
545 (let1 arg (fr-next-arg! fmtstr argptr)
546 (if (exact? arg)
547 (display (number->string arg radix upcase) port)
548 (display arg port))))
549 ($ with-format-params ([mincol 0]
550 [padchar #\space]
551 [comma #\,]
552 [interval 3]
553 [point #\.])
554 (format-num-body fmtstr argptr port ctrl radix upcase
555 flags mincol padchar comma interval point))))
556
557 (define (insert-comma-in-digits str comma interval point)
558 (define (insert s)
559 (let* ([len (string-length s)]
560 [leading (modulo len interval)]
561 [leading (if (and (= leading 1) ;avoid -,100,000 etc.
562 (memv (string-ref s 0) '(#\+ #\-)))
563 (+ leading interval)
564 leading)])
565 (let loop ([x leading]
566 [r (if (zero? leading)
567 '()
568 (list (substring s 0 leading)))])
569 (if (= x len)
570 (string-join (reverse r) (string comma))
571 (loop (+ x interval) (cons (substring s x (+ x interval)) r))))))
572 (receive (pre post) (string-scan str #\. 'both)
573 (if pre
574 (string-append (insert pre) (string point) post)
575 (insert str))))
576
577 ;; ~R
578 (define (make-format-r fmtstr params flags upcase)
579 (if (null? params)
580 (^[argptr port ctrl]
581 (format-numeral-R port
582 (fr-next-arg! fmtstr argptr)
583 (has-@? flags)
584 (has-:? flags)
585 upcase))
586 ($ with-format-params ([radix 10]
587 [mincol 0]
588 [padchar #\space]
589 [comma #\,]
590 [interval 3]
591 [point #\.])
592 (unless (<= 2 radix 36)
593 (error "Formatting ~nR: radix out of range (must be between 2 and 36):"
594 radix))
595 (format-num-body fmtstr argptr port ctrl radix upcase
596 flags mincol padchar comma interval point))))
597
598 ;; ~F, ~E, ~G ; we only support ~F for now
599 ;; kind is 'E 'F or 'G
600 ;; @ flag is used to force plus sign (CL)
601 ;; : flag is used for notational rounding (Gauche only)
602 (define (make-format-flo fmtstr params flags kind)
603 ($ with-format-params ([width 0]
604 [digits -1]
605 [scale 0]
606 [ovchar #f]
607 [padchar #\space])
608 (let1 arg (fr-next-arg! fmtstr argptr)
609 (cond [(real? arg)
610 (flo-fmt (inexact (* arg (expt 10 scale)))
611 width digits 0 ovchar padchar
612 (has-@? flags) (has-:? flags) #f port)]
613 [(complex? arg)
614 (let1 s (call-with-output-string
615 (^p
616 (flo-fmt (* (real-part arg) (expt 10 scale))
617 0 digits 0 ovchar padchar
618 (has-@? flags) (has-:? flags) #f p)
619 (flo-fmt (* (imag-part arg) (expt 10 scale))
620 0 digits 0 ovchar padchar
621 #t (has-:? flags) #f p)
622 (display "i" p)))
623 (let1 len (string-length s)
624 (when (< len width)
625 (dotimes [(- width len)] (write-char padchar port)))
626 (display s port)))]
627 [else
628 (let1 sarg (write-to-string arg display)
629 (let1 len (string-length sarg)
630 (when (< len width)
631 (dotimes [(- width len)] (write-char padchar port)))
632 (display sarg port)))]))))
633
634 ;; ~$ (monetary floating point)
635 ;; The order of parameters and their defaults differ from ~F
636 ;; We use notatational rounding (:-flag is used for sign-front.
637 (define (make-format-currency fmtstr params flags)
638 ($ with-format-params ([digits 2]
639 [pre-digits 1]
640 [width 0]
641 [padchar #\space])
642 (let1 arg (fr-peek-arg fmtstr argptr)
643 (if (real? arg)
644 (flo-fmt (inexact (fr-next-arg! fmtstr argptr))
645 width digits pre-digits
646 #f padchar (has-@? flags) #t (has-:? flags) port)
647 ;; if arg isn't real, use ~wD.
648 (format-num-body fmtstr argptr port ctrl 10 #f
649 '() width #\space #\, 3 #\.)))))
650
651 (define (flo-fmt val width digits pre-digits
652 ovchar padchar plus? notational? sign-front? port)
653 (let* ([s0 (number->string val 10
654 (cond-list
655 [plus? 'plus]
656 [notational? 'notational])
657 digits)]
658 [s (if (> pre-digits 0) ;special for ~$
659 (let* ([m (#/^([+-]?)(\d+)/ s0)]
660 [pre (m 2)])
661 (if (> pre-digits (string-length pre))
662 (string-append
663 (m 1)
664 (make-string (- pre-digits (string-length pre)) #\0)
665 pre (m 'after))
666 s0))
667 s0)]
668 [l (string-length s)])
669 (if (< width l)
670 (if ovchar
671 (dotimes [width] (write-char ovchar port))
672 (display s port))
673 (receive (pre-sign body)
674 (if (and sign-front? (memv (string-ref s 0) '(#\+ #\-)))
675 (values (string-copy s 0 1) (string-copy s 1))
676 (values "" s))
677 (display pre-sign port)
678 (dotimes [(- width l)] (write-char padchar port))
679 (display body port)))))
680
681 ;; ~?
682 (define (make-format-recur fmtstr flags)
683 (define (fcompile str)
684 (unless (string? str)
685 (error "Argument for ~? must be a string, but got" str))
686 ($ formatter-compile-rec str $ formatter-parse $ formatter-lex str))
687 (if (has-@? flags)
688 ;; take
689 (^[argptr port ctrl]
690 (let1 formatter (fcompile (fr-next-arg! fmtstr argptr))
691 (formatter argptr port ctrl)))
692 (^[argptr port ctrl]
693 (let* ([formatter (fcompile (fr-next-arg! fmtstr argptr))]
694 [xargptr (fr-make-argptr (fr-next-arg! fmtstr argptr))])
695 (formatter xargptr port ctrl)))))
696
697 ;; ~*
698 (define (make-format-jump fmtstr params flags)
699 ($ with-format-params ([count 1])
700 (let1 count (if (has-:? flags) (- count) count)
701 (if (has-@? flags)
702 (fr-jump-arg! argptr count)
703 (fr-jump-arg-relative! argptr count)))))
704
705 ;; ~&
706 (define (make-format-fresh-line fmtstr params flags)
707 ($ with-format-params ([count 1])
708 (when (>= count 1)
709 (fresh-line port)
710 (when (>= count 2)
711 (dotimes [(- count 1)] (display "\n" port))))))
712
713 ;; ~P
714 (define (make-format-plural fmtstr flags)
715 (^[argptr port ctl]
716 (when (has-:? flags)
717 (fr-jump-arg-relative! argptr -1))
718 (let1 arg (fr-next-arg! fmtstr argptr)
719 ;; NB: Only exact 1 is singular.
720 (if (eqv? arg 1)
721 (when (has-@? flags)
722 (display "y" port))
723 (if (has-@? flags)
724 (display "ies" port)
725 (display "s" port))))))
726
727 ;; ~t, ~%, ~~, ~|
728 (define (make-format-single fmtstr ch params flags)
729 ($ with-format-params ([count 1])
730 (display (make-string count ch) port)))
731
732 ;; ~[...~;...~]
733 (define (make-format-case fmtstr clauses default-clause)
734 (define branches
735 (map (cut formatter-compile-rec fmtstr <>) clauses))
736 (define fallback
737 (if default-clause
738 (formatter-compile-rec fmtstr default-clause)
739 (^[argptr port ctl] argptr)))
740 (^[argptr port ctl]
741 (let1 arg (fr-next-arg! fmtstr argptr)
742 (unless (exact-integer? arg)
743 (error "Argument for ~[ must be an exact integer, but got" arg))
744 (let1 branch-formatter (list-ref branches arg fallback)
745 (branch-formatter argptr port ctl)))))
746
747 (define (make-format-if fmtstr alternative consequent)
748 (define alt-formatter (formatter-compile-rec fmtstr alternative))
749 (define csq-formatter (formatter-compile-rec fmtstr consequent))
750 (^[argptr port ctl]
751 (let1 arg (fr-next-arg! fmtstr argptr)
752 (if arg
753 (csq-formatter argptr port ctl)
754 (alt-formatter argptr port ctl)))))
755
756 (define (make-format-maybe fmtstr consequent)
757 (define csq-formatter (formatter-compile-rec fmtstr consequent))
758 (^[argptr port ctl]
759 (if-let1 arg (fr-peek-arg fmtstr argptr)
760 (csq-formatter argptr port ctl)
761 (begin (fr-jump-arg! argptr 1)
762 (^[argptr port ctl] argptr)))))
763
764 ;; Tree -> Formatter
765 ;; src : source format string for error message
766 (define (formatter-compile-rec src tree)
767 (match tree
768 [(? string?) (^[a p c] (display tree p))]
769 [(? null?) (^[a p c] #f)]
770 [('Seq . rest) ($ make-format-seq src
771 $ map (cut formatter-compile-rec src <>) rest)]
772 [('S fs . ps) (make-format-expr src ps fs write)]
773 [('A fs . ps) (make-format-expr src ps fs display)]
774 [('C fs . ps) (make-format-char src fs)]
775 [('W fs . ps) (make-format-pprint src fs)]
776 [('D fs . ps) (make-format-num src ps fs 10 #f)]
777 [('B fs . ps) (make-format-num src ps fs 2 #f)]
778 [('O fs . ps) (make-format-num src ps fs 8 #f)]
779 [('x fs . ps) (make-format-num src ps fs 16 #f)]
780 [('X fs . ps) (make-format-num src ps fs 16 #t)]
781 [('F fs . ps) (make-format-flo src ps fs 'F)]
782 [('$ fs . ps) (make-format-currency src ps fs)]
783 [((or 'R 'r) fs . ps) (make-format-r src ps fs (eq? (car tree) 'R))]
784 [('? fs) (make-format-recur src fs)]
785 [('* fs . ps) (make-format-jump src ps fs)]
786 [('& fs . ps) (make-format-fresh-line src ps fs)]
787 [('P fs) (make-format-plural src fs)]
788 [('char fs c . ps) (make-format-single src c ps fs)]
789 [('case cls default) (make-format-case src cls default)]
790 [('if alt csq) (make-format-if src alt csq)]
791 [('maybe csq) (make-format-maybe src csq)]
792 [_ (error "Unsupported formatter directive:" tree)]))
793
794 ;; Toplevel compiler
795 ;; Returns formatter procedure
796 ;; Formatter :: Port, [Arg] -> Void
797 (define (formatter-compile fmtstr)
798 (let1 fmt ($ formatter-compile-rec fmtstr $ formatter-parse
799 $ formatter-lex fmtstr)
800 (^[args port ctrl]
801 (let1 argptr (fr-make-argptr args)
802 (fmt argptr port ctrl)
803 (unless (fr-args-used? argptr)
804 (errorf "Too many arguments given to format string ~s" fmtstr))))))
805
806 (define (call-formatter shared? locking? formatter port ctrl args)
807 (cond [((with-module gauche.internal %port-write-state) port)
808 ;; We're in middle of shared writing.
809 ;; TODO: If we're in the walk pass, all we need to do is to recurse
810 ;; into arguments of aggregate types, so we can make this more
811 ;; efficient than running the full formatter.
812 (formatter args port ctrl)]
813 [shared? ($ (with-module gauche.internal %with-2pass-setup) port
814 formatter formatter args port ctrl)]
815 [locking? (with-port-locking port formatter args port ctrl)]
816 [else (formatter args port ctrl)]))
817
818 (define (format-2 formatter-cache shared? out control fmtstr args)
819 (let1 formatter (if formatter-cache
820 (or (unbox formatter-cache)
821 (rlet1 f (formatter-compile fmtstr)
822 (set-box! formatter-cache f)))
823 (formatter-compile fmtstr))
824 (case out
825 [(#t)
826 (call-formatter shared? #t formatter (current-output-port) control args)]
827 [(#f) (let1 out (open-output-string)
828 (call-formatter shared? #f formatter out control args)
829 (get-output-string out))]
830 [else (call-formatter shared? #t formatter out control args)])))
831
832 ;; This is a bridge to the internal API. Although this isn't exported,
833 ;; inliner or compiler macro may insert a call to this. You shouldn't
834 ;; change the signature across versions.
835 ;;
836 ;; CONTEXT is a list parameters statically constructed during compilation
837 ;; phase. ARGS is the actual parameter list passed.
838 ;;
839 ;; CONTEXT is currently three-argument list:
840 ;; shared? - a flag to distinguish format (#f) and format/ss (#t).
841 ;; literal-str-pos - the position of the first string literal in
842 ;; the actual parameters, up to 2. If the format directive
843 ;; string is a literal, we can cache the formatter.
844 ;; We may not be able to statically determine the format
845 ;; string, because of the optional port/write-controls arguments.
846 ;; formatter-cache - if there's a string literal in the 0, 1 or 2nd argument,
847 ;; the compiler macro allocates a box and passes it.
848 ;; This will be used to cache the formatter.
849 ;;
850 ;; We make CONTEXT a list so that we can extend it in future without changing
851 ;; the signature. Those CONTEXT can be computed at compile-time and becomes
852 ;; a static literal list.
853 (define (format-internal context args)
854 (match-let1 (shared? literal-str-pos format-cache . _) context
855 (let loop ([port 'unseen]
856 [control 'unseen]
857 [as args]
858 [pos 0])
859 (cond [(null? as) (error "format: too few arguments" args)]
860 [(string? (car as))
861 (format-2 (and (eqv? pos literal-str-pos) format-cache)
862 shared?
863 (if (eq? port 'unseen) #f port)
864 (if (eq? control 'unseen) #f control)
865 (car as)
866 (cdr as))]
867 [(or (port? (car as)) (boolean? (car as)))
868 (if (eq? port 'unseen)
869 (loop (car as) control (cdr as) (+ pos 1))
870 (error "format: multiple ports given" args))]
871 [(is-a? (car as) <write-controls>)
872 (if (eq? control 'unseen)
873 (loop port (car as) (cdr as) (+ pos 1))
874 (error "format: multiple controls given" args))]
875 [else (error "format: invalid argument" (car as))]))))
876
877 ;; The external API, format and format/ss, are defined in libmacro.scm.
878 ;; We want to make them hybrid macro, and the definition needs to come
879 ;; after macro system initialization.