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