3 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!IMPL")
14 ;;;; exported printer control variables
16 ;;; FIXME: Many of these have nontrivial types, e.g. *PRINT-LEVEL*,
17 ;;; *PRINT-LENGTH*, and *PRINT-LINES* are (OR NULL UNSIGNED-BYTE).
19 (!defvar
*print-readably
* nil
21 "If true, all objects will be printed readably. If readable printing
22 is impossible, an error will be signalled. This overrides the value of
24 (!defvar
*print-escape
* t
26 "Should we print in a reasonably machine-readable way? (possibly
27 overridden by *PRINT-READABLY*)")
28 (!defvar
*print-pretty
* nil
; (set later when pretty-printer is initialized)
30 "Should pretty printing be used?")
31 (!defvar
*print-base
* 10.
33 "The output base for RATIONALs (including integers).")
34 (!defvar
*print-radix
* nil
36 "Should base be verified when printing RATIONALs?")
37 (!defvar
*print-level
* nil
39 "How many levels should be printed before abbreviating with \"#\"?")
40 (!defvar
*print-length
* nil
42 "How many elements at any level should be printed before abbreviating
44 (!defvar
*print-circle
* nil
46 "Should we use #n= and #n# notation to preserve uniqueness in general (and
47 circularity in particular) when printing?")
48 (!defvar
*print-case
* :upcase
50 "What case should the printer should use default?")
51 (!defvar
*print-array
* t
53 "Should the contents of arrays be printed?")
54 (!defvar
*print-gensym
* t
56 "Should #: prefixes be used when printing symbols with null SYMBOL-PACKAGE?")
57 (defvar *print-lines
* nil
59 "The maximum number of lines to print per object.")
60 (defvar *print-right-margin
* nil
62 "The position of the right margin in ems (for pretty-printing).")
63 (defvar *print-miser-width
* nil
65 "If the remaining space between the current column and the right margin
66 is less than this, then print using ``miser-style'' output. Miser
67 style conditional newlines are turned on, and all indentations are
68 turned off. If NIL, never use miser mode.")
69 (defvar *print-pprint-dispatch
*)
71 (setf (fdocumentation '*print-pprint-dispatch
* 'variable
)
72 "The pprint-dispatch-table that controls how to pretty-print objects.")
73 (!defvar
*suppress-print-errors
* nil
75 "Suppress printer errors when the condition is of the type designated by this
76 variable: an unreadable object representing the error is printed instead.")
78 (defmacro with-standard-io-syntax
(&body body
)
80 "Bind the reader and printer control variables to values that enable READ
81 to reliably read the results of PRINT. These values are:
83 *PACKAGE* the COMMON-LISP-USER package
93 *PRINT-MISER-WIDTH* NIL
94 *PRINT-PPRINT-DISPATCH* the standard pprint dispatch table
98 *PRINT-RIGHT-MARGIN* NIL
100 *READ-DEFAULT-FLOAT-FORMAT* SINGLE-FLOAT
103 *READTABLE* the standard readtable
104 SB-EXT:*SUPPRESS-PRINT-ERRORS* NIL
106 `(%with-standard-io-syntax
(lambda () ,@body
)))
108 ;; duplicate defglobal because this file is compiled before "reader"
109 (defglobal *standard-readtable
* nil
)
110 (defun %with-standard-io-syntax
(function)
111 (declare (type function function
))
112 (let ((*package
* (find-package "COMMON-LISP-USER"))
115 (*print-case
* :upcase
)
122 (*print-miser-width
* nil
)
123 (*print-pprint-dispatch
* sb
!pretty
::*standard-pprint-dispatch-table
*)
127 (*print-right-margin
* nil
)
129 (*read-default-float-format
* 'single-float
)
131 (*read-suppress
* nil
)
132 (*readtable
* *standard-readtable
*)
133 (*suppress-print-errors
* nil
))
136 ;;;; routines to print objects
138 (defun write (object &key
139 ((:stream stream
) *standard-output
*)
140 ((:escape
*print-escape
*) *print-escape
*)
141 ((:radix
*print-radix
*) *print-radix
*)
142 ((:base
*print-base
*) *print-base
*)
143 ((:circle
*print-circle
*) *print-circle
*)
144 ((:pretty
*print-pretty
*) *print-pretty
*)
145 ((:level
*print-level
*) *print-level
*)
146 ((:length
*print-length
*) *print-length
*)
147 ((:case
*print-case
*) *print-case
*)
148 ((:array
*print-array
*) *print-array
*)
149 ((:gensym
*print-gensym
*) *print-gensym
*)
150 ((:readably
*print-readably
*) *print-readably
*)
151 ((:right-margin
*print-right-margin
*)
152 *print-right-margin
*)
153 ((:miser-width
*print-miser-width
*)
155 ((:lines
*print-lines
*) *print-lines
*)
156 ((:pprint-dispatch
*print-pprint-dispatch
*)
157 *print-pprint-dispatch
*)
158 ((:suppress-errors
*suppress-print-errors
*)
159 *suppress-print-errors
*))
161 "Output OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*."
162 (output-object object
(out-synonym-of stream
))
165 (defun prin1 (object &optional stream
)
167 "Output a mostly READable printed representation of OBJECT on the specified
169 (let ((*print-escape
* t
))
170 (output-object object
(out-synonym-of stream
)))
173 (defun princ (object &optional stream
)
175 "Output an aesthetic but not necessarily READable printed representation
176 of OBJECT on the specified STREAM."
177 (let ((*print-escape
* nil
)
178 (*print-readably
* nil
))
179 (output-object object
(out-synonym-of stream
)))
182 (defun print (object &optional stream
)
184 "Output a newline, the mostly READable printed representation of OBJECT, and
185 space to the specified STREAM."
186 (let ((stream (out-synonym-of stream
)))
188 (prin1 object stream
)
189 (write-char #\space stream
)
192 (defun pprint (object &optional stream
)
194 "Prettily output OBJECT preceded by a newline."
195 (let ((*print-pretty
* t
)
197 (stream (out-synonym-of stream
)))
199 (output-object object stream
))
202 (defun write-to-string
204 ((:escape
*print-escape
*) *print-escape
*)
205 ((:radix
*print-radix
*) *print-radix
*)
206 ((:base
*print-base
*) *print-base
*)
207 ((:circle
*print-circle
*) *print-circle
*)
208 ((:pretty
*print-pretty
*) *print-pretty
*)
209 ((:level
*print-level
*) *print-level
*)
210 ((:length
*print-length
*) *print-length
*)
211 ((:case
*print-case
*) *print-case
*)
212 ((:array
*print-array
*) *print-array
*)
213 ((:gensym
*print-gensym
*) *print-gensym
*)
214 ((:readably
*print-readably
*) *print-readably
*)
215 ((:right-margin
*print-right-margin
*) *print-right-margin
*)
216 ((:miser-width
*print-miser-width
*) *print-miser-width
*)
217 ((:lines
*print-lines
*) *print-lines
*)
218 ((:pprint-dispatch
*print-pprint-dispatch
*)
219 *print-pprint-dispatch
*)
220 ((:suppress-errors
*suppress-print-errors
*)
221 *suppress-print-errors
*))
223 "Return the printed representation of OBJECT as a string."
224 (stringify-object object
))
226 (defun prin1-to-string (object)
228 "Return the printed representation of OBJECT as a string with
230 (let ((*print-escape
* t
))
231 (stringify-object object
)))
233 (defun princ-to-string (object)
235 "Return the printed representation of OBJECT as a string with
237 (let ((*print-escape
* nil
)
238 (*print-readably
* nil
))
239 (stringify-object object
)))
241 ;;; This produces the printed representation of an object as a string.
242 ;;; The few ...-TO-STRING functions above call this.
243 (defun stringify-object (object)
244 (let ((stream (make-string-output-stream)))
245 (setup-printer-state)
246 (output-object object stream
)
247 (get-output-stream-string stream
)))
249 ;;;; support for the PRINT-UNREADABLE-OBJECT macro
251 (defun print-not-readable-error (object stream
)
253 (error 'print-not-readable
:object object
)
255 :report
"Print unreadably."
256 (let ((*print-readably
* nil
))
257 (output-object object stream
)
260 :report
"Supply an object to be printed instead."
263 (read-evaluated-form "~@<Enter an object (evaluated): ~@:>"))
264 (output-object o stream
)
267 ;;; guts of PRINT-UNREADABLE-OBJECT
268 (defun %print-unreadable-object
(object stream type identity
&optional body
)
269 (declare (type (or null function
) body
))
271 (print-not-readable-error object stream
)
272 (flet ((print-description ()
274 (write (type-of object
) :stream stream
:circle nil
275 :level nil
:length nil
)
276 (write-char #\space stream
)
277 (pprint-newline :fill stream
))
281 (when (or body
(not type
))
282 (write-char #\space stream
))
283 (pprint-newline :fill stream
)
284 (write-char #\
{ stream
)
285 (write (get-lisp-obj-address object
) :stream stream
287 (write-char #\
} stream
))))
288 (cond ((print-pretty-on-stream-p stream
)
289 ;; Since we're printing prettily on STREAM, format the
290 ;; object within a logical block. PPRINT-LOGICAL-BLOCK does
291 ;; not rebind the stream when it is already a pretty stream,
292 ;; so output from the body will go to the same stream.
293 (pprint-logical-block (stream nil
:prefix
"#<" :suffix
">")
294 (print-description)))
296 (write-string "#<" stream
)
298 (write-char #\
> stream
)))))
301 ;;;; OUTPUT-OBJECT -- the main entry point
303 ;;; Objects whose print representation identifies them EQLly don't
304 ;;; need to be checked for circularity.
305 (defun uniquely-identified-by-print-p (x)
309 (symbol-package x
))))
311 (defvar *in-print-error
* nil
)
313 ;;; Output OBJECT to STREAM observing all printer control variables.
314 (defun output-object (object stream
)
315 (labels ((print-it (stream)
317 (sb!pretty
:output-pretty-object object stream
)
318 (output-ugly-object object stream
)))
320 (if *suppress-print-errors
*
321 (handler-bind ((condition
322 (lambda (condition) nil
323 (when (typep condition
*suppress-print-errors
*)
324 (cond (*in-print-error
*
325 (write-string "(error printing " stream
)
326 (write-string *in-print-error
* stream
)
327 (write-string ")" stream
))
329 ;; Give outer handlers a chance.
331 (continue "Suppress the error.")
333 (let ((*print-readably
* nil
)
336 "#<error printing a " stream
)
337 (let ((*in-print-error
* "type"))
338 (output-object (type-of object
) stream
))
339 (write-string ": " stream
)
340 (let ((*in-print-error
* "condition"))
341 (output-object condition stream
))
342 (write-string ">" stream
))))
343 (return-from handle-it object
)))))
347 (multiple-value-bind (marker initiate
)
348 (check-for-circularity object t
)
349 (if (eq initiate
:initiate
)
350 (let ((*circularity-hash-table
*
351 (make-hash-table :test
'eq
)))
352 (check-it (make-broadcast-stream))
353 (let ((*circularity-counter
* 0))
357 (when (handle-circularity marker stream
)
359 (handle-it stream
))))))
360 (cond (;; Maybe we don't need to bother with circularity detection.
361 (or (not *print-circle
*)
362 (uniquely-identified-by-print-p object
))
364 (;; If we have already started circularity detection, this
365 ;; object might be a shared reference. If we have not, then
366 ;; if it is a compound object it might contain a circular
367 ;; reference to itself or multiple shared references.
368 (or *circularity-hash-table
*
369 (compound-object-p object
))
372 (handle-it stream
)))))
374 ;;; a hack to work around recurring gotchas with printing while
375 ;;; DEFGENERIC PRINT-OBJECT is being built
377 ;;; (hopefully will go away naturally when CLOS moves into cold init)
378 (defvar *print-object-is-disabled-p
*)
380 ;;; Output OBJECT to STREAM observing all printer control variables
381 ;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
382 ;;; then the pretty printer will be used for any components of OBJECT,
383 ;;; just not for OBJECT itself.
384 (defun output-ugly-object (object stream
)
386 ;; KLUDGE: The TYPECASE approach here is non-ANSI; the ANSI definition of
387 ;; PRINT-OBJECT says it provides printing and we're supposed to provide
388 ;; PRINT-OBJECT methods covering all classes. We deviate from this
389 ;; by using PRINT-OBJECT only when we print instance values. However,
390 ;; ANSI makes it hard to tell that we're deviating from this:
391 ;; (1) ANSI specifies that the user isn't supposed to call PRINT-OBJECT
393 ;; (2) ANSI (section 11.1.2.1.2) says it's undefined to define
394 ;; a method on an external symbol in the CL package which is
395 ;; applicable to arg lists containing only direct instances of
396 ;; standardized classes.
397 ;; Thus, in order for the user to detect our sleaziness in conforming
398 ;; code, he has to do something relatively obscure like
399 ;; (1) actually use tools like FIND-METHOD to look for PRINT-OBJECT
401 ;; (2) define a PRINT-OBJECT method which is specialized on the stream
402 ;; value (e.g. a Gray stream object).
403 ;; As long as no one comes up with a non-obscure way of detecting this
404 ;; sleaziness, fixing this nonconformity will probably have a low
405 ;; priority. -- WHN 2001-11-25
408 (output-symbol object stream
)
409 (output-list object stream
)))
411 ;; The first case takes the above idea one step further: If an instance
412 ;; isn't a citizen yet, it has no right to a print-object method.
413 (cond ((sb!kernel
::undefined-classoid-p
(layout-classoid (layout-of object
)))
414 ;; not only is this unreadable, it's unprintable too.
415 (print-unreadable-object (object stream
:identity t
)
416 (format stream
"UNPRINTABLE instance of ~W"
417 (layout-classoid (layout-of object
)))))
418 ((not (and (boundp '*print-object-is-disabled-p
*)
419 *print-object-is-disabled-p
*))
420 (print-object object stream
))
421 ((typep object
'structure-object
)
422 (default-structure-print object stream
*current-level-in-print
*))
424 (write-string "#<INSTANCE but not STRUCTURE-OBJECT>" stream
))))
425 (funcallable-instance
427 ((not (and (boundp '*print-object-is-disabled-p
*)
428 *print-object-is-disabled-p
*))
429 (print-object object stream
))
430 (t (output-fun object stream
))))
432 (output-fun object stream
))
434 (output-symbol object stream
))
438 (output-integer object stream
))
440 (output-float object stream
))
442 (output-ratio object stream
))
444 (output-complex object stream
))))
446 (output-character object stream
))
448 (output-vector object stream
))
450 (output-array object stream
))
452 (output-sap object stream
))
454 (output-weak-pointer object stream
))
456 (output-lra object stream
))
458 (output-code-component object stream
))
460 (output-fdefn object stream
))
463 (output-simd-pack object stream
))
465 (output-random object stream
))))
469 ;;; values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last
470 ;;; time the printer was called
471 (defvar *previous-case
* nil
)
472 (defvar *previous-readtable-case
* nil
)
474 ;;; This variable contains the current definition of one of three
475 ;;; symbol printers. SETUP-PRINTER-STATE sets this variable.
476 (defvar *internal-symbol-output-fun
* nil
)
477 (declaim (function *internal-symbol-output-fun
*))
479 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
480 ;;; and with any embedded |'s or \'s escaped.
481 (defun output-quoted-symbol-name (pname stream
)
482 (declare (string pname
))
483 (write-char #\| stream
)
484 (dotimes (index (length pname
))
485 (let ((char (schar pname index
)))
486 (when (or (char= char
#\\) (char= char
#\|
))
487 (write-char #\\ stream
))
488 (write-char char stream
)))
489 (write-char #\| stream
))
491 (defun output-symbol (object stream
)
492 (declare (symbol object
))
493 (if (or *print-escape
* *print-readably
*)
494 (let ((package (symbol-package object
))
495 (name (symbol-name object
))
496 (current (sane-package)))
498 ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
499 ;; requires that keywords be printed with preceding colons
500 ;; always, regardless of the value of *PACKAGE*.
501 ((eq package
*keyword-package
*)
502 (write-char #\
: stream
))
503 ;; Otherwise, if the symbol's home package is the current
504 ;; one, then a prefix is never necessary.
505 ((eq package current
))
506 ;; Uninterned symbols print with a leading #:.
508 (when (or *print-gensym
* *print-readably
*)
509 (write-string "#:" stream
)))
511 (multiple-value-bind (symbol accessible
)
512 (find-symbol name current
)
513 ;; If we can find the symbol by looking it up, it need not
514 ;; be qualified. This can happen if the symbol has been
515 ;; inherited from a package other than its home package.
517 ;; To preserve print-read consistency, use the local nickname if
519 (unless (and accessible
(eq symbol object
))
520 (let ((prefix (or (car (rassoc package
(package-%local-nicknames current
)))
521 (package-name package
))))
522 (output-symbol-name prefix stream
))
523 (if (nth-value 1 (find-external-symbol name package
))
524 (write-char #\
: stream
)
525 (write-string "::" stream
))))))
526 (output-symbol-name name stream
))
527 (output-symbol-name (symbol-name object
) stream nil
)))
529 ;;; Output the string NAME as if it were a symbol name. In other
530 ;;; words, diddle its case according to *PRINT-CASE* and
532 (defun output-symbol-name (name stream
&optional
(maybe-quote t
))
533 (declare (type simple-string name
))
534 (let ((*readtable
* (if *print-readably
* *standard-readtable
* *readtable
*)))
535 (setup-printer-state)
536 (if (and maybe-quote
(or
537 (and (readtable-normalization *readtable
*)
538 (not (sb!unicode
:normalized-p name
:nfkc
)))
539 (symbol-quotep name
)))
540 (output-quoted-symbol-name name stream
)
541 (funcall *internal-symbol-output-fun
* name stream
))))
543 ;;;; escaping symbols
545 ;;; When we print symbols we have to figure out if they need to be
546 ;;; printed with escape characters. This isn't a whole lot easier than
547 ;;; reading symbols in the first place.
549 ;;; For each character, the value of the corresponding element is a
550 ;;; fixnum with bits set corresponding to attributes that the
551 ;;; character has. At characters have at least one bit set, so we can
552 ;;; search for any character with a positive test.
553 (defvar *character-attributes
*
554 (make-array 160 ; FIXME
555 :element-type
'(unsigned-byte 16)
557 (declaim (type (simple-array (unsigned-byte 16) (#.160)) ; FIXME
558 *character-attributes
*))
560 ;;; constants which are a bit-mask for each interesting character attribute
561 (defconstant other-attribute
(ash 1 0)) ; Anything else legal.
562 (defconstant number-attribute
(ash 1 1)) ; A numeric digit.
563 (defconstant uppercase-attribute
(ash 1 2)) ; An uppercase letter.
564 (defconstant lowercase-attribute
(ash 1 3)) ; A lowercase letter.
565 (defconstant sign-attribute
(ash 1 4)) ; +-
566 (defconstant extension-attribute
(ash 1 5)) ; ^_
567 (defconstant dot-attribute
(ash 1 6)) ; .
568 (defconstant slash-attribute
(ash 1 7)) ; /
569 (defconstant funny-attribute
(ash 1 8)) ; Anything illegal.
571 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
573 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
574 ;;; that don't need to be escaped (according to READTABLE-CASE.)
575 (defparameter *attribute-names
*
576 `((number . number-attribute
) (lowercase . lowercase-attribute
)
577 (uppercase . uppercase-attribute
) (letter . letter-attribute
)
578 (sign . sign-attribute
) (extension . extension-attribute
)
579 (dot . dot-attribute
) (slash . slash-attribute
)
580 (other . other-attribute
) (funny . funny-attribute
)))
584 ;;; For each character, the value of the corresponding element is the
585 ;;; lowest base in which that character is a digit.
586 (declaim (type (simple-array (unsigned-byte 8) (128)) ; FIXME: range?
588 (defvar *digit-bases
*
589 (make-array 128 ; FIXME
590 :element-type
'(unsigned-byte 8)))
592 (defun !printer-cold-init
()
593 (setq *digit-bases
* (make-array 128 ; FIXME
594 :element-type
'(unsigned-byte 8)
596 *character-attributes
* (make-array 160 ; FIXME
597 :element-type
'(unsigned-byte 16)
600 (let ((char (digit-char i
36)))
601 (setf (aref *digit-bases
* (char-code char
)) i
)))
603 (flet ((set-bit (char bit
)
604 (let ((code (char-code char
)))
605 (setf (aref *character-attributes
* code
)
606 (logior bit
(aref *character-attributes
* code
))))))
608 (dolist (char '(#\
! #\
@ #\$
#\%
#\
& #\
* #\
= #\~
#\
[ #\
] #\
{ #\
}
610 (set-bit char other-attribute
))
613 (set-bit (digit-char i
) number-attribute
))
615 (do ((code (char-code #\A
) (1+ code
))
616 (end (char-code #\Z
)))
618 (declare (fixnum code end
))
619 (set-bit (code-char code
) uppercase-attribute
)
620 (set-bit (char-downcase (code-char code
)) lowercase-attribute
))
622 (set-bit #\- sign-attribute
)
623 (set-bit #\
+ sign-attribute
)
624 (set-bit #\^ extension-attribute
)
625 (set-bit #\_ extension-attribute
)
626 (set-bit #\. dot-attribute
)
627 (set-bit #\
/ slash-attribute
)
629 ;; Mark anything not explicitly allowed as funny.
630 (dotimes (i 160) ; FIXME
631 (when (zerop (aref *character-attributes
* i
))
632 (setf (aref *character-attributes
* i
) funny-attribute
))))
633 ) ; end !COLD-PRINT-INIT
635 ;;; A FSM-like thingie that determines whether a symbol is a potential
636 ;;; number or has evil characters in it.
637 (defun symbol-quotep (name)
638 (declare (simple-string name
))
639 (macrolet ((advance (tag &optional
(at-end t
))
642 ,(if at-end
'(go TEST-SIGN
) '(return nil
)))
643 (setq current
(schar name index
)
644 code
(char-code current
)
646 ((< code
160) (aref attributes code
))
647 ((upper-case-p current
) uppercase-attribute
)
648 ((lower-case-p current
) lowercase-attribute
)
649 (t other-attribute
)))
652 (test (&rest attributes
)
664 `(and (< code
128) ; FIXME
665 (< (the fixnum
(aref bases code
)) base
))))
667 (prog ((len (length name
))
668 (attributes *character-attributes
*)
669 (bases *digit-bases
*)
672 (case (%readtable-case
*readtable
*)
673 (:upcase uppercase-attribute
)
674 (:downcase lowercase-attribute
)
675 (t (logior lowercase-attribute uppercase-attribute
))))
680 (declare (fixnum len base index bits code
))
683 TEST-SIGN
; At end, see whether it is a sign...
684 (return (not (test sign
)))
686 OTHER
; not potential number, see whether funny chars...
687 (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
690 (do ((i (1- index
) (1+ i
)))
691 ((= i len
) (return-from symbol-quotep nil
))
692 (unless (zerop (logand (let* ((char (schar name i
))
693 (code (char-code char
)))
695 ((< code
160) (aref attributes code
))
696 ((upper-case-p char
) uppercase-attribute
)
697 ((lower-case-p char
) lowercase-attribute
)
698 (t other-attribute
)))
700 (return-from symbol-quotep t
))))
705 (advance LAST-DIGIT-ALPHA
)
707 (when (test letter number other slash
) (advance OTHER nil
))
708 (when (char= current
#\.
) (advance DOT-FOUND
))
709 (when (test sign extension
) (advance START-STUFF nil
))
712 DOT-FOUND
; leading dots...
713 (when (test letter
) (advance START-DOT-MARKER nil
))
714 (when (digitp) (advance DOT-DIGIT
))
715 (when (test number other
) (advance OTHER nil
))
716 (when (test extension slash sign
) (advance START-DOT-STUFF nil
))
717 (when (char= current
#\.
) (advance DOT-FOUND
))
720 START-STUFF
; leading stuff before any dot or digit
723 (advance LAST-DIGIT-ALPHA
)
725 (when (test number other
) (advance OTHER nil
))
726 (when (test letter
) (advance START-MARKER nil
))
727 (when (char= current
#\.
) (advance START-DOT-STUFF nil
))
728 (when (test sign extension slash
) (advance START-STUFF nil
))
731 START-MARKER
; number marker in leading stuff...
732 (when (test letter
) (advance OTHER nil
))
735 START-DOT-STUFF
; leading stuff containing dot without digit...
736 (when (test letter
) (advance START-DOT-STUFF nil
))
737 (when (digitp) (advance DOT-DIGIT
))
738 (when (test sign extension dot slash
) (advance START-DOT-STUFF nil
))
739 (when (test number other
) (advance OTHER nil
))
742 START-DOT-MARKER
; number marker in leading stuff with dot..
743 ;; leading stuff containing dot without digit followed by letter...
744 (when (test letter
) (advance OTHER nil
))
747 DOT-DIGIT
; in a thing with dots...
748 (when (test letter
) (advance DOT-MARKER
))
749 (when (digitp) (advance DOT-DIGIT
))
750 (when (test number other
) (advance OTHER nil
))
751 (when (test sign extension dot slash
) (advance DOT-DIGIT
))
754 DOT-MARKER
; number marker in number with dot...
755 (when (test letter
) (advance OTHER nil
))
758 LAST-DIGIT-ALPHA
; previous char is a letter digit...
759 (when (or (digitp) (test sign slash
))
760 (advance ALPHA-DIGIT
))
761 (when (test letter number other dot
) (advance OTHER nil
))
764 ALPHA-DIGIT
; seen a digit which is a letter...
765 (when (or (digitp) (test sign slash
))
767 (advance LAST-DIGIT-ALPHA
)
768 (advance ALPHA-DIGIT
)))
769 (when (test letter
) (advance ALPHA-MARKER
))
770 (when (test number other dot
) (advance OTHER nil
))
773 ALPHA-MARKER
; number marker in number with alpha digit...
774 (when (test letter
) (advance OTHER nil
))
777 DIGIT
; seen only ordinary (non-alphabetic) numeric digits...
780 (advance ALPHA-DIGIT
)
782 (when (test number other
) (advance OTHER nil
))
783 (when (test letter
) (advance MARKER
))
784 (when (test extension slash sign
) (advance DIGIT
))
785 (when (char= current
#\.
) (advance DOT-DIGIT
))
788 MARKER
; number marker in a numeric number...
789 ;; ("What," you may ask, "is a 'number marker'?" It's something
790 ;; that a conforming implementation might use in number syntax.
791 ;; See ANSI 2.3.1.1 "Potential Numbers as Tokens".)
792 (when (test letter
) (advance OTHER nil
))
795 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN*
797 ;;;; case hackery: These functions are stored in
798 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN* according to the values of
799 ;;;; *PRINT-CASE* and READTABLE-CASE.
802 ;;; READTABLE-CASE *PRINT-CASE*
804 ;;; :DOWNCASE :DOWNCASE
806 (defun output-preserve-symbol (pname stream
)
807 (declare (simple-string pname
))
808 (write-string pname stream
))
811 ;;; READTABLE-CASE *PRINT-CASE*
812 ;;; :UPCASE :DOWNCASE
813 (defun output-lowercase-symbol (pname stream
)
814 (declare (simple-string pname
))
815 (dotimes (index (length pname
))
816 (let ((char (schar pname index
)))
817 (write-char (char-downcase char
) stream
))))
820 ;;; READTABLE-CASE *PRINT-CASE*
821 ;;; :DOWNCASE :UPCASE
822 (defun output-uppercase-symbol (pname stream
)
823 (declare (simple-string pname
))
824 (dotimes (index (length pname
))
825 (let ((char (schar pname index
)))
826 (write-char (char-upcase char
) stream
))))
829 ;;; READTABLE-CASE *PRINT-CASE*
830 ;;; :UPCASE :CAPITALIZE
831 ;;; :DOWNCASE :CAPITALIZE
832 (defun output-capitalize-symbol (pname stream
)
833 (declare (simple-string pname
))
834 (let ((prev-not-alphanum t
)
835 (up (eq (%readtable-case
*readtable
*) :upcase
)))
836 (dotimes (i (length pname
))
837 (let ((char (char pname i
)))
839 (if (or prev-not-alphanum
(lower-case-p char
))
841 (char-downcase char
))
842 (if prev-not-alphanum
846 (setq prev-not-alphanum
(not (alphanumericp char
)))))))
849 ;;; READTABLE-CASE *PRINT-CASE*
851 (defun output-invert-symbol (pname stream
)
852 (declare (simple-string pname
))
855 (dotimes (i (length pname
))
856 (let ((ch (schar pname i
)))
857 (when (both-case-p ch
)
858 (if (upper-case-p ch
)
860 (setq all-upper nil
)))))
861 (cond (all-upper (output-lowercase-symbol pname stream
))
862 (all-lower (output-uppercase-symbol pname stream
))
864 (write-string pname stream
)))))
866 ;;; Set the internal global symbol *INTERNAL-SYMBOL-OUTPUT-FUN*
867 ;;; to the right function depending on the values of *PRINT-CASE*
868 ;;; and (%READTABLE-CASE *READTABLE*).
869 (defun setup-printer-state ()
870 (let ((readtable-case (%readtable-case
*readtable
*))
871 (print-case *print-case
*))
872 (unless (and (eq print-case
*previous-case
*)
873 (eq readtable-case
*previous-readtable-case
*))
874 (setq *previous-case
* print-case
)
875 (setq *previous-readtable-case
* readtable-case
)
876 (setq *internal-symbol-output-fun
*
877 ;; a morally equivalent reformulation of FOP-KNOWN-FUN
878 (macrolet ((load-time-fn (name) `(load-time-value #',name t
)))
882 (:upcase
(load-time-fn output-preserve-symbol
))
883 (:downcase
(load-time-fn output-lowercase-symbol
))
884 (:capitalize
(load-time-fn output-capitalize-symbol
))))
887 (:upcase
(load-time-fn output-uppercase-symbol
))
888 (:downcase
(load-time-fn output-preserve-symbol
))
889 (:capitalize
(load-time-fn output-capitalize-symbol
))))
890 (:preserve
(load-time-fn output-preserve-symbol
))
891 (:invert
(load-time-fn output-invert-symbol
))))))))
895 (let ((*readtable
* (copy-readtable nil
)))
896 (format t
"READTABLE-CASE Input Symbol-name~@
897 ----------------------------------~%")
898 (dolist (readtable-case '(:upcase
:downcase
:preserve
:invert
))
899 (setf (readtable-case *readtable
*) readtable-case
)
900 (dolist (input '("ZEBRA" "Zebra" "zebra"))
901 (format t
"~&:~A~16T~A~24T~A"
902 (string-upcase readtable-case
)
904 (symbol-name (read-from-string input
)))))))
907 (let ((*readtable
* (copy-readtable nil
)))
908 (format t
"READTABLE-CASE *PRINT-CASE* Symbol-name Output Princ~@
909 --------------------------------------------------------~%")
910 (dolist (readtable-case '(:upcase
:downcase
:preserve
:invert
))
911 (setf (readtable-case *readtable
*) readtable-case
)
912 (dolist (*print-case
* '(:upcase
:downcase
:capitalize
))
913 (dolist (symbol '(|ZEBRA| |Zebra| |zebra|
))
914 (format t
"~&:~A~15T:~A~29T~A~42T~A~50T~A"
915 (string-upcase readtable-case
)
916 (string-upcase *print-case
*)
918 (prin1-to-string symbol
)
919 (princ-to-string symbol
)))))))
922 ;;;; recursive objects
924 (defun output-list (list stream
)
925 (descend-into (stream)
926 (write-char #\
( stream
)
930 (punt-print-if-too-long length stream
)
931 (output-object (pop list
) stream
)
934 (when (or (atom list
)
935 (check-for-circularity list
))
936 (write-string " . " stream
)
937 (output-object list stream
)
939 (write-char #\space stream
)
941 (write-char #\
) stream
)))
943 (defun output-unreadable-vector-readably (vector stream
)
944 (declare (vector vector
))
945 (write-string "#." stream
)
946 (write `(coerce ,(coerce vector
'(vector t
))
947 '(simple-array ,(array-element-type vector
) (*)))
950 (defun output-vector (vector stream
)
951 (declare (vector vector
))
952 (cond ((stringp vector
)
953 (cond ((and *print-readably
*
954 (not (eq (array-element-type vector
)
957 (make-array 0 :element-type
'character
))))))
958 (print-not-readable-error vector stream
))
959 ((or *print-escape
* *print-readably
*)
960 (write-char #\" stream
)
961 (quote-string vector stream
)
962 (write-char #\" stream
))
964 (write-string vector stream
))))
965 ((not (or *print-array
* *print-readably
*))
966 (output-terse-array vector stream
))
967 ((bit-vector-p vector
)
968 (write-string "#*" stream
)
969 (dovector (bit vector
)
970 ;; (Don't use OUTPUT-OBJECT here, since this code
971 ;; has to work for all possible *PRINT-BASE* values.)
972 (write-char (if (zerop bit
) #\
0 #\
1) stream
)))
973 ((or (not *print-readably
*)
974 (array-readably-printable-p vector
))
975 (descend-into (stream)
976 (write-string "#(" stream
)
977 (dotimes (i (length vector
))
979 (write-char #\space stream
))
980 (punt-print-if-too-long i stream
)
981 (output-object (aref vector i
) stream
))
982 (write-string ")" stream
)))
984 (output-unreadable-vector-readably vector stream
))
986 (print-not-readable-error vector stream
))))
988 ;;; This function outputs a string quoting characters sufficiently
989 ;;; so that someone can read it in again. Basically, put a slash in
990 ;;; front of an character satisfying NEEDS-SLASH-P.
991 (defun quote-string (string stream
)
992 (macrolet ((needs-slash-p (char)
993 ;; KLUDGE: We probably should look at the readtable, but just do
994 ;; this for now. [noted by anonymous long ago] -- WHN 19991130
995 `(or (char= ,char
#\\)
997 (with-array-data ((data string
) (start) (end)
998 :check-fill-pointer t
)
999 (do ((index start
(1+ index
)))
1001 (let ((char (schar data index
)))
1002 (when (needs-slash-p char
) (write-char #\\ stream
))
1003 (write-char char stream
))))))
1005 (defun array-readably-printable-p (array)
1006 (and (eq (array-element-type array
) t
)
1007 (let ((zero (position 0 (array-dimensions array
)))
1008 (number (position 0 (array-dimensions array
)
1009 :test
(complement #'eql
)
1011 (or (null zero
) (null number
) (> zero number
)))))
1013 ;;; Output the printed representation of any array in either the #< or #A
1015 (defun output-array (array stream
)
1016 (if (or *print-array
* *print-readably
*)
1017 (output-array-guts array stream
)
1018 (output-terse-array array stream
)))
1020 ;;; Output the abbreviated #< form of an array.
1021 (defun output-terse-array (array stream
)
1022 (let ((*print-level
* nil
)
1023 (*print-length
* nil
))
1024 (print-unreadable-object (array stream
:type t
:identity t
))))
1026 ;;; Convert an array into a list that can be used with MAKE-ARRAY's
1027 ;;; :INITIAL-CONTENTS keyword argument.
1028 (defun listify-array (array)
1029 (with-array-data ((data array
) (start) (end))
1030 (declare (ignore end
))
1031 (labels ((listify (dimensions index
)
1032 (if (null dimensions
)
1034 (let* ((dimension (car dimensions
))
1035 (dimensions (cdr dimensions
))
1036 (count (reduce #'* dimensions
)))
1037 (loop for i below dimension
1038 collect
(listify dimensions index
)
1039 do
(incf index count
))))))
1040 (listify (array-dimensions array
) start
))))
1042 (defun output-unreadable-array-readably (array stream
)
1043 (write-string "#." stream
)
1044 (write `(make-array ',(array-dimensions array
)
1045 :element-type
',(array-element-type array
)
1046 :initial-contents
',(listify-array array
))
1049 ;;; Output the readable #A form of an array.
1050 (defun output-array-guts (array stream
)
1051 (cond ((or (not *print-readably
*)
1052 (array-readably-printable-p array
))
1053 (write-char #\
# stream
)
1054 (let ((*print-base
* 10)
1055 (*print-radix
* nil
))
1056 (output-integer (array-rank array
) stream
))
1057 (write-char #\A stream
)
1058 (with-array-data ((data array
) (start) (end))
1059 (declare (ignore end
))
1060 (sub-output-array-guts data
(array-dimensions array
) stream start
)))
1062 (output-unreadable-array-readably array stream
))
1064 (print-not-readable-error array stream
))))
1066 (defun sub-output-array-guts (array dimensions stream index
)
1067 (declare (type (simple-array * (*)) array
) (fixnum index
))
1068 (cond ((null dimensions
)
1069 (output-object (aref array index
) stream
))
1071 (descend-into (stream)
1072 (write-char #\
( stream
)
1073 (let* ((dimension (car dimensions
))
1074 (dimensions (cdr dimensions
))
1075 (count (reduce #'* dimensions
)))
1076 (dotimes (i dimension
)
1078 (write-char #\space stream
))
1079 (punt-print-if-too-long i stream
)
1080 (sub-output-array-guts array dimensions stream index
)
1081 (incf index count
)))
1082 (write-char #\
) stream
)))))
1084 ;;; a trivial non-generic-function placeholder for PRINT-OBJECT, for
1085 ;;; use until CLOS is set up (at which time it will be replaced with
1086 ;;; the real generic function implementation)
1087 (defun print-object (instance stream
)
1088 (default-structure-print instance stream
*current-level-in-print
*))
1090 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
1092 (defun %output-radix
(base stream
)
1093 (write-char #\
# stream
)
1094 (write-char (case base
1098 (t (%output-reasonable-integer-in-base base
10 stream
)
1102 (defun %output-reasonable-integer-in-base
(n base stream
)
1103 (multiple-value-bind (q r
)
1105 ;; Recurse until you have all the digits pushed on
1108 (%output-reasonable-integer-in-base q base stream
))
1109 ;; Then as each recursive call unwinds, turn the
1110 ;; digit (in remainder) into a character and output
1113 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r
)
1116 ;;; *POWER-CACHE* is an alist mapping bases to power-vectors. It is
1117 ;;; filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
1118 ;;; always prior a GC to drop overly large bignums from the cache.
1120 ;;; It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
1121 ;;; POWERS-FOR-BASE, see that you don't break the assumptions!
1122 (defvar *power-cache
* nil
)
1124 (defconstant +power-cache-integer-length-limit
+ 2048)
1126 (defun scrub-power-cache ()
1127 (let ((cache *power-cache
*))
1128 (dolist (cell cache
)
1129 (let ((powers (cdr cell
)))
1130 (declare (simple-vector powers
))
1131 (let ((too-big (position-if
1133 (>= (integer-length x
)
1134 +power-cache-integer-length-limit
+))
1137 (setf (cdr cell
) (subseq powers
0 too-big
))))))
1138 ;; Since base 10 is overwhelmingly common, make sure it's at head.
1139 ;; Try to keep other bases in a hopefully sensible order as well.
1140 (if (eql 10 (caar cache
))
1141 (setf *power-cache
* cache
)
1142 ;; If we modify the list destructively we need to copy it, otherwise
1143 ;; an alist lookup in progress might be screwed.
1144 (setf *power-cache
* (sort (copy-list cache
)
1146 (declare (fixnum a b
))
1156 ;;; Compute (and cache) a power vector for a BASE and LIMIT:
1157 ;;; the vector holds integers for which
1158 ;;; (aref powers k) == (expt base (expt 2 k))
1160 (defun powers-for-base (base limit
)
1161 (flet ((compute-powers (from)
1163 (do ((p from
(* p p
)))
1165 ;; We don't actually need this, but we also
1166 ;; prefer not to cons it up a second time...
1169 (nreverse powers
))))
1170 ;; Grab a local reference so that we won't stuff consed at the
1171 ;; head by other threads -- or sorting by SCRUB-POWER-CACHE.
1172 (let ((cache *power-cache
*))
1173 (let ((cell (assoc base cache
)))
1175 (let* ((powers (cdr cell
))
1176 (len (length powers
))
1177 (max (svref powers
(1- len
))))
1181 (concatenate 'vector powers
1182 (compute-powers (* max max
)))))
1183 (setf (cdr cell
) new
)
1185 (let ((powers (coerce (compute-powers base
) 'vector
)))
1186 ;; Add new base to head: SCRUB-POWER-CACHE will later
1187 ;; put it to a better place.
1188 (setf *power-cache
* (acons base powers cache
))
1191 ;; Algorithm by Harald Hanche-Olsen, sbcl-devel 2005-02-05
1192 (defun %output-huge-integer-in-base
(n base stream
)
1193 (declare (type bignum n
) (type fixnum base
))
1194 ;; POWER is a vector for which the following holds:
1195 ;; (aref power k) == (expt base (expt 2 k))
1196 (let* ((power (powers-for-base base n
))
1197 (k-start (or (position-if (lambda (x) (> x n
)) power
)
1198 (bug "power-vector too short"))))
1199 (labels ((bisect (n k exactp
)
1200 (declare (fixnum k
))
1201 ;; N is the number to bisect
1202 ;; K on initial entry BASE^(2^K) > N
1203 ;; EXACTP is true if 2^K is the exact number of digits
1206 (loop repeat
(ash 1 k
) do
(write-char #\
0 stream
))))
1209 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n
)
1213 (multiple-value-bind (q r
) (truncate n
(aref power k
))
1214 ;; EXACTP is NIL only at the head of the
1215 ;; initial number, as we don't know the number
1216 ;; of digits there, but we do know that it
1217 ;; doesn't get any leading zeros.
1219 (bisect r k
(or exactp
(plusp q
))))))))
1220 (bisect n k-start nil
))))
1222 (defun %output-integer-in-base
(integer base stream
)
1223 (when (minusp integer
)
1224 (write-char #\- stream
)
1225 (setf integer
(- integer
)))
1226 ;; The ideal cutoff point between these two algorithms is almost
1227 ;; certainly quite platform dependent: this gives 87 for 32 bit
1228 ;; SBCL, which is about right at least for x86/Darwin.
1229 (if (or (fixnump integer
)
1230 (< (integer-length integer
) (* 3 sb
!vm
:n-positive-fixnum-bits
)))
1231 (%output-reasonable-integer-in-base integer base stream
)
1232 (%output-huge-integer-in-base integer base stream
)))
1234 (defun output-integer (integer stream
)
1235 (let ((base *print-base
*))
1236 (when (and (/= base
10) *print-radix
*)
1237 (%output-radix base stream
))
1238 (%output-integer-in-base integer base stream
)
1239 (when (and *print-radix
* (= base
10))
1240 (write-char #\. stream
))))
1242 (defun output-ratio (ratio stream
)
1243 (let ((base *print-base
*))
1245 (%output-radix base stream
))
1246 (%output-integer-in-base
(numerator ratio
) base stream
)
1247 (write-char #\
/ stream
)
1248 (%output-integer-in-base
(denominator ratio
) base stream
)))
1250 (defun output-complex (complex stream
)
1251 (write-string "#C(" stream
)
1252 ;; FIXME: Could this just be OUTPUT-NUMBER?
1253 (output-object (realpart complex
) stream
)
1254 (write-char #\space stream
)
1255 (output-object (imagpart complex
) stream
)
1256 (write-char #\
) stream
))
1260 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1261 ;;; most of the work for all printing of floating point numbers in
1262 ;;; FORMAT. It converts a floating point number to a string in a free
1263 ;;; or fixed format with no exponent. The interpretation of the
1264 ;;; arguments is as follows:
1266 ;;; X - The floating point number to convert, which must not be
1268 ;;; WIDTH - The preferred field width, used to determine the number
1269 ;;; of fraction digits to produce if the FDIGITS parameter
1270 ;;; is unspecified or NIL. If the non-fraction digits and the
1271 ;;; decimal point alone exceed this width, no fraction digits
1272 ;;; will be produced unless a non-NIL value of FDIGITS has been
1273 ;;; specified. Field overflow is not considerd an error at this
1275 ;;; FDIGITS - The number of fractional digits to produce. Insignificant
1276 ;;; trailing zeroes may be introduced as needed. May be
1277 ;;; unspecified or NIL, in which case as many digits as possible
1278 ;;; are generated, subject to the constraint that there are no
1279 ;;; trailing zeroes.
1280 ;;; SCALE - If this parameter is specified or non-NIL, then the number
1281 ;;; printed is (* x (expt 10 scale)). This scaling is exact,
1282 ;;; and cannot lose precision.
1283 ;;; FMIN - This parameter, if specified or non-NIL, is the minimum
1284 ;;; number of fraction digits which will be produced, regardless
1285 ;;; of the value of WIDTH or FDIGITS. This feature is used by
1286 ;;; the ~E format directive to prevent complete loss of
1287 ;;; significance in the printed value due to a bogus choice of
1291 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1292 ;;; where the results have the following interpretation:
1294 ;;; DIGIT-STRING - The decimal representation of X, with decimal point.
1295 ;;; DIGIT-LENGTH - The length of the string DIGIT-STRING.
1296 ;;; LEADING-POINT - True if the first character of DIGIT-STRING is the
1298 ;;; TRAILING-POINT - True if the last character of DIGIT-STRING is the
1300 ;;; POINT-POS - The position of the digit preceding the decimal
1301 ;;; point. Zero indicates point before first digit.
1303 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1304 ;;; accuracy. Specifically, the decimal number printed is the closest
1305 ;;; possible approximation to the true value of the binary number to
1306 ;;; be printed from among all decimal representations with the same
1307 ;;; number of digits. In free-format output, i.e. with the number of
1308 ;;; digits unconstrained, it is guaranteed that all the information is
1309 ;;; preserved, so that a properly- rounding reader can reconstruct the
1310 ;;; original binary number, bit-for-bit, from its printed decimal
1311 ;;; representation. Furthermore, only as many digits as necessary to
1312 ;;; satisfy this condition will be printed.
1314 ;;; FLOAT-DIGITS actually generates the digits for positive numbers;
1315 ;;; see below for comments.
1317 (defun flonum-to-string (x &optional width fdigits scale fmin
)
1318 (declare (type float x
))
1319 ;; FIXME: I think only FORMAT-DOLLARS calls FLONUM-TO-STRING with
1320 ;; possibly-negative X.
1322 (multiple-value-bind (e string
)
1324 (flonum-to-digits x
(min (- (+ fdigits
(or scale
0)))
1326 (if (and width
(> width
1))
1327 (let ((w (multiple-value-list
1331 (if (and scale
(minusp scale
))
1334 (f (multiple-value-list
1335 (flonum-to-digits x
(- (+ (or fmin
0)
1336 (if scale scale
0)))))))
1338 ((>= (length (cadr w
)) (length (cadr f
)))
1340 (t (values-list f
))))
1341 (flonum-to-digits x
)))
1342 (let ((e (if (zerop x
)
1344 (+ e
(or scale
0))))
1345 (stream (make-string-output-stream)))
1348 (write-string string stream
:end
(min (length string
) e
))
1349 (dotimes (i (- e
(length string
)))
1350 (write-char #\
0 stream
))
1351 (write-char #\. stream
)
1352 (write-string string stream
:start
(min (length string
) e
))
1354 (dotimes (i (- fdigits
1356 (min (length string
) e
))))
1357 (write-char #\
0 stream
))))
1359 (write-string "." stream
)
1361 (write-char #\
0 stream
))
1362 (write-string string stream
:end
(when fdigits
1363 (min (length string
)
1367 (dotimes (i (+ fdigits e
(- (length string
))))
1368 (write-char #\
0 stream
)))))
1369 (let ((string (get-output-stream-string stream
)))
1370 (values string
(length string
)
1371 (char= (char string
0) #\.
)
1372 (char= (char string
(1- (length string
))) #\.
)
1373 (position #\. string
))))))
1375 ;;; implementation of figure 1 from Burger and Dybvig, 1996. It is
1376 ;;; extended in order to handle rounding.
1378 ;;; As the implementation of the Dragon from Classic CMUCL (and
1379 ;;; previously in SBCL above FLONUM-TO-STRING) says: "DO NOT EVEN
1380 ;;; THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE
1381 ;;; PAPER!", and in this case we have to add that even reading the
1382 ;;; paper might not bring immediate illumination as CSR has attempted
1383 ;;; to turn idiomatic Scheme into idiomatic Lisp.
1385 ;;; FIXME: figure 1 from Burger and Dybvig is the unoptimized
1386 ;;; algorithm, noticeably slow at finding the exponent. Figure 2 has
1387 ;;; an improved algorithm, but CSR ran out of energy.
1389 ;;; possible extension for the enthusiastic: printing floats in bases
1390 ;;; other than base 10.
1391 (defconstant single-float-min-e
1392 (- 2 sb
!vm
:single-float-bias sb
!vm
:single-float-digits
))
1393 (defconstant double-float-min-e
1394 (- 2 sb
!vm
:double-float-bias sb
!vm
:double-float-digits
))
1396 (defconstant long-float-min-e
1397 (nth-value 1 (decode-float least-positive-long-float
)))
1399 (defun flonum-to-digits (v &optional position relativep
)
1400 (let ((print-base 10) ; B
1402 (float-digits (float-digits v
)) ; p
1403 (digit-characters "0123456789")
1406 (single-float single-float-min-e
)
1407 (double-float double-float-min-e
)
1409 (long-float long-float-min-e
))))
1410 (multiple-value-bind (f e
)
1411 (integer-decode-float v
)
1412 (let (;; FIXME: these even tests assume normal IEEE rounding
1413 ;; mode. I wonder if we should cater for non-normal?
1416 (with-push-char (:element-type base-char
)
1417 (labels ((scale (r s m
+ m-
)
1419 (s s
(* s print-base
)))
1420 ((not (or (> (+ r m
+) s
)
1421 (and high-ok
(= (+ r m
+) s
))))
1423 (r r
(* r print-base
))
1424 (m+ m
+ (* m
+ print-base
))
1425 (m- m-
(* m- print-base
)))
1426 ((not (and (plusp (- r m-
)) ; Extension to handle zero
1427 (or (< (* (+ r m
+) print-base
) s
)
1429 (= (* (+ r m
+) print-base
) s
)))))
1430 (values k
(generate r s m
+ m-
)))))))
1431 (generate (r s m
+ m-
)
1435 (setf (values d r
) (truncate (* r print-base
) s
))
1436 (setf m
+ (* m
+ print-base
))
1437 (setf m-
(* m- print-base
))
1438 (setf tc1
(or (< r m-
) (and low-ok
(= r m-
))))
1439 (setf tc2
(or (> (+ r m
+) s
)
1440 (and high-ok
(= (+ r m
+) s
))))
1443 (push-char (char digit-characters d
))
1447 ((and (not tc1
) tc2
) (1+ d
))
1448 ((and tc1
(not tc2
)) d
)
1450 (if (< (* r
2) s
) d
(1+ d
))))))
1451 (push-char (char digit-characters d
))
1452 (return-from generate
(get-pushed-string))))))
1456 (let* ((be (expt float-radix e
))
1457 (be1 (* be float-radix
)))
1458 (if (/= f
(expt float-radix
(1- float-digits
)))
1468 (/= f
(expt float-radix
(1- float-digits
))))
1470 s
(* (expt float-radix
(- e
)) 2)
1473 (setf r
(* f float-radix
2)
1474 s
(* (expt float-radix
(- 1 e
)) 2)
1479 (aver (> position
0))
1481 ;; running out of letters here
1482 (l 1 (* l print-base
)))
1483 ((>= (* s l
) (+ r m
+))
1485 (if (< (+ r
(* s
(/ (expt print-base
(- k position
)) 2)))
1486 (* s
(expt print-base k
)))
1487 (setf position
(- k position
))
1488 (setf position
(- k position
1))))))
1489 (let ((low (max m-
(/ (* s
(expt print-base position
)) 2)))
1490 (high (max m
+ (/ (* s
(expt print-base position
)) 2))))
1497 (values r s m
+ m-
))))
1498 (multiple-value-bind (r s m
+ m-
) (initialize)
1499 (scale r s m
+ m-
))))))))
1501 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns
1502 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1503 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1504 ;;; original number. There may be some loss of precision due the
1505 ;;; floating point representation. The scaling is always done with
1506 ;;; long float arithmetic, which helps printing of lesser precisions
1507 ;;; as well as avoiding generic arithmetic.
1509 ;;; When computing our initial scale factor using EXPT, we pull out
1510 ;;; part of the computation to avoid over/under flow. When
1511 ;;; denormalized, we must pull out a large factor, since there is more
1512 ;;; negative exponent range than positive range.
1514 (eval-when (:compile-toplevel
:execute
)
1515 (setf *read-default-float-format
*
1516 #!+long-float
'long-float
#!-long-float
'double-float
))
1517 (defun scale-exponent (original-x)
1518 (let* ((x (coerce original-x
'long-float
)))
1519 (multiple-value-bind (sig exponent
) (decode-float x
)
1520 (declare (ignore sig
))
1522 (values (float 0.0e0 original-x
) 1)
1523 (let* ((ex (locally (declare (optimize (safety 0)))
1526 ;; this is the closest double float
1527 ;; to (log 2 10), but expressed so
1528 ;; that we're not vulnerable to the
1529 ;; host lisp's interpretation of
1530 ;; arithmetic. (FIXME: it turns
1531 ;; out that sbcl itself is off by 1
1532 ;; ulp in this value, which is a
1533 ;; little unfortunate.)
1536 (make-double-float 1070810131 1352628735)
1538 (error "(log 2 10) not computed")))))))
1540 (if (float-denormalized-p x
)
1542 (* x
1.0e16
(expt 10.0e0
(- (- ex
) 16)))
1544 (* x
1.0e18
(expt 10.0e0
(- (- ex
) 18)))
1545 (* x
10.0e0
(expt 10.0e0
(- (- ex
) 1))))
1546 (/ x
10.0e0
(expt 10.0e0
(1- ex
))))))
1547 (do ((d 10.0e0
(* d
10.0e0
))
1551 (do ((m 10.0e0
(* m
10.0e0
))
1555 (values (float z original-x
) ex
))
1556 (declare (long-float m
) (integer ex
))))
1557 (declare (long-float d
))))))))
1558 (eval-when (:compile-toplevel
:execute
)
1559 (setf *read-default-float-format
* 'single-float
))
1561 ;;;; entry point for the float printer
1563 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1564 ;;; argument is printed free-format, in either exponential or
1565 ;;; non-exponential notation, depending on its magnitude.
1567 ;;; NOTE: When a number is to be printed in exponential format, it is
1568 ;;; scaled in floating point. Since precision may be lost in this
1569 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1570 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1571 ;;; extensive computations with integers of similar magnitude to that
1572 ;;; of the number being printed. For large exponents, the bignums
1573 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1574 ;;; fast and the exponent range is not too large, then it might become
1575 ;;; attractive to handle exponential notation with the same accuracy
1576 ;;; as non-exponential notation, using the method described in the
1577 ;;; Steele and White paper.
1579 ;;; NOTE II: this has been bypassed slightly by implementing Burger
1580 ;;; and Dybvig, 1996. When someone has time (KLUDGE) they can
1581 ;;; probably (a) implement the optimizations suggested by Burger and
1582 ;;; Dyvbig, and (b) remove all vestiges of Dragon4, including from
1583 ;;; fixed-format printing.
1585 ;;; Print the appropriate exponent marker for X and the specified exponent.
1586 (defun print-float-exponent (x exp stream
)
1587 (declare (type float x
) (type integer exp
) (type stream stream
))
1588 (let ((*print-radix
* nil
))
1589 (if (typep x
*read-default-float-format
*)
1591 (format stream
"e~D" exp
))
1592 (format stream
"~C~D"
1600 (defun output-float-infinity (x stream
)
1601 (declare (float x
) (stream stream
))
1603 (write-string "#." stream
))
1605 (return-from output-float-infinity
1606 (print-not-readable-error x stream
)))
1608 (write-string "#<" stream
)))
1609 (write-string "SB-EXT:" stream
)
1610 (write-string (symbol-name (float-format-name x
)) stream
)
1611 (write-string (if (plusp x
) "-POSITIVE-" "-NEGATIVE-")
1613 (write-string "INFINITY" stream
)
1615 (write-string ">" stream
)))
1617 (defun output-float-nan (x stream
)
1618 (print-unreadable-object (x stream
)
1619 (princ (float-format-name x
) stream
)
1620 (write-string (if (float-trapping-nan-p x
) " trapping" " quiet") stream
)
1621 (write-string " NaN" stream
)))
1623 ;;; the function called by OUTPUT-OBJECT to handle floats
1624 (defun output-float (x stream
)
1626 ((float-infinity-p x
)
1627 (output-float-infinity x stream
))
1629 (output-float-nan x stream
))
1631 (let ((x (cond ((minusp (float-sign x
))
1632 (write-char #\- stream
)
1638 (write-string "0.0" stream
)
1639 (print-float-exponent x
0 stream
))
1641 (output-float-aux x stream -
3 8)))))))
1643 (defun output-float-aux (x stream e-min e-max
)
1644 (multiple-value-bind (e string
)
1645 (flonum-to-digits x
)
1650 (write-string string stream
:end
(min (length string
) e
))
1651 (dotimes (i (- e
(length string
)))
1652 (write-char #\
0 stream
))
1653 (write-char #\. stream
)
1654 (write-string string stream
:start
(min (length string
) e
))
1655 (when (<= (length string
) e
)
1656 (write-char #\
0 stream
))
1657 (print-float-exponent x
0 stream
))
1659 (write-string "0." stream
)
1661 (write-char #\
0 stream
))
1662 (write-string string stream
)
1663 (print-float-exponent x
0 stream
))))
1664 (t (write-string string stream
:end
1)
1665 (write-char #\. stream
)
1666 (write-string string stream
:start
1)
1667 (print-float-exponent x
(1- e
) stream
)))))
1669 ;;;; other leaf objects
1671 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1672 ;;; the character name or the character in the #\char format.
1673 (defun output-character (char stream
)
1674 (if (or *print-escape
* *print-readably
*)
1675 (let ((graphicp (and (graphic-char-p char
)
1676 (standard-char-p char
)))
1677 (name (char-name char
)))
1678 (write-string "#\\" stream
)
1679 (if (and name
(or (not graphicp
) *print-readably
*))
1680 (quote-string name stream
)
1681 (write-char char stream
)))
1682 (write-char char stream
)))
1684 (defun output-sap (sap stream
)
1685 (declare (type system-area-pointer sap
))
1687 (format stream
"#.(~S #X~8,'0X)" 'int-sap
(sap-int sap
)))
1689 (print-unreadable-object (sap stream
)
1690 (format stream
"system area pointer: #X~8,'0X" (sap-int sap
))))))
1692 (defun output-weak-pointer (weak-pointer stream
)
1693 (declare (type weak-pointer weak-pointer
))
1694 (print-unreadable-object (weak-pointer stream
)
1695 (multiple-value-bind (value validp
) (weak-pointer-value weak-pointer
)
1697 (write-string "weak pointer: " stream
)
1698 (write value
:stream stream
))
1700 (write-string "broken weak pointer" stream
))))))
1702 (defun output-code-component (component stream
)
1703 (print-unreadable-object (component stream
:identity t
)
1704 (let ((dinfo (%code-debug-info component
)))
1705 (cond ((eq dinfo
:bogus-lra
)
1706 (write-string "bogus code object" stream
))
1708 (write-string "code object" stream
)
1710 (write-char #\space stream
)
1711 (output-object (sb!c
::debug-info-name dinfo
) stream
)))))))
1713 (defun output-lra (lra stream
)
1714 (print-unreadable-object (lra stream
:identity t
)
1715 (write-string "return PC object" stream
)))
1717 (defun output-fdefn (fdefn stream
)
1718 (print-unreadable-object (fdefn stream
)
1719 (write-string "FDEFINITION for " stream
)
1720 ;; It's somewhat unhelpful to print as <FDEFINITION for (SETF #)>
1721 ;; Generalized function names are indivisible.
1722 (let ((name (fdefn-name fdefn
)))
1724 (output-object name stream
)
1725 ;; This needn't protect against improper lists.
1726 ;; (You'd get crashes in INTERNAL-NAME-P and other places)
1727 (format stream
"(~{~S~^ ~})" name
)))))
1730 (defun output-simd-pack (pack stream
)
1731 (declare (type simd-pack pack
))
1732 (cond ((and *print-readably
* *read-eval
*)
1734 ((simd-pack double-float
)
1735 (multiple-value-call #'format stream
1737 '%make-simd-pack-double
1738 (%simd-pack-doubles pack
)))
1739 ((simd-pack single-float
)
1740 (multiple-value-call #'format stream
1741 "#.(~S ~S ~S ~S ~S)"
1742 '%make-simd-pack-single
1743 (%simd-pack-singles pack
)))
1745 (multiple-value-call #'format stream
1746 "#.(~S #X~16,'0X #X~16,'0X)"
1747 '%make-simd-pack-ub64
1748 (%simd-pack-ub64s pack
)))))
1750 (print-unreadable-object (pack stream
)
1751 (flet ((all-ones-p (value start end
&aux
(mask (- (ash 1 end
) (ash 1 start
))))
1752 (= (logand value mask
) mask
))
1753 (split-num (value start
)
1756 and v
= (ash value
(- start
)) then
(ash v -
8)
1757 collect
(logand v
#xFF
))))
1758 (multiple-value-bind (low high
)
1759 (%simd-pack-ub64s pack
)
1761 ((simd-pack double-float
)
1762 (multiple-value-bind (v0 v1
) (%simd-pack-doubles pack
)
1763 (format stream
"~S~@{ ~:[~,13E~;~*TRUE~]~}"
1765 (all-ones-p low
0 64) v0
1766 (all-ones-p high
0 64) v1
)))
1767 ((simd-pack single-float
)
1768 (multiple-value-bind (v0 v1 v2 v3
) (%simd-pack-singles pack
)
1769 (format stream
"~S~@{ ~:[~,7E~;~*TRUE~]~}"
1771 (all-ones-p low
0 32) v0
1772 (all-ones-p low
32 64) v1
1773 (all-ones-p high
0 32) v2
1774 (all-ones-p high
32 64) v3
)))
1776 (format stream
"~S~@{ ~{ ~2,'0X~}~}"
1778 (split-num low
0) (split-num low
32)
1779 (split-num high
0) (split-num high
32))))))))))
1783 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1784 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1786 ;;; The definition here is a simple temporary placeholder. It will be
1787 ;;; overwritten by a smarter version (capable of calling generic
1788 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1789 (defun printed-as-funcallable-standard-class (object stream
)
1790 (declare (ignore object stream
))
1793 (defun output-fun (object stream
)
1794 (let* ((name (%fun-name object
))
1795 (proper-name-p (and (legal-fun-name-p name
) (fboundp name
)
1796 (eq (fdefinition name
) object
))))
1797 (print-unreadable-object (object stream
:identity
(not proper-name-p
))
1798 (format stream
"~:[FUNCTION~;CLOSURE~]~@[ ~S~]"
1802 ;;;; catch-all for unknown things
1804 (defun output-random (object stream
)
1805 (print-unreadable-object (object stream
:identity t
)
1806 (let ((lowtag (lowtag-of object
)))
1808 (#.sb
!vm
:other-pointer-lowtag
1809 (let ((widetag (widetag-of object
)))
1811 (#.sb
!vm
:value-cell-header-widetag
1812 (write-string "value cell " stream
)
1813 (output-object (value-cell-ref object
) stream
))
1815 (write-string "unknown pointer object, widetag=" stream
)
1816 (let ((*print-base
* 16) (*print-radix
* t
))
1817 (output-integer widetag stream
))))))
1818 ((#.sb
!vm
:fun-pointer-lowtag
1819 #.sb
!vm
:instance-pointer-lowtag
1820 #.sb
!vm
:list-pointer-lowtag
)
1821 (write-string "unknown pointer object, lowtag=" stream
)
1822 (let ((*print-base
* 16) (*print-radix
* t
))
1823 (output-integer lowtag stream
)))
1825 (case (widetag-of object
)
1826 (#.sb
!vm
:unbound-marker-widetag
1827 (write-string "unbound marker" stream
))
1829 (write-string "unknown immediate object, lowtag=" stream
)
1830 (let ((*print-base
* 2) (*print-radix
* t
))
1831 (output-integer lowtag stream
))
1832 (write-string ", widetag=" stream
)
1833 (let ((*print-base
* 16) (*print-radix
* t
))
1834 (output-integer (widetag-of object
) stream
)))))))))