Debian Codegraph @

src/lsp/format.lsp

raw
1 ;;;; -*- Mode: Lisp; Syntax: Common-Lisp; indent-tabs-mode: nil; Package: SYSTEM -*-
2 ;;;; vim: set filetype=lisp tabstop=8 shiftwidth=2 expandtab:
3
4 ;;;;
5 ;;; -*- Package: FORMAT -*-
6 ;;;
7 ;;; **********************************************************************
8 ;;; This code was written as part of the CMU Common Lisp project at
9 ;;; Carnegie Mellon University, and has been placed in the public domain.
10 ;;;
11 ;;;
12 ;;; **********************************************************************
13 ;;;
14 ;;; Functions to implement FORMAT and FORMATTER for CMU Common Lisp.
15 ;;;
16 ;;; Written by William Lott, with lots of stuff stolen from the previous
17 ;;; version by David Adam and later rewritten by Bill Maddox.
18 ;;;
19 ;;; Various fixes and adaptations provided by Juan Jose Garcia-Ripoll and
20 ;;; Daniel KochmaƄski for Embeddable Common-Lisp.
21 ;;;
22
23 (in-package "SYS")
24
25 (pushnew :cdr-7 *features*)
26 (pushnew :formatter *features*)
27
28 ;;;; Float printing.
29
30 ;;;
31 ;;; Written by Bill Maddox
32 ;;;
33 ;;;
34 ;;;
35 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does most of
36 ;;; the work for all printing of floating point numbers in the printer and in
37 ;;; FORMAT. It converts a floating point number to a string in a free or
38 ;;; fixed format with no exponent. The interpretation of the arguments is as
39 ;;; follows:
40 ;;;
41 ;;; X - The floating point number to convert, which must not be
42 ;;; negative.
43 ;;; WIDTH - The preferred field width, used to determine the number
44 ;;; of fraction digits to produce if the FDIGITS parameter
45 ;;; is unspecified or NIL. If the non-fraction digits and the
46 ;;; decimal point alone exceed this width, no fraction digits
47 ;;; will be produced unless a non-NIL value of FDIGITS has been
48 ;;; specified. Field overflow is not considerd an error at this
49 ;;; level.
50 ;;; FDIGITS - The number of fractional digits to produce. Insignificant
51 ;;; trailing zeroes may be introduced as needed. May be
52 ;;; unspecified or NIL, in which case as many digits as possible
53 ;;; are generated, subject to the constraint that there are no
54 ;;; trailing zeroes.
55 ;;; SCALE - If this parameter is specified or non-zero, then the number
56 ;;; printed is (* x (expt 10 scale)). This scaling is exact,
57 ;;; and cannot lose precision.
58 ;;; FMIN - This parameter, if specified or non-zero, is the minimum
59 ;;; number of fraction digits which will be produced, regardless
60 ;;; of the value of WIDTH or FDIGITS. This feature is used by
61 ;;; the ~E format directive to prevent complete loss of
62 ;;; significance in the printed value due to a bogus choice of
63 ;;; scale factor.
64 ;;;
65 ;;; Most of the optional arguments are for the benefit for FORMAT and are not
66 ;;; used by the printer.
67 ;;;
68 ;;; Returns:
69 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT POINT-POS EXPONENT)
70 ;;; where the results have the following interpretation:
71 ;;;
72 ;;; DIGIT-STRING - The decimal representation of X, with decimal point.
73 ;;; DIGIT-LENGTH - The length of the string DIGIT-STRING.
74 ;;; LEADING-POINT - True if the first character of DIGIT-STRING is the
75 ;;; decimal point.
76 ;;; TRAILING-POINT - True if the last character of DIGIT-STRING is the
77 ;;; decimal point.
78 ;;; POINT-POS - The position of the digit preceding the decimal
79 ;;; point. Zero indicates point before first digit.
80 ;;; EXPONENT - The exponent of the number in base 10 after rounding
81 ;;; (excluding the scale factor)
82 ;;;
83 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee accuracy.
84 ;;; Specifically, the decimal number printed is the closest possible
85 ;;; approximation to the true value of the binary number to be printed from
86 ;;; among all decimal representations with the same number of digits. In
87 ;;; free-format output, i.e. with the number of digits unconstrained, it is
88 ;;; guaranteed that all the information is preserved, so that a properly-
89 ;;; rounding reader can reconstruct the original binary number, bit-for-bit,
90 ;;; from its printed decimal representation. Furthermore, only as many digits
91 ;;; as necessary to satisfy this condition will be printed.
92 ;;;
93 ;;;
94 ;;; FLOAT-STRING actually generates the digits for positive numbers. The
95 ;;; algorithm is essentially that of algorithm Dragon4 in "How to Print
96 ;;; Floating-Point Numbers Accurately" by Steele and White. The current
97 ;;; (draft) version of this paper may be found in [CMUC]<steele>tradix.press.
98 ;;; DO NOT EVEN THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING
99 ;;; THE PAPER!
100
101 (defparameter *digits* "0123456789")
102
103 (defun float-to-digits* (digits number position relativep)
104 "Does what float-to-digits, but also detects if result is zero."
105 (multiple-value-bind (exp string)
106 (float-to-digits digits
107 number
108 position
109 relativep)
110 (values exp
111 string
112 (and position
113 (< exp (- (abs position)))))))
114
115 (defun flonum-to-string (x &optional width fdigits (scale 0) (fmin 0))
116 (declare (type float x))
117 (if (zerop x)
118 ;; Zero is a special case which FLOAT-STRING cannot handle.
119 (cond ((null fdigits) (values ".0" 2 t nil 0 1))
120 ((zerop fdigits) (values "0." 2 nil t 1 1))
121 (T (let ((s (make-string (1+ fdigits) :initial-element #\0)))
122 (setf (schar s 0) #\.)
123 (values s (length s) t nil 0 1))))
124 (multiple-value-bind (e string zero?)
125 (cond (fdigits
126 (float-to-digits* nil x
127 (min (- (+ fdigits scale))
128 (- (+ fmin scale)))
129 nil))
130 ((null width)
131 (float-to-digits* nil x nil nil))
132 (T (let (;; w: the width-1 leading non-zero digits
133 (w (multiple-value-list
134 (float-to-digits* nil x
135 (max 0
136 (+ (- width 2)
137 (max 0 scale)))
138 t)))
139 ;; f: the fmin+1 leading non-zero digits; this
140 ;; is used if w is empty (not enough space)
141 (f (multiple-value-list
142 (float-to-digits* nil x
143 (- (+ fmin scale))
144 nil))))
145 (if (>= (first f) (first w))
146 (values-list w)
147 (values-list f)))))
148 (let* ((exp (+ e scale))
149 (stream (make-string-output-stream))
150 (length (length string)))
151 ;; Integer part
152 (when (plusp exp)
153 (write-string string
154 stream
155 :end (min length exp))
156 (dotimes (i (- exp length))
157 (write-char #\0 stream)))
158 ;; Separator and fraction
159 (write-char #\. stream)
160 ;; Fraction part
161 (cond ((and zero? fdigits)
162 (dotimes (i fdigits)
163 (write-char #\0 stream)))
164 (fdigits
165 (let ((characters-used 0))
166 (dotimes (i (min (- exp) fdigits))
167 (incf characters-used)
168 (write-char #\0 stream))
169 (let* ((start (max 0 (min length exp)))
170 (end (max start
171 (min length
172 (+ start (- fdigits characters-used))))))
173 (write-string string stream
174 :start start
175 :end end)
176 (incf characters-used (- end start))
177 (dotimes (i (- fdigits characters-used))
178 (write-char #\0 stream)))))
179 (zero?
180 (write-char #\0 stream))
181 (T
182 (dotimes (i (- exp))
183 (write-char #\0 stream))
184 (let ((start (max 0 (min length exp))))
185 (write-string string stream
186 :start start))))
187 (let* ((string (get-output-stream-string stream))
188 (length (length string))
189 (position (position #\. string)))
190 (values string
191 length
192 (= position 0)
193 (= position (1- length))
194 position
195 e))))))
196
197 (defun exponent-in-base10 (x)
198 (if (= x 0)
199 1
200 (1+ (floor (log (abs x) 10)))))
201
202 (defstruct (format-directive
203 #-ecl(:print-function %print-format-directive)
204 #+ecl :named
205 #+ecl(:type vector))
206 (string t :type simple-string)
207 (start 0 :type (and unsigned-byte fixnum))
208 (end 0 :type (and unsigned-byte fixnum))
209 (character #\Space :type base-char)
210 (colonp nil :type (member t nil))
211 (atsignp nil :type (member t nil))
212 (params nil :type list))
213
214 (deftype format-directive () 'vector)
215
216 #-ecl
217 (defun %print-format-directive (struct stream depth)
218 (declare (ignore depth))
219 (print-unreadable-object (struct stream)
220 (write-string (format-directive-string struct) stream
221 :start (format-directive-start struct)
222 :end (format-directive-end struct))))
223
224 (defconstant default-line-length 80)
225
226 (defconstant +format-directive-limit+ (1+ (char-code #\~)))
227
228 #+formatter
229 (defparameter *format-directive-expanders*
230 (make-array +format-directive-limit+ :initial-element nil))
231 (defparameter *format-directive-interpreters*
232 (make-array +format-directive-limit+ :initial-element nil))
233
234 (defparameter *default-format-error-control-string* nil)
235 (defparameter *default-format-error-offset* nil)
236
237 ;; If this flag is 1, directives ~W, ~_, ~<...~:>, ~I or ~T were found.
238 ;; If the flag is 2, directive ~<...~:;...~> was found.
239 ;; NIL otherwise.
240 (defparameter *output-layout-mode* nil)
241
242 ;; The condition FORMAT-ERROR is found later in conditions.lsp
243
244
245 ;;;; TOKENIZE-CONTROL-STRING
246
247 (defun tokenize-control-string (string)
248 (declare (simple-string string)
249 (si::c-local))
250 (let ((index 0)
251 (end (length string))
252 (result nil))
253 (loop
254 (let ((next-directive (or (position #\~ string :start index) end)))
255 (when (> next-directive index)
256 (push (subseq string index next-directive) result))
257 (when (= next-directive end)
258 (return))
259 (let ((directive (parse-directive string next-directive)))
260 (push directive result)
261 (setf index (format-directive-end directive)))))
262 (nreverse result)))
263
264 (defun parse-directive (string start)
265 (declare (simple-string string)
266 (si::c-local))
267 (let ((posn (1+ start)) (params nil) (colonp nil) (atsignp nil)
268 (end (length string)))
269 (flet ((get-char ()
270 (if (= posn end)
271 (error 'format-error
272 :complaint "String ended before directive was found."
273 :control-string string
274 :offset start)
275 (schar string posn))))
276 (loop
277 (let ((char (get-char)))
278 (cond ((and (not colonp) (not atsignp)
279 (or (char<= #\0 char #\9) (char= char #\+) (char= char #\-)))
280 (multiple-value-bind
281 (param new-posn)
282 (parse-integer string :start posn :junk-allowed t)
283 (push (cons posn param) params)
284 (setf posn new-posn)
285 (case (get-char)
286 (#\,)
287 ((#\: #\@)
288 (decf posn))
289 (t
290 (return)))))
291 ((and (not colonp) (not atsignp)
292 (or (char= char #\v) (char= char #\V)))
293 (push (cons posn :arg) params)
294 (incf posn)
295 (case (get-char)
296 (#\,)
297 ((#\: #\@)
298 (decf posn))
299 (t
300 (return))))
301 ((and (not colonp) (not atsignp)
302 (char= char #\#))
303 (push (cons posn :remaining) params)
304 (incf posn)
305 (case (get-char)
306 (#\,)
307 ((#\: #\@)
308 (decf posn))
309 (t
310 (return))))
311 ((and (not colonp) (not atsignp)
312 (char= char #\'))
313 (incf posn)
314 (push (cons posn (get-char)) params)
315 (incf posn)
316 (unless (char= (get-char) #\,)
317 (decf posn)))
318 ((and (not colonp) (not atsignp)
319 (char= char #\,))
320 (push (cons posn nil) params))
321 ((char= char #\:)
322 (if colonp
323 (error 'format-error
324 :complaint "Too many colons supplied."
325 :control-string string
326 :offset posn)
327 (setf colonp t)))
328 ((char= char #\@)
329 (if atsignp
330 (error 'format-error
331 :complaint "Too many at-signs supplied."
332 :control-string string
333 :offset posn)
334 (setf atsignp t)))
335 (t
336 (return))))
337 (incf posn))
338 (let ((char (get-char)))
339 (when (char= char #\/)
340 (let ((closing-slash (position #\/ string :start (1+ posn))))
341 (if closing-slash
342 (setf posn closing-slash)
343 (error 'format-error
344 :complaint "No matching closing slash."
345 :control-string string
346 :offset posn))))
347 (make-format-directive
348 :string string :start start :end (1+ posn)
349 :character (char-upcase char)
350 :colonp colonp :atsignp atsignp
351 :params (nreverse params))))))
352
353
354 ;;;; Specials used to communicate information.
355
356 ;;; *UP-UP-AND-OUT-ALLOWED* -- internal.
357 ;;;
358 ;;; Used both by the expansion stuff and the interpreter stuff. When it is
359 ;;; non-NIL, up-up-and-out (~:^) is allowed. Otherwise, ~:^ isn't allowed.
360 ;;;
361 (defparameter *up-up-and-out-allowed* nil)
362
363 ;;; *LOGICAL-BLOCK-POPPER* -- internal.
364 ;;;
365 ;;; Used by the interpreter stuff. When it non-NIL, its a function that will
366 ;;; invoke PPRINT-POP in the right lexical environemnt.
367 ;;;
368 (defparameter *logical-block-popper* nil)
369
370 ;;; *EXPANDER-NEXT-ARG-MACRO* -- internal.
371 ;;;
372 ;;; Used by the expander stuff. This is bindable so that ~<...~:>
373 ;;; can change it.
374 ;;;
375 #+formatter
376 (defparameter *expander-next-arg-macro* 'expander-next-arg)
377
378 ;;; *ONLY-SIMPLE-ARGS* -- internal.
379 ;;;
380 ;;; Used by the expander stuff. Initially starts as T, and gets set to NIL
381 ;;; if someone needs to do something strange with the arg list (like use
382 ;;; the rest, or something).
383 ;;;
384 (defvar *only-simple-args*)
385
386 ;;; *ORIG-ARGS-AVAILABLE* -- internal.
387 ;;;
388 ;;; Used by the expander stuff. We do an initial pass with this as NIL.
389 ;;; If someone doesn't like this, they (throw 'need-orig-args nil) and we try
390 ;;; again with it bound to T. If this is T, we don't try to do anything
391 ;;; fancy with args.
392 ;;;
393 (defparameter *orig-args-available* nil)
394
395 ;;; *SIMPLE-ARGS* -- internal.
396 ;;;
397 ;;; Used by the expander stuff. List of (symbol . offset) for simple args.
398 ;;;
399 (defvar *simple-args*)
400
401
402
403
404 ;;;; FORMAT
405
406 #-ecl
407 (defun format (destination control-string &rest format-arguments)
408 "Provides various facilities for formatting output.
409 CONTROL-STRING contains a string to be output, possibly with embedded
410 directives, which are flagged with the escape character \"~\". Directives
411 generally expand into additional text to be output, usually consuming one
412 or more of the FORMAT-ARGUMENTS in the process. A few useful directives
413 are:
414 ~A or ~nA Prints one argument as if by PRINC
415 ~S or ~nS Prints one argument as if by PRIN1
416 ~D or ~nD Prints one argument as a decimal integer
417 ~% Does a TERPRI
418 ~& Does a FRESH-LINE
419
420 where n is the width of the field in which the object is printed.
421
422 DESTINATION controls where the result will go. If DESTINATION is T, then
423 the output is sent to the standard output stream. If it is NIL, then the
424 output is returned in a string as the value of the call. Otherwise,
425 DESTINATION must be a stream to which the output will be sent.
426
427 Example: (FORMAT NIL \"The answer is ~D.\" 10) => \"The answer is 10.\"
428
429 FORMAT has many additional capabilities not described here. Consult
430 Section 22.3 (Formatted Output) of the ANSI Common Lisp standard for
431 details."
432 (etypecase destination
433 (null
434 (with-output-to-string (stream)
435 (formatter-aux stream control-string format-arguments)))
436 (string
437 (with-output-to-string (stream destination)
438 (formatter-aux stream control-string format-arguments)))
439 ((member t)
440 (formatter-aux *standard-output* control-string format-arguments)
441 nil)
442 (stream
443 (formatter-aux destination control-string format-arguments)
444 nil)))
445
446 (defun formatter-aux (stream string-or-fun orig-args &optional (args orig-args))
447 (if (functionp string-or-fun)
448 (apply string-or-fun stream args)
449 (catch 'up-and-out
450 (let* ((string (etypecase string-or-fun
451 (simple-string
452 string-or-fun)
453 (string
454 (coerce string-or-fun 'simple-string))))
455 (*output-layout-mode* nil)
456 (*default-format-error-control-string* string)
457 (*logical-block-popper* nil))
458 (interpret-directive-list stream (tokenize-control-string string)
459 orig-args args)))))
460
461 (defun interpret-directive-list (stream directives orig-args args)
462 (declare (si::c-local))
463 (if directives
464 (let ((directive (car directives)))
465 (etypecase directive
466 (simple-string
467 (write-string directive stream)
468 (interpret-directive-list stream (cdr directives) orig-args args))
469 (#-ecl format-directive #+ecl vector
470 (multiple-value-bind
471 (new-directives new-args)
472 (let* ((code (char-code (format-directive-character directive)))
473 (function
474 (and (< code +format-directive-limit+)
475 (svref *format-directive-interpreters* code)))
476 (*default-format-error-offset*
477 (1- (format-directive-end directive))))
478 (unless function
479 (error 'format-error
480 :complaint "Unknown format directive."))
481 (multiple-value-bind
482 (new-directives new-args)
483 (funcall function stream directive
484 (cdr directives) orig-args args)
485 (values new-directives new-args)))
486 (interpret-directive-list stream new-directives
487 orig-args new-args)))))
488 args))
489
490
491 ;;;; FORMATTER
492
493 #+formatter
494 (progn
495 (defmacro formatter (control-string)
496 `#',(%formatter control-string))
497
498 (defun %formatter (control-string)
499 (declare (si::c-local))
500 (block nil
501 (catch 'need-orig-args
502 (let* ((*simple-args* nil)
503 (*only-simple-args* t)
504 (guts (expand-control-string control-string))
505 (args nil))
506 (dolist (arg *simple-args*)
507 (push `(,(car arg)
508 (error
509 'format-error
510 :complaint "Required argument missing"
511 :control-string ,control-string
512 :offset ,(cdr arg)))
513 args))
514 (return `(lambda (stream &optional ,@args &rest args)
515 ,guts
516 args))))
517 (let ((*orig-args-available* t)
518 (*only-simple-args* nil))
519 `(lambda (stream &rest orig-args)
520 (let ((args orig-args))
521 ,(expand-control-string control-string)
522 args)))))
523
524 (defun expand-control-string (string)
525 (declare (si::c-local))
526 (let* ((string (etypecase string
527 (simple-string
528 string)
529 (string
530 (coerce string 'simple-string))))
531 (*output-layout-mode* nil)
532 (*default-format-error-control-string* string)
533 (directives (tokenize-control-string string)))
534 `(block nil
535 ,@(expand-directive-list directives))))
536
537 (defun expand-directive-list (directives)
538 (declare (si::c-local))
539 (let ((results nil)
540 (remaining-directives directives))
541 (loop
542 (unless remaining-directives
543 (return))
544 (multiple-value-bind
545 (form new-directives)
546 (expand-directive (car remaining-directives)
547 (cdr remaining-directives))
548 (when form
549 (push form results))
550 (setf remaining-directives new-directives)))
551 (reverse results)))
552
553 (defun expand-directive (directive more-directives)
554 (declare (si::c-local))
555 (etypecase directive
556 (simple-string
557 (values `(write-string ,directive stream)
558 more-directives))
559 (format-directive
560 (let* ((code (char-code (format-directive-character directive)))
561 (expander
562 (and (< code +format-directive-limit+)
563 (svref *format-directive-expanders* code)))
564 (*default-format-error-offset*
565 (1- (format-directive-end directive))))
566 (if expander
567 (funcall expander directive more-directives)
568 (error 'format-error
569 :complaint "Unknown directive."))))))
570
571 (defun expand-next-arg (&optional offset)
572 (declare (si::c-local))
573 (if (or *orig-args-available* (not *only-simple-args*))
574 `(,*expander-next-arg-macro*
575 ,*default-format-error-control-string*
576 ,(or offset *default-format-error-offset*))
577 (let ((symbol (gensym "FORMAT-ARG-")))
578 (push (cons symbol (or offset *default-format-error-offset*))
579 *simple-args*)
580 symbol)))
581
582 (defun need-hairy-args ()
583 (declare (si::c-local))
584 (when *only-simple-args*
585 ))
586
587
588 ;;;; Format directive definition macros and runtime support.
589
590 (defmacro expander-next-arg (string offset)
591 `(if args
592 (pop args)
593 (error 'format-error
594 :complaint "No more arguments."
595 :control-string ,string
596 :offset ,offset)))
597
598 (defmacro expander-pprint-next-arg (string offset)
599 `(progn
600 (when (null args)
601 (error 'format-error
602 :complaint "No more arguments."
603 :control-string ,string
604 :offset ,offset))
605 (pprint-pop)
606 (pop args)))
607 );#+formatter
608
609 (eval-when (:compile-toplevel :execute)
610
611 ;;; NEXT-ARG -- internal.
612 ;;;
613 ;;; This macro is used to extract the next argument from the current arg list.
614 ;;; This is the version used by format directive interpreters.
615 ;;;
616 (defmacro next-arg (&optional offset)
617 `(progn
618 (when (null args)
619 (error 'format-error
620 :complaint "No more arguments."
621 ,@(when offset
622 `(:offset ,offset))))
623 (when *logical-block-popper*
624 (funcall *logical-block-popper*))
625 (pop args)))
626
627 (defmacro def-complex-format-directive (char lambda-list &body body)
628 #+formatter
629 (let* ((name (or (char-name char) (string char)))
630 (defun-name (intern (concatenate 'string name "-FORMAT-DIRECTIVE-EXPANDER")))
631 (directive (gensym))
632 (directives (if lambda-list (car (last lambda-list)) (gensym))))
633 `(%set-format-directive-expander ,char
634 (ext::lambda-block ,defun-name (,directive ,directives)
635 ,@(if lambda-list
636 `((let ,(mapcar #'(lambda (var)
637 `(,var
638 (,(intern (concatenate
639 'string
640 "FORMAT-DIRECTIVE-"
641 (symbol-name var))
642 (symbol-package 'foo))
643 ,directive)))
644 (butlast lambda-list))
645 ,@body))
646 `((declare (ignore ,directive ,directives))
647 ,@body))))))
648
649 (defmacro def-format-directive (char lambda-list &body body)
650 #+formatter
651 (let ((directives (gensym))
652 (declarations nil)
653 (body-without-decls body))
654 (loop
655 (let ((form (car body-without-decls)))
656 (unless (and (consp form) (eq (car form) 'declare))
657 (return))
658 (push (pop body-without-decls) declarations)))
659 (setf declarations (reverse declarations))
660 `(def-complex-format-directive ,char (,@lambda-list ,directives)
661 ,@declarations
662 (values (progn ,@body-without-decls)
663 ,directives))))
664
665 (defmacro expand-bind-defaults (specs params &body body)
666 (once-only ((params params))
667 (if specs
668 (collect ((expander-bindings) (runtime-bindings))
669 (dolist (spec specs)
670 (destructuring-bind (var default) spec
671 (let ((symbol (gensym)))
672 (expander-bindings
673 `(,var ',symbol))
674 (runtime-bindings
675 `(list ',symbol
676 (let* ((param-and-offset (pop ,params))
677 (offset (car param-and-offset))
678 (param (cdr param-and-offset)))
679 (case param
680 (:arg `(or ,(expand-next-arg offset)
681 ,,default))
682 (:remaining
683 (setf *only-simple-args* nil)
684 '(length args))
685 ((nil) ,default)
686 (t param))))))))
687 `(let ,(expander-bindings)
688 `(let ,(list ,@(runtime-bindings))
689 ,@(if ,params
690 (error 'format-error
691 :complaint
692 "Too many parameters, expected no more than ~D"
693 :arguments (list ,(length specs))
694 :offset (caar ,params)))
695 ,,@body)))
696 `(progn
697 (when ,params
698 (error 'format-error
699 :complaint "Too many parameters, expected no more than 0"
700 :offset (caar ,params)))
701 ,@body))))
702
703 (defmacro def-complex-format-interpreter (char lambda-list &body body)
704 (let ((directive (gensym))
705 (directives (if lambda-list (car (last lambda-list)) (gensym))))
706 `(%set-format-directive-interpreter ,char
707 (lambda (stream ,directive ,directives orig-args args)
708 (declare (ignorable stream orig-args args))
709 ,@(if lambda-list
710 `((let ,(mapcar #'(lambda (var)
711 `(,var
712 (,(intern (concatenate
713 'string
714 "FORMAT-DIRECTIVE-"
715 (symbol-name var))
716 (symbol-package 'foo))
717 ,directive)))
718 (butlast lambda-list))
719 (values (progn ,@body) args)))
720 `((declare (ignore ,directive ,directives))
721 ,@body))))))
722
723 (defmacro def-format-interpreter (char lambda-list &body body)
724 (let ((directives (gensym)))
725 `(def-complex-format-interpreter ,char (,@lambda-list ,directives)
726 ,@body
727 ,directives)))
728
729 (defmacro interpret-bind-defaults (specs params &body body)
730 (once-only ((params params))
731 (collect ((bindings))
732 (dolist (spec specs)
733 (destructuring-bind (var default) spec
734 (bindings `(,var (let* ((param-and-offset (pop ,params))
735 (offset (car param-and-offset))
736 (param (cdr param-and-offset)))
737 (case param
738 (:arg (or (next-arg offset) ,default))
739 (:remaining (length args))
740 ((nil) ,default)
741 (t param)))))))
742 `(let* ,(bindings)
743 (when ,params
744 (error 'format-error
745 :complaint
746 "Too many parameters, expected no more than ~D"
747 :arguments (list ,(length specs))
748 :offset (caar ,params)))
749 ,@body))))
750
751 ); eval-when
752
753 #+formatter
754 (defun %set-format-directive-expander (char fn)
755 (setf (aref *format-directive-expanders* (char-code (char-upcase char))) fn)
756 char)
757
758 (defun %set-format-directive-interpreter (char fn)
759 (declare (si::c-local))
760 (setf (aref *format-directive-interpreters*
761 (char-code (char-upcase char)))
762 fn)
763 char)
764
765 (defun find-directive (directives kind stop-at-semi)
766 (declare (si::c-local))
767 (if directives
768 (let ((next (car directives)))
769 (if (format-directive-p next)
770 (let ((char (format-directive-character next)))
771 (if (or (char= kind char)
772 (and stop-at-semi (char= char #\;)))
773 (car directives)
774 (find-directive
775 (cdr (flet ((after (char)
776 (member (find-directive (cdr directives)
777 char
778 nil)
779 directives)))
780 (case char
781 (#\( (after #\)))
782 (#\< (after #\>))
783 (#\[ (after #\]))
784 (#\{ (after #\}))
785 (t directives))))
786 kind stop-at-semi)))
787 (find-directive (cdr directives) kind stop-at-semi)))))
788
789
790 ;;;; Simple outputting noise.
791
792 (defun format-write-field (stream string mincol colinc minpad padchar padleft)
793 (declare (si::c-local))
794 (unless padleft
795 (write-string string stream))
796 (setf minpad (max minpad 0))
797 (dotimes (i minpad)
798 (write-char padchar stream))
799 (and mincol minpad colinc
800 (do ((chars (+ (length string) minpad) (+ chars colinc)))
801 ((>= chars mincol))
802 (dotimes (i colinc)
803 (write-char padchar stream))))
804 (when padleft
805 (write-string string stream)))
806
807 (defun format-princ (stream arg colonp atsignp mincol colinc minpad padchar)
808 #-formatter
809 (declare (si::c-local))
810 (format-write-field stream
811 (if (or arg (not colonp))
812 (princ-to-string arg)
813 "()")
814 mincol colinc minpad padchar atsignp))
815
816 (def-format-directive #\A (colonp atsignp params)
817 (if params
818 (expand-bind-defaults ((mincol 0) (colinc 1) (minpad 0)
819 (padchar #\space))
820 params
821 `(format-princ stream ,(expand-next-arg) ',colonp ',atsignp
822 ,mincol ,colinc ,minpad ,padchar))
823 `(princ ,(if colonp
824 `(or ,(expand-next-arg) "()")
825 (expand-next-arg))
826 stream)))
827
828 (def-format-interpreter #\A (colonp atsignp params)
829 (if params
830 (interpret-bind-defaults ((mincol 0) (colinc 1) (minpad 0)
831 (padchar #\space))
832 params
833 (format-princ stream (next-arg) colonp atsignp
834 mincol colinc minpad padchar))
835 (princ (if colonp (or (next-arg) "()") (next-arg)) stream)))
836
837 (defun format-prin1 (stream arg colonp atsignp mincol colinc minpad padchar)
838 #-formatter
839 (declare (si::c-local))
840 (format-write-field stream
841 (if (or arg (not colonp))
842 (prin1-to-string arg)
843 "()")
844 mincol colinc minpad padchar atsignp))
845
846 (def-format-directive #\S (colonp atsignp params)
847 (cond (params
848 (expand-bind-defaults ((mincol 0) (colinc 1) (minpad 0)
849 (padchar #\space))
850 params
851 `(format-prin1 stream ,(expand-next-arg) ,colonp ,atsignp
852 ,mincol ,colinc ,minpad ,padchar)))
853 (colonp
854 `(let ((arg ,(expand-next-arg)))
855 (if arg
856 (prin1 arg stream)
857 (princ "()" stream))))
858 (t
859 `(prin1 ,(expand-next-arg) stream))))
860
861 (def-format-interpreter #\S (colonp atsignp params)
862 (cond (params
863 (interpret-bind-defaults ((mincol 0) (colinc 1) (minpad 0)
864 (padchar #\space))
865 params
866 (format-prin1 stream (next-arg) colonp atsignp
867 mincol colinc minpad padchar)))
868 (colonp
869 (let ((arg (next-arg)))
870 (if arg
871 (prin1 arg stream)
872 (princ "()" stream))))
873 (t
874 (prin1 (next-arg) stream))))
875
876 (def-format-directive #\C (colonp atsignp params)
877 (expand-bind-defaults () params
878 (if colonp
879 `(format-print-named-character ,(expand-next-arg) stream)
880 (if atsignp
881 `(prin1 ,(expand-next-arg) stream)
882 `(write-char ,(expand-next-arg) stream)))))
883
884 (def-format-interpreter #\C (colonp atsignp params)
885 (interpret-bind-defaults () params
886 (if colonp
887 (format-print-named-character (next-arg) stream)
888 (if atsignp
889 (prin1 (next-arg) stream)
890 (write-char (next-arg) stream)))))
891
892 ;;; "printing" as defined in the ANSI CL glossary, which is normative.
893 (defun char-printing-p (char)
894 (declare (si::c-local))
895 (and (not (eql char #\Space))
896 (graphic-char-p char)))
897
898 (defun format-print-named-character (char stream)
899 (cond ((not (char-printing-p char))
900 (write-string (char-name char) stream))
901 (t
902 (write-char char stream))))
903
904 (def-format-directive #\W (colonp atsignp params)
905 (check-output-layout-mode 1)
906 (expand-bind-defaults () params
907 (if (or colonp atsignp)
908 `(let (,@(when colonp
909 '((*print-pretty* t)))
910 ,@(when atsignp
911 '((*print-level* nil)
912 (*print-length* nil))))
913 (write-object ,(expand-next-arg) stream))
914 `(write-object ,(expand-next-arg) stream))))
915
916 (def-format-interpreter #\W (colonp atsignp params)
917 (check-output-layout-mode 1)
918 (interpret-bind-defaults () params
919 (let ((*print-pretty* (or colonp *print-pretty*))
920 (*print-level* (and atsignp *print-level*))
921 (*print-length* (and atsignp *print-length*)))
922 (write-object (next-arg) stream))))
923
924
925 ;;;; Integer outputting.
926
927 ;;; FORMAT-PRINT-NUMBER does most of the work for the numeric printing
928 ;;; directives. The parameters are interpreted as defined for ~D.
929 ;;;
930 (defun format-print-integer (stream number print-commas-p print-sign-p
931 radix mincol padchar commachar commainterval)
932 #-formatter
933 (declare (si::c-local))
934 (let ((*print-base* radix)
935 (*print-radix* nil))
936 (if (integerp number)
937 (let* ((text (princ-to-string (abs number)))
938 (commaed (if print-commas-p
939 (format-add-commas text commachar commainterval)
940 text))
941 (signed (cond ((minusp number)
942 (concatenate 'string "-" commaed))
943 (print-sign-p
944 (concatenate 'string "+" commaed))
945 (t commaed))))
946 ;; colinc = 1, minpad = 0, padleft = t
947 (format-write-field stream signed mincol 1 0 padchar t))
948 (princ number stream))))
949
950 (defun format-add-commas (string commachar commainterval)
951 (declare (si::c-local))
952 (let ((length (length string)))
953 (multiple-value-bind (commas extra)
954 (truncate (1- length) commainterval)
955 (let ((new-string (make-string (+ length commas)))
956 (first-comma (1+ extra)))
957 (replace new-string string :end1 first-comma :end2 first-comma)
958 (do ((src first-comma (+ src commainterval))
959 (dst first-comma (+ dst commainterval 1)))
960 ((= src length))
961 (setf (schar new-string dst) commachar)
962 (replace new-string string :start1 (1+ dst)
963 :start2 src :end2 (+ src commainterval)))
964 new-string))))
965
966 #+formatter
967 (defun expand-format-integer (base colonp atsignp params)
968 (if (or colonp atsignp params)
969 (expand-bind-defaults
970 ((mincol 0) (padchar #\space) (commachar #\,) (commainterval 3))
971 params
972 `(format-print-integer stream ,(expand-next-arg) ,colonp ,atsignp
973 ,base ,mincol ,padchar ,commachar
974 ,commainterval))
975 `(write ,(expand-next-arg) :stream stream :base ,base :radix nil
976 :escape nil)))
977
978 (eval-when (:compile-toplevel :execute)
979 (defmacro interpret-format-integer (base)
980 `(if (or colonp atsignp params)
981 (interpret-bind-defaults
982 ((mincol 0) (padchar #\space) (commachar #\,) (commainterval 3))
983 params
984 (format-print-integer stream (next-arg) colonp atsignp ,base mincol
985 padchar commachar commainterval))
986 (write (next-arg) :stream stream :base ,base :radix nil :escape nil)))
987 )
988
989 (def-format-directive #\D (colonp atsignp params)
990 (expand-format-integer 10 colonp atsignp params))
991
992 (def-format-interpreter #\D (colonp atsignp params)
993 (interpret-format-integer 10))
994
995 (def-format-directive #\B (colonp atsignp params)
996 (expand-format-integer 2 colonp atsignp params))
997
998 (def-format-interpreter #\B (colonp atsignp params)
999 (interpret-format-integer 2))
1000
1001 (def-format-directive #\O (colonp atsignp params)
1002 (expand-format-integer 8 colonp atsignp params))
1003
1004 (def-format-interpreter #\O (colonp atsignp params)
1005 (interpret-format-integer 8))
1006
1007 (def-format-directive #\X (colonp atsignp params)
1008 (expand-format-integer 16 colonp atsignp params))
1009
1010 (def-format-interpreter #\X (colonp atsignp params)
1011 (interpret-format-integer 16))
1012
1013 (def-format-directive #\R (colonp atsignp params)
1014 (expand-bind-defaults
1015 ((base nil) (mincol 0) (padchar #\space) (commachar #\,)
1016 (commainterval 3))
1017 params
1018 (let ((n-arg (gensym)))
1019 `(let ((,n-arg ,(expand-next-arg)))
1020 (if ,base
1021 (format-print-integer stream ,n-arg ,colonp ,atsignp
1022 ,base ,mincol
1023 ,padchar ,commachar ,commainterval)
1024 ,(if atsignp
1025 (if colonp
1026 `(format-print-old-roman stream ,n-arg)
1027 `(format-print-roman stream ,n-arg))
1028 (if colonp
1029 `(format-print-ordinal stream ,n-arg)
1030 `(format-print-cardinal stream ,n-arg))))))))
1031
1032 (def-format-interpreter #\R (colonp atsignp params)
1033 (interpret-bind-defaults
1034 ((base nil) (mincol 0) (padchar #\space) (commachar #\,)
1035 (commainterval 3))
1036 params
1037 (if base
1038 (format-print-integer stream (next-arg) colonp atsignp base mincol
1039 padchar commachar commainterval)
1040 (if atsignp
1041 (if colonp
1042 (format-print-old-roman stream (next-arg))
1043 (format-print-roman stream (next-arg)))
1044 (if colonp
1045 (format-print-ordinal stream (next-arg))
1046 (format-print-cardinal stream (next-arg)))))))
1047
1048 (defconstant cardinal-ones
1049 #(nil "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"))
1050
1051 (defconstant cardinal-tens
1052 #(nil nil "twenty" "thirty" "forty"
1053 "fifty" "sixty" "seventy" "eighty" "ninety"))
1054
1055 (defconstant cardinal-teens
1056 #("ten" "eleven" "twelve" "thirteen" "fourteen" ;;; RAD
1057 "fifteen" "sixteen" "seventeen" "eighteen" "nineteen"))
1058
1059 (defconstant cardinal-periods
1060 #("" " thousand" " million" " billion" " trillion" " quadrillion"
1061 " quintillion" " sextillion" " septillion" " octillion" " nonillion"
1062 " decillion" " undecillion" " duodecillion" " tredecillion"
1063 " quattuordecillion" " quindecillion" " sexdecillion" " septendecillion"
1064 " octodecillion" " novemdecillion" " vigintillion"))
1065
1066 (defconstant ordinal-ones
1067 #(nil "first" "second" "third" "fourth"
1068 "fifth" "sixth" "seventh" "eighth" "ninth")
1069 "Table of ordinal ones-place digits in English")
1070
1071 (defconstant ordinal-tens
1072 #(nil "tenth" "twentieth" "thirtieth" "fortieth"
1073 "fiftieth" "sixtieth" "seventieth" "eightieth" "ninetieth")
1074 "Table of ordinal tens-place digits in English")
1075
1076 (defun format-print-small-cardinal (stream n)
1077 (declare (si::c-local))
1078 (multiple-value-bind
1079 (hundreds rem) (truncate n 100)
1080 (when (plusp hundreds)
1081 (write-string (svref cardinal-ones hundreds) stream)
1082 (write-string " hundred" stream)
1083 (when (plusp rem)
1084 (write-char #\space stream)))
1085 (when (plusp rem)
1086 (multiple-value-bind (tens ones)
1087 (truncate rem 10)
1088 (cond ((< 1 tens)
1089 (write-string (svref cardinal-tens tens) stream)
1090 (when (plusp ones)
1091 (write-char #\- stream)
1092 (write-string (svref cardinal-ones ones) stream)))
1093 ((= tens 1)
1094 (write-string (svref cardinal-teens ones) stream))
1095 ((plusp ones)
1096 (write-string (svref cardinal-ones ones) stream)))))))
1097
1098 (defun format-print-cardinal (stream n)
1099 #-formatter
1100 (declare (si::c-local))
1101 (cond ((minusp n)
1102 (write-string "negative " stream)
1103 (format-print-cardinal-aux stream (- n) 0 n))
1104 ((zerop n)
1105 (write-string "zero" stream))
1106 (t
1107 (format-print-cardinal-aux stream n 0 n))))
1108
1109 (defun format-print-cardinal-aux (stream n period err)
1110 (declare (si::c-local))
1111 (multiple-value-bind (beyond here) (truncate n 1000)
1112 (unless (<= period 20)
1113 (error "Number too large to print in English: ~:D" err))
1114 (unless (zerop beyond)
1115 (format-print-cardinal-aux stream beyond (1+ period) err))
1116 (unless (zerop here)
1117 (unless (zerop beyond)
1118 (write-char #\space stream))
1119 (format-print-small-cardinal stream here)
1120 (write-string (svref cardinal-periods period) stream))))
1121
1122 (defun format-print-ordinal (stream n)
1123 #-formatter
1124 (declare (si::c-local))
1125 (when (minusp n)
1126 (write-string "negative " stream))
1127 (let ((number (abs n)))
1128 (multiple-value-bind
1129 (top bot) (truncate number 100)
1130 (unless (zerop top)
1131 (format-print-cardinal stream (- number bot)))
1132 (when (and (plusp top) (plusp bot))
1133 (write-char #\space stream))
1134 (multiple-value-bind
1135 (tens ones) (truncate bot 10)
1136 (cond ((= bot 12) (write-string "twelfth" stream))
1137 ((= tens 1)
1138 (write-string (svref cardinal-teens ones) stream);;;RAD
1139 (write-string "th" stream))
1140 ((and (zerop tens) (plusp ones))
1141 (write-string (svref ordinal-ones ones) stream))
1142 ((and (zerop ones)(plusp tens))
1143 (write-string (svref ordinal-tens tens) stream))
1144 ((plusp bot)
1145 (write-string (svref cardinal-tens tens) stream)
1146 (write-char #\- stream)
1147 (write-string (svref ordinal-ones ones) stream))
1148 ((plusp number)
1149 (write-string "th" stream))
1150 (t
1151 (write-string "zeroth" stream)))))))
1152
1153 ;;; Print Roman numerals
1154
1155 (defun format-print-old-roman (stream n)
1156 #-formatter
1157 (declare (si::c-local))
1158 (unless (< 0 n 5000)
1159 (error "Number too large to print in old Roman numerals: ~:D" n))
1160 (do ((char-list '(#\D #\C #\L #\X #\V #\I) (cdr char-list))
1161 (val-list '(500 100 50 10 5 1) (cdr val-list))
1162 (cur-char #\M (car char-list))
1163 (cur-val 1000 (car val-list))
1164 (start n (do ((i start (progn
1165 (write-char cur-char stream)
1166 (- i cur-val))))
1167 ((< i cur-val) i))))
1168 ((zerop start))))
1169
1170 (defun format-print-roman (stream n)
1171 #-formatter
1172 (declare (si::c-local))
1173 (unless (< 0 n 4000)
1174 (error "Number too large to print in Roman numerals: ~:D" n))
1175 (do ((char-list '(#\D #\C #\L #\X #\V #\I) (cdr char-list))
1176 (val-list '(500 100 50 10 5 1) (cdr val-list))
1177 (sub-chars '(#\C #\X #\X #\I #\I) (cdr sub-chars))
1178 (sub-val '(100 10 10 1 1 0) (cdr sub-val))
1179 (cur-char #\M (car char-list))
1180 (cur-val 1000 (car val-list))
1181 (cur-sub-char #\C (car sub-chars))
1182 (cur-sub-val 100 (car sub-val))
1183 (start n (do ((i start (progn
1184 (write-char cur-char stream)
1185 (- i cur-val))))
1186 ((< i cur-val)
1187 (cond ((<= (- cur-val cur-sub-val) i)
1188 (write-char cur-sub-char stream)
1189 (write-char cur-char stream)
1190 (- i (- cur-val cur-sub-val)))
1191 (t i))))))
1192 ((zerop start))))
1193
1194
1195 ;;;; Plural.
1196
1197 (def-format-directive #\P (colonp atsignp params end)
1198 (expand-bind-defaults () params
1199 (let ((arg (cond
1200 ((not colonp)
1201 (expand-next-arg))
1202 (*orig-args-available*
1203 `(if (eq orig-args args)
1204 (error 'format-error
1205 :complaint "No previous argument."
1206 :offset ,(1- end))
1207 (do ((arg-ptr orig-args (cdr arg-ptr)))
1208 ((eq (cdr arg-ptr) args)
1209 (car arg-ptr)))))
1210 (*only-simple-args*
1211 (unless *simple-args*
1212 (error 'format-error
1213 :complaint "No previous argument."))
1214 (caar *simple-args*))
1215 (t
1216 (throw 'need-orig-args nil)))))
1217 (if atsignp
1218 `(write-string (if (eql ,arg 1) "y" "ies") stream)
1219 `(unless (eql ,arg 1) (write-char #\s stream))))))
1220
1221 (def-format-interpreter #\P (colonp atsignp params)
1222 (interpret-bind-defaults () params
1223 (let ((arg (if colonp
1224 (if (eq orig-args args)
1225 (error 'format-error
1226 :complaint "No previous argument.")
1227 (do ((arg-ptr orig-args (cdr arg-ptr)))
1228 ((eq (cdr arg-ptr) args)
1229 (car arg-ptr))))
1230 (next-arg))))
1231 (if atsignp
1232 (write-string (if (eql arg 1) "y" "ies") stream)
1233 (unless (eql arg 1) (write-char #\s stream))))))
1234
1235
1236 ;;;; Floating point noise.
1237
1238 (defun decimal-string (n)
1239 (declare (si::c-local))
1240 (write-to-string n :base 10 :radix nil :escape nil))
1241
1242 (def-format-directive #\F (colonp atsignp params)
1243 (when colonp
1244 (error 'format-error
1245 :complaint
1246 "Cannot specify the colon modifier with this directive."))
1247 (expand-bind-defaults ((w nil) (d nil) (k 0) (ovf nil) (pad #\space)) params
1248 `(format-fixed stream ,(expand-next-arg) ,w ,d ,k ,ovf ,pad ,atsignp)))
1249
1250 (def-format-interpreter #\F (colonp atsignp params)
1251 (when colonp
1252 (error 'format-error
1253 :complaint
1254 "Cannot specify the colon modifier with this directive."))
1255 (interpret-bind-defaults ((w nil) (d nil) (k 0) (ovf nil) (pad #\space))
1256 params
1257 (format-fixed stream (next-arg) w d k ovf pad atsignp)))
1258
1259 (defun format-fixed (stream number w d k ovf pad atsign)
1260 #-formatter
1261 (declare (si::c-local))
1262 (if (numberp number)
1263 (if (floatp number)
1264 (format-fixed-aux stream number w d k ovf pad atsign)
1265 (if (rationalp number)
1266 (format-fixed-aux stream
1267 (coerce number 'single-float)
1268 w d k ovf pad atsign)
1269 (format-write-field stream
1270 (decimal-string number)
1271 w 1 0 #\space t)))
1272 (format-princ stream number nil nil w 1 0 pad)))
1273
1274
1275 ;;; We return true if we overflowed, so that ~G can output the overflow char
1276 ;;; instead of spaces.
1277 ;;;
1278 (defun format-fixed-aux (stream number w d k ovf pad atsign)
1279 (declare (si::c-local))
1280 (cond
1281 ((or (not (or w d k))
1282 (and (floatp number)
1283 (or (float-infinity-p number)
1284 (float-nan-p number))))
1285 (prin1 number stream)
1286 nil)
1287 (t
1288 (let ((spaceleft w))
1289 (when (and w (or atsign
1290 (minusp number)
1291 #+ieee-floating-point
1292 (and (zerop number)
1293 (minusp (atan number -1)))))
1294 (decf spaceleft))
1295 (multiple-value-bind (str len lpoint tpoint)
1296 (sys::flonum-to-string (abs number) spaceleft d k)
1297 ;; if caller specifically requested no fraction digits, suppress the
1298 ;; trailing zero
1299 (when (eql d 0)
1300 (setq tpoint nil))
1301 (when w
1302 (decf spaceleft len)
1303 ;; obligatory trailing zero (unless explicitly cut with ,d)
1304 (when tpoint
1305 (decf spaceleft))
1306 ;; optional leading zero
1307 (when lpoint
1308 (if (or (> spaceleft 0)
1309 (eql d 0))
1310 (decf spaceleft)
1311 (setq lpoint nil))))
1312 (cond ((and w (< spaceleft 0) ovf)
1313 ;;field width overflow
1314 (dotimes (i w)
1315 (write-char ovf stream))
1316 t)
1317 (t
1318 (when w (dotimes (i spaceleft) (write-char pad stream)))
1319 (if (or (minusp number)
1320 #+ieee-floating-point
1321 (and (zerop number)
1322 (minusp (atan number -1))))
1323 (write-char #\- stream)
1324 (if atsign (write-char #\+ stream)))
1325 (when lpoint (write-char #\0 stream))
1326 (write-string str stream)
1327 (when tpoint (write-char #\0 stream))
1328 nil)))))))
1329
1330 (def-format-directive #\E (colonp atsignp params)
1331 (when colonp
1332 (error 'format-error
1333 :complaint
1334 "Cannot specify the colon modifier with this directive."))
1335 (expand-bind-defaults
1336 ((w nil) (d nil) (e nil) (k 1) (ovf nil) (pad #\space) (mark nil))
1337 params
1338 `(format-exponential stream ,(expand-next-arg) ,w ,d ,e ,k ,ovf ,pad ,mark
1339 ,atsignp)))
1340
1341 (def-format-interpreter #\E (colonp atsignp params)
1342 (when colonp
1343 (error 'format-error
1344 :complaint
1345 "Cannot specify the colon modifier with this directive."))
1346 (interpret-bind-defaults
1347 ((w nil) (d nil) (e nil) (k 1) (ovf nil) (pad #\space) (mark nil))
1348 params
1349 (format-exponential stream (next-arg) w d e k ovf pad mark atsignp)))
1350
1351 (defun format-exponential (stream number w d e k ovf pad marker atsign)
1352 #-formatter
1353 (declare (si::c-local))
1354 (cond
1355 ((not (numberp number))
1356 (format-princ stream number nil nil w 1 0 pad))
1357 ((floatp number)
1358 (format-exp-aux stream number w d e k ovf pad marker atsign))
1359 ((rationalp number)
1360 (format-exp-aux stream
1361 (coerce number 'single-float)
1362 w d e k ovf pad marker atsign))
1363 (T
1364 (format-write-field stream
1365 (decimal-string number)
1366 w 1 0 #\space t))))
1367
1368 (defun format-exponent-marker (number)
1369 (declare (si::c-local))
1370 (if (typep number *read-default-float-format*)
1371 #\e
1372 (typecase number
1373 (single-float #\f)
1374 (double-float #\d)
1375 (short-float #\s)
1376 (long-float #\l))))
1377
1378 ;;;Here we prevent the scale factor from shifting all significance out of
1379 ;;;a number to the right. We allow insignificant zeroes to be shifted in
1380 ;;;to the left right, athough it is an error to specify k and d such that this
1381 ;;;occurs. Perhaps we should detect both these condtions and flag them as
1382 ;;;errors. As for now, we let the user get away with it, and merely guarantee
1383 ;;;that at least one significant digit will appear.
1384
1385 ;;; [email protected]: The Hyperspec seems to say that the exponent
1386 ;;; marker is always printed. Make it so. Also, the original version
1387 ;;; causes errors when printing infinities or NaN's. The Hyperspec is
1388 ;;; silent here, so let's just print out infinities and NaN's instead
1389 ;;; of causing an error.
1390 (defun format-exp-aux (stream number w d e k ovf pad marker atsign)
1391 (declare (si::c-local))
1392 (if (and (floatp number)
1393 (or (float-infinity-p number)
1394 (float-nan-p number)))
1395 (prin1 number stream)
1396 (let* ((expt (sys::exponent-in-base10 number))
1397 (rescaled-expt (- expt k))
1398 (estr (decimal-string (abs rescaled-expt)))
1399 (elen (if e (max (length estr) e) (length estr)))
1400 (fdig (if d (if (plusp k) (1+ (- d k)) d) nil))
1401 (fmin (if (minusp k) (- 1 k) 0))
1402 (spaceleft (if w
1403 (- w 2 elen
1404 (if (or atsign (minusp number))
1405 1 0))
1406 nil)))
1407 (if (and w ovf e (> elen e)) ;exponent overflow
1408 (dotimes (i w) (write-char ovf stream))
1409 (multiple-value-bind (fstr flen lpoint tpoint ppos expt-after-rounding)
1410 (sys::flonum-to-string number spaceleft fdig (- rescaled-expt) fmin)
1411 (declare (ignore ppos))
1412 (when (/= expt-after-rounding expt)
1413 (setf rescaled-expt (- expt-after-rounding k)
1414 estr (decimal-string (abs rescaled-expt))
1415 elen (if e (max (length estr) e) (length estr))
1416 spaceleft (if w
1417 (- w 2 elen
1418 (if (or atsign (minusp number))
1419 1 0))
1420 nil)
1421 (values fstr flen lpoint tpoint)
1422 (sys::flonum-to-string number spaceleft fdig (- rescaled-expt) fmin)))
1423 (when (eql fdig 0) (setq tpoint nil))
1424 (when w
1425 (decf spaceleft flen)
1426 (when lpoint
1427 (if (> spaceleft 0)
1428 (decf spaceleft)
1429 (setq lpoint nil)))
1430 (when tpoint
1431 (if (<= spaceleft 0)
1432 (setq tpoint nil)
1433 (decf spaceleft))))
1434 (cond ((and w (< spaceleft 0) ovf)
1435 ;;significand overflow
1436 (dotimes (i w) (write-char ovf stream)))
1437 (t (when w
1438 (dotimes (i spaceleft) (write-char pad stream)))
1439 (if (minusp number)
1440 (write-char #\- stream)
1441 (if atsign (write-char #\+ stream)))
1442 (when lpoint (write-char #\0 stream))
1443 (write-string fstr stream)
1444 (when tpoint (write-char #\0 stream))
1445 (write-char (if marker
1446 marker
1447 (format-exponent-marker number))
1448 stream)
1449 (write-char (if (minusp rescaled-expt) #\- #\+) stream)
1450 (when e
1451 ;;zero-fill before exponent if necessary
1452 (dotimes (i (- e (length estr)))
1453 (write-char #\0 stream)))
1454 (write-string estr stream))))))))
1455
1456 (def-format-directive #\G (colonp atsignp params)
1457 (when colonp
1458 (error 'format-error
1459 :complaint
1460 "Cannot specify the colon modifier with this directive."))
1461 (expand-bind-defaults
1462 ((w nil) (d nil) (e nil) (k 0) (ovf nil) (pad #\space) (mark nil))
1463 params
1464 `(format-general stream ,(expand-next-arg) ,w ,d ,e ,k ,ovf ,pad ,mark ,atsignp)))
1465
1466 (def-format-interpreter #\G (colonp atsignp params)
1467 (when colonp
1468 (error 'format-error
1469 :complaint
1470 "Cannot specify the colon modifier with this directive."))
1471 (interpret-bind-defaults
1472 ((w nil) (d nil) (e nil) (k 0) (ovf nil) (pad #\space) (mark nil))
1473 params
1474 (format-general stream (next-arg) w d e k ovf pad mark atsignp)))
1475
1476 (defun format-general (stream number w d e k ovf pad marker atsign)
1477 #-formatter
1478 (declare (si::c-local))
1479 (if (numberp number)
1480 (if (floatp number)
1481 (format-general-aux stream number w d e k ovf pad marker atsign)
1482 (if (rationalp number)
1483 (format-general-aux stream
1484 (coerce number 'single-float)
1485 w d e k ovf pad marker atsign)
1486 (format-write-field stream
1487 (decimal-string number)
1488 w 1 0 #\space t)))
1489 (format-princ stream number nil nil w 1 0 pad)))
1490
1491
1492 ;;; [email protected]: Same change as for format-exp-aux.
1493 (defun format-general-aux (stream number w d e k ovf pad marker atsign)
1494 (declare (si::c-local))
1495 (if (and (floatp number)
1496 (or (float-infinity-p number)
1497 (float-nan-p number)))
1498 (prin1 number stream)
1499 (let ((n (sys::exponent-in-base10 number)))
1500 ;;Default d if omitted. The procedure is taken directly
1501 ;;from the definition given in the manual, and is not
1502 ;;very efficient, since we generate the digits twice.
1503 ;;Future maintainers are encouraged to improve on this.
1504 (unless d
1505 (multiple-value-bind (str len)
1506 (sys::flonum-to-string (abs number))
1507 (declare (ignore str))
1508 (let ((q (if (= len 1) 1 (1- len))))
1509 (setq d (max q (min n 7))))))
1510 (let* ((ee (if e (+ e 2) 4))
1511 (ww (if w (- w ee) nil))
1512 (dd (- d n)))
1513 (cond ((<= 0 dd d)
1514 (let ((char (if (format-fixed-aux stream number ww dd 0
1515 ovf pad atsign)
1516 ovf
1517 #\space)))
1518 (dotimes (i ee) (write-char char stream))))
1519 (t
1520 (format-exp-aux stream number w d e (or k 1)
1521 ovf pad marker atsign)))))))
1522
1523 (def-format-directive #\$ (colonp atsignp params)
1524 (expand-bind-defaults ((d 2) (n 1) (w 0) (pad #\space)) params
1525 `(format-dollars stream ,(expand-next-arg) ,d ,n ,w ,pad ,colonp
1526 ,atsignp)))
1527
1528 (def-format-interpreter #\$ (colonp atsignp params)
1529 (interpret-bind-defaults ((d 2) (n 1) (w 0) (pad #\space)) params
1530 (format-dollars stream (next-arg) d n w pad colonp atsignp)))
1531
1532 (defun format-dollars (stream number d n w pad colon atsign)
1533 #-formatter
1534 (declare (si::c-local))
1535 (if (rationalp number) (setq number (coerce number 'single-float)))
1536 (if (floatp number)
1537 (let* ((signstr (if (minusp number) "-" (if atsign "+" "")))
1538 (signlen (length signstr)))
1539 (multiple-value-bind (str strlen ig2 ig3 pointplace)
1540 (sys::flonum-to-string (abs number) nil d)
1541 (declare (ignore ig2 ig3))
1542 (when colon (write-string signstr stream))
1543 (dotimes (i (- w signlen (max 0 (- n pointplace)) strlen))
1544 (write-char pad stream))
1545 (unless colon (write-string signstr stream))
1546 (dotimes (i (- n pointplace)) (write-char #\0 stream))
1547 (write-string str stream)))
1548 (format-write-field stream
1549 (decimal-string number)
1550 w 1 0 #\space t)))
1551
1552
1553 ;;;; line/page breaks and other stuff like that.
1554
1555 (def-format-directive #\% (colonp atsignp params)
1556 (when (or colonp atsignp)
1557 (error 'format-error
1558 :complaint
1559 "Cannot specify either colon or atsign for this directive."))
1560 (if params
1561 (expand-bind-defaults ((count 1)) params
1562 `(dotimes (i ,count)
1563 (terpri stream)))
1564 '(terpri stream)))
1565
1566 (def-format-interpreter #\% (colonp atsignp params)
1567 (when (or colonp atsignp)
1568 (error 'format-error
1569 :complaint
1570 "Cannot specify either colon or atsign for this directive."))
1571 (interpret-bind-defaults ((count 1)) params
1572 (dotimes (i count)
1573 (terpri stream))))
1574
1575 (def-format-directive #\& (colonp atsignp params)
1576 (when (or colonp atsignp)
1577 (error 'format-error
1578 :complaint
1579 "Cannot specify either colon or atsign for this directive."))
1580 (if params
1581 (expand-bind-defaults ((count 1)) params
1582 `(progn
1583 (fresh-line stream)
1584 (dotimes (i (1- ,count))
1585 (terpri stream))))
1586 '(fresh-line stream)))
1587
1588 (def-format-interpreter #\& (colonp atsignp params)
1589 (when (or colonp atsignp)
1590 (error 'format-error
1591 :complaint
1592 "Cannot specify either colon or atsign for this directive."))
1593 (interpret-bind-defaults ((count 1)) params
1594 (fresh-line stream)
1595 (dotimes (i (1- count))
1596 (terpri stream))))
1597
1598 (def-format-directive #\| (colonp atsignp params)
1599 (when (or colonp atsignp)
1600 (error 'format-error
1601 :complaint
1602 "Cannot specify either colon or atsign for this directive."))
1603 (if params
1604 (expand-bind-defaults ((count 1)) params
1605 `(dotimes (i ,count)
1606 (write-char #\page stream)))
1607 '(write-char #\page stream)))
1608
1609 (def-format-interpreter #\| (colonp atsignp params)
1610 (when (or colonp atsignp)
1611 (error 'format-error
1612 :complaint
1613 "Cannot specify either colon or atsign for this directive."))
1614 (interpret-bind-defaults ((count 1)) params
1615 (dotimes (i count)
1616 (write-char #\page stream))))
1617
1618 (def-format-directive #\~ (colonp atsignp params)
1619 (when (or colonp atsignp)
1620 (error 'format-error
1621 :complaint
1622 "Cannot specify either colon or atsign for this directive."))
1623 (if params
1624 (expand-bind-defaults ((count 1)) params
1625 `(dotimes (i ,count)
1626 (write-char #\~ stream)))
1627 '(write-char #\~ stream)))
1628
1629 (def-format-interpreter #\~ (colonp atsignp params)
1630 (when (or colonp atsignp)
1631 (error 'format-error
1632 :complaint
1633 "Cannot specify either colon or atsign for this directive."))
1634 (interpret-bind-defaults ((count 1)) params
1635 (dotimes (i count)
1636 (write-char #\~ stream))))
1637
1638 (def-complex-format-directive #\newline (colonp atsignp params directives)
1639 (when (and colonp atsignp)
1640 (error 'format-error
1641 :complaint
1642 "Cannot specify both colon and atsign for this directive."))
1643 (values (expand-bind-defaults () params
1644 (if atsignp
1645 '(write-char #\newline stream)
1646 nil))
1647 (if (and (not colonp)
1648 directives
1649 (simple-string-p (car directives)))
1650 (cons (string-left-trim '(#\space #\newline #\tab)
1651 (car directives))
1652 (cdr directives))
1653 directives)))
1654
1655 (def-complex-format-interpreter #\newline (colonp atsignp params directives)
1656 (when (and colonp atsignp)
1657 (error 'format-error
1658 :complaint
1659 "Cannot specify both colon and atsign for this directive."))
1660 (interpret-bind-defaults () params
1661 (when atsignp
1662 (write-char #\newline stream)))
1663 (if (and (not colonp)
1664 directives
1665 (simple-string-p (car directives)))
1666 (cons (string-left-trim '(#\space #\newline #\tab)
1667 (car directives))
1668 (cdr directives))
1669 directives))
1670
1671 (def-complex-format-directive #\return (colonp atsignp params directives)
1672 (when (and colonp atsignp)
1673 (error 'format-error
1674 :complaint
1675 "Cannot specify both colon and atsign for this directive."))
1676 (values (expand-bind-defaults () params
1677 (if atsignp
1678 '(write-char #\newline stream)
1679 nil))
1680 (if (and (not colonp)
1681 directives
1682 (simple-string-p (car directives)))
1683 (cons (string-left-trim '(#\space #\newline #\tab)
1684 (car directives))
1685 (cdr directives))
1686 directives)))
1687
1688 (def-complex-format-interpreter #\return (colonp atsignp params directives)
1689 (when (and colonp atsignp)
1690 (error 'format-error
1691 :complaint
1692 "Cannot specify both colon and atsign for this directive."))
1693 (interpret-bind-defaults () params
1694 (when atsignp
1695 (write-char #\newline stream)))
1696 (if (and (not colonp)
1697 directives
1698 (simple-string-p (car directives)))
1699 (cons (string-left-trim '(#\space #\newline #\tab)
1700 (car directives))
1701 (cdr directives))
1702 directives))
1703
1704 ;;;; Tab and simple pretty-printing noise.
1705
1706 (def-format-directive #\T (colonp atsignp params)
1707 (cond (colonp
1708 (check-output-layout-mode 1)
1709 (expand-bind-defaults ((n 1) (m 1)) params
1710 `(pprint-tab ,(if atsignp :section-relative :section)
1711 ,n ,m stream)))
1712 (atsignp
1713 (expand-bind-defaults ((colrel 1) (colinc 1)) params
1714 `(format-relative-tab stream ,colrel ,colinc)))
1715 (t
1716 (expand-bind-defaults ((colnum 1) (colinc 1)) params
1717 `(format-absolute-tab stream ,colnum ,colinc)))))
1718
1719 (def-format-interpreter #\T (colonp atsignp params)
1720 (cond (colonp
1721 (check-output-layout-mode 1)
1722 (interpret-bind-defaults ((n 1) (m 1)) params
1723 (pprint-tab (if atsignp :section-relative :section) n m stream)))
1724 (atsignp
1725 (interpret-bind-defaults ((colrel 1) (colinc 1)) params
1726 (format-relative-tab stream colrel colinc)))
1727 (t
1728 (interpret-bind-defaults ((colnum 1) (colinc 1)) params
1729 (format-absolute-tab stream colnum colinc)))))
1730
1731 (defun output-spaces (stream n)
1732 (declare (si::c-local))
1733 (let ((spaces #.(make-string 100 :initial-element #\space)))
1734 (loop
1735 (when (< n (length spaces))
1736 (return))
1737 (write-string spaces stream)
1738 (decf n (length spaces)))
1739 (write-string spaces stream :end n)))
1740
1741 (defun format-relative-tab (stream colrel colinc)
1742 #-formatter
1743 (declare (si::c-local))
1744 (if (#-ecl pp:pretty-stream-p #+ecl sys::pretty-stream-p stream)
1745 (pprint-tab :line-relative colrel colinc stream)
1746 (let* ((cur (#-ecl sys::charpos #+ecl sys::file-column stream))
1747 (spaces (if (and cur (plusp colinc))
1748 (- (* (ceiling (+ cur colrel) colinc) colinc) cur)
1749 colrel)))
1750 (output-spaces stream spaces))))
1751
1752 (defun format-absolute-tab (stream colnum colinc)
1753 #-formatter
1754 (declare (si::c-local))
1755 (if (#-ecl pp:pretty-stream-p #+ecl sys::pretty-stream-p stream)
1756 (pprint-tab :line colnum colinc stream)
1757 (let ((cur (#-ecl sys::charpos #+ecl sys:file-column stream)))
1758 (cond ((null cur)
1759 (write-string " " stream))
1760 ((< cur colnum)
1761 (output-spaces stream (- colnum cur)))
1762 (t
1763 (unless (zerop colinc)
1764 (output-spaces stream
1765 (- colinc (rem (- cur colnum) colinc)))))))))
1766
1767 (def-format-directive #\_ (colonp atsignp params)
1768 (check-output-layout-mode 1)
1769 (expand-bind-defaults () params
1770 `(pprint-newline ,(if colonp
1771 (if atsignp
1772 :mandatory
1773 :fill)
1774 (if atsignp
1775 :miser
1776 :linear))
1777 stream)))
1778
1779 (def-format-interpreter #\_ (colonp atsignp params)
1780 (check-output-layout-mode 1)
1781 (interpret-bind-defaults () params
1782 (pprint-newline (if colonp
1783 (if atsignp
1784 :mandatory
1785 :fill)
1786 (if atsignp
1787 :miser
1788 :linear))
1789 stream)))
1790
1791 (def-format-directive #\I (colonp atsignp params)
1792 (check-output-layout-mode 1)
1793 (when atsignp
1794 (error 'format-error
1795 :complaint "Cannot specify the at-sign modifier."))
1796 (expand-bind-defaults ((n 0)) params
1797 `(pprint-indent ,(if colonp :current :block) ,n stream)))
1798
1799 (def-format-interpreter #\I (colonp atsignp params)
1800 (check-output-layout-mode 1)
1801 (when atsignp
1802 (error 'format-error
1803 :complaint "Cannot specify the at-sign modifier."))
1804 (interpret-bind-defaults ((n 0)) params
1805 (pprint-indent (if colonp :current :block) n stream)))
1806
1807
1808 ;;;; *
1809
1810 (def-format-directive #\* (colonp atsignp params end)
1811 (if atsignp
1812 (if colonp
1813 (error 'format-error
1814 :complaint "Cannot specify both colon and at-sign.")
1815 (expand-bind-defaults ((posn 0)) params
1816 (unless *orig-args-available*
1817 (throw 'need-orig-args nil))
1818 `(if (<= 0 ,posn (length orig-args))
1819 (setf args (nthcdr ,posn orig-args))
1820 (error 'format-error
1821 :complaint "Index ~D out of bounds. Should have been ~
1822 between 0 and ~D."
1823 :arguments (list ,posn (length orig-args))
1824 :offset ,(1- end)))))
1825 (if colonp
1826 (expand-bind-defaults ((n 1)) params
1827 (unless *orig-args-available*
1828 (throw 'need-orig-args nil))
1829 `(do ((cur-posn 0 (1+ cur-posn))
1830 (arg-ptr orig-args (cdr arg-ptr)))
1831 ((eq arg-ptr args)
1832 (let ((new-posn (- cur-posn ,n)))
1833 (if (<= 0 new-posn (length orig-args))
1834 (setf args (nthcdr new-posn orig-args))
1835 (error 'format-error
1836 :complaint
1837 "Index ~D out of bounds. Should have been ~
1838 between 0 and ~D."
1839 :arguments
1840 (list new-posn (length orig-args))
1841 :offset ,(1- end)))))))
1842 (if params
1843 (expand-bind-defaults ((n 1)) params
1844 (setf *only-simple-args* nil)
1845 `(dotimes (i ,n)
1846 ,(expand-next-arg)))
1847 (expand-next-arg)))))
1848
1849 (def-format-interpreter #\* (colonp atsignp params)
1850 (if atsignp
1851 (if colonp
1852 (error 'format-error
1853 :complaint "Cannot specify both colon and at-sign.")
1854 (interpret-bind-defaults ((posn 0)) params
1855 (if (<= 0 posn (length orig-args))
1856 (setf args (nthcdr posn orig-args))
1857 (error 'format-error
1858 :complaint "Index ~D out of bounds. Should have been ~
1859 between 0 and ~D."
1860 :arguments (list posn (length orig-args))))))
1861 (if colonp
1862 (interpret-bind-defaults ((n 1)) params
1863 (do ((cur-posn 0 (1+ cur-posn))
1864 (arg-ptr orig-args (cdr arg-ptr)))
1865 ((eq arg-ptr args)
1866 (let ((new-posn (- cur-posn n)))
1867 (if (<= 0 new-posn (length orig-args))
1868 (setf args (nthcdr new-posn orig-args))
1869 (error 'format-error
1870 :complaint
1871 "Index ~D out of bounds. Should have been ~
1872 between 0 and ~D."
1873 :arguments
1874 (list new-posn (length orig-args))))))))
1875 (interpret-bind-defaults ((n 1)) params
1876 (dotimes (i n)
1877 (next-arg))))))
1878
1879
1880 ;;;; Indirection.
1881
1882 (def-format-directive #\? (colonp atsignp params string end)
1883 (when colonp
1884 (error 'format-error
1885 :complaint "Cannot specify the colon modifier."))
1886 (expand-bind-defaults () params
1887 `(handler-bind
1888 ((format-error
1889 #'(lambda (condition)
1890 (error 'format-error
1891 :complaint
1892 "~A~%while processing indirect format string:"
1893 :arguments (list condition)
1894 :print-banner nil
1895 :control-string ,string
1896 :offset ,(1- end)))))
1897 ,(if atsignp
1898 (if *orig-args-available*
1899 `(setf args (formatter-aux stream ,(expand-next-arg) orig-args args))
1900 (throw 'need-orig-args nil))
1901 `(formatter-aux stream ,(expand-next-arg) ,(expand-next-arg))))))
1902
1903 (def-format-interpreter #\? (colonp atsignp params string end)
1904 (when colonp
1905 (error 'format-error
1906 :complaint "Cannot specify the colon modifier."))
1907 (interpret-bind-defaults () params
1908 (handler-bind
1909 ((format-error
1910 #'(lambda (condition)
1911 (error 'format-error
1912 :complaint
1913 "~A~%while processing indirect format string:"
1914 :arguments (list condition)
1915 :print-banner nil
1916 :control-string string
1917 :offset (1- end)))))
1918 (if atsignp
1919 (setf args (formatter-aux stream (next-arg) orig-args args))
1920 (formatter-aux stream (next-arg) (next-arg))))))
1921
1922
1923 ;;;; Capitalization.
1924
1925 (defun nstring-capitalize-first (s)
1926 (nstring-downcase s)
1927 (let ((where (position-if #'alpha-char-p s)))
1928 (when where
1929 (nstring-capitalize s :start 0 :end (1+ where)))
1930 s))
1931
1932 (def-complex-format-directive #\( (colonp atsignp params directives)
1933 (let ((close (find-directive directives #\) nil)))
1934 (unless close
1935 (error 'format-error
1936 :complaint "No corresponding close paren."))
1937 (let* ((posn (position close directives))
1938 (before (subseq directives 0 posn))
1939 (after (nthcdr (1+ posn) directives)))
1940 (values
1941 (expand-bind-defaults () params
1942 #-ecl
1943 `(let ((stream (make-case-frob-stream stream
1944 ,(if colonp
1945 (if atsignp
1946 :upcase
1947 :capitalize)
1948 (if atsignp
1949 :capitalize-first
1950 :downcase)))))
1951 ,@(expand-directive-list before))
1952 #+ecl
1953 `(let ((string (make-array 10 :element-type 'character
1954 :fill-pointer 0 :adjustable t)))
1955 (unwind-protect
1956 (with-output-to-string (stream string)
1957 ,@(expand-directive-list before))
1958 (princ (,(if colonp
1959 (if atsignp 'nstring-upcase 'nstring-capitalize)
1960 (if atsignp 'nstring-capitalize-first 'nstring-downcase))
1961 string)
1962 stream))))
1963 after))))
1964
1965 (def-complex-format-interpreter #\( (colonp atsignp params directives)
1966 (let ((close (find-directive directives #\) nil)))
1967 (unless close
1968 (error 'format-error
1969 :complaint "No corresponding close paren."))
1970 (interpret-bind-defaults () params
1971 #-ecl
1972 (let* ((posn (position close directives))
1973 (before (subseq directives 0 posn))
1974 (after (nthcdr (1+ posn) directives))
1975 (stream (make-case-frob-stream stream
1976 (if colonp
1977 (if atsignp
1978 :upcase
1979 :capitalize)
1980 (if atsignp
1981 :capitalize-first
1982 :downcase)))))
1983 (setf args (interpret-directive-list stream before orig-args args))
1984 after)
1985 #+ecl
1986 (let* ((posn (position close directives))
1987 (before (subseq directives 0 posn))
1988 (jumped t)
1989 (after (nthcdr (1+ posn) directives))
1990 (string (make-array 10 :element-type 'character
1991 :adjustable t :fill-pointer 0)))
1992 (unwind-protect
1993 (with-output-to-string (stream string)
1994 (setf args (interpret-directive-list stream before orig-args args)))
1995 (princ (funcall
1996 (if colonp
1997 (if atsignp 'nstring-upcase 'nstring-capitalize)
1998 (if atsignp 'nstring-capitalize-first 'nstring-downcase))
1999 string) stream))
2000 after))))
2001
2002 (def-complex-format-directive #\) ()
2003 (error 'format-error
2004 :complaint "No corresponding open paren."))
2005
2006 (def-complex-format-interpreter #\) ()
2007 (error 'format-error
2008 :complaint "No corresponding open paren."))
2009
2010
2011 ;;;; Conditionals
2012
2013 (defun parse-conditional-directive (directives)
2014 (declare (si::c-local))
2015 (let ((sublists nil)
2016 (last-semi-with-colon-p nil)
2017 (remaining directives))
2018 (loop
2019 (let ((close-or-semi (find-directive remaining #\] t)))
2020 (unless close-or-semi
2021 (error 'format-error
2022 :complaint "No corresponding close bracket."))
2023 (let ((posn (position close-or-semi remaining)))
2024 (push (subseq remaining 0 posn) sublists)
2025 (setf remaining (nthcdr (1+ posn) remaining))
2026 (when (char= (format-directive-character close-or-semi) #\])
2027 (return))
2028 (setf last-semi-with-colon-p
2029 (format-directive-colonp close-or-semi)))))
2030 (values sublists last-semi-with-colon-p remaining)))
2031
2032 (def-complex-format-directive #\[ (colonp atsignp params directives)
2033 (multiple-value-bind
2034 (sublists last-semi-with-colon-p remaining)
2035 (parse-conditional-directive directives)
2036 (values
2037 (if atsignp
2038 (if colonp
2039 (error 'format-error
2040 :complaint
2041 "Cannot specify both the colon and at-sign modifiers.")
2042 (if (cdr sublists)
2043 (error 'format-error
2044 :complaint
2045 "Can only specify one section")
2046 (expand-bind-defaults () params
2047 (expand-maybe-conditional (car sublists)))))
2048 (if colonp
2049 (if (= (length sublists) 2)
2050 (expand-bind-defaults () params
2051 (expand-true-false-conditional (car sublists)
2052 (cadr sublists)))
2053 (error 'format-error
2054 :complaint
2055 "Must specify exactly two sections."))
2056 (expand-bind-defaults ((index nil)) params
2057 (setf *only-simple-args* nil)
2058 (let* ((clauses nil)
2059 (case `(or ,index ,(expand-next-arg))))
2060 (when last-semi-with-colon-p
2061 (push `(t ,@(expand-directive-list (pop sublists)))
2062 clauses))
2063 (let ((count (length sublists)))
2064 (dolist (sublist sublists)
2065 (push `(,(decf count)
2066 ,@(expand-directive-list sublist))
2067 clauses)))
2068 `(case ,case ,@clauses)))))
2069 remaining)))
2070
2071 #+formatter
2072 (defun expand-maybe-conditional (sublist)
2073 (declare (si::c-local))
2074 (flet ((hairy ()
2075 `(let ((prev-args args)
2076 (arg ,(expand-next-arg)))
2077 (when arg
2078 (setf args prev-args)
2079 ,@(expand-directive-list sublist)))))
2080 (if *only-simple-args*
2081 (multiple-value-bind (guts new-args)
2082 (let ((*simple-args* *simple-args*))
2083 (values (expand-directive-list sublist)
2084 *simple-args*))
2085 (cond ((and new-args (eq *simple-args* (cdr new-args)))
2086 (setf *simple-args* new-args)
2087 `(when ,(caar new-args)
2088 ,@guts))
2089 (t
2090 (setf *only-simple-args* nil)
2091 (hairy))))
2092 (hairy))))
2093
2094 #+formatter
2095 (defun expand-true-false-conditional (true false)
2096 (declare (si::c-local))
2097 (let ((arg (expand-next-arg)))
2098 (flet ((hairy ()
2099 `(if ,arg
2100 (progn
2101 ,@(expand-directive-list true))
2102 (progn
2103 ,@(expand-directive-list false)))))
2104 (if *only-simple-args*
2105 (multiple-value-bind
2106 (true-guts true-args true-simple)
2107 (let ((*simple-args* *simple-args*)
2108 (*only-simple-args* t))
2109 (values (expand-directive-list true)
2110 *simple-args*
2111 *only-simple-args*))
2112 (multiple-value-bind
2113 (false-guts false-args false-simple)
2114 (let ((*simple-args* *simple-args*)
2115 (*only-simple-args* t))
2116 (values (expand-directive-list false)
2117 *simple-args*
2118 *only-simple-args*))
2119 (if (= (length true-args) (length false-args))
2120 `(if ,arg
2121 (progn
2122 ,@true-guts)
2123 ,(do ((false false-args (cdr false))
2124 (true true-args (cdr true))
2125 (bindings nil (cons `(,(caar false) ,(caar true))
2126 bindings)))
2127 ((eq true *simple-args*)
2128 (setf *simple-args* true-args)
2129 (setf *only-simple-args*
2130 (and true-simple false-simple))
2131 (if bindings
2132 `(let ,bindings
2133 ,@false-guts)
2134 `(progn
2135 ,@false-guts)))))
2136 (progn
2137 (setf *only-simple-args* nil)
2138 (hairy)))))
2139 (hairy)))))
2140
2141
2142
2143 (def-complex-format-interpreter #\[ (colonp atsignp params directives)
2144 (multiple-value-bind
2145 (sublists last-semi-with-colon-p remaining)
2146 (parse-conditional-directive directives)
2147 (setf args
2148 (if atsignp
2149 (if colonp
2150 (error 'format-error
2151 :complaint
2152 "Cannot specify both the colon and at-sign modifiers.")
2153 (if (cdr sublists)
2154 (error 'format-error
2155 :complaint
2156 "Can only specify one section")
2157 (interpret-bind-defaults () params
2158 (let ((prev-args args)
2159 (arg (next-arg)))
2160 (if arg
2161 (interpret-directive-list stream
2162 (car sublists)
2163 orig-args
2164 prev-args)
2165 args)))))
2166 (if colonp
2167 (if (= (length sublists) 2)
2168 (interpret-bind-defaults () params
2169 (if (next-arg)
2170 (interpret-directive-list stream (car sublists)
2171 orig-args args)
2172 (interpret-directive-list stream (cadr sublists)
2173 orig-args args)))
2174 (error 'format-error
2175 :complaint
2176 "Must specify exactly two sections."))
2177 (interpret-bind-defaults ((index (next-arg))) params
2178 (let* ((default (and last-semi-with-colon-p
2179 (pop sublists)))
2180 (last (1- (length sublists)))
2181 (sublist
2182 (if (<= 0 index last)
2183 (nth (- last index) sublists)
2184 default)))
2185 (interpret-directive-list stream sublist orig-args
2186 args))))))
2187 remaining))
2188
2189 (def-complex-format-directive #\; ()
2190 (error 'format-error
2191 :complaint
2192 "~~; not contained within either ~~[...~~] or ~~<...~~>."))
2193
2194 (def-complex-format-interpreter #\; ()
2195 (error 'format-error
2196 :complaint
2197 "~~; not contained within either ~~[...~~] or ~~<...~~>."))
2198
2199 (def-complex-format-interpreter #\] ()
2200 (error 'format-error
2201 :complaint
2202 "No corresponding open bracket."))
2203
2204 (def-complex-format-directive #\] ()
2205 (error 'format-error
2206 :complaint
2207 "No corresponding open bracket."))
2208
2209
2210 ;;;; Up-and-out.
2211
2212 (defvar *outside-args*)
2213
2214 (def-format-directive #\^ (colonp atsignp params)
2215 (when atsignp
2216 (error 'format-error
2217 :complaint "cannot use the at-sign modifier with this directive"))
2218 (when (and colonp (not *up-up-and-out-allowed*))
2219 (error 'format-error
2220 :complaint "attempt to use ~~:^ outside a ~~:{...~~} construct"))
2221 `(when ,(expand-bind-defaults ((arg1 nil) (arg2 nil) (arg3 nil)) params
2222 `(cond (,arg3 (<= ,arg1 ,arg2 ,arg3))
2223 (,arg2 (eql ,arg1 ,arg2))
2224 (,arg1 (eql ,arg1 0))
2225 (t ,(if colonp
2226 '(null outside-args)
2227 (progn
2228 (setf *only-simple-args* nil)
2229 '(null args))))))
2230 ,(if colonp
2231 '(return-from outside-loop nil)
2232 '(return))))
2233
2234 (def-format-interpreter #\^ (colonp atsignp params)
2235 (when atsignp
2236 (error 'format-error
2237 :complaint "cannot specify the at-sign modifier"))
2238 (when (and colonp (not *up-up-and-out-allowed*))
2239 (error 'format-error
2240 :complaint "attempt to use ~~:^ outside a ~~:{...~~} construct"))
2241 (when (interpret-bind-defaults ((arg1 nil) (arg2 nil) (arg3 nil)) params
2242 (cond (arg3 (<= arg1 arg2 arg3))
2243 (arg2 (eql arg1 arg2))
2244 (arg1 (eql arg1 0))
2245 (t (if colonp
2246 (null *outside-args*)
2247 (null args)))))
2248 (throw (if colonp 'up-up-and-out 'up-and-out)
2249 args)))
2250
2251
2252 ;;;; Iteration.
2253
2254 (def-complex-format-directive #\{ (colonp atsignp params string end directives)
2255 (let ((close (find-directive directives #\} nil)))
2256 (unless close
2257 (error 'format-error
2258 :complaint "no corresponding close brace"))
2259 (let* ((closed-with-colon (format-directive-colonp close))
2260 (posn (position close directives)))
2261 (labels
2262 ((compute-insides ()
2263 (if (zerop posn)
2264 (if *orig-args-available*
2265 `((handler-bind
2266 ((format-error
2267 (lambda (condition)
2268 (error 'format-error
2269 :complaint
2270 "~A~%while processing indirect format string:"
2271 :args (list condition)
2272 :print-banner nil
2273 :control-string ,string
2274 :offset ,(1- end)))))
2275 (setf args
2276 (formatter-aux stream inside-string orig-args args))))
2277 (throw 'need-orig-args nil))
2278 (let ((*up-up-and-out-allowed* colonp))
2279 (expand-directive-list (subseq directives 0 posn)))))
2280 (compute-loop (count)
2281 (when atsignp
2282 (setf *only-simple-args* nil))
2283 `(loop
2284 ,@(unless closed-with-colon
2285 '((when (null args)
2286 (return))))
2287 ,@(when count
2288 `((when (and ,count (minusp (decf ,count)))
2289 (return))))
2290 ,@(if colonp
2291 (let ((*expander-next-arg-macro* 'expander-next-arg)
2292 (*only-simple-args* nil)
2293 (*orig-args-available* t))
2294 `((let* ((orig-args ,(expand-next-arg))
2295 (outside-args args)
2296 (args orig-args))
2297 (declare (ignorable orig-args outside-args args))
2298 (block nil
2299 ,@(compute-insides)))))
2300 (compute-insides))
2301 ,@(when closed-with-colon
2302 '((when (null args)
2303 (return))))))
2304 (compute-block (count)
2305 (if colonp
2306 `(block outside-loop
2307 ,(compute-loop count))
2308 (compute-loop count)))
2309 (compute-bindings (count)
2310 (if atsignp
2311 (compute-block count)
2312 `(let* ((orig-args ,(expand-next-arg))
2313 (args orig-args))
2314 (declare (ignorable orig-args args))
2315 ,(let ((*expander-next-arg-macro* 'expander-next-arg)
2316 (*only-simple-args* nil)
2317 (*orig-args-available* t))
2318 (compute-block count))))))
2319 (values (if params
2320 (expand-bind-defaults ((count nil)) params
2321 (if (zerop posn)
2322 `(let ((inside-string ,(expand-next-arg)))
2323 ,(compute-bindings count))
2324 (compute-bindings count)))
2325 (if (zerop posn)
2326 `(let ((inside-string ,(expand-next-arg)))
2327 ,(compute-bindings nil))
2328 (compute-bindings nil)))
2329 (nthcdr (1+ posn) directives))))))
2330
2331 (def-complex-format-interpreter #\{
2332 (colonp atsignp params string end directives)
2333 (let ((close (find-directive directives #\} nil)))
2334 (unless close
2335 (error 'format-error
2336 :complaint
2337 "No corresponding close brace."))
2338 (interpret-bind-defaults ((max-count nil)) params
2339 (let* ((closed-with-colon (format-directive-colonp close))
2340 (posn (position close directives))
2341 (insides (if (zerop posn)
2342 (next-arg)
2343 (subseq directives 0 posn)))
2344 (*up-up-and-out-allowed* colonp))
2345 (labels
2346 ((do-guts (orig-args args)
2347 (if (zerop posn)
2348 (handler-bind
2349 ((format-error
2350 #'(lambda (condition)
2351 (error 'format-error
2352 :complaint
2353 "~A~%while processing indirect format string:"
2354 :arguments (list condition)
2355 :print-banner nil
2356 :control-string string
2357 :offset (1- end)))))
2358 (formatter-aux stream insides orig-args args))
2359 (interpret-directive-list stream insides
2360 orig-args args)))
2361 (bind-args (orig-args args)
2362 (if colonp
2363 (let* ((arg (next-arg))
2364 (*logical-block-popper* nil)
2365 (*outside-args* args))
2366 (catch 'up-and-out
2367 (do-guts arg arg))
2368 args)
2369 (do-guts orig-args args)))
2370 (do-loop (orig-args args)
2371 (catch (if colonp 'up-up-and-out 'up-and-out)
2372 (loop
2373 (when (and (not closed-with-colon) (null args))
2374 (return))
2375 (when (and max-count (minusp (decf max-count)))
2376 (return))
2377 (setf args (bind-args orig-args args))
2378 (when (and closed-with-colon (null args))
2379 (return)))
2380 args)))
2381 (if atsignp
2382 (setf args (do-loop orig-args args))
2383 (let ((arg (next-arg))
2384 (*logical-block-popper* nil))
2385 (do-loop arg arg)))
2386 (nthcdr (1+ posn) directives))))))
2387
2388 (def-complex-format-directive #\} ()
2389 (error 'format-error
2390 :complaint "No corresponding open brace."))
2391
2392 (def-complex-format-interpreter #\} ()
2393 (error 'format-error
2394 :complaint "No corresponding open brace."))
2395
2396
2397
2398 ;;;; Justification.
2399
2400 (defparameter *illegal-inside-justification*
2401 (mapcar (lambda (x) (parse-directive x 0))
2402 '("~W" "~:W" "~@W" "~:@W"
2403 "~_" "~:_" "~@_" "~:@_"
2404 "~:>" "~:@>"
2405 "~I" "~:I" "~@I" "~:@I"
2406 "~:T" "~:@T")))
2407
2408 (defun check-output-layout-mode (mode)
2409 (declare (si::c-local))
2410 (when (and *output-layout-mode*
2411 (not (eql *output-layout-mode* mode)))
2412 (error 'format-error
2413 :complaint "Cannot mix ~~W, ~~_, ~~<...~~:>, ~~I, or ~~T with ~~<...~~:;...~~>"))
2414 (setf *output-layout-mode* mode))
2415
2416 (defun illegal-inside-justification-p (directive)
2417 (member directive *illegal-inside-justification*
2418 :test (lambda (x y)
2419 (and (format-directive-p x)
2420 (format-directive-p y)
2421 (eql (format-directive-character x) (format-directive-character y))
2422 (eql (format-directive-colonp x) (format-directive-colonp y))
2423 (eql (format-directive-atsignp x) (format-directive-atsignp y))))))
2424
2425 (def-complex-format-directive #\< (colonp atsignp params string end directives)
2426 (multiple-value-bind
2427 (segments first-semi close remaining)
2428 (parse-format-justification directives)
2429 (values
2430 (if (format-directive-colonp close)
2431 (multiple-value-bind
2432 (prefix per-line-p insides suffix)
2433 (parse-format-logical-block segments colonp first-semi
2434 close params string end)
2435 (expand-format-logical-block prefix per-line-p insides
2436 suffix atsignp))
2437 (let ((count (reduce #'+ (mapcar (lambda (x)
2438 (count-if #'illegal-inside-justification-p x))
2439 segments))))
2440 (when (> count 0)
2441 ;; ANSI specifies that "an error is signalled" in this
2442 ;; situation.
2443 (error 'format-error
2444 :complaint "~D illegal directive~:P found inside justification block"
2445 :arguments (list count)))
2446 (expand-format-justification segments colonp atsignp
2447 first-semi params)))
2448 remaining)))
2449
2450 (def-complex-format-interpreter #\<
2451 (colonp atsignp params string end directives)
2452 (multiple-value-bind
2453 (segments first-semi close remaining)
2454 (parse-format-justification directives)
2455 (setf args
2456 (if (format-directive-colonp close)
2457 (multiple-value-bind
2458 (prefix per-line-p insides suffix)
2459 (parse-format-logical-block segments colonp first-semi
2460 close params string end)
2461 (interpret-format-logical-block stream orig-args args
2462 prefix per-line-p insides
2463 suffix atsignp))
2464 (let ((count (reduce #'+ (mapcar (lambda (x)
2465 (count-if #'illegal-inside-justification-p x))
2466 segments))))
2467 (when (> count 0)
2468 ;; ANSI specifies that "an error is signalled" in this
2469 ;; situation.
2470 (error 'format-error
2471 :complaint "~D illegal directive~:P found inside justification block"
2472 :arguments (list count)))
2473 (interpret-format-justification stream orig-args args
2474 segments colonp atsignp
2475 first-semi params))))
2476 remaining))
2477
2478 (defun parse-format-justification (directives)
2479 (declare (si::c-local))
2480 (let ((first-semi nil)
2481 (close nil)
2482 (remaining directives))
2483 (collect ((segments))
2484 (loop
2485 (let ((close-or-semi (find-directive remaining #\> t)))
2486 (unless close-or-semi
2487 (error 'format-error
2488 :complaint "No corresponding close bracket."))
2489 (let ((posn (position close-or-semi remaining)))
2490 (segments (subseq remaining 0 posn))
2491 (setf remaining (nthcdr (1+ posn) remaining)))
2492 (when (char= (format-directive-character close-or-semi)
2493 #\>)
2494 (setf close close-or-semi)
2495 (return))
2496 (unless first-semi
2497 (setf first-semi close-or-semi))))
2498 (values (segments) first-semi close remaining))))
2499
2500 #+formatter
2501 (defun expand-format-justification (segments colonp atsignp first-semi params)
2502 (declare (si::c-local))
2503 (let ((newline-segment-p
2504 (and first-semi
2505 (format-directive-colonp first-semi))))
2506 (when newline-segment-p
2507 (check-output-layout-mode 2))
2508 (expand-bind-defaults
2509 ((mincol 0) (colinc 1) (minpad 0) (padchar #\space))
2510 params
2511 `(let ((segments nil)
2512 ,@(when newline-segment-p
2513 '((newline-segment nil)
2514 (extra-space 0)
2515 (line-len 72))))
2516 (block nil
2517 ,@(when newline-segment-p
2518 `((setf newline-segment
2519 (with-output-to-string (stream)
2520 ,@(expand-directive-list (pop segments))))
2521 ,(expand-bind-defaults
2522 ((extra 0)
2523 (line-len '(or *print-right-margin*
2524 (gray:stream-line-length stream)
2525 default-line-length)))
2526 (format-directive-params first-semi)
2527 `(setf extra-space ,extra line-len ,line-len))))
2528 ,@(mapcar #'(lambda (segment)
2529 `(push (with-output-to-string (stream)
2530 ,@(expand-directive-list segment))
2531 segments))
2532 segments))
2533 (format-justification stream
2534 ,@(if newline-segment-p
2535 '(newline-segment extra-space line-len)
2536 '(nil 0 0))
2537 segments ,colonp ,atsignp
2538 ,mincol ,colinc ,minpad ,padchar)))))
2539
2540 (defun interpret-format-justification
2541 (stream orig-args args segments colonp atsignp first-semi params)
2542 (declare (si::c-local))
2543 (interpret-bind-defaults
2544 ((mincol 0) (colinc 1) (minpad 0) (padchar #\space))
2545 params
2546 (let ((newline-string nil)
2547 (strings nil)
2548 (extra-space 0)
2549 (line-len 0))
2550 (setf args
2551 (catch 'up-and-out
2552 (when (and first-semi (format-directive-colonp first-semi))
2553 (check-output-layout-mode 2)
2554 (interpret-bind-defaults
2555 ((extra 0)
2556 (len (or *print-right-margin*
2557 (gray:stream-line-length stream)
2558 default-line-length)))
2559 (format-directive-params first-semi)
2560 (setf newline-string
2561 (with-output-to-string (stream)
2562 (setf args
2563 (interpret-directive-list stream
2564 (pop segments)
2565 orig-args
2566 args))))
2567 (setf extra-space extra)
2568 (setf line-len len)))
2569 (dolist (segment segments)
2570 (push (with-output-to-string (stream)
2571 (setf args
2572 (interpret-directive-list stream segment
2573 orig-args args)))
2574 strings))
2575 args))
2576 (format-justification stream newline-string extra-space line-len strings
2577 colonp atsignp mincol colinc minpad padchar)))
2578 args)
2579
2580 (defun format-justification (stream newline-prefix extra-space line-len strings
2581 pad-left pad-right mincol colinc minpad padchar)
2582 #-formatter
2583 (declare (si::c-local))
2584 (setf strings (reverse strings))
2585 (when (and (not pad-left) (not pad-right) (null (cdr strings)))
2586 (setf pad-left t))
2587 (let* ((num-gaps (1- (length strings)))
2588 (chars (+ (* num-gaps minpad)
2589 (loop for string in strings summing (length string))))
2590 (length (if (> chars mincol)
2591 (+ mincol (* (ceiling (- chars mincol) colinc) colinc))
2592 mincol))
2593 (padding (- length chars)))
2594 (when (and newline-prefix
2595 (> (+ (or (#-ecl sys::charpos #+ecl sys:file-column stream) 0)
2596 length extra-space)
2597 line-len))
2598 (write-string newline-prefix stream))
2599 (when pad-left
2600 (incf num-gaps))
2601 (when pad-right
2602 (incf num-gaps))
2603 (when (zerop num-gaps)
2604 (incf num-gaps)
2605 (setf pad-left t))
2606 (flet ((do-padding (border)
2607 (let ((pad-len (truncate padding num-gaps)))
2608 (decf padding pad-len)
2609 (decf num-gaps)
2610 (unless border
2611 (incf pad-len minpad))
2612 (dotimes (i pad-len) (write-char padchar stream)))))
2613 (when pad-left
2614 (do-padding t))
2615 (when strings
2616 (write-string (car strings) stream)
2617 (dolist (string (cdr strings))
2618 (do-padding nil)
2619 (write-string string stream)))
2620 (when pad-right
2621 (do-padding t)))))
2622
2623 (defun parse-format-logical-block
2624 (segments colonp first-semi close params string end)
2625 (declare (si::c-local))
2626 (check-output-layout-mode 1)
2627 (when params
2628 (error 'format-error
2629 :complaint "No parameters can be supplied with ~~<...~~:>."
2630 :offset (caar params)))
2631 (multiple-value-bind
2632 (prefix insides suffix)
2633 (multiple-value-bind (prefix-default suffix-default)
2634 (if colonp (values "(" ")") (values "" ""))
2635 (flet ((extract-string (list prefix-p)
2636 (let ((directive (find-if #'format-directive-p list)))
2637 (if directive
2638 (error 'format-error
2639 :complaint
2640 "Cannot include format directives inside the ~
2641 ~:[suffix~;prefix~] segment of ~~<...~~:>"
2642 :arguments (list prefix-p)
2643 :offset (1- (format-directive-end directive)))
2644 (apply #'concatenate 'string list)))))
2645 (case (length segments)
2646 (0 (values prefix-default nil suffix-default))
2647 (1 (values prefix-default (car segments) suffix-default))
2648 (2 (values (extract-string (car segments) t)
2649 (cadr segments) suffix-default))
2650 (3 (values (extract-string (car segments) t)
2651 (cadr segments)
2652 (extract-string (caddr segments) nil)))
2653 (t
2654 (error 'format-error
2655 :complaint "Too many segments for ~~<...~~:>.")))))
2656 (when (format-directive-atsignp close)
2657 (setf insides
2658 (add-fill-style-newlines insides
2659 string
2660 (if first-semi
2661 (format-directive-end first-semi)
2662 end))))
2663 (values prefix
2664 (and first-semi (format-directive-atsignp first-semi))
2665 insides
2666 suffix)))
2667
2668 (defun add-fill-style-newlines (list string offset &optional previous-directive-is-newline)
2669 (declare (si::c-local))
2670 (if list
2671 (let ((directive (car list)))
2672 (if (and (simple-string-p directive)
2673 (not previous-directive-is-newline))
2674 (nconc (add-fill-style-newlines-aux directive string offset)
2675 (add-fill-style-newlines (cdr list)
2676 string
2677 (+ offset (length directive))
2678 nil))
2679 (cons directive
2680 (add-fill-style-newlines (cdr list)
2681 string
2682 (format-directive-end directive)
2683 (char= (format-directive-character directive)
2684 #\newline)))))
2685 nil))
2686
2687 (defun add-fill-style-newlines-aux (literal string offset)
2688 (declare (si::c-local))
2689 (let ((end (length literal))
2690 (posn 0))
2691 (collect ((results))
2692 (loop
2693 (let ((blank (position #\space literal :start posn)))
2694 (when (null blank)
2695 (results (subseq literal posn))
2696 (return))
2697 (let ((non-blank (or (position #\space literal :start blank
2698 :test #'char/=)
2699 end)))
2700 (results (subseq literal posn non-blank))
2701 (results (make-format-directive
2702 :string string :character #\_
2703 :start (+ offset non-blank) :end (+ offset non-blank)
2704 :colonp t :atsignp nil :params nil))
2705 (setf posn non-blank))
2706 (when (= posn end)
2707 (return))))
2708 (results))))
2709
2710 #+formatter
2711 (defun expand-format-logical-block (prefix per-line-p insides suffix atsignp)
2712 `(let ((arg ,(if atsignp 'args (expand-next-arg))))
2713 ,@(when atsignp
2714 (setf *only-simple-args* nil)
2715 '((setf args nil)))
2716 (pprint-logical-block
2717 (stream arg
2718 ,(if per-line-p :per-line-prefix :prefix) ,prefix
2719 :suffix ,suffix)
2720 (let ((args arg)
2721 ,@(unless atsignp
2722 `((orig-args arg))))
2723 (declare (ignorable args ,@(unless atsignp '(orig-args))))
2724 (block nil
2725 ,@(let ((*expander-next-arg-macro* 'expander-pprint-next-arg)
2726 (*only-simple-args* nil)
2727 (*orig-args-available* t))
2728 (expand-directive-list insides)))))))
2729
2730 (defun interpret-format-logical-block
2731 (stream orig-args args prefix per-line-p insides suffix atsignp)
2732 (declare (si::c-local))
2733 (let ((arg (if atsignp args (next-arg))))
2734 (if per-line-p
2735 (pprint-logical-block
2736 (stream arg :per-line-prefix prefix :suffix suffix)
2737 (let ((*logical-block-popper* #'(lambda () (pprint-pop))))
2738 (catch 'up-and-out
2739 (interpret-directive-list stream insides
2740 (if atsignp orig-args arg)
2741 arg))))
2742 (pprint-logical-block (stream arg :prefix prefix :suffix suffix)
2743 (let ((*logical-block-popper* #'(lambda () (pprint-pop))))
2744 (catch 'up-and-out
2745 (interpret-directive-list stream insides
2746 (if atsignp orig-args arg)
2747 arg))))))
2748 (if atsignp nil args))
2749
2750 (def-complex-format-directive #\> ()
2751 (error 'format-error
2752 :complaint "No corresponding open bracket."))
2753
2754
2755 ;;;; User-defined method.
2756
2757 (def-format-directive #\/ (string start end colonp atsignp params)
2758 (let ((symbol (extract-user-function-name string start end)))
2759 (collect ((param-names) (bindings))
2760 (dolist (param-and-offset params)
2761 (let ((param (cdr param-and-offset)))
2762 (let ((param-name (gensym)))
2763 (param-names param-name)
2764 (bindings `(,param-name
2765 ,(case param
2766 (:arg (expand-next-arg))
2767 (:remaining '(length args))
2768 (t param)))))))
2769 `(let ,(bindings)
2770 (,symbol stream ,(expand-next-arg) ,colonp ,atsignp
2771 ,@(param-names))))))
2772
2773 (def-format-interpreter #\/ (string start end colonp atsignp params)
2774 (let ((symbol (extract-user-function-name string start end)))
2775 (collect ((args))
2776 (dolist (param-and-offset params)
2777 (let ((param (cdr param-and-offset)))
2778 (case param
2779 (:arg (args (next-arg)))
2780 (:remaining (args (length args)))
2781 (t (args param)))))
2782 (apply (fdefinition symbol) stream (next-arg) colonp atsignp (args)))))
2783
2784 (defun extract-user-function-name (string start end)
2785 (declare (si::c-local))
2786 (let ((slash (position #\/ string :start start :end (1- end)
2787 :from-end t)))
2788 (unless slash
2789 (error 'format-error
2790 :complaint "Malformed ~~/ directive."))
2791 (let* ((name (string-upcase (let ((foo string))
2792 ;; Hack alert: This is to keep the compiler
2793 ;; quit about deleting code inside the subseq
2794 ;; expansion.
2795 (subseq foo (1+ slash) (1- end)))))
2796 (first-colon (position #\: name))
2797 (second-colon (if first-colon (position #\: name :start (1+ first-colon))))
2798 (package-name (if first-colon
2799 (subseq name 0 first-colon)
2800 "COMMON-LISP-USER"))
2801 (package (find-package package-name)))
2802 (unless package
2803 (error 'format-error
2804 :complaint "No package named ~S"
2805 :arguments (list package-name)))
2806 (intern (cond
2807 ((and second-colon (= second-colon (1+ first-colon)))
2808 (subseq name (1+ second-colon)))
2809 (first-colon
2810 (subseq name (1+ first-colon)))
2811 (t name))
2812 package))))
2813
2814
2815 ;;;; Compile-time checking of format arguments and control string
2816
2817 #-ecl(progn
2818 ;;;
2819 ;;; Return the min/max numbers of arguments required for a call to
2820 ;;; FORMAT with control string FORMAT-STRING, null if we can't tell,
2821 ;;; or a string with an error message if parsing the control string
2822 ;;; causes a FORMAT-ERROR.
2823 ;;;
2824 ;;; This is called from FORMAT deftransforms.
2825 ;;;
2826 (defun min/max-format-arguments-count (string)
2827 #-formatter
2828 (declare (si::c-local))
2829 (handler-case
2830 (catch 'give-up
2831 ;; For the side effect of validating the control string.
2832 (%formatter string)
2833 (%min/max-format-args (tokenize-control-string string)))
2834 (format-error (e)
2835 (format nil "~a" e))))
2836
2837 (defun %min/max-format-args (directives)
2838 #-formatter
2839 (declare (si::c-local))
2840 (let ((min-req 0) (max-req 0))
2841 (flet ((incf-both (&optional (n 1))
2842 (incf min-req n)
2843 (incf max-req n)))
2844 (loop
2845 (let ((dir (pop directives)))
2846 (when (null dir)
2847 (return (values min-req max-req)))
2848 (when (format-directive-p dir)
2849 (incf-both (count :arg (format-directive-params dir) :key #'cdr))
2850 (let ((c (format-directive-character dir)))
2851 (cond ((find c "ABCDEFGORSWX$/")
2852 (incf-both))
2853 ((char= c #\P)
2854 (unless (format-directive-colonp dir)
2855 (incf-both)))
2856 ((or (find c "IT%&|_<>();") (char= c #\newline)))
2857 ((char= c #\[)
2858 (multiple-value-bind (min max remaining)
2859 (%min/max-conditional-args dir directives)
2860 (setq directives remaining)
2861 (incf min-req min)
2862 (incf max-req max)))
2863 ((char= c #\{)
2864 (multiple-value-bind (min max remaining)
2865 (%min/max-iteration-args dir directives)
2866 (setq directives remaining)
2867 (incf min-req min)
2868 (incf max-req max)))
2869 ((char= c #\?)
2870 (cond ((format-directive-atsignp dir)
2871 (incf min-req)
2872 (setq max-req most-positive-fixnum))
2873 (t (incf-both 2))))
2874 (t (throw 'give-up nil))))))))))
2875
2876 ;;;
2877 ;;; ANSI: if arg is out of range, no clause is selected. That means
2878 ;;; the minimum number of args required for the interior of ~[~] is
2879 ;;; always zero.
2880 ;;;
2881 (defun %min/max-conditional-args (conditional directives)
2882 #-formatter
2883 (declare (si::c-local))
2884 (multiple-value-bind (sublists last-semi-with-colon-p remaining)
2885 (parse-conditional-directive directives)
2886 (declare (ignore last-semi-with-colon-p))
2887 (let ((sub-max (loop for s in sublists maximize
2888 (nth-value 1 (%min/max-format-args s))))
2889 (min-req 1)
2890 max-req)
2891 (cond ((format-directive-atsignp conditional)
2892 (setq max-req (max 1 sub-max)))
2893 ((loop for p in (format-directive-params conditional)
2894 thereis (or (integerp (cdr p))
2895 (memq (cdr p) '(:remaining :arg))))
2896 (setq min-req 0)
2897 (setq max-req sub-max))
2898 (t
2899 (setq max-req (1+ sub-max))))
2900 (values min-req max-req remaining))))
2901
2902 (defun %min/max-iteration-args (iteration directives)
2903 #-formatter
2904 (declare (si::c-local))
2905 (let* ((close (find-directive directives #\} nil))
2906 (posn (position close directives))
2907 (remaining (nthcdr (1+ posn) directives)))
2908 (if (format-directive-atsignp iteration)
2909 (values (if (zerop posn) 1 0) most-positive-fixnum remaining)
2910 (let ((nreq (if (zerop posn) 2 1)))
2911 (values nreq nreq remaining)))))
2912 )