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