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