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 (!defvar
*print-readably
* nil
18 "If true, all objects will be printed readably. If readable printing
19 is impossible, an error will be signalled. This overrides the value of
21 (!defvar
*print-escape
* t
23 "Should we print in a reasonably machine-readable way? (possibly
24 overridden by *PRINT-READABLY*)")
25 (!defvar
*print-pretty
* nil
; (set later when pretty-printer is initialized)
27 "Should pretty printing be used?")
28 (!defvar
*print-base
* 10.
30 "The output base for RATIONALs (including integers).")
31 (!defvar
*print-radix
* nil
33 "Should base be verified when printing RATIONALs?")
34 (!defvar
*print-level
* nil
36 "How many levels should be printed before abbreviating with \"#\"?")
37 (!defvar
*print-length
* nil
39 "How many elements at any level should be printed before abbreviating
41 (!defvar
*print-circle
* nil
43 "Should we use #n= and #n# notation to preserve uniqueness in general (and
44 circularity in particular) when printing?")
45 (!defvar
*print-case
* :upcase
47 "What case should the printer should use default?")
48 (!defvar
*print-array
* t
50 "Should the contents of arrays be printed?")
51 (!defvar
*print-gensym
* t
53 "Should #: prefixes be used when printing symbols with null SYMBOL-PACKAGE?")
54 (!defvar
*print-lines
* nil
56 "The maximum number of lines to print per object.")
57 (!defvar
*print-right-margin
* nil
59 "The position of the right margin in ems (for pretty-printing).")
60 (!defvar
*print-miser-width
* nil
62 "If the remaining space between the current column and the right margin
63 is less than this, then print using ``miser-style'' output. Miser
64 style conditional newlines are turned on, and all indentations are
65 turned off. If NIL, never use miser mode.")
66 (defvar *print-pprint-dispatch
*
67 (sb!pretty
::make-pprint-dispatch-table
) ; for type-correctness
69 "The pprint-dispatch-table that controls how to pretty-print objects.")
70 (!defvar
*suppress-print-errors
* nil
72 "Suppress printer errors when the condition is of the type designated by this
73 variable: an unreadable object representing the error is printed instead.")
75 (defmacro with-standard-io-syntax
(&body body
)
77 "Bind the reader and printer control variables to values that enable READ
78 to reliably read the results of PRINT. These values are:
80 *PACKAGE* the COMMON-LISP-USER package
90 *PRINT-MISER-WIDTH* NIL
91 *PRINT-PPRINT-DISPATCH* the standard pprint dispatch table
95 *PRINT-RIGHT-MARGIN* NIL
97 *READ-DEFAULT-FLOAT-FORMAT* SINGLE-FLOAT
100 *READTABLE* the standard readtable
101 SB-EXT:*SUPPRESS-PRINT-ERRORS* NIL
103 `(%with-standard-io-syntax
(lambda () ,@body
)))
105 (defglobal sb
!pretty
::*standard-pprint-dispatch-table
* nil
)
106 ;; duplicate defglobal because this file is compiled before "reader"
107 (defglobal *standard-readtable
* nil
)
109 (defun %with-standard-io-syntax
(function)
110 (declare (type function function
))
111 (let ((*package
* (find-package "COMMON-LISP-USER"))
114 (*print-case
* :upcase
)
121 (*print-miser-width
* nil
)
122 (*print-pprint-dispatch
* sb
!pretty
::*standard-pprint-dispatch-table
*)
126 (*print-right-margin
* nil
)
128 (*read-default-float-format
* 'single-float
)
130 (*read-suppress
* nil
)
131 (*readtable
* *standard-readtable
*)
132 (*suppress-print-errors
* nil
))
135 ;;;; routines to print objects
137 (macrolet ((def (fn doc
&rest forms
)
138 (declare (ignorable doc
))
142 ,@(if (eq fn
'write
) '(stream))
143 ((:escape
*print-escape
*) *print-escape
*)
144 ((:radix
*print-radix
*) *print-radix
*)
145 ((:base
*print-base
*) *print-base
*)
146 ((:circle
*print-circle
*) *print-circle
*)
147 ((:pretty
*print-pretty
*) *print-pretty
*)
148 ((:level
*print-level
*) *print-level
*)
149 ((:length
*print-length
*) *print-length
*)
150 ((:case
*print-case
*) *print-case
*)
151 ((:array
*print-array
*) *print-array
*)
152 ((:gensym
*print-gensym
*) *print-gensym
*)
153 ((:readably
*print-readably
*) *print-readably
*)
154 ((:right-margin
*print-right-margin
*)
155 *print-right-margin
*)
156 ((:miser-width
*print-miser-width
*)
158 ((:lines
*print-lines
*) *print-lines
*)
159 ((:pprint-dispatch
*print-pprint-dispatch
*)
160 *print-pprint-dispatch
*)
161 ((:suppress-errors
*suppress-print-errors
*)
162 *suppress-print-errors
*))
166 "Output OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*."
167 (output-object object
(out-synonym-of stream
))
170 "Return the printed representation of OBJECT as a string."
171 (stringify-object object
)))
173 ;;; Same as a call to (WRITE OBJECT :STREAM STREAM), but returning OBJECT.
174 (defun %write
(object stream
)
175 (output-object object
(out-synonym-of stream
))
178 (defun prin1 (object &optional stream
)
180 "Output a mostly READable printed representation of OBJECT on the specified
182 (let ((*print-escape
* t
))
183 (output-object object
(out-synonym-of stream
)))
186 (defun princ (object &optional stream
)
188 "Output an aesthetic but not necessarily READable printed representation
189 of OBJECT on the specified STREAM."
190 (let ((*print-escape
* nil
)
191 (*print-readably
* nil
))
192 (output-object object
(out-synonym-of stream
)))
195 (defun print (object &optional stream
)
197 "Output a newline, the mostly READable printed representation of OBJECT, and
198 space to the specified STREAM."
199 (let ((stream (out-synonym-of stream
)))
201 (prin1 object stream
)
202 (write-char #\space stream
)
205 (defun pprint (object &optional stream
)
207 "Prettily output OBJECT preceded by a newline."
208 (let ((*print-pretty
* t
)
210 (stream (out-synonym-of stream
)))
212 (output-object object stream
))
215 (defun prin1-to-string (object)
217 "Return the printed representation of OBJECT as a string with
219 (let ((*print-escape
* t
))
220 (stringify-object object
)))
222 (defun princ-to-string (object)
224 "Return the printed representation of OBJECT as a string with
226 (let ((*print-escape
* nil
)
227 (*print-readably
* nil
))
228 (stringify-object object
)))
230 ;;; This produces the printed representation of an object as a string.
231 ;;; The few ...-TO-STRING functions above call this.
232 (defun stringify-object (object)
233 (let ((stream (make-string-output-stream)))
234 (setup-printer-state)
235 (output-object object stream
)
236 (get-output-stream-string stream
)))
238 ;;;; support for the PRINT-UNREADABLE-OBJECT macro
240 (defun print-not-readable-error (object stream
)
242 (error 'print-not-readable
:object object
)
244 :report
"Print unreadably."
245 (let ((*print-readably
* nil
))
246 (output-object object stream
)
249 :report
"Supply an object to be printed instead."
252 (read-evaluated-form "~@<Enter an object (evaluated): ~@:>"))
253 (output-object o stream
)
256 ;;; guts of PRINT-UNREADABLE-OBJECT
257 (defun %print-unreadable-object
(object stream type identity
&optional body
)
258 (declare (type (or null function
) body
))
260 (print-not-readable-error object stream
)
261 (flet ((print-description ()
263 (write (type-of object
) :stream stream
:circle nil
264 :level nil
:length nil
)
265 (write-char #\space stream
)
266 (pprint-newline :fill stream
))
270 (when (or body
(not type
))
271 (write-char #\space stream
))
272 (pprint-newline :fill stream
)
273 (write-char #\
{ stream
)
274 (write (get-lisp-obj-address object
) :stream stream
276 (write-char #\
} stream
))))
277 (cond ((print-pretty-on-stream-p stream
)
278 ;; Since we're printing prettily on STREAM, format the
279 ;; object within a logical block. PPRINT-LOGICAL-BLOCK does
280 ;; not rebind the stream when it is already a pretty stream,
281 ;; so output from the body will go to the same stream.
282 (pprint-logical-block (stream nil
:prefix
"#<" :suffix
">")
283 (print-description)))
285 (write-string "#<" stream
)
287 (write-char #\
> stream
)))))
290 ;;;; OUTPUT-OBJECT -- the main entry point
292 ;;; Objects whose print representation identifies them EQLly don't
293 ;;; need to be checked for circularity.
294 (defun uniquely-identified-by-print-p (x)
298 (symbol-package x
))))
300 (defvar *in-print-error
* nil
)
302 ;;; Output OBJECT to STREAM observing all printer control variables.
303 (defun output-object (object stream
)
304 ;; FIXME: this function is declared EXPLICIT-CHECK, so it allows STREAM
305 ;; to be T or NIL (a stream-designator), which is not really right
306 ;; if eventually the call will be to a PRINT-OBJECT method,
307 ;; since the generic function should always receive a stream.
308 (labels ((print-it (stream)
310 (sb!pretty
:output-pretty-object object stream
)
311 (output-ugly-object object stream
)))
313 (if *suppress-print-errors
*
314 (handler-bind ((condition
315 (lambda (condition) nil
316 (when (typep condition
*suppress-print-errors
*)
317 (cond (*in-print-error
*
318 (write-string "(error printing " stream
)
319 (write-string *in-print-error
* stream
)
320 (write-string ")" stream
))
322 ;; Give outer handlers a chance.
324 (continue "Suppress the error.")
326 (let ((*print-readably
* nil
)
329 "#<error printing a " stream
)
330 (let ((*in-print-error
* "type"))
331 (output-object (type-of object
) stream
))
332 (write-string ": " stream
)
333 (let ((*in-print-error
* "condition"))
334 (output-object condition stream
))
335 (write-string ">" stream
))))
336 (return-from handle-it object
)))))
340 (multiple-value-bind (marker initiate
)
341 (check-for-circularity object t
)
342 (if (eq initiate
:initiate
)
343 (let ((*circularity-hash-table
*
344 (make-hash-table :test
'eq
)))
345 (check-it (make-broadcast-stream))
346 (let ((*circularity-counter
* 0))
350 (when (handle-circularity marker stream
)
352 (handle-it stream
))))))
353 (cond (;; Maybe we don't need to bother with circularity detection.
354 (or (not *print-circle
*)
355 (uniquely-identified-by-print-p object
))
357 (;; If we have already started circularity detection, this
358 ;; object might be a shared reference. If we have not, then
359 ;; if it is a compound object it might contain a circular
360 ;; reference to itself or multiple shared references.
361 (or *circularity-hash-table
*
362 (compound-object-p object
))
365 (handle-it stream
)))))
367 ;;; a hack to work around recurring gotchas with printing while
368 ;;; DEFGENERIC PRINT-OBJECT is being built
370 ;;; (hopefully will go away naturally when CLOS moves into cold init)
371 (defvar *print-object-is-disabled-p
*)
373 ;;; Output OBJECT to STREAM observing all printer control variables
374 ;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
375 ;;; then the pretty printer will be used for any components of OBJECT,
376 ;;; just not for OBJECT itself.
377 (defun output-ugly-object (object stream
)
379 ;; KLUDGE: The TYPECASE approach here is non-ANSI; the ANSI definition of
380 ;; PRINT-OBJECT says it provides printing and we're supposed to provide
381 ;; PRINT-OBJECT methods covering all classes. We deviate from this
382 ;; by using PRINT-OBJECT only when we print instance values. However,
383 ;; ANSI makes it hard to tell that we're deviating from this:
384 ;; (1) ANSI specifies that the user isn't supposed to call PRINT-OBJECT
386 ;; (2) ANSI (section 11.1.2.1.2) says it's undefined to define
387 ;; a method on an external symbol in the CL package which is
388 ;; applicable to arg lists containing only direct instances of
389 ;; standardized classes.
390 ;; Thus, in order for the user to detect our sleaziness in conforming
391 ;; code, he has to do something relatively obscure like
392 ;; (1) actually use tools like FIND-METHOD to look for PRINT-OBJECT
394 ;; (2) define a PRINT-OBJECT method which is specialized on the stream
395 ;; value (e.g. a Gray stream object).
396 ;; As long as no one comes up with a non-obscure way of detecting this
397 ;; sleaziness, fixing this nonconformity will probably have a low
398 ;; priority. -- WHN 2001-11-25
401 (output-symbol object stream
)
402 (output-list object stream
)))
404 ;; The first case takes the above idea one step further: If an instance
405 ;; isn't a citizen yet, it has no right to a print-object method.
406 (cond ((sb!kernel
::undefined-classoid-p
(layout-classoid (layout-of object
)))
407 ;; not only is this unreadable, it's unprintable too.
408 (print-unreadable-object (object stream
:identity t
)
409 (format stream
"UNPRINTABLE instance of ~W"
410 (layout-classoid (layout-of object
)))))
411 ((not (and (boundp '*print-object-is-disabled-p
*)
412 *print-object-is-disabled-p
*))
413 (print-object object stream
))
414 ((typep object
'structure-object
)
415 (default-structure-print object stream
*current-level-in-print
*))
417 (write-string "#<INSTANCE but not STRUCTURE-OBJECT>" stream
))))
418 (funcallable-instance
420 ((not (and (boundp '*print-object-is-disabled-p
*)
421 *print-object-is-disabled-p
*))
422 (print-object object stream
))
423 (t (output-fun object stream
))))
425 (output-fun object stream
))
427 (output-symbol object stream
))
431 (output-integer object stream
))
433 (output-float object stream
))
435 (output-ratio object stream
))
437 (output-complex object stream
))))
439 (output-character object stream
))
441 (output-vector object stream
))
443 (output-array object stream
))
445 (output-sap object stream
))
447 (output-weak-pointer object stream
))
449 (output-lra object stream
))
451 (output-code-component object stream
))
453 (output-fdefn object stream
))
456 (output-simd-pack object stream
))
458 (output-random object stream
))))
462 ;;; values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last
463 ;;; time the printer was called
464 (defvar *previous-case
* nil
)
465 (defvar *previous-readtable-case
* nil
)
467 ;;; This variable contains the current definition of one of three
468 ;;; symbol printers. SETUP-PRINTER-STATE sets this variable.
469 (defvar *internal-symbol-output-fun
* nil
)
470 (declaim (function *internal-symbol-output-fun
*))
472 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
473 ;;; and with any embedded |'s or \'s escaped.
474 (defun output-quoted-symbol-name (pname stream
)
475 (declare (string pname
))
476 (write-char #\| stream
)
477 (dotimes (index (length pname
))
478 (let ((char (schar pname index
)))
479 (when (or (char= char
#\\) (char= char
#\|
))
480 (write-char #\\ stream
))
481 (write-char char stream
)))
482 (write-char #\| stream
))
484 (defun output-symbol (object stream
)
485 (declare (symbol object
))
486 (if (or *print-escape
* *print-readably
*)
487 (let ((package (symbol-package object
))
488 (name (symbol-name object
))
489 (current (sane-package)))
491 ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
492 ;; requires that keywords be printed with preceding colons
493 ;; always, regardless of the value of *PACKAGE*.
494 ((eq package
*keyword-package
*)
495 (write-char #\
: stream
))
496 ;; Otherwise, if the symbol's home package is the current
497 ;; one, then a prefix is never necessary.
498 ((eq package current
))
499 ;; Uninterned symbols print with a leading #:.
501 (when (or *print-gensym
* *print-readably
*)
502 (write-string "#:" stream
)))
504 (multiple-value-bind (symbol accessible
)
505 (find-symbol name current
)
506 ;; If we can find the symbol by looking it up, it need not
507 ;; be qualified. This can happen if the symbol has been
508 ;; inherited from a package other than its home package.
510 ;; To preserve print-read consistency, use the local nickname if
512 (unless (and accessible
(eq symbol object
))
513 (let ((prefix (or (car (rassoc package
(package-%local-nicknames current
)))
514 (package-name package
))))
515 (output-symbol-name prefix stream
))
516 (if (nth-value 1 (find-external-symbol name package
))
517 (write-char #\
: stream
)
518 (write-string "::" stream
))))))
519 (output-symbol-name name stream
))
520 (output-symbol-name (symbol-name object
) stream nil
)))
522 ;;; Output the string NAME as if it were a symbol name. In other
523 ;;; words, diddle its case according to *PRINT-CASE* and
525 (defun output-symbol-name (name stream
&optional
(maybe-quote t
))
526 (declare (type simple-string name
))
527 (let ((*readtable
* (if *print-readably
* *standard-readtable
* *readtable
*)))
528 (setup-printer-state)
529 (if (and maybe-quote
(or
530 (and (readtable-normalization *readtable
*)
531 (not (sb!unicode
:normalized-p name
:nfkc
)))
532 (symbol-quotep name
)))
533 (output-quoted-symbol-name name stream
)
534 (funcall *internal-symbol-output-fun
* name stream
))))
536 ;;;; escaping symbols
538 ;;; When we print symbols we have to figure out if they need to be
539 ;;; printed with escape characters. This isn't a whole lot easier than
540 ;;; reading symbols in the first place.
542 ;;; For each character, the value of the corresponding element is a
543 ;;; fixnum with bits set corresponding to attributes that the
544 ;;; character has. At characters have at least one bit set, so we can
545 ;;; search for any character with a positive test.
546 (defvar *character-attributes
*
547 (make-array 160 ; FIXME
548 :element-type
'(unsigned-byte 16)
550 (declaim (type (simple-array (unsigned-byte 16) (#.160)) ; FIXME
551 *character-attributes
*))
553 ;;; constants which are a bit-mask for each interesting character attribute
554 (defconstant other-attribute
(ash 1 0)) ; Anything else legal.
555 (defconstant number-attribute
(ash 1 1)) ; A numeric digit.
556 (defconstant uppercase-attribute
(ash 1 2)) ; An uppercase letter.
557 (defconstant lowercase-attribute
(ash 1 3)) ; A lowercase letter.
558 (defconstant sign-attribute
(ash 1 4)) ; +-
559 (defconstant extension-attribute
(ash 1 5)) ; ^_
560 (defconstant dot-attribute
(ash 1 6)) ; .
561 (defconstant slash-attribute
(ash 1 7)) ; /
562 (defconstant funny-attribute
(ash 1 8)) ; Anything illegal.
564 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
566 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
567 ;;; that don't need to be escaped (according to READTABLE-CASE.)
568 (defparameter *attribute-names
*
569 `((number . number-attribute
) (lowercase . lowercase-attribute
)
570 (uppercase . uppercase-attribute
) (letter . letter-attribute
)
571 (sign . sign-attribute
) (extension . extension-attribute
)
572 (dot . dot-attribute
) (slash . slash-attribute
)
573 (other . other-attribute
) (funny . funny-attribute
)))
577 ;;; For each character, the value of the corresponding element is the
578 ;;; lowest base in which that character is a digit.
579 (declaim (type (simple-array (unsigned-byte 8) (128)) ; FIXME: range?
581 (defvar *digit-bases
*
582 (make-array 128 ; FIXME
583 :element-type
'(unsigned-byte 8)))
585 (defun !printer-cold-init
()
586 ;; The dispatch table will be changed later, so this doesn't really matter
587 ;; except if a full call to WRITE wants to read the current binding.
588 (setq *print-pprint-dispatch
* (sb!pretty
::make-pprint-dispatch-table
))
589 (setq *digit-bases
* (make-array 128 ; FIXME
590 :element-type
'(unsigned-byte 8)
592 *character-attributes
* (make-array 160 ; FIXME
593 :element-type
'(unsigned-byte 16)
596 (let ((char (digit-char i
36)))
597 (setf (aref *digit-bases
* (char-code char
)) i
)))
599 (flet ((set-bit (char bit
)
600 (let ((code (char-code char
)))
601 (setf (aref *character-attributes
* code
)
602 (logior bit
(aref *character-attributes
* code
))))))
604 (dolist (char '(#\
! #\
@ #\$
#\%
#\
& #\
* #\
= #\~
#\
[ #\
] #\
{ #\
}
606 (set-bit char other-attribute
))
609 (set-bit (digit-char i
) number-attribute
))
611 (do ((code (char-code #\A
) (1+ code
))
612 (end (char-code #\Z
)))
614 (declare (fixnum code end
))
615 (set-bit (code-char code
) uppercase-attribute
)
616 (set-bit (char-downcase (code-char code
)) lowercase-attribute
))
618 (set-bit #\- sign-attribute
)
619 (set-bit #\
+ sign-attribute
)
620 (set-bit #\^ extension-attribute
)
621 (set-bit #\_ extension-attribute
)
622 (set-bit #\. dot-attribute
)
623 (set-bit #\
/ slash-attribute
)
625 ;; Mark anything not explicitly allowed as funny.
626 (dotimes (i 160) ; FIXME
627 (when (zerop (aref *character-attributes
* i
))
628 (setf (aref *character-attributes
* i
) funny-attribute
))))
629 ) ; end !COLD-PRINT-INIT
631 ;;; A FSM-like thingie that determines whether a symbol is a potential
632 ;;; number or has evil characters in it.
633 (defun symbol-quotep (name)
634 (declare (simple-string name
))
635 (macrolet ((advance (tag &optional
(at-end t
))
638 ,(if at-end
'(go TEST-SIGN
) '(return nil
)))
639 (setq current
(schar name index
)
640 code
(char-code current
)
642 ((< code
160) (aref attributes code
))
643 ((upper-case-p current
) uppercase-attribute
)
644 ((lower-case-p current
) lowercase-attribute
)
645 (t other-attribute
)))
648 (test (&rest attributes
)
660 `(and (< code
128) ; FIXME
661 (< (the fixnum
(aref bases code
)) base
))))
663 (prog ((len (length name
))
664 (attributes *character-attributes
*)
665 (bases *digit-bases
*)
668 (case (%readtable-case
*readtable
*)
669 (:upcase uppercase-attribute
)
670 (:downcase lowercase-attribute
)
671 (t (logior lowercase-attribute uppercase-attribute
))))
676 (declare (fixnum len base index bits code
))
679 TEST-SIGN
; At end, see whether it is a sign...
680 (return (not (test sign
)))
682 OTHER
; not potential number, see whether funny chars...
683 (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
686 (do ((i (1- index
) (1+ i
)))
687 ((= i len
) (return-from symbol-quotep nil
))
688 (unless (zerop (logand (let* ((char (schar name i
))
689 (code (char-code char
)))
691 ((< code
160) (aref attributes code
))
692 ((upper-case-p char
) uppercase-attribute
)
693 ((lower-case-p char
) lowercase-attribute
)
694 (t other-attribute
)))
696 (return-from symbol-quotep t
))))
701 (advance LAST-DIGIT-ALPHA
)
703 (when (test letter number other slash
) (advance OTHER nil
))
704 (when (char= current
#\.
) (advance DOT-FOUND
))
705 (when (test sign extension
) (advance START-STUFF nil
))
708 DOT-FOUND
; leading dots...
709 (when (test letter
) (advance START-DOT-MARKER nil
))
710 (when (digitp) (advance DOT-DIGIT
))
711 (when (test number other
) (advance OTHER nil
))
712 (when (test extension slash sign
) (advance START-DOT-STUFF nil
))
713 (when (char= current
#\.
) (advance DOT-FOUND
))
716 START-STUFF
; leading stuff before any dot or digit
719 (advance LAST-DIGIT-ALPHA
)
721 (when (test number other
) (advance OTHER nil
))
722 (when (test letter
) (advance START-MARKER nil
))
723 (when (char= current
#\.
) (advance START-DOT-STUFF nil
))
724 (when (test sign extension slash
) (advance START-STUFF nil
))
727 START-MARKER
; number marker in leading stuff...
728 (when (test letter
) (advance OTHER nil
))
731 START-DOT-STUFF
; leading stuff containing dot without digit...
732 (when (test letter
) (advance START-DOT-STUFF nil
))
733 (when (digitp) (advance DOT-DIGIT
))
734 (when (test sign extension dot slash
) (advance START-DOT-STUFF nil
))
735 (when (test number other
) (advance OTHER nil
))
738 START-DOT-MARKER
; number marker in leading stuff with dot..
739 ;; leading stuff containing dot without digit followed by letter...
740 (when (test letter
) (advance OTHER nil
))
743 DOT-DIGIT
; in a thing with dots...
744 (when (test letter
) (advance DOT-MARKER
))
745 (when (digitp) (advance DOT-DIGIT
))
746 (when (test number other
) (advance OTHER nil
))
747 (when (test sign extension dot slash
) (advance DOT-DIGIT
))
750 DOT-MARKER
; number marker in number with dot...
751 (when (test letter
) (advance OTHER nil
))
754 LAST-DIGIT-ALPHA
; previous char is a letter digit...
755 (when (or (digitp) (test sign slash
))
756 (advance ALPHA-DIGIT
))
757 (when (test letter number other dot
) (advance OTHER nil
))
760 ALPHA-DIGIT
; seen a digit which is a letter...
761 (when (or (digitp) (test sign slash
))
763 (advance LAST-DIGIT-ALPHA
)
764 (advance ALPHA-DIGIT
)))
765 (when (test letter
) (advance ALPHA-MARKER
))
766 (when (test number other dot
) (advance OTHER nil
))
769 ALPHA-MARKER
; number marker in number with alpha digit...
770 (when (test letter
) (advance OTHER nil
))
773 DIGIT
; seen only ordinary (non-alphabetic) numeric digits...
776 (advance ALPHA-DIGIT
)
778 (when (test number other
) (advance OTHER nil
))
779 (when (test letter
) (advance MARKER
))
780 (when (test extension slash sign
) (advance DIGIT
))
781 (when (char= current
#\.
) (advance DOT-DIGIT
))
784 MARKER
; number marker in a numeric number...
785 ;; ("What," you may ask, "is a 'number marker'?" It's something
786 ;; that a conforming implementation might use in number syntax.
787 ;; See ANSI 2.3.1.1 "Potential Numbers as Tokens".)
788 (when (test letter
) (advance OTHER nil
))
791 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN*
793 ;;;; case hackery: These functions are stored in
794 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN* according to the values of
795 ;;;; *PRINT-CASE* and READTABLE-CASE.
798 ;;; READTABLE-CASE *PRINT-CASE*
800 ;;; :DOWNCASE :DOWNCASE
802 (defun output-preserve-symbol (pname stream
)
803 (declare (simple-string pname
))
804 (write-string pname stream
))
807 ;;; READTABLE-CASE *PRINT-CASE*
808 ;;; :UPCASE :DOWNCASE
809 (defun output-lowercase-symbol (pname stream
)
810 (declare (simple-string pname
))
811 (dotimes (index (length pname
))
812 (let ((char (schar pname index
)))
813 (write-char (char-downcase char
) stream
))))
816 ;;; READTABLE-CASE *PRINT-CASE*
817 ;;; :DOWNCASE :UPCASE
818 (defun output-uppercase-symbol (pname stream
)
819 (declare (simple-string pname
))
820 (dotimes (index (length pname
))
821 (let ((char (schar pname index
)))
822 (write-char (char-upcase char
) stream
))))
825 ;;; READTABLE-CASE *PRINT-CASE*
826 ;;; :UPCASE :CAPITALIZE
827 ;;; :DOWNCASE :CAPITALIZE
828 (defun output-capitalize-symbol (pname stream
)
829 (declare (simple-string pname
))
830 (let ((prev-not-alphanum t
)
831 (up (eq (%readtable-case
*readtable
*) :upcase
)))
832 (dotimes (i (length pname
))
833 (let ((char (char pname i
)))
835 (if (or prev-not-alphanum
(lower-case-p char
))
837 (char-downcase char
))
838 (if prev-not-alphanum
842 (setq prev-not-alphanum
(not (alphanumericp char
)))))))
845 ;;; READTABLE-CASE *PRINT-CASE*
847 (defun output-invert-symbol (pname stream
)
848 (declare (simple-string pname
))
851 (dotimes (i (length pname
))
852 (let ((ch (schar pname i
)))
853 (when (both-case-p ch
)
854 (if (upper-case-p ch
)
856 (setq all-upper nil
)))))
857 (cond (all-upper (output-lowercase-symbol pname stream
))
858 (all-lower (output-uppercase-symbol pname stream
))
860 (write-string pname stream
)))))
862 ;;; Set the internal global symbol *INTERNAL-SYMBOL-OUTPUT-FUN*
863 ;;; to the right function depending on the values of *PRINT-CASE*
864 ;;; and (%READTABLE-CASE *READTABLE*).
865 (defun setup-printer-state ()
866 (let ((readtable-case (%readtable-case
*readtable
*))
867 (print-case *print-case
*))
868 (unless (and (eq print-case
*previous-case
*)
869 (eq readtable-case
*previous-readtable-case
*))
870 (setq *previous-case
* print-case
)
871 (setq *previous-readtable-case
* readtable-case
)
872 (setq *internal-symbol-output-fun
*
873 ;; a morally equivalent reformulation of FOP-KNOWN-FUN
874 (macrolet ((load-time-fn (name) `(load-time-value #',name t
)))
878 (:upcase
(load-time-fn output-preserve-symbol
))
879 (:downcase
(load-time-fn output-lowercase-symbol
))
880 (:capitalize
(load-time-fn output-capitalize-symbol
))))
883 (:upcase
(load-time-fn output-uppercase-symbol
))
884 (:downcase
(load-time-fn output-preserve-symbol
))
885 (:capitalize
(load-time-fn output-capitalize-symbol
))))
886 (:preserve
(load-time-fn output-preserve-symbol
))
887 (:invert
(load-time-fn output-invert-symbol
))))))))
891 (let ((*readtable
* (copy-readtable nil
)))
892 (format t
"READTABLE-CASE Input Symbol-name~@
893 ----------------------------------~%")
894 (dolist (readtable-case '(:upcase
:downcase
:preserve
:invert
))
895 (setf (readtable-case *readtable
*) readtable-case
)
896 (dolist (input '("ZEBRA" "Zebra" "zebra"))
897 (format t
"~&:~A~16T~A~24T~A"
898 (string-upcase readtable-case
)
900 (symbol-name (read-from-string input
)))))))
903 (let ((*readtable
* (copy-readtable nil
)))
904 (format t
"READTABLE-CASE *PRINT-CASE* Symbol-name Output Princ~@
905 --------------------------------------------------------~%")
906 (dolist (readtable-case '(:upcase
:downcase
:preserve
:invert
))
907 (setf (readtable-case *readtable
*) readtable-case
)
908 (dolist (*print-case
* '(:upcase
:downcase
:capitalize
))
909 (dolist (symbol '(|ZEBRA| |Zebra| |zebra|
))
910 (format t
"~&:~A~15T:~A~29T~A~42T~A~50T~A"
911 (string-upcase readtable-case
)
912 (string-upcase *print-case
*)
914 (prin1-to-string symbol
)
915 (princ-to-string symbol
)))))))
918 ;;;; recursive objects
920 (defun output-list (list stream
)
921 (descend-into (stream)
922 (write-char #\
( stream
)
926 (punt-print-if-too-long length stream
)
927 (output-object (pop list
) stream
)
930 (when (or (atom list
)
931 (check-for-circularity list
))
932 (write-string " . " stream
)
933 (output-object list stream
)
935 (write-char #\space stream
)
937 (write-char #\
) stream
)))
939 (defun output-unreadable-vector-readably (vector stream
)
940 (declare (vector vector
))
941 (write-string "#." stream
)
942 (write `(coerce ,(coerce vector
'(vector t
))
943 '(simple-array ,(array-element-type vector
) (*)))
946 (defun output-vector (vector stream
)
947 (declare (vector vector
))
948 (cond ((stringp vector
)
949 (cond ((and *print-readably
*
950 (not (eq (array-element-type vector
)
953 (make-array 0 :element-type
'character
))))))
954 (print-not-readable-error vector stream
))
955 ((or *print-escape
* *print-readably
*)
956 (write-char #\" stream
)
957 (quote-string vector stream
)
958 (write-char #\" stream
))
960 (write-string vector stream
))))
961 ((not (or *print-array
* *print-readably
*))
962 (output-terse-array vector stream
))
963 ((bit-vector-p vector
)
964 (write-string "#*" stream
)
965 (dovector (bit vector
)
966 ;; (Don't use OUTPUT-OBJECT here, since this code
967 ;; has to work for all possible *PRINT-BASE* values.)
968 (write-char (if (zerop bit
) #\
0 #\
1) stream
)))
969 ((or (not *print-readably
*)
970 (array-readably-printable-p vector
))
971 (descend-into (stream)
972 (write-string "#(" stream
)
973 (dotimes (i (length vector
))
975 (write-char #\space stream
))
976 (punt-print-if-too-long i stream
)
977 (output-object (aref vector i
) stream
))
978 (write-string ")" stream
)))
980 (output-unreadable-vector-readably vector stream
))
982 (print-not-readable-error vector stream
))))
984 ;;; This function outputs a string quoting characters sufficiently
985 ;;; so that someone can read it in again. Basically, put a slash in
986 ;;; front of an character satisfying NEEDS-SLASH-P.
987 (defun quote-string (string stream
)
988 (macrolet ((needs-slash-p (char)
989 ;; KLUDGE: We probably should look at the readtable, but just do
990 ;; this for now. [noted by anonymous long ago] -- WHN 19991130
991 `(or (char= ,char
#\\)
993 (with-array-data ((data string
) (start) (end)
994 :check-fill-pointer t
)
995 (do ((index start
(1+ index
)))
997 (let ((char (schar data index
)))
998 (when (needs-slash-p char
) (write-char #\\ stream
))
999 (write-char char stream
))))))
1001 (defun array-readably-printable-p (array)
1002 (and (eq (array-element-type array
) t
)
1003 (let ((zero (position 0 (array-dimensions array
)))
1004 (number (position 0 (array-dimensions array
)
1005 :test
(complement #'eql
)
1007 (or (null zero
) (null number
) (> zero number
)))))
1009 ;;; Output the printed representation of any array in either the #< or #A
1011 (defun output-array (array stream
)
1012 (if (or *print-array
* *print-readably
*)
1013 (output-array-guts array stream
)
1014 (output-terse-array array stream
)))
1016 ;;; Output the abbreviated #< form of an array.
1017 (defun output-terse-array (array stream
)
1018 (let ((*print-level
* nil
)
1019 (*print-length
* nil
))
1020 (print-unreadable-object (array stream
:type t
:identity t
))))
1022 ;;; Convert an array into a list that can be used with MAKE-ARRAY's
1023 ;;; :INITIAL-CONTENTS keyword argument.
1024 (defun listify-array (array)
1025 (with-array-data ((data array
) (start) (end))
1026 (declare (ignore end
))
1027 (labels ((listify (dimensions index
)
1028 (if (null dimensions
)
1030 (let* ((dimension (car dimensions
))
1031 (dimensions (cdr dimensions
))
1032 (count (reduce #'* dimensions
)))
1033 (loop for i below dimension
1034 collect
(listify dimensions index
)
1035 do
(incf index count
))))))
1036 (listify (array-dimensions array
) start
))))
1038 (defun output-unreadable-array-readably (array stream
)
1039 (write-string "#." stream
)
1040 (write `(make-array ',(array-dimensions array
)
1041 :element-type
',(array-element-type array
)
1042 :initial-contents
',(listify-array array
))
1045 ;;; Output the readable #A form of an array.
1046 (defun output-array-guts (array stream
)
1047 (cond ((or (not *print-readably
*)
1048 (array-readably-printable-p array
))
1049 (write-char #\
# stream
)
1050 (let ((*print-base
* 10)
1051 (*print-radix
* nil
))
1052 (output-integer (array-rank array
) stream
))
1053 (write-char #\A stream
)
1054 (with-array-data ((data array
) (start) (end))
1055 (declare (ignore end
))
1056 (sub-output-array-guts data
(array-dimensions array
) stream start
)))
1058 (output-unreadable-array-readably array stream
))
1060 (print-not-readable-error array stream
))))
1062 (defun sub-output-array-guts (array dimensions stream index
)
1063 (declare (type (simple-array * (*)) array
) (fixnum index
))
1064 (cond ((null dimensions
)
1065 (output-object (aref array index
) stream
))
1067 (descend-into (stream)
1068 (write-char #\
( stream
)
1069 (let* ((dimension (car dimensions
))
1070 (dimensions (cdr dimensions
))
1071 (count (reduce #'* dimensions
)))
1072 (dotimes (i dimension
)
1074 (write-char #\space stream
))
1075 (punt-print-if-too-long i stream
)
1076 (sub-output-array-guts array dimensions stream index
)
1077 (incf index count
)))
1078 (write-char #\
) stream
)))))
1080 ;;; a trivial non-generic-function placeholder for PRINT-OBJECT, for
1081 ;;; use until CLOS is set up (at which time it will be replaced with
1082 ;;; the real generic function implementation)
1083 (defun print-object (instance stream
)
1084 (default-structure-print instance stream
*current-level-in-print
*))
1086 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
1088 (defun %output-radix
(base stream
)
1089 (write-char #\
# stream
)
1090 (write-char (case base
1094 (t (%output-reasonable-integer-in-base base
10 stream
)
1098 (defun %output-reasonable-integer-in-base
(n base stream
)
1099 (multiple-value-bind (q r
)
1101 ;; Recurse until you have all the digits pushed on
1104 (%output-reasonable-integer-in-base q base stream
))
1105 ;; Then as each recursive call unwinds, turn the
1106 ;; digit (in remainder) into a character and output
1109 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r
)
1112 ;;; *POWER-CACHE* is an alist mapping bases to power-vectors. It is
1113 ;;; filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
1114 ;;; always prior a GC to drop overly large bignums from the cache.
1116 ;;; It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
1117 ;;; POWERS-FOR-BASE, see that you don't break the assumptions!
1118 (defvar *power-cache
* nil
)
1120 (defconstant +power-cache-integer-length-limit
+ 2048)
1122 (defun scrub-power-cache ()
1123 (let ((cache *power-cache
*))
1124 (dolist (cell cache
)
1125 (let ((powers (cdr cell
)))
1126 (declare (simple-vector powers
))
1127 (let ((too-big (position-if
1129 (>= (integer-length x
)
1130 +power-cache-integer-length-limit
+))
1133 (setf (cdr cell
) (subseq powers
0 too-big
))))))
1134 ;; Since base 10 is overwhelmingly common, make sure it's at head.
1135 ;; Try to keep other bases in a hopefully sensible order as well.
1136 (if (eql 10 (caar cache
))
1137 (setf *power-cache
* cache
)
1138 ;; If we modify the list destructively we need to copy it, otherwise
1139 ;; an alist lookup in progress might be screwed.
1140 (setf *power-cache
* (sort (copy-list cache
)
1142 (declare (fixnum a b
))
1152 ;;; Compute (and cache) a power vector for a BASE and LIMIT:
1153 ;;; the vector holds integers for which
1154 ;;; (aref powers k) == (expt base (expt 2 k))
1156 (defun powers-for-base (base limit
)
1157 (flet ((compute-powers (from)
1159 (do ((p from
(* p p
)))
1161 ;; We don't actually need this, but we also
1162 ;; prefer not to cons it up a second time...
1165 (nreverse powers
))))
1166 ;; Grab a local reference so that we won't stuff consed at the
1167 ;; head by other threads -- or sorting by SCRUB-POWER-CACHE.
1168 (let ((cache *power-cache
*))
1169 (let ((cell (assoc base cache
)))
1171 (let* ((powers (cdr cell
))
1172 (len (length powers
))
1173 (max (svref powers
(1- len
))))
1177 (concatenate 'vector powers
1178 (compute-powers (* max max
)))))
1179 (setf (cdr cell
) new
)
1181 (let ((powers (coerce (compute-powers base
) 'vector
)))
1182 ;; Add new base to head: SCRUB-POWER-CACHE will later
1183 ;; put it to a better place.
1184 (setf *power-cache
* (acons base powers cache
))
1187 ;; Algorithm by Harald Hanche-Olsen, sbcl-devel 2005-02-05
1188 (defun %output-huge-integer-in-base
(n base stream
)
1189 (declare (type bignum n
) (type fixnum base
))
1190 ;; POWER is a vector for which the following holds:
1191 ;; (aref power k) == (expt base (expt 2 k))
1192 (let* ((power (powers-for-base base n
))
1193 (k-start (or (position-if (lambda (x) (> x n
)) power
)
1194 (bug "power-vector too short"))))
1195 (labels ((bisect (n k exactp
)
1196 (declare (fixnum k
))
1197 ;; N is the number to bisect
1198 ;; K on initial entry BASE^(2^K) > N
1199 ;; EXACTP is true if 2^K is the exact number of digits
1202 (loop repeat
(ash 1 k
) do
(write-char #\
0 stream
))))
1205 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n
)
1209 (multiple-value-bind (q r
) (truncate n
(aref power k
))
1210 ;; EXACTP is NIL only at the head of the
1211 ;; initial number, as we don't know the number
1212 ;; of digits there, but we do know that it
1213 ;; doesn't get any leading zeros.
1215 (bisect r k
(or exactp
(plusp q
))))))))
1216 (bisect n k-start nil
))))
1218 (defun %output-integer-in-base
(integer base stream
)
1219 (when (minusp integer
)
1220 (write-char #\- stream
)
1221 (setf integer
(- integer
)))
1222 ;; The ideal cutoff point between these two algorithms is almost
1223 ;; certainly quite platform dependent: this gives 87 for 32 bit
1224 ;; SBCL, which is about right at least for x86/Darwin.
1225 (if (or (fixnump integer
)
1226 (< (integer-length integer
) (* 3 sb
!vm
:n-positive-fixnum-bits
)))
1227 (%output-reasonable-integer-in-base integer base stream
)
1228 (%output-huge-integer-in-base integer base stream
)))
1230 (defun output-integer (integer stream
)
1231 (let ((base *print-base
*))
1232 (when (and (/= base
10) *print-radix
*)
1233 (%output-radix base stream
))
1234 (%output-integer-in-base integer base stream
)
1235 (when (and *print-radix
* (= base
10))
1236 (write-char #\. stream
))))
1238 (defun output-ratio (ratio stream
)
1239 (let ((base *print-base
*))
1241 (%output-radix base stream
))
1242 (%output-integer-in-base
(numerator ratio
) base stream
)
1243 (write-char #\
/ stream
)
1244 (%output-integer-in-base
(denominator ratio
) base stream
)))
1246 (defun output-complex (complex stream
)
1247 (write-string "#C(" stream
)
1248 ;; FIXME: Could this just be OUTPUT-NUMBER?
1249 (output-object (realpart complex
) stream
)
1250 (write-char #\space stream
)
1251 (output-object (imagpart complex
) stream
)
1252 (write-char #\
) stream
))
1256 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1257 ;;; most of the work for all printing of floating point numbers in
1258 ;;; FORMAT. It converts a floating point number to a string in a free
1259 ;;; or fixed format with no exponent. The interpretation of the
1260 ;;; arguments is as follows:
1262 ;;; X - The floating point number to convert, which must not be
1264 ;;; WIDTH - The preferred field width, used to determine the number
1265 ;;; of fraction digits to produce if the FDIGITS parameter
1266 ;;; is unspecified or NIL. If the non-fraction digits and the
1267 ;;; decimal point alone exceed this width, no fraction digits
1268 ;;; will be produced unless a non-NIL value of FDIGITS has been
1269 ;;; specified. Field overflow is not considerd an error at this
1271 ;;; FDIGITS - The number of fractional digits to produce. Insignificant
1272 ;;; trailing zeroes may be introduced as needed. May be
1273 ;;; unspecified or NIL, in which case as many digits as possible
1274 ;;; are generated, subject to the constraint that there are no
1275 ;;; trailing zeroes.
1276 ;;; SCALE - If this parameter is specified or non-NIL, then the number
1277 ;;; printed is (* x (expt 10 scale)). This scaling is exact,
1278 ;;; and cannot lose precision.
1279 ;;; FMIN - This parameter, if specified or non-NIL, is the minimum
1280 ;;; number of fraction digits which will be produced, regardless
1281 ;;; of the value of WIDTH or FDIGITS. This feature is used by
1282 ;;; the ~E format directive to prevent complete loss of
1283 ;;; significance in the printed value due to a bogus choice of
1287 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1288 ;;; where the results have the following interpretation:
1290 ;;; DIGIT-STRING - The decimal representation of X, with decimal point.
1291 ;;; DIGIT-LENGTH - The length of the string DIGIT-STRING.
1292 ;;; LEADING-POINT - True if the first character of DIGIT-STRING is the
1294 ;;; TRAILING-POINT - True if the last character of DIGIT-STRING is the
1296 ;;; POINT-POS - The position of the digit preceding the decimal
1297 ;;; point. Zero indicates point before first digit.
1299 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1300 ;;; accuracy. Specifically, the decimal number printed is the closest
1301 ;;; possible approximation to the true value of the binary number to
1302 ;;; be printed from among all decimal representations with the same
1303 ;;; number of digits. In free-format output, i.e. with the number of
1304 ;;; digits unconstrained, it is guaranteed that all the information is
1305 ;;; preserved, so that a properly- rounding reader can reconstruct the
1306 ;;; original binary number, bit-for-bit, from its printed decimal
1307 ;;; representation. Furthermore, only as many digits as necessary to
1308 ;;; satisfy this condition will be printed.
1310 ;;; FLOAT-DIGITS actually generates the digits for positive numbers;
1311 ;;; see below for comments.
1313 (defun flonum-to-string (x &optional width fdigits scale fmin
)
1314 (declare (type float x
))
1315 ;; FIXME: I think only FORMAT-DOLLARS calls FLONUM-TO-STRING with
1316 ;; possibly-negative X.
1318 (multiple-value-bind (e string
)
1320 (flonum-to-digits x
(min (- (+ fdigits
(or scale
0)))
1322 (if (and width
(> width
1))
1323 (let ((w (multiple-value-list
1327 (if (and scale
(minusp scale
))
1330 (f (multiple-value-list
1331 (flonum-to-digits x
(- (+ (or fmin
0)
1332 (if scale scale
0)))))))
1334 ((>= (length (cadr w
)) (length (cadr f
)))
1336 (t (values-list f
))))
1337 (flonum-to-digits x
)))
1338 (let ((e (if (zerop x
)
1340 (+ e
(or scale
0))))
1341 (stream (make-string-output-stream)))
1344 (write-string string stream
:end
(min (length string
) e
))
1345 (dotimes (i (- e
(length string
)))
1346 (write-char #\
0 stream
))
1347 (write-char #\. stream
)
1348 (write-string string stream
:start
(min (length string
) e
))
1350 (dotimes (i (- fdigits
1352 (min (length string
) e
))))
1353 (write-char #\
0 stream
))))
1355 (write-string "." stream
)
1357 (write-char #\
0 stream
))
1358 (write-string string stream
:end
(when fdigits
1359 (min (length string
)
1363 (dotimes (i (+ fdigits e
(- (length string
))))
1364 (write-char #\
0 stream
)))))
1365 (let ((string (get-output-stream-string stream
)))
1366 (values string
(length string
)
1367 (char= (char string
0) #\.
)
1368 (char= (char string
(1- (length string
))) #\.
)
1369 (position #\. string
))))))
1371 ;;; implementation of figure 1 from Burger and Dybvig, 1996. It is
1372 ;;; extended in order to handle rounding.
1374 ;;; As the implementation of the Dragon from Classic CMUCL (and
1375 ;;; previously in SBCL above FLONUM-TO-STRING) says: "DO NOT EVEN
1376 ;;; THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE
1377 ;;; PAPER!", and in this case we have to add that even reading the
1378 ;;; paper might not bring immediate illumination as CSR has attempted
1379 ;;; to turn idiomatic Scheme into idiomatic Lisp.
1381 ;;; FIXME: figure 1 from Burger and Dybvig is the unoptimized
1382 ;;; algorithm, noticeably slow at finding the exponent. Figure 2 has
1383 ;;; an improved algorithm, but CSR ran out of energy.
1385 ;;; possible extension for the enthusiastic: printing floats in bases
1386 ;;; other than base 10.
1387 (defconstant single-float-min-e
1388 (- 2 sb
!vm
:single-float-bias sb
!vm
:single-float-digits
))
1389 (defconstant double-float-min-e
1390 (- 2 sb
!vm
:double-float-bias sb
!vm
:double-float-digits
))
1392 (defconstant long-float-min-e
1393 (nth-value 1 (decode-float least-positive-long-float
)))
1395 (defun flonum-to-digits (v &optional position relativep
)
1396 (let ((print-base 10) ; B
1398 (float-digits (float-digits v
)) ; p
1399 (digit-characters "0123456789")
1402 (single-float single-float-min-e
)
1403 (double-float double-float-min-e
)
1405 (long-float long-float-min-e
))))
1406 (multiple-value-bind (f e
)
1407 (integer-decode-float v
)
1408 (let (;; FIXME: these even tests assume normal IEEE rounding
1409 ;; mode. I wonder if we should cater for non-normal?
1412 (with-push-char (:element-type base-char
)
1413 (labels ((scale (r s m
+ m-
)
1415 (s s
(* s print-base
)))
1416 ((not (or (> (+ r m
+) s
)
1417 (and high-ok
(= (+ r m
+) s
))))
1419 (r r
(* r print-base
))
1420 (m+ m
+ (* m
+ print-base
))
1421 (m- m-
(* m- print-base
)))
1422 ((not (and (plusp (- r m-
)) ; Extension to handle zero
1423 (or (< (* (+ r m
+) print-base
) s
)
1425 (= (* (+ r m
+) print-base
) s
)))))
1426 (values k
(generate r s m
+ m-
)))))))
1427 (generate (r s m
+ m-
)
1431 (setf (values d r
) (truncate (* r print-base
) s
))
1432 (setf m
+ (* m
+ print-base
))
1433 (setf m-
(* m- print-base
))
1434 (setf tc1
(or (< r m-
) (and low-ok
(= r m-
))))
1435 (setf tc2
(or (> (+ r m
+) s
)
1436 (and high-ok
(= (+ r m
+) s
))))
1439 (push-char (char digit-characters d
))
1443 ((and (not tc1
) tc2
) (1+ d
))
1444 ((and tc1
(not tc2
)) d
)
1446 (if (< (* r
2) s
) d
(1+ d
))))))
1447 (push-char (char digit-characters d
))
1448 (return-from generate
(get-pushed-string))))))
1452 (let* ((be (expt float-radix e
))
1453 (be1 (* be float-radix
)))
1454 (if (/= f
(expt float-radix
(1- float-digits
)))
1464 (/= f
(expt float-radix
(1- float-digits
))))
1466 s
(* (expt float-radix
(- e
)) 2)
1469 (setf r
(* f float-radix
2)
1470 s
(* (expt float-radix
(- 1 e
)) 2)
1475 (aver (> position
0))
1477 ;; running out of letters here
1478 (l 1 (* l print-base
)))
1479 ((>= (* s l
) (+ r m
+))
1481 (if (< (+ r
(* s
(/ (expt print-base
(- k position
)) 2)))
1482 (* s
(expt print-base k
)))
1483 (setf position
(- k position
))
1484 (setf position
(- k position
1))))))
1485 (let ((low (max m-
(/ (* s
(expt print-base position
)) 2)))
1486 (high (max m
+ (/ (* s
(expt print-base position
)) 2))))
1493 (values r s m
+ m-
))))
1494 (multiple-value-bind (r s m
+ m-
) (initialize)
1495 (scale r s m
+ m-
))))))))
1497 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns
1498 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1499 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1500 ;;; original number. There may be some loss of precision due the
1501 ;;; floating point representation. The scaling is always done with
1502 ;;; long float arithmetic, which helps printing of lesser precisions
1503 ;;; as well as avoiding generic arithmetic.
1505 ;;; When computing our initial scale factor using EXPT, we pull out
1506 ;;; part of the computation to avoid over/under flow. When
1507 ;;; denormalized, we must pull out a large factor, since there is more
1508 ;;; negative exponent range than positive range.
1510 (eval-when (:compile-toplevel
:execute
)
1511 (setf *read-default-float-format
*
1512 #!+long-float
'long-float
#!-long-float
'double-float
))
1513 (defun scale-exponent (original-x)
1514 (let* ((x (coerce original-x
'long-float
)))
1515 (multiple-value-bind (sig exponent
) (decode-float x
)
1516 (declare (ignore sig
))
1518 (values (float 0.0e0 original-x
) 1)
1519 (let* ((ex (locally (declare (optimize (safety 0)))
1522 ;; this is the closest double float
1523 ;; to (log 2 10), but expressed so
1524 ;; that we're not vulnerable to the
1525 ;; host lisp's interpretation of
1526 ;; arithmetic. (FIXME: it turns
1527 ;; out that sbcl itself is off by 1
1528 ;; ulp in this value, which is a
1529 ;; little unfortunate.)
1532 (make-double-float 1070810131 1352628735)
1534 (error "(log 2 10) not computed")))))))
1536 (if (float-denormalized-p x
)
1538 (* x
1.0e16
(expt 10.0e0
(- (- ex
) 16)))
1540 (* x
1.0e18
(expt 10.0e0
(- (- ex
) 18)))
1541 (* x
10.0e0
(expt 10.0e0
(- (- ex
) 1))))
1542 (/ x
10.0e0
(expt 10.0e0
(1- ex
))))))
1543 (do ((d 10.0e0
(* d
10.0e0
))
1547 (do ((m 10.0e0
(* m
10.0e0
))
1551 (values (float z original-x
) ex
))
1552 (declare (long-float m
) (integer ex
))))
1553 (declare (long-float d
))))))))
1554 (eval-when (:compile-toplevel
:execute
)
1555 (setf *read-default-float-format
* 'single-float
))
1557 ;;;; entry point for the float printer
1559 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1560 ;;; argument is printed free-format, in either exponential or
1561 ;;; non-exponential notation, depending on its magnitude.
1563 ;;; NOTE: When a number is to be printed in exponential format, it is
1564 ;;; scaled in floating point. Since precision may be lost in this
1565 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1566 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1567 ;;; extensive computations with integers of similar magnitude to that
1568 ;;; of the number being printed. For large exponents, the bignums
1569 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1570 ;;; fast and the exponent range is not too large, then it might become
1571 ;;; attractive to handle exponential notation with the same accuracy
1572 ;;; as non-exponential notation, using the method described in the
1573 ;;; Steele and White paper.
1575 ;;; NOTE II: this has been bypassed slightly by implementing Burger
1576 ;;; and Dybvig, 1996. When someone has time (KLUDGE) they can
1577 ;;; probably (a) implement the optimizations suggested by Burger and
1578 ;;; Dyvbig, and (b) remove all vestiges of Dragon4, including from
1579 ;;; fixed-format printing.
1581 ;;; Print the appropriate exponent marker for X and the specified exponent.
1582 (defun print-float-exponent (x exp stream
)
1583 (declare (type float x
) (type integer exp
) (type stream stream
))
1584 (let ((*print-radix
* nil
))
1585 (if (typep x
*read-default-float-format
*)
1587 (format stream
"e~D" exp
))
1588 (format stream
"~C~D"
1596 (defun output-float-infinity (x stream
)
1597 (declare (float x
) (stream stream
))
1599 (write-string "#." stream
))
1601 (return-from output-float-infinity
1602 (print-not-readable-error x stream
)))
1604 (write-string "#<" stream
)))
1605 (write-string "SB-EXT:" stream
)
1606 (write-string (symbol-name (float-format-name x
)) stream
)
1607 (write-string (if (plusp x
) "-POSITIVE-" "-NEGATIVE-")
1609 (write-string "INFINITY" stream
)
1611 (write-string ">" stream
)))
1613 (defun output-float-nan (x stream
)
1614 (print-unreadable-object (x stream
)
1615 (princ (float-format-name x
) stream
)
1616 (write-string (if (float-trapping-nan-p x
) " trapping" " quiet") stream
)
1617 (write-string " NaN" stream
)))
1619 ;;; the function called by OUTPUT-OBJECT to handle floats
1620 (defun output-float (x stream
)
1622 ((float-infinity-p x
)
1623 (output-float-infinity x stream
))
1625 (output-float-nan x stream
))
1627 (let ((x (cond ((minusp (float-sign x
))
1628 (write-char #\- stream
)
1634 (write-string "0.0" stream
)
1635 (print-float-exponent x
0 stream
))
1637 (output-float-aux x stream -
3 8)))))))
1639 (defun output-float-aux (x stream e-min e-max
)
1640 (multiple-value-bind (e string
)
1641 (flonum-to-digits x
)
1646 (write-string string stream
:end
(min (length string
) e
))
1647 (dotimes (i (- e
(length string
)))
1648 (write-char #\
0 stream
))
1649 (write-char #\. stream
)
1650 (write-string string stream
:start
(min (length string
) e
))
1651 (when (<= (length string
) e
)
1652 (write-char #\
0 stream
))
1653 (print-float-exponent x
0 stream
))
1655 (write-string "0." stream
)
1657 (write-char #\
0 stream
))
1658 (write-string string stream
)
1659 (print-float-exponent x
0 stream
))))
1660 (t (write-string string stream
:end
1)
1661 (write-char #\. stream
)
1662 (write-string string stream
:start
1)
1663 (print-float-exponent x
(1- e
) stream
)))))
1665 ;;;; other leaf objects
1667 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1668 ;;; the character name or the character in the #\char format.
1669 (defun output-character (char stream
)
1670 (if (or *print-escape
* *print-readably
*)
1671 (let ((graphicp (and (graphic-char-p char
)
1672 (standard-char-p char
)))
1673 (name (char-name char
)))
1674 (write-string "#\\" stream
)
1675 (if (and name
(or (not graphicp
) *print-readably
*))
1676 (quote-string name stream
)
1677 (write-char char stream
)))
1678 (write-char char stream
)))
1680 (defun output-sap (sap stream
)
1681 (declare (type system-area-pointer sap
))
1683 (format stream
"#.(~S #X~8,'0X)" 'int-sap
(sap-int sap
)))
1685 (print-unreadable-object (sap stream
)
1686 (format stream
"system area pointer: #X~8,'0X" (sap-int sap
))))))
1688 (defun output-weak-pointer (weak-pointer stream
)
1689 (declare (type weak-pointer weak-pointer
))
1690 (print-unreadable-object (weak-pointer stream
)
1691 (multiple-value-bind (value validp
) (weak-pointer-value weak-pointer
)
1693 (write-string "weak pointer: " stream
)
1694 (write value
:stream stream
))
1696 (write-string "broken weak pointer" stream
))))))
1698 (defun output-code-component (component stream
)
1699 (print-unreadable-object (component stream
:identity t
)
1700 (let ((dinfo (%code-debug-info component
)))
1701 (cond ((eq dinfo
:bogus-lra
)
1702 (write-string "bogus code object" stream
))
1704 (write-string "code object" stream
)
1706 (write-char #\space stream
)
1707 (output-object (sb!c
::debug-info-name dinfo
) stream
)))))))
1709 (defun output-lra (lra stream
)
1710 (print-unreadable-object (lra stream
:identity t
)
1711 (write-string "return PC object" stream
)))
1713 (defun output-fdefn (fdefn stream
)
1714 (print-unreadable-object (fdefn stream
)
1715 (write-string "FDEFINITION for " stream
)
1716 ;; It's somewhat unhelpful to print as <FDEFINITION for (SETF #)>
1717 ;; Generalized function names are indivisible.
1718 (let ((name (fdefn-name fdefn
)))
1720 (output-object name stream
)
1721 ;; This needn't protect against improper lists.
1722 ;; (You'd get crashes in INTERNAL-NAME-P and other places)
1723 (format stream
"(~{~S~^ ~})" name
)))))
1726 (defun output-simd-pack (pack stream
)
1727 (declare (type simd-pack pack
))
1728 (cond ((and *print-readably
* *read-eval
*)
1730 ((simd-pack double-float
)
1731 (multiple-value-call #'format stream
1733 '%make-simd-pack-double
1734 (%simd-pack-doubles pack
)))
1735 ((simd-pack single-float
)
1736 (multiple-value-call #'format stream
1737 "#.(~S ~S ~S ~S ~S)"
1738 '%make-simd-pack-single
1739 (%simd-pack-singles pack
)))
1741 (multiple-value-call #'format stream
1742 "#.(~S #X~16,'0X #X~16,'0X)"
1743 '%make-simd-pack-ub64
1744 (%simd-pack-ub64s pack
)))))
1746 (print-unreadable-object (pack stream
)
1747 (flet ((all-ones-p (value start end
&aux
(mask (- (ash 1 end
) (ash 1 start
))))
1748 (= (logand value mask
) mask
))
1749 (split-num (value start
)
1752 and v
= (ash value
(- start
)) then
(ash v -
8)
1753 collect
(logand v
#xFF
))))
1754 (multiple-value-bind (low high
)
1755 (%simd-pack-ub64s pack
)
1757 ((simd-pack double-float
)
1758 (multiple-value-bind (v0 v1
) (%simd-pack-doubles pack
)
1759 (format stream
"~S~@{ ~:[~,13E~;~*TRUE~]~}"
1761 (all-ones-p low
0 64) v0
1762 (all-ones-p high
0 64) v1
)))
1763 ((simd-pack single-float
)
1764 (multiple-value-bind (v0 v1 v2 v3
) (%simd-pack-singles pack
)
1765 (format stream
"~S~@{ ~:[~,7E~;~*TRUE~]~}"
1767 (all-ones-p low
0 32) v0
1768 (all-ones-p low
32 64) v1
1769 (all-ones-p high
0 32) v2
1770 (all-ones-p high
32 64) v3
)))
1772 (format stream
"~S~@{ ~{ ~2,'0X~}~}"
1774 (split-num low
0) (split-num low
32)
1775 (split-num high
0) (split-num high
32))))))))))
1779 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1780 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1782 ;;; The definition here is a simple temporary placeholder. It will be
1783 ;;; overwritten by a smarter version (capable of calling generic
1784 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1785 (defun printed-as-funcallable-standard-class (object stream
)
1786 (declare (ignore object stream
))
1789 (defun output-fun (object stream
)
1790 (let* ((name (%fun-name object
))
1791 (proper-name-p (and (legal-fun-name-p name
) (fboundp name
)
1792 (eq (fdefinition name
) object
))))
1793 (print-unreadable-object (object stream
:identity
(not proper-name-p
))
1794 (format stream
"~:[FUNCTION~;CLOSURE~]~@[ ~S~]"
1798 ;;;; catch-all for unknown things
1800 (defun output-random (object stream
)
1801 (print-unreadable-object (object stream
:identity t
)
1802 (let ((lowtag (lowtag-of object
)))
1804 (#.sb
!vm
:other-pointer-lowtag
1805 (let ((widetag (widetag-of object
)))
1807 (#.sb
!vm
:value-cell-header-widetag
1808 (write-string "value cell " stream
)
1809 (output-object (value-cell-ref object
) stream
))
1811 (write-string "unknown pointer object, widetag=" stream
)
1812 (let ((*print-base
* 16) (*print-radix
* t
))
1813 (output-integer widetag stream
))))))
1814 ((#.sb
!vm
:fun-pointer-lowtag
1815 #.sb
!vm
:instance-pointer-lowtag
1816 #.sb
!vm
:list-pointer-lowtag
)
1817 (write-string "unknown pointer object, lowtag=" stream
)
1818 (let ((*print-base
* 16) (*print-radix
* t
))
1819 (output-integer lowtag stream
)))
1821 (case (widetag-of object
)
1822 (#.sb
!vm
:unbound-marker-widetag
1823 (write-string "unbound marker" stream
))
1825 (write-string "unknown immediate object, lowtag=" stream
)
1826 (let ((*print-base
* 2) (*print-radix
* t
))
1827 (output-integer lowtag stream
))
1828 (write-string ", widetag=" stream
)
1829 (let ((*print-base
* 16) (*print-radix
* t
))
1830 (output-integer (widetag-of object
) stream
)))))))))