Make 'primordial-extensions' very primordial.
[sbcl.git] / src / code / target-format.lisp
blob6a2fae731b1798f62fa5d96ec7a2e31ee6bd5f9e
1 ;;;; functions to implement FORMAT and FORMATTER
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!FORMAT")
14 ;;;; FORMAT
16 (defun format (destination control-string &rest format-arguments)
17 #!+sb-doc
18 "Provides various facilities for formatting output.
19 CONTROL-STRING contains a string to be output, possibly with embedded
20 directives, which are flagged with the escape character \"~\". Directives
21 generally expand into additional text to be output, usually consuming one
22 or more of the FORMAT-ARGUMENTS in the process. A few useful directives
23 are:
24 ~A or ~nA Prints one argument as if by PRINC
25 ~S or ~nS Prints one argument as if by PRIN1
26 ~D or ~nD Prints one argument as a decimal integer
27 ~% Does a TERPRI
28 ~& Does a FRESH-LINE
29 where n is the width of the field in which the object is printed.
31 DESTINATION controls where the result will go. If DESTINATION is T, then
32 the output is sent to the standard output stream. If it is NIL, then the
33 output is returned in a string as the value of the call. Otherwise,
34 DESTINATION must be a stream to which the output will be sent.
36 Example: (FORMAT NIL \"The answer is ~D.\" 10) => \"The answer is 10.\"
38 FORMAT has many additional capabilities not described here. Consult the
39 manual for details."
40 (declare (explicit-check))
41 (etypecase destination
42 (null
43 (with-simple-output-to-string (stream)
44 (%format stream control-string format-arguments)))
45 (string
46 (with-simple-output-to-string (stream destination)
47 (%format stream control-string format-arguments)))
48 ((member t)
49 (%format *standard-output* control-string format-arguments)
50 nil)
51 (stream
52 (%format destination control-string format-arguments)
53 nil)))
55 (defun %format (stream string-or-fun orig-args &optional (args orig-args))
56 (if (functionp string-or-fun)
57 (apply string-or-fun stream args)
58 (catch 'up-and-out
59 (let* ((string (etypecase string-or-fun
60 (simple-string
61 string-or-fun)
62 (string
63 (coerce string-or-fun 'simple-string))))
64 (*default-format-error-control-string* string)
65 (*logical-block-popper* nil))
66 (interpret-directive-list stream (tokenize-control-string string)
67 orig-args args)))))
69 (defun interpret-directive-list (stream directives orig-args args)
70 (if directives
71 (let ((directive (car directives)))
72 (etypecase directive
73 (simple-string
74 (write-string directive stream)
75 (interpret-directive-list stream (cdr directives) orig-args args))
76 (format-directive
77 (multiple-value-bind (new-directives new-args)
78 (let* ((character (format-directive-character directive))
79 (function
80 (typecase character
81 (base-char
82 (svref *format-directive-interpreters* (char-code character)))))
83 (*default-format-error-offset*
84 (1- (format-directive-end directive))))
85 (unless function
86 (error 'format-error
87 :complaint "unknown format directive ~@[(character: ~A)~]"
88 :args (list (char-name character))))
89 (multiple-value-bind (new-directives new-args)
90 (funcall function stream directive
91 (cdr directives) orig-args args)
92 (values new-directives new-args)))
93 (interpret-directive-list stream new-directives
94 orig-args new-args)))))
95 args))
97 ;;;; FORMAT directive definition macros and runtime support
99 (eval-when (:compile-toplevel :execute)
101 ;;; This macro is used to extract the next argument from the current arg list.
102 ;;; This is the version used by format directive interpreters.
103 (sb!xc:defmacro next-arg (&optional offset)
104 `(progn
105 (when (null args)
106 (error 'format-error
107 :complaint "no more arguments"
108 ,@(when offset
109 `(:offset ,offset))))
110 (when *logical-block-popper*
111 (funcall *logical-block-popper*))
112 (pop args)))
114 (sb!xc:defmacro def-complex-format-interpreter (char lambda-list &body body)
115 (let ((defun-name
116 (intern (format nil
117 "~:@(~:C~)-FORMAT-DIRECTIVE-INTERPRETER"
118 char)))
119 (directive (sb!xc:gensym "DIRECTIVE"))
120 (directives (if lambda-list (car (last lambda-list)) (sb!xc:gensym "DIRECTIVES"))))
121 `(progn
122 (defun ,defun-name (stream ,directive ,directives orig-args args)
123 (declare (ignorable stream orig-args args))
124 ,@(if lambda-list
125 `((let ,(mapcar (lambda (var)
126 `(,var
127 (,(symbolicate "FORMAT-DIRECTIVE-" var)
128 ,directive)))
129 (butlast lambda-list))
130 (values (progn ,@body) args)))
131 `((declare (ignore ,directive ,directives))
132 ,@body)))
133 (%set-format-directive-interpreter ,char #',defun-name))))
135 (sb!xc:defmacro def-format-interpreter (char lambda-list &body body)
136 (let ((directives (sb!xc:gensym "DIRECTIVES")))
137 `(def-complex-format-interpreter ,char (,@lambda-list ,directives)
138 ,@body
139 ,directives)))
141 (sb!xc:defmacro interpret-bind-defaults (specs params &body body)
142 (once-only ((params params))
143 (collect ((bindings))
144 (dolist (spec specs)
145 (destructuring-bind (var default) spec
146 (bindings `(,var (let* ((param-and-offset (pop ,params))
147 (offset (car param-and-offset))
148 (param (cdr param-and-offset)))
149 (case param
150 (:arg (or (next-arg offset) ,default))
151 (:remaining (length args))
152 ((nil) ,default)
153 (t param)))))))
154 `(let* ,(bindings)
155 (when ,params
156 (error 'format-error
157 :complaint
158 "too many parameters, expected no more than ~W"
159 :args (list ,(length specs))
160 :offset (caar ,params)))
161 ,@body))))
163 ) ; EVAL-WHEN
165 ;;;; format interpreters and support functions for simple output
167 (defun format-write-field (stream string mincol colinc minpad padchar padleft)
168 (when (and colinc (<= colinc 0))
169 (error 'format-error
170 :complaint "The value of colinc is ~a, should be a positive integer"
171 :args (list colinc)))
172 (when (and mincol (< mincol 0))
173 (error 'format-error
174 :complaint "The value of mincol is ~a, should be a non-negative integer"
175 :args (list mincol)))
176 (unless padleft
177 (write-string string stream))
178 (dotimes (i minpad)
179 (write-char padchar stream))
180 ;; As of sbcl-0.6.12.34, we could end up here when someone tries to
181 ;; print e.g. (FORMAT T "~F" "NOTFLOAT"), in which case ANSI says
182 ;; we're supposed to soldier on bravely, and so we have to deal with
183 ;; the unsupplied-MINCOL-and-COLINC case without blowing up.
184 (when (and mincol colinc)
185 (do ((chars (+ (length string) (max minpad 0)) (+ chars colinc)))
186 ((>= chars mincol))
187 (dotimes (i colinc)
188 (write-char padchar stream))))
189 (when padleft
190 (write-string string stream)))
192 (defun format-princ (stream arg colonp atsignp mincol colinc minpad padchar)
193 (format-write-field stream
194 (if (or arg (not colonp))
195 (princ-to-string arg)
196 "()")
197 mincol colinc minpad padchar atsignp))
199 (def-format-interpreter #\A (colonp atsignp params)
200 (if params
201 (interpret-bind-defaults ((mincol 0) (colinc 1) (minpad 0)
202 (padchar #\space))
203 params
204 (format-princ stream (next-arg) colonp atsignp
205 mincol colinc minpad padchar))
206 (princ (if colonp (or (next-arg) "()") (next-arg)) stream)))
208 (defun format-prin1 (stream arg colonp atsignp mincol colinc minpad padchar)
209 (format-write-field stream
210 (if (or arg (not colonp))
211 (prin1-to-string arg)
212 "()")
213 mincol colinc minpad padchar atsignp))
215 (def-format-interpreter #\S (colonp atsignp params)
216 (cond (params
217 (interpret-bind-defaults ((mincol 0) (colinc 1) (minpad 0)
218 (padchar #\space))
219 params
220 (format-prin1 stream (next-arg) colonp atsignp
221 mincol colinc minpad padchar)))
222 (colonp
223 (let ((arg (next-arg)))
224 (if arg
225 (prin1 arg stream)
226 (princ "()" stream))))
228 (prin1 (next-arg) stream))))
230 (def-format-interpreter #\C (colonp atsignp params)
231 (interpret-bind-defaults () params
232 (let ((arg (next-arg)))
233 (unless (typep arg 'character)
234 (error 'format-error
235 :complaint "~s is not of type CHARACTER."
236 :args (list arg)))
237 (cond (colonp
238 (format-print-named-character arg stream))
239 (atsignp
240 (prin1 arg stream))
242 (write-char arg stream))))))
244 ;;; "printing" as defined in the ANSI CL glossary, which is normative.
245 (defun char-printing-p (char)
246 (and (not (eql char #\Space))
247 (graphic-char-p char)))
249 (defun format-print-named-character (char stream)
250 (cond ((not (char-printing-p char))
251 (write-string (string-capitalize (char-name char)) stream))
253 (write-char char stream))))
255 (def-format-interpreter #\W (colonp atsignp params)
256 (interpret-bind-defaults () params
257 (let ((*print-pretty* (or colonp *print-pretty*))
258 (*print-level* (unless atsignp *print-level*))
259 (*print-length* (unless atsignp *print-length*)))
260 (output-object (next-arg) stream))))
262 ;;;; format interpreters and support functions for integer output
264 ;;; FORMAT-PRINT-NUMBER does most of the work for the numeric printing
265 ;;; directives. The parameters are interpreted as defined for ~D.
266 (defun format-print-integer (stream number print-commas-p print-sign-p
267 radix mincol padchar commachar commainterval)
268 (let ((*print-base* radix)
269 (*print-radix* nil))
270 (if (integerp number)
271 (let* ((text (princ-to-string (abs number)))
272 (commaed (if print-commas-p
273 (format-add-commas text commachar commainterval)
274 text))
275 (signed (cond ((minusp number)
276 (concatenate 'string "-" commaed))
277 (print-sign-p
278 (concatenate 'string "+" commaed))
279 (t commaed))))
280 ;; colinc = 1, minpad = 0, padleft = t
281 (format-write-field stream signed mincol 1 0 padchar t))
282 (princ number stream))))
284 (defun format-add-commas (string commachar commainterval)
285 (let ((length (length string)))
286 (multiple-value-bind (commas extra) (truncate (1- length) commainterval)
287 (let ((new-string (make-string (+ length commas)))
288 (first-comma (1+ extra)))
289 (replace new-string string :end1 first-comma :end2 first-comma)
290 (do ((src first-comma (+ src commainterval))
291 (dst first-comma (+ dst commainterval 1)))
292 ((= src length))
293 (setf (schar new-string dst) commachar)
294 (replace new-string string :start1 (1+ dst)
295 :start2 src :end2 (+ src commainterval)))
296 new-string))))
298 (eval-when (:compile-toplevel :execute)
299 (sb!xc:defmacro interpret-format-integer (base)
300 `(if (or colonp atsignp params)
301 (interpret-bind-defaults
302 ((mincol 0) (padchar #\space) (commachar #\,) (commainterval 3))
303 params
304 (format-print-integer stream (next-arg) colonp atsignp ,base mincol
305 padchar commachar commainterval))
306 (let ((*print-base* ,base)
307 (*print-radix* nil))
308 (princ (next-arg) stream))))
309 ) ; EVAL-WHEN
311 (def-format-interpreter #\D (colonp atsignp params)
312 (interpret-format-integer 10))
314 (def-format-interpreter #\B (colonp atsignp params)
315 (interpret-format-integer 2))
317 (def-format-interpreter #\O (colonp atsignp params)
318 (interpret-format-integer 8))
320 (def-format-interpreter #\X (colonp atsignp params)
321 (interpret-format-integer 16))
323 (def-format-interpreter #\R (colonp atsignp params)
324 (interpret-bind-defaults
325 ((base nil) (mincol 0) (padchar #\space) (commachar #\,)
326 (commainterval 3))
327 params
328 (let ((arg (next-arg)))
329 (unless (or base
330 (integerp arg))
331 (error 'format-error
332 :complaint "~s is not of type INTEGER."
333 :args (list arg)))
334 (if base
335 (format-print-integer stream arg colonp atsignp base mincol
336 padchar commachar commainterval)
337 (if atsignp
338 (if colonp
339 (format-print-old-roman stream arg)
340 (format-print-roman stream arg))
341 (if colonp
342 (format-print-ordinal stream arg)
343 (format-print-cardinal stream arg)))))))
345 (defparameter *cardinal-ones*
346 #(nil "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"))
348 (defparameter *cardinal-tens*
349 #(nil nil "twenty" "thirty" "forty"
350 "fifty" "sixty" "seventy" "eighty" "ninety"))
352 (defparameter *cardinal-teens*
353 #("ten" "eleven" "twelve" "thirteen" "fourteen" ;;; RAD
354 "fifteen" "sixteen" "seventeen" "eighteen" "nineteen"))
356 (defparameter *cardinal-periods*
357 #("" " thousand" " million" " billion" " trillion" " quadrillion"
358 " quintillion" " sextillion" " septillion" " octillion" " nonillion"
359 " decillion" " undecillion" " duodecillion" " tredecillion"
360 " quattuordecillion" " quindecillion" " sexdecillion" " septendecillion"
361 " octodecillion" " novemdecillion" " vigintillion"))
363 (defparameter *ordinal-ones*
364 #(nil "first" "second" "third" "fourth"
365 "fifth" "sixth" "seventh" "eighth" "ninth"))
367 (defparameter *ordinal-tens*
368 #(nil "tenth" "twentieth" "thirtieth" "fortieth"
369 "fiftieth" "sixtieth" "seventieth" "eightieth" "ninetieth"))
371 (defun format-print-small-cardinal (stream n)
372 (multiple-value-bind (hundreds rem) (truncate n 100)
373 (when (plusp hundreds)
374 (write-string (svref *cardinal-ones* hundreds) stream)
375 (write-string " hundred" stream)
376 (when (plusp rem)
377 (write-char #\space stream)))
378 (when (plusp rem)
379 (multiple-value-bind (tens ones) (truncate rem 10)
380 (cond ((< 1 tens)
381 (write-string (svref *cardinal-tens* tens) stream)
382 (when (plusp ones)
383 (write-char #\- stream)
384 (write-string (svref *cardinal-ones* ones) stream)))
385 ((= tens 1)
386 (write-string (svref *cardinal-teens* ones) stream))
387 ((plusp ones)
388 (write-string (svref *cardinal-ones* ones) stream)))))))
390 (defun format-print-cardinal (stream n)
391 (cond ((minusp n)
392 (write-string "negative " stream)
393 (format-print-cardinal-aux stream (- n) 0 n))
394 ((zerop n)
395 (write-string "zero" stream))
397 (format-print-cardinal-aux stream n 0 n))))
399 (defun format-print-cardinal-aux (stream n period err)
400 (multiple-value-bind (beyond here) (truncate n 1000)
401 (unless (<= period 21)
402 (error "number too large to print in English: ~:D" err))
403 (unless (zerop beyond)
404 (format-print-cardinal-aux stream beyond (1+ period) err))
405 (unless (zerop here)
406 (unless (zerop beyond)
407 (write-char #\space stream))
408 (format-print-small-cardinal stream here)
409 (write-string (svref *cardinal-periods* period) stream))))
411 (defun format-print-ordinal (stream n)
412 (when (minusp n)
413 (write-string "negative " stream))
414 (let ((number (abs n)))
415 (multiple-value-bind (top bot) (truncate number 100)
416 (unless (zerop top)
417 (format-print-cardinal stream (- number bot)))
418 (when (and (plusp top) (plusp bot))
419 (write-char #\space stream))
420 (multiple-value-bind (tens ones) (truncate bot 10)
421 (cond ((= bot 12) (write-string "twelfth" stream))
422 ((= tens 1)
423 (write-string (svref *cardinal-teens* ones) stream);;;RAD
424 (write-string "th" stream))
425 ((and (zerop tens) (plusp ones))
426 (write-string (svref *ordinal-ones* ones) stream))
427 ((and (zerop ones)(plusp tens))
428 (write-string (svref *ordinal-tens* tens) stream))
429 ((plusp bot)
430 (write-string (svref *cardinal-tens* tens) stream)
431 (write-char #\- stream)
432 (write-string (svref *ordinal-ones* ones) stream))
433 ((plusp number)
434 (write-string "th" stream))
436 (write-string "zeroth" stream)))))))
438 ;;; Print Roman numerals
440 (defun format-print-old-roman (stream n)
441 (unless (< 0 n 5000)
442 (error "Number too large to print in old Roman numerals: ~:D" n))
443 (do ((char-list '(#\D #\C #\L #\X #\V #\I) (cdr char-list))
444 (val-list '(500 100 50 10 5 1) (cdr val-list))
445 (cur-char #\M (car char-list))
446 (cur-val 1000 (car val-list))
447 (start n (do ((i start (progn
448 (write-char cur-char stream)
449 (- i cur-val))))
450 ((< i cur-val) i))))
451 ((zerop start))))
453 (defun format-print-roman (stream n)
454 (unless (< 0 n 4000)
455 (error "Number too large to print in Roman numerals: ~:D" n))
456 (do ((char-list '(#\D #\C #\L #\X #\V #\I) (cdr char-list))
457 (val-list '(500 100 50 10 5 1) (cdr val-list))
458 (sub-chars '(#\C #\X #\X #\I #\I) (cdr sub-chars))
459 (sub-val '(100 10 10 1 1 0) (cdr sub-val))
460 (cur-char #\M (car char-list))
461 (cur-val 1000 (car val-list))
462 (cur-sub-char #\C (car sub-chars))
463 (cur-sub-val 100 (car sub-val))
464 (start n (do ((i start (progn
465 (write-char cur-char stream)
466 (- i cur-val))))
467 ((< i cur-val)
468 (cond ((<= (- cur-val cur-sub-val) i)
469 (write-char cur-sub-char stream)
470 (write-char cur-char stream)
471 (- i (- cur-val cur-sub-val)))
472 (t i))))))
473 ((zerop start))))
475 ;;;; plural
477 (def-format-interpreter #\P (colonp atsignp params)
478 (interpret-bind-defaults () params
479 (let ((arg (if colonp
480 (if (eq orig-args args)
481 (error 'format-error
482 :complaint "no previous argument")
483 (do ((arg-ptr orig-args (cdr arg-ptr)))
484 ((eq (cdr arg-ptr) args)
485 (car arg-ptr))))
486 (next-arg))))
487 (if atsignp
488 (write-string (if (eql arg 1) "y" "ies") stream)
489 (unless (eql arg 1) (write-char #\s stream))))))
491 ;;;; format interpreters and support functions for floating point output
493 (defun decimal-string (n)
494 (write-to-string n :base 10 :radix nil :escape nil))
496 (def-format-interpreter #\F (colonp atsignp params)
497 (when colonp
498 (error 'format-error
499 :complaint
500 "cannot specify the colon modifier with this directive"))
501 (interpret-bind-defaults ((w nil) (d nil) (k nil) (ovf nil) (pad #\space))
502 params
503 (format-fixed stream (next-arg) w d k ovf pad atsignp)))
505 (defun format-fixed (stream number w d k ovf pad atsign)
506 (typecase number
507 (float
508 (format-fixed-aux stream number w d k ovf pad atsign))
509 (rational
510 (format-fixed-aux stream (coerce number 'single-float)
511 w d k ovf pad atsign))
512 (number
513 (format-write-field stream (decimal-string number) w 1 0 #\space t))
515 (let ((*print-base* 10))
516 (format-princ stream number nil nil w 1 0 pad)))))
518 ;;; We return true if we overflowed, so that ~G can output the overflow char
519 ;;; instead of spaces.
520 (defun format-fixed-aux (stream number w d k ovf pad atsign)
521 (declare (type float number))
522 (cond
523 ((or (float-infinity-p number)
524 (float-nan-p number))
525 (prin1 number stream)
526 nil)
528 (sb!impl::string-dispatch (single-float double-float)
529 number
530 (let ((spaceleft w))
531 (when (and w (or atsign (minusp (float-sign number))))
532 (decf spaceleft))
533 (multiple-value-bind (str len lpoint tpoint)
534 (sb!impl::flonum-to-string (abs number) spaceleft d k)
535 ;; if caller specifically requested no fraction digits, suppress the
536 ;; optional trailing zero
537 (when (and d (zerop d))
538 (setq tpoint nil))
539 (when w
540 (decf spaceleft len)
541 ;; optional leading zero
542 (when lpoint
543 (if (or (> spaceleft 0) tpoint) ;force at least one digit
544 (decf spaceleft)
545 (setq lpoint nil)))
546 ;; optional trailing zero
547 (when tpoint
548 (if (> spaceleft 0)
549 (decf spaceleft)
550 (setq tpoint nil))))
551 (cond ((and w (< spaceleft 0) ovf)
552 ;; field width overflow
553 (dotimes (i w)
554 (write-char ovf stream))
557 (when w
558 (dotimes (i spaceleft)
559 (write-char pad stream)))
560 (if (minusp (float-sign number))
561 (write-char #\- stream)
562 (when atsign
563 (write-char #\+ stream)))
564 (when lpoint
565 (write-char #\0 stream))
566 (write-string str stream)
567 (when tpoint
568 (write-char #\0 stream))
569 nil))))))))
571 (def-format-interpreter #\E (colonp atsignp params)
572 (when colonp
573 (error 'format-error
574 :complaint
575 "cannot specify the colon modifier with this directive"))
576 (interpret-bind-defaults
577 ((w nil) (d nil) (e nil) (k 1) (ovf nil) (pad #\space) (mark nil))
578 params
579 (format-exponential stream (next-arg) w d e k ovf pad mark atsignp)))
581 (defun format-exponential (stream number w d e k ovf pad marker atsign)
582 (if (numberp number)
583 (if (floatp number)
584 (format-exp-aux stream number w d e k ovf pad marker atsign)
585 (if (rationalp number)
586 (format-exp-aux stream
587 (coerce number 'single-float)
588 w d e k ovf pad marker atsign)
589 (format-write-field stream
590 (decimal-string number)
591 w 1 0 #\space t)))
592 (let ((*print-base* 10))
593 (format-princ stream number nil nil w 1 0 pad))))
595 (defun format-exponent-marker (number)
596 (if (typep number *read-default-float-format*)
598 (typecase number
599 (single-float #\f)
600 (double-float #\d)
601 (short-float #\s)
602 (long-float #\l))))
604 ;;; Here we prevent the scale factor from shifting all significance out of
605 ;;; a number to the right. We allow insignificant zeroes to be shifted in
606 ;;; to the left right, athough it is an error to specify k and d such that this
607 ;;; occurs. Perhaps we should detect both these condtions and flag them as
608 ;;; errors. As for now, we let the user get away with it, and merely guarantee
609 ;;; that at least one significant digit will appear.
611 ;;; Raymond Toy writes: The Hyperspec seems to say that the exponent
612 ;;; marker is always printed. Make it so. Also, the original version
613 ;;; causes errors when printing infinities or NaN's. The Hyperspec is
614 ;;; silent here, so let's just print out infinities and NaN's instead
615 ;;; of causing an error.
616 (defun format-exp-aux (stream number w d e k ovf pad marker atsign)
617 (declare (type float number))
618 (if (or (float-infinity-p number)
619 (float-nan-p number))
620 (prin1 number stream)
621 (multiple-value-bind (num expt) (sb!impl::scale-exponent (abs number))
622 (let* ((k (if (= num 1.0) (1- k) k))
623 (expt (- expt k))
624 (estr (decimal-string (abs expt)))
625 (elen (if e (max (length estr) e) (length estr)))
626 spaceleft)
627 (when w
628 (setf spaceleft (- w 2 elen))
629 (when (or atsign (minusp (float-sign number)))
630 (decf spaceleft)))
631 (if (and w ovf e (> elen e)) ;exponent overflow
632 (dotimes (i w) (write-char ovf stream))
633 (let* ((fdig (if d (if (plusp k) (1+ (- d k)) d) nil))
634 (fmin (if (minusp k) 1 fdig)))
635 (multiple-value-bind (fstr flen lpoint tpoint)
636 (sb!impl::flonum-to-string num spaceleft fdig k fmin)
637 (when (and d (zerop d)) (setq tpoint nil))
638 (when w
639 (decf spaceleft flen)
640 (when lpoint
641 (if (or (> spaceleft 0) tpoint)
642 (decf spaceleft)
643 (setq lpoint nil)))
644 (when (and tpoint (<= spaceleft 0))
645 (setq tpoint nil)))
646 (cond ((and w (< spaceleft 0) ovf)
647 ;;significand overflow
648 (dotimes (i w) (write-char ovf stream)))
649 (t (when w
650 (dotimes (i spaceleft) (write-char pad stream)))
651 (if (minusp (float-sign number))
652 (write-char #\- stream)
653 (if atsign (write-char #\+ stream)))
654 (when lpoint (write-char #\0 stream))
655 (write-string fstr stream)
656 (write-char (if marker
657 marker
658 (format-exponent-marker number))
659 stream)
660 (write-char (if (minusp expt) #\- #\+) stream)
661 (when e
662 ;;zero-fill before exponent if necessary
663 (dotimes (i (- e (length estr)))
664 (write-char #\0 stream)))
665 (write-string estr stream))))))))))
667 (def-format-interpreter #\G (colonp atsignp params)
668 (when colonp
669 (error 'format-error
670 :complaint
671 "cannot specify the colon modifier with this directive"))
672 (interpret-bind-defaults
673 ((w nil) (d nil) (e nil) (k nil) (ovf nil) (pad #\space) (mark nil))
674 params
675 (format-general stream (next-arg) w d e k ovf pad mark atsignp)))
677 (defun format-general (stream number w d e k ovf pad marker atsign)
678 (if (numberp number)
679 (if (floatp number)
680 (format-general-aux stream number w d e k ovf pad marker atsign)
681 (if (rationalp number)
682 (format-general-aux stream
683 (coerce number 'single-float)
684 w d e k ovf pad marker atsign)
685 (format-write-field stream
686 (decimal-string number)
687 w 1 0 #\space t)))
688 (let ((*print-base* 10))
689 (format-princ stream number nil nil w 1 0 pad))))
691 ;;; Raymond Toy writes: same change as for format-exp-aux
692 (defun format-general-aux (stream number w d e k ovf pad marker atsign)
693 (declare (type float number))
694 (if (or (float-infinity-p number)
695 (float-nan-p number))
696 (prin1 number stream)
697 (multiple-value-bind (ignore n) (sb!impl::scale-exponent (abs number))
698 (declare (ignore ignore))
699 ;; KLUDGE: Default d if omitted. The procedure is taken directly from
700 ;; the definition given in the manual, and is not very efficient, since
701 ;; we generate the digits twice. Future maintainers are encouraged to
702 ;; improve on this. -- rtoy?? 1998??
703 (unless d
704 (multiple-value-bind (str len)
705 (sb!impl::flonum-to-string (abs number))
706 (declare (ignore str))
707 (let ((q (if (= len 1) 1 (1- len))))
708 (setq d (max q (min n 7))))))
709 (let* ((ee (if e (+ e 2) 4))
710 (ww (if w (- w ee) nil))
711 (dd (- d n)))
712 (cond ((<= 0 dd d)
713 (let ((char (if (format-fixed-aux stream number ww dd nil
714 ovf pad atsign)
716 #\space)))
717 (dotimes (i ee) (write-char char stream))))
719 (format-exp-aux stream number w d e (or k 1)
720 ovf pad marker atsign)))))))
722 (def-format-interpreter #\$ (colonp atsignp params)
723 (interpret-bind-defaults ((d 2) (n 1) (w 0) (pad #\space)) params
724 (format-dollars stream (next-arg) d n w pad colonp atsignp)))
726 (defun format-dollars (stream number d n w pad colon atsign)
727 (when (rationalp number)
728 ;; This coercion to SINGLE-FLOAT seems as though it gratuitously
729 ;; loses precision (why not LONG-FLOAT?) but it's the default
730 ;; behavior in the ANSI spec, so in some sense it's the right
731 ;; thing, and at least the user shouldn't be surprised.
732 (setq number (coerce number 'single-float)))
733 (if (floatp number)
734 (let* ((signstr (if (minusp (float-sign number))
736 (if atsign "+" "")))
737 (signlen (length signstr)))
738 (multiple-value-bind (str strlen ig2 ig3 pointplace)
739 (sb!impl::flonum-to-string number nil d nil)
740 (declare (ignore ig2 ig3 strlen))
741 (when colon
742 (write-string signstr stream))
743 (dotimes (i (- w signlen (max n pointplace) 1 d))
744 (write-char pad stream))
745 (unless colon
746 (write-string signstr stream))
747 (dotimes (i (- n pointplace))
748 (write-char #\0 stream))
749 (write-string str stream)))
750 (let ((*print-base* 10))
751 (format-write-field stream
752 (princ-to-string number)
753 w 1 0 #\space t))))
755 ;;;; FORMAT interpreters and support functions for line/page breaks etc.
757 (def-format-interpreter #\% (colonp atsignp params)
758 (when (or colonp atsignp)
759 (error 'format-error
760 :complaint
761 "cannot specify either colon or atsign for this directive"))
762 (interpret-bind-defaults ((count 1)) params
763 (dotimes (i count)
764 (terpri stream))))
766 (def-format-interpreter #\& (colonp atsignp params)
767 (when (or colonp atsignp)
768 (error 'format-error
769 :complaint
770 "cannot specify either colon or atsign for this directive"))
771 (interpret-bind-defaults ((count 1)) params
772 (when (plusp count)
773 (fresh-line stream)
774 (dotimes (i (1- count))
775 (terpri stream)))))
777 (def-format-interpreter #\| (colonp atsignp params)
778 (when (or colonp atsignp)
779 (error 'format-error
780 :complaint
781 "cannot specify either colon or atsign for this directive"))
782 (interpret-bind-defaults ((count 1)) params
783 (dotimes (i count)
784 (write-char (code-char form-feed-char-code) stream))))
786 (def-format-interpreter #\~ (colonp atsignp params)
787 (when (or colonp atsignp)
788 (error 'format-error
789 :complaint
790 "cannot specify either colon or atsign for this directive"))
791 (interpret-bind-defaults ((count 1)) params
792 (dotimes (i count)
793 (write-char #\~ stream))))
795 (def-complex-format-interpreter #\newline (colonp atsignp params directives)
796 (when (and colonp atsignp)
797 (error 'format-error
798 :complaint
799 "cannot specify both colon and atsign for this directive"))
800 (interpret-bind-defaults () params
801 (when atsignp
802 (write-char #\newline stream)))
803 (if (and (not colonp)
804 directives
805 (simple-string-p (car directives)))
806 (cons (string-left-trim *format-whitespace-chars*
807 (car directives))
808 (cdr directives))
809 directives))
811 ;;;; format interpreters and support functions for tabs and simple pretty
812 ;;;; printing
814 (def-format-interpreter #\T (colonp atsignp params)
815 (if colonp
816 (interpret-bind-defaults ((n 1) (m 1)) params
817 (pprint-tab (if atsignp :section-relative :section) n m stream))
818 (if atsignp
819 (interpret-bind-defaults ((colrel 1) (colinc 1)) params
820 (format-relative-tab stream colrel colinc))
821 (interpret-bind-defaults ((colnum 1) (colinc 1)) params
822 (format-absolute-tab stream colnum colinc)))))
824 (defun output-spaces (stream n)
825 (let ((spaces #.(make-string 100 :initial-element #\space)))
826 (loop
827 (when (< n (length spaces))
828 (return))
829 (write-string spaces stream)
830 (decf n (length spaces)))
831 (write-string spaces stream :end n)))
833 (defun format-relative-tab (stream colrel colinc)
834 (if (sb!pretty:pretty-stream-p stream)
835 (pprint-tab :line-relative colrel colinc stream)
836 (let* ((cur (sb!impl::charpos stream))
837 (spaces (if (and cur (plusp colinc))
838 (- (* (ceiling (+ cur colrel) colinc) colinc) cur)
839 colrel)))
840 (output-spaces stream spaces))))
842 (defun format-absolute-tab (stream colnum colinc)
843 (if (sb!pretty:pretty-stream-p stream)
844 (pprint-tab :line colnum colinc stream)
845 (let ((cur (sb!impl::charpos stream)))
846 (cond ((null cur)
847 (write-string " " stream))
848 ((< cur colnum)
849 (output-spaces stream (- colnum cur)))
851 (unless (zerop colinc)
852 (output-spaces stream
853 (- colinc (rem (- cur colnum) colinc)))))))))
855 (def-format-interpreter #\_ (colonp atsignp params)
856 (interpret-bind-defaults () params
857 (pprint-newline (if colonp
858 (if atsignp
859 :mandatory
860 :fill)
861 (if atsignp
862 :miser
863 :linear))
864 stream)))
866 (def-format-interpreter #\I (colonp atsignp params)
867 (when atsignp
868 (error 'format-error
869 :complaint "cannot specify the at-sign modifier"))
870 (interpret-bind-defaults ((n 0)) params
871 (pprint-indent (if colonp :current :block) n stream)))
873 ;;;; format interpreter for ~*
875 (def-format-interpreter #\* (colonp atsignp params)
876 (if atsignp
877 (if colonp
878 (error 'format-error
879 :complaint "cannot specify both colon and at-sign")
880 (interpret-bind-defaults ((posn 0)) params
881 (if (<= 0 posn (length orig-args))
882 (setf args (nthcdr posn orig-args))
883 (error 'format-error
884 :complaint "Index ~W is out of bounds. (It should ~
885 have been between 0 and ~W.)"
886 :args (list posn (length orig-args))))))
887 (if colonp
888 (interpret-bind-defaults ((n 1)) params
889 (do ((cur-posn 0 (1+ cur-posn))
890 (arg-ptr orig-args (cdr arg-ptr)))
891 ((eq arg-ptr args)
892 (let ((new-posn (- cur-posn n)))
893 (if (<= 0 new-posn (length orig-args))
894 (setf args (nthcdr new-posn orig-args))
895 (error 'format-error
896 :complaint
897 "Index ~W is out of bounds. (It should
898 have been between 0 and ~W.)"
899 :args
900 (list new-posn (length orig-args))))))))
901 (interpret-bind-defaults ((n 1)) params
902 (dotimes (i n)
903 (next-arg))))))
905 ;;;; format interpreter for indirection
907 (def-format-interpreter #\? (colonp atsignp params string end)
908 (when colonp
909 (error 'format-error
910 :complaint "cannot specify the colon modifier"))
911 (interpret-bind-defaults () params
912 (handler-bind
913 ((format-error
914 (lambda (condition)
915 (error 'format-error
916 :complaint
917 "~A~%while processing indirect format string:"
918 :args (list condition)
919 :print-banner nil
920 :control-string string
921 :offset (1- end)))))
922 (if atsignp
923 (setf args (%format stream (next-arg) orig-args args))
924 (%format stream (next-arg) (next-arg))))))
926 ;;;; format interpreters for capitalization
928 (def-complex-format-interpreter #\( (colonp atsignp params directives)
929 (let ((close (find-directive directives #\) nil)))
930 (unless close
931 (error 'format-error
932 :complaint "no corresponding close paren"))
933 (interpret-bind-defaults () params
934 (let* ((posn (position close directives))
935 (before (subseq directives 0 posn))
936 (after (nthcdr (1+ posn) directives))
937 (stream (make-case-frob-stream stream
938 (if colonp
939 (if atsignp
940 :upcase
941 :capitalize)
942 (if atsignp
943 :capitalize-first
944 :downcase)))))
945 (setf args (interpret-directive-list stream before orig-args args))
946 after))))
948 (def-complex-format-interpreter #\) ()
949 (error 'format-error
950 :complaint "no corresponding open paren"))
952 ;;;; format interpreters and support functions for conditionalization
954 (def-complex-format-interpreter #\[ (colonp atsignp params directives)
955 (multiple-value-bind (sublists last-semi-with-colon-p remaining)
956 (parse-conditional-directive directives)
957 (setf args
958 (if atsignp
959 (if colonp
960 (error 'format-error
961 :complaint
962 "cannot specify both the colon and at-sign modifiers")
963 (if (cdr sublists)
964 (error 'format-error
965 :complaint
966 "can only specify one section")
967 (interpret-bind-defaults () params
968 (let ((prev-args args)
969 (arg (next-arg)))
970 (if arg
971 (interpret-directive-list stream
972 (car sublists)
973 orig-args
974 prev-args)
975 args)))))
976 (if colonp
977 (if (= (length sublists) 2)
978 (interpret-bind-defaults () params
979 (if (next-arg)
980 (interpret-directive-list stream (car sublists)
981 orig-args args)
982 (interpret-directive-list stream (cadr sublists)
983 orig-args args)))
984 (error 'format-error
985 :complaint
986 "must specify exactly two sections"))
987 (interpret-bind-defaults ((index (next-arg))) params
988 (let* ((default (and last-semi-with-colon-p
989 (pop sublists)))
990 (last (1- (length sublists)))
991 (sublist
992 (if (<= 0 index last)
993 (nth (- last index) sublists)
994 default)))
995 (interpret-directive-list stream sublist orig-args
996 args))))))
997 remaining))
999 (def-complex-format-interpreter #\; ()
1000 (error 'format-error
1001 :complaint
1002 "~~; not contained within either ~~[...~~] or ~~<...~~>"))
1004 (def-complex-format-interpreter #\] ()
1005 (error 'format-error
1006 :complaint
1007 "no corresponding open bracket"))
1009 ;;;; format interpreter for up-and-out
1011 (defvar *outside-args*)
1013 (def-format-interpreter #\^ (colonp atsignp params)
1014 (when atsignp
1015 (error 'format-error
1016 :complaint "cannot specify the at-sign modifier"))
1017 (when (and colonp (not *up-up-and-out-allowed*))
1018 (error 'format-error
1019 :complaint "attempt to use ~~:^ outside a ~~:{...~~} construct"))
1020 (when (interpret-bind-defaults ((arg1 nil) (arg2 nil) (arg3 nil)) params
1021 (cond (arg3 (<= arg1 arg2 arg3))
1022 (arg2 (eql arg1 arg2))
1023 (arg1 (eql arg1 0))
1024 (t (if colonp
1025 (null *outside-args*)
1026 (null args)))))
1027 (throw (if colonp 'up-up-and-out 'up-and-out)
1028 args)))
1030 ;;;; format interpreters for iteration
1032 (def-complex-format-interpreter #\{
1033 (colonp atsignp params string end directives)
1034 (let ((close (find-directive directives #\} nil)))
1035 (unless close
1036 (error 'format-error
1037 :complaint
1038 "no corresponding close brace"))
1039 (interpret-bind-defaults ((max-count nil)) params
1040 (let* ((closed-with-colon (format-directive-colonp close))
1041 (posn (position close directives))
1042 (insides (if (zerop posn)
1043 (next-arg)
1044 (subseq directives 0 posn)))
1045 (*up-up-and-out-allowed* colonp))
1046 (labels
1047 ((do-guts (orig-args args)
1048 (if (zerop posn)
1049 (handler-bind
1050 ((format-error
1051 (lambda (condition)
1052 (error
1053 'format-error
1054 :complaint
1055 "~A~%while processing indirect format string:"
1056 :args (list condition)
1057 :print-banner nil
1058 :control-string string
1059 :offset (1- end)))))
1060 (%format stream insides orig-args args))
1061 (interpret-directive-list stream insides
1062 orig-args args)))
1063 (bind-args (orig-args args)
1064 (if colonp
1065 (let* ((arg (next-arg))
1066 (*logical-block-popper* nil)
1067 (*outside-args* args))
1068 (catch 'up-and-out
1069 (do-guts arg arg))
1070 args)
1071 (do-guts orig-args args)))
1072 (do-loop (orig-args args)
1073 (catch (if colonp 'up-up-and-out 'up-and-out)
1074 (loop
1075 (when (and (not closed-with-colon) (null args))
1076 (return))
1077 (when (and max-count (minusp (decf max-count)))
1078 (return))
1079 (setf args (bind-args orig-args args))
1080 (when (and closed-with-colon (null args))
1081 (return)))
1082 args)))
1083 (if atsignp
1084 (setf args (do-loop orig-args args))
1085 (let ((arg (next-arg))
1086 (*logical-block-popper* nil))
1087 (do-loop arg arg)))
1088 (nthcdr (1+ posn) directives))))))
1090 (def-complex-format-interpreter #\} ()
1091 (error 'format-error
1092 :complaint "no corresponding open brace"))
1094 ;;;; format interpreters and support functions for justification
1096 (def-complex-format-interpreter #\<
1097 (colonp atsignp params string end directives)
1098 (multiple-value-bind (segments first-semi close remaining)
1099 (parse-format-justification directives)
1100 (setf args
1101 (if (format-directive-colonp close) ; logical block vs. justification
1102 (multiple-value-bind (prefix per-line-p insides suffix)
1103 (parse-format-logical-block segments colonp first-semi
1104 close params string end)
1105 (interpret-format-logical-block stream orig-args args
1106 prefix per-line-p insides
1107 suffix atsignp))
1108 (let ((count (reduce #'+ (mapcar (lambda (x) (count-if #'illegal-inside-justification-p x)) segments))))
1109 (when (> count 0)
1110 ;; ANSI specifies that "an error is signalled" in this
1111 ;; situation.
1112 (error 'format-error
1113 :complaint "~D illegal directive~:P found inside justification block"
1114 :args (list count)
1115 :references (list '(:ansi-cl :section (22 3 5 2)))))
1116 ;; ANSI does not explicitly say that an error should
1117 ;; be signalled, but the @ modifier is not explicitly
1118 ;; allowed for ~> either.
1119 (when (format-directive-atsignp close)
1120 (error 'format-error
1121 :complaint "@ modifier not allowed in close ~
1122 directive of justification ~
1123 block (i.e. ~~<...~~@>."
1124 :offset (1- (format-directive-end close))
1125 :references (list '(:ansi-cl :section (22 3 6 2)))))
1126 (interpret-format-justification stream orig-args args
1127 segments colonp atsignp
1128 first-semi params))))
1129 remaining))
1131 (defun interpret-format-justification
1132 (stream orig-args args segments colonp atsignp first-semi params)
1133 (interpret-bind-defaults
1134 ((mincol 0) (colinc 1) (minpad 0) (padchar #\space))
1135 params
1136 (let ((newline-string nil)
1137 (strings nil)
1138 (extra-space 0)
1139 (line-len 0))
1140 (setf args
1141 (catch 'up-and-out
1142 (when (and first-semi (format-directive-colonp first-semi))
1143 (interpret-bind-defaults
1144 ((extra 0)
1145 (len (or (sb!impl::line-length stream) 72)))
1146 (format-directive-params first-semi)
1147 (setf newline-string
1148 (with-simple-output-to-string (stream)
1149 (setf args
1150 (interpret-directive-list stream
1151 (pop segments)
1152 orig-args
1153 args))))
1154 (setf extra-space extra)
1155 (setf line-len len)))
1156 (dolist (segment segments)
1157 (push (with-simple-output-to-string (stream)
1158 (setf args
1159 (interpret-directive-list stream segment
1160 orig-args args)))
1161 strings))
1162 args))
1163 (format-justification stream newline-string extra-space line-len strings
1164 colonp atsignp mincol colinc minpad padchar)))
1165 args)
1167 (defun format-justification (stream newline-prefix extra-space line-len strings
1168 pad-left pad-right mincol colinc minpad padchar)
1169 (setf strings (reverse strings))
1170 (let* ((num-gaps (+ (1- (length strings))
1171 (if pad-left 1 0)
1172 (if pad-right 1 0)))
1173 (chars (+ (* num-gaps minpad)
1174 (loop
1175 for string in strings
1176 summing (length string))))
1177 (length (if (> chars mincol)
1178 (+ mincol (* (ceiling (- chars mincol) colinc) colinc))
1179 mincol))
1180 (padding (+ (- length chars) (* num-gaps minpad))))
1181 (when (and newline-prefix
1182 (> (+ (or (sb!impl::charpos stream) 0)
1183 length extra-space)
1184 line-len))
1185 (write-string newline-prefix stream))
1186 (flet ((do-padding ()
1187 (let ((pad-len
1188 (if (zerop num-gaps) padding (truncate padding num-gaps))))
1189 (decf padding pad-len)
1190 (decf num-gaps)
1191 (dotimes (i pad-len) (write-char padchar stream)))))
1192 (when (or pad-left (and (not pad-right) (null (cdr strings))))
1193 (do-padding))
1194 (when strings
1195 (write-string (car strings) stream)
1196 (dolist (string (cdr strings))
1197 (do-padding)
1198 (write-string string stream)))
1199 (when pad-right
1200 (do-padding)))))
1202 (defun interpret-format-logical-block
1203 (stream orig-args args prefix per-line-p insides suffix atsignp)
1204 (let ((arg (if atsignp args (next-arg))))
1205 (if per-line-p
1206 (pprint-logical-block
1207 (stream arg :per-line-prefix prefix :suffix suffix)
1208 (let ((*logical-block-popper* (lambda () (pprint-pop))))
1209 (catch 'up-and-out
1210 (interpret-directive-list stream insides
1211 (if atsignp orig-args arg)
1212 arg))))
1213 (pprint-logical-block (stream arg :prefix prefix :suffix suffix)
1214 (let ((*logical-block-popper* (lambda () (pprint-pop))))
1215 (catch 'up-and-out
1216 (interpret-directive-list stream insides
1217 (if atsignp orig-args arg)
1218 arg))))))
1219 (if atsignp nil args))
1221 ;;;; format interpreter and support functions for user-defined method
1223 (def-format-interpreter #\/ (string start end colonp atsignp params)
1224 (let ((symbol (extract-user-fun-name string start end)))
1225 (collect ((args))
1226 (dolist (param-and-offset params)
1227 (let ((param (cdr param-and-offset)))
1228 (case param
1229 (:arg (args (next-arg)))
1230 (:remaining (args (length args)))
1231 (t (args param)))))
1232 (apply (fdefinition symbol) stream (next-arg) colonp atsignp (args)))))