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 (defun %with-standard-io-syntax (function)
109 (declare (type function function))
110 (let ((*package* (find-package "COMMON-LISP-USER"))
113 (*print-case* :upcase)
120 (*print-miser-width* nil)
121 (*print-pprint-dispatch* sb!pretty::*standard-pprint-dispatch-table*)
125 (*print-right-margin* nil)
127 (*read-default-float-format* 'single-float)
129 (*read-suppress* nil)
130 (*readtable* *standard-readtable*)
131 (*suppress-print-errors* nil))
134 ;;;; routines to print objects
137 ;;; keyword variables shared by WRITE and WRITE-TO-STRING, and
138 ;;; the bindings they map to.
139 (eval-when (:compile-toplevel :load-toplevel)
140 (defvar *printer-keyword-variables*
141 '(:escape *print-escape*
144 :circle *print-circle*
145 :pretty *print-pretty*
147 :length *print-length*
150 :gensym *print-gensym*
151 :readably *print-readably*
152 :right-margin *print-right-margin*
153 :miser-width *print-miser-width*
155 :pprint-dispatch *print-pprint-dispatch*
156 :suppress-errors *suppress-print-errors*)))
158 (defun write (object &key
159 ((:stream stream) *standard-output*)
160 ((:escape *print-escape*) *print-escape*)
161 ((:radix *print-radix*) *print-radix*)
162 ((:base *print-base*) *print-base*)
163 ((:circle *print-circle*) *print-circle*)
164 ((:pretty *print-pretty*) *print-pretty*)
165 ((:level *print-level*) *print-level*)
166 ((:length *print-length*) *print-length*)
167 ((:case *print-case*) *print-case*)
168 ((:array *print-array*) *print-array*)
169 ((:gensym *print-gensym*) *print-gensym*)
170 ((:readably *print-readably*) *print-readably*)
171 ((:right-margin *print-right-margin*)
172 *print-right-margin*)
173 ((:miser-width *print-miser-width*)
175 ((:lines *print-lines*) *print-lines*)
176 ((:pprint-dispatch *print-pprint-dispatch*)
177 *print-pprint-dispatch*)
178 ((:suppress-errors *suppress-print-errors*)
179 *suppress-print-errors*))
181 "Output OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*."
182 (output-object object (out-synonym-of stream))
185 ;;; Optimize common case of constant keyword arguments
186 (define-compiler-macro write (&whole form object &rest keys)
190 ;; Odd number of keys, punt
192 (return-from write form)))
193 (let* ((key (pop keys))
195 (variable (or (getf *printer-keyword-variables* key)
196 (when (eq :stream key)
198 (return-from write form))))
199 (when (assoc variable bind)
200 ;; First key has precedence, but we still need to execute the
201 ;; argument, and in the right order.
202 (setf variable (gensym "IGNORE"))
203 (push variable ignore))
204 (push (list variable value) bind)))
205 (unless (assoc 'stream bind)
206 (push (list 'stream '*standard-output*) bind))
207 (once-only ((object object))
208 `(let ,(nreverse bind)
209 ,@(when ignore `((declare (ignore ,@ignore))))
210 (output-object ,object (out-synonym-of stream))
213 (defun prin1 (object &optional stream)
215 "Output a mostly READable printed representation of OBJECT on the specified
217 (let ((*print-escape* t))
218 (output-object object (out-synonym-of stream)))
221 (defun princ (object &optional stream)
223 "Output an aesthetic but not necessarily READable printed representation
224 of OBJECT on the specified STREAM."
225 (let ((*print-escape* nil)
226 (*print-readably* nil))
227 (output-object object (out-synonym-of stream)))
230 (defun print (object &optional stream)
232 "Output a newline, the mostly READable printed representation of OBJECT, and
233 space to the specified STREAM."
234 (let ((stream (out-synonym-of stream)))
236 (prin1 object stream)
237 (write-char #\space stream)
240 (defun pprint (object &optional stream)
242 "Prettily output OBJECT preceded by a newline."
243 (let ((*print-pretty* t)
245 (stream (out-synonym-of stream)))
247 (output-object object stream))
250 (defun write-to-string
252 ((:escape *print-escape*) *print-escape*)
253 ((:radix *print-radix*) *print-radix*)
254 ((:base *print-base*) *print-base*)
255 ((:circle *print-circle*) *print-circle*)
256 ((:pretty *print-pretty*) *print-pretty*)
257 ((:level *print-level*) *print-level*)
258 ((:length *print-length*) *print-length*)
259 ((:case *print-case*) *print-case*)
260 ((:array *print-array*) *print-array*)
261 ((:gensym *print-gensym*) *print-gensym*)
262 ((:readably *print-readably*) *print-readably*)
263 ((:right-margin *print-right-margin*) *print-right-margin*)
264 ((:miser-width *print-miser-width*) *print-miser-width*)
265 ((:lines *print-lines*) *print-lines*)
266 ((:pprint-dispatch *print-pprint-dispatch*)
267 *print-pprint-dispatch*)
268 ((:suppress-errors *suppress-print-errors*)
269 *suppress-print-errors*))
271 "Return the printed representation of OBJECT as a string."
272 (stringify-object object))
274 ;;; Optimize common case of constant keyword arguments
275 (define-compiler-macro write-to-string (&whole form object &rest keys)
279 ;; Odd number of keys, punt
281 (return-from write-to-string form)))
282 (let* ((key (pop keys))
284 (variable (or (getf *printer-keyword-variables* key)
285 (return-from write-to-string form))))
286 (when (assoc variable bind)
287 ;; First key has precedence, but we still need to execute the
288 ;; argument, and in the right order.
289 (setf variable (gensym "IGNORE"))
290 (push variable ignore))
291 (push (list variable value) bind)))
293 (once-only ((object object))
294 `(let ,(nreverse bind)
295 ,@(when ignore `((declare (ignore ,@ignore))))
296 (stringify-object ,object)))
297 `(stringify-object ,object))))
299 (defun prin1-to-string (object)
301 "Return the printed representation of OBJECT as a string with
303 (let ((*print-escape* t))
304 (stringify-object object)))
306 (defun princ-to-string (object)
308 "Return the printed representation of OBJECT as a string with
310 (let ((*print-escape* nil)
311 (*print-readably* nil))
312 (stringify-object object)))
314 ;;; This produces the printed representation of an object as a string.
315 ;;; The few ...-TO-STRING functions above call this.
316 (defun stringify-object (object)
317 (let ((stream (make-string-output-stream)))
318 (setup-printer-state)
319 (output-object object stream)
320 (get-output-stream-string stream)))
322 ;;;; support for the PRINT-UNREADABLE-OBJECT macro
324 (defun print-not-readable-error (object stream)
326 (error 'print-not-readable :object object)
328 :report "Print unreadably."
329 (let ((*print-readably* nil))
330 (output-object object stream)
333 :report "Supply an object to be printed instead."
336 (read-evaluated-form "~@<Enter an object (evaluated): ~@:>"))
337 (output-object o stream)
340 ;;; guts of PRINT-UNREADABLE-OBJECT
341 (defun %print-unreadable-object (object stream type identity body)
342 (declare (type (or null function) body))
344 (print-not-readable-error object stream)
345 (flet ((print-description ()
347 (write (type-of object) :stream stream :circle nil
348 :level nil :length nil)
349 (write-char #\space stream)
350 (pprint-newline :fill stream))
354 (when (or body (not type))
355 (write-char #\space stream))
356 (pprint-newline :fill stream)
357 (write-char #\{ stream)
358 (write (get-lisp-obj-address object) :stream stream
360 (write-char #\} stream))))
361 (cond ((print-pretty-on-stream-p stream)
362 ;; Since we're printing prettily on STREAM, format the
363 ;; object within a logical block. PPRINT-LOGICAL-BLOCK does
364 ;; not rebind the stream when it is already a pretty stream,
365 ;; so output from the body will go to the same stream.
366 (pprint-logical-block (stream nil :prefix "#<" :suffix ">")
367 (print-description)))
369 (write-string "#<" stream)
371 (write-char #\> stream)))))
374 ;;;; OUTPUT-OBJECT -- the main entry point
376 ;;; Objects whose print representation identifies them EQLly don't
377 ;;; need to be checked for circularity.
378 (defun uniquely-identified-by-print-p (x)
382 (symbol-package x))))
384 (defvar *in-print-error* nil)
386 ;;; Output OBJECT to STREAM observing all printer control variables.
387 (defun output-object (object stream)
388 (labels ((print-it (stream)
390 (sb!pretty:output-pretty-object object stream)
391 (output-ugly-object object stream)))
393 (if *suppress-print-errors*
394 (handler-bind ((condition
395 (lambda (condition) nil
396 (when (typep condition *suppress-print-errors*)
397 (cond (*in-print-error*
398 (write-string "(error printing " stream)
399 (write-string *in-print-error* stream)
400 (write-string ")" stream))
402 ;; Give outer handlers a chance.
404 (continue "Suppress the error.")
406 (let ((*print-readably* nil)
409 "#<error printing a " stream)
410 (let ((*in-print-error* "type"))
411 (output-object (type-of object) stream))
412 (write-string ": " stream)
413 (let ((*in-print-error* "condition"))
414 (output-object condition stream))
415 (write-string ">" stream))))
416 (return-from handle-it object)))))
420 (multiple-value-bind (marker initiate)
421 (check-for-circularity object t)
422 (if (eq initiate :initiate)
423 (let ((*circularity-hash-table*
424 (make-hash-table :test 'eq)))
425 (check-it (make-broadcast-stream))
426 (let ((*circularity-counter* 0))
430 (when (handle-circularity marker stream)
432 (handle-it stream))))))
433 (cond (;; Maybe we don't need to bother with circularity detection.
434 (or (not *print-circle*)
435 (uniquely-identified-by-print-p object))
437 (;; If we have already started circularity detection, this
438 ;; object might be a shared reference. If we have not, then
439 ;; if it is a compound object it might contain a circular
440 ;; reference to itself or multiple shared references.
441 (or *circularity-hash-table*
442 (compound-object-p object))
445 (handle-it stream)))))
447 ;;; a hack to work around recurring gotchas with printing while
448 ;;; DEFGENERIC PRINT-OBJECT is being built
450 ;;; (hopefully will go away naturally when CLOS moves into cold init)
451 (defvar *print-object-is-disabled-p*)
453 ;;; Output OBJECT to STREAM observing all printer control variables
454 ;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
455 ;;; then the pretty printer will be used for any components of OBJECT,
456 ;;; just not for OBJECT itself.
457 (defun output-ugly-object (object stream)
459 ;; KLUDGE: The TYPECASE approach here is non-ANSI; the ANSI definition of
460 ;; PRINT-OBJECT says it provides printing and we're supposed to provide
461 ;; PRINT-OBJECT methods covering all classes. We deviate from this
462 ;; by using PRINT-OBJECT only when we print instance values. However,
463 ;; ANSI makes it hard to tell that we're deviating from this:
464 ;; (1) ANSI specifies that the user isn't supposed to call PRINT-OBJECT
466 ;; (2) ANSI (section 11.1.2.1.2) says it's undefined to define
467 ;; a method on an external symbol in the CL package which is
468 ;; applicable to arg lists containing only direct instances of
469 ;; standardized classes.
470 ;; Thus, in order for the user to detect our sleaziness in conforming
471 ;; code, he has to do something relatively obscure like
472 ;; (1) actually use tools like FIND-METHOD to look for PRINT-OBJECT
474 ;; (2) define a PRINT-OBJECT method which is specialized on the stream
475 ;; value (e.g. a Gray stream object).
476 ;; As long as no one comes up with a non-obscure way of detecting this
477 ;; sleaziness, fixing this nonconformity will probably have a low
478 ;; priority. -- WHN 2001-11-25
481 (output-symbol object stream)
482 (output-list object stream)))
484 (cond ((not (and (boundp '*print-object-is-disabled-p*)
485 *print-object-is-disabled-p*))
486 (print-object object stream))
487 ((typep object 'structure-object)
488 (default-structure-print object stream *current-level-in-print*))
490 (write-string "#<INSTANCE but not STRUCTURE-OBJECT>" stream))))
491 (funcallable-instance
493 ((not (and (boundp '*print-object-is-disabled-p*)
494 *print-object-is-disabled-p*))
495 (print-object object stream))
496 (t (output-fun object stream))))
498 (output-fun object stream))
500 (output-symbol object stream))
504 (output-integer object stream))
506 (output-float object stream))
508 (output-ratio object stream))
510 (output-complex object stream))))
512 (output-character object stream))
514 (output-vector object stream))
516 (output-array object stream))
518 (output-sap object stream))
520 (output-weak-pointer object stream))
522 (output-lra object stream))
524 (output-code-component object stream))
526 (output-fdefn object stream))
529 (output-simd-pack object stream))
531 (output-random object stream))))
535 ;;; values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last
536 ;;; time the printer was called
537 (defvar *previous-case* nil)
538 (defvar *previous-readtable-case* nil)
540 ;;; This variable contains the current definition of one of three
541 ;;; symbol printers. SETUP-PRINTER-STATE sets this variable.
542 (defvar *internal-symbol-output-fun* nil)
544 ;;; This function sets the internal global symbol
545 ;;; *INTERNAL-SYMBOL-OUTPUT-FUN* to the right function depending on
546 ;;; the value of *PRINT-CASE*. See the manual for details. The print
547 ;;; buffer stream is also reset.
548 (defun setup-printer-state ()
549 (unless (and (eq *print-case* *previous-case*)
550 (eq (readtable-case *readtable*) *previous-readtable-case*))
551 (setq *previous-case* *print-case*)
552 (setq *previous-readtable-case* (readtable-case *readtable*))
553 (unless (member *print-case* '(:upcase :downcase :capitalize))
554 (setq *print-case* :upcase)
555 (error "invalid *PRINT-CASE* value: ~S" *previous-case*))
556 (unless (member *previous-readtable-case*
557 '(:upcase :downcase :invert :preserve))
558 (setf (readtable-case *readtable*) :upcase)
559 (error "invalid READTABLE-CASE value: ~S" *previous-readtable-case*))
561 (setq *internal-symbol-output-fun*
562 (case *previous-readtable-case*
565 (:upcase #'output-preserve-symbol)
566 (:downcase #'output-lowercase-symbol)
567 (:capitalize #'output-capitalize-symbol)))
570 (:upcase #'output-uppercase-symbol)
571 (:downcase #'output-preserve-symbol)
572 (:capitalize #'output-capitalize-symbol)))
573 (:preserve #'output-preserve-symbol)
574 (:invert #'output-invert-symbol)))))
576 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
577 ;;; and with any embedded |'s or \'s escaped.
578 (defun output-quoted-symbol-name (pname stream)
579 (write-char #\| stream)
580 (dotimes (index (length pname))
581 (let ((char (schar pname index)))
582 (when (or (char= char #\\) (char= char #\|))
583 (write-char #\\ stream))
584 (write-char char stream)))
585 (write-char #\| stream))
587 (defun output-symbol (object stream)
588 (if (or *print-escape* *print-readably*)
589 (let ((package (symbol-package object))
590 (name (symbol-name object))
591 (current (sane-package)))
593 ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
594 ;; requires that keywords be printed with preceding colons
595 ;; always, regardless of the value of *PACKAGE*.
596 ((eq package *keyword-package*)
597 (write-char #\: stream))
598 ;; Otherwise, if the symbol's home package is the current
599 ;; one, then a prefix is never necessary.
600 ((eq package current))
601 ;; Uninterned symbols print with a leading #:.
603 (when (or *print-gensym* *print-readably*)
604 (write-string "#:" stream)))
606 (multiple-value-bind (symbol accessible)
607 (find-symbol name current)
608 ;; If we can find the symbol by looking it up, it need not
609 ;; be qualified. This can happen if the symbol has been
610 ;; inherited from a package other than its home package.
612 ;; To preserve print-read consistency, use the local nickname if
614 (unless (and accessible (eq symbol object))
615 (let ((prefix (or (car (rassoc package (package-%local-nicknames current)))
616 (package-name package))))
617 (output-symbol-name prefix stream))
618 (multiple-value-bind (symbol externalp)
619 (find-external-symbol name package)
620 (declare (ignore symbol))
622 (write-char #\: stream)
623 (write-string "::" stream)))))))
624 (output-symbol-name name stream))
625 (output-symbol-name (symbol-name object) stream nil)))
627 ;;; Output the string NAME as if it were a symbol name. In other
628 ;;; words, diddle its case according to *PRINT-CASE* and
630 (defun output-symbol-name (name stream &optional (maybe-quote t))
631 (declare (type simple-string name))
632 (let ((*readtable* (if *print-readably* *standard-readtable* *readtable*)))
633 (setup-printer-state)
634 (if (and maybe-quote (symbol-quotep name))
635 (output-quoted-symbol-name name stream)
636 (funcall *internal-symbol-output-fun* name stream))))
638 ;;;; escaping symbols
640 ;;; When we print symbols we have to figure out if they need to be
641 ;;; printed with escape characters. This isn't a whole lot easier than
642 ;;; reading symbols in the first place.
644 ;;; For each character, the value of the corresponding element is a
645 ;;; fixnum with bits set corresponding to attributes that the
646 ;;; character has. At characters have at least one bit set, so we can
647 ;;; search for any character with a positive test.
648 (defvar *character-attributes*
649 (make-array 160 ; FIXME
650 :element-type '(unsigned-byte 16)
652 (declaim (type (simple-array (unsigned-byte 16) (#.160)) ; FIXME
653 *character-attributes*))
655 ;;; constants which are a bit-mask for each interesting character attribute
656 (defconstant other-attribute (ash 1 0)) ; Anything else legal.
657 (defconstant number-attribute (ash 1 1)) ; A numeric digit.
658 (defconstant uppercase-attribute (ash 1 2)) ; An uppercase letter.
659 (defconstant lowercase-attribute (ash 1 3)) ; A lowercase letter.
660 (defconstant sign-attribute (ash 1 4)) ; +-
661 (defconstant extension-attribute (ash 1 5)) ; ^_
662 (defconstant dot-attribute (ash 1 6)) ; .
663 (defconstant slash-attribute (ash 1 7)) ; /
664 (defconstant funny-attribute (ash 1 8)) ; Anything illegal.
666 (eval-when (:compile-toplevel :load-toplevel :execute)
668 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
669 ;;; that don't need to be escaped (according to READTABLE-CASE.)
670 (defparameter *attribute-names*
671 `((number . number-attribute) (lowercase . lowercase-attribute)
672 (uppercase . uppercase-attribute) (letter . letter-attribute)
673 (sign . sign-attribute) (extension . extension-attribute)
674 (dot . dot-attribute) (slash . slash-attribute)
675 (other . other-attribute) (funny . funny-attribute)))
679 (flet ((set-bit (char bit)
680 (let ((code (char-code char)))
681 (setf (aref *character-attributes* code)
682 (logior bit (aref *character-attributes* code))))))
684 (dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
686 (set-bit char other-attribute))
689 (set-bit (digit-char i) number-attribute))
691 (do ((code (char-code #\A) (1+ code))
692 (end (char-code #\Z)))
694 (declare (fixnum code end))
695 (set-bit (code-char code) uppercase-attribute)
696 (set-bit (char-downcase (code-char code)) lowercase-attribute))
698 (set-bit #\- sign-attribute)
699 (set-bit #\+ sign-attribute)
700 (set-bit #\^ extension-attribute)
701 (set-bit #\_ extension-attribute)
702 (set-bit #\. dot-attribute)
703 (set-bit #\/ slash-attribute)
705 ;; Mark anything not explicitly allowed as funny.
706 (dotimes (i 160) ; FIXME
707 (when (zerop (aref *character-attributes* i))
708 (setf (aref *character-attributes* i) funny-attribute))))
710 ;;; For each character, the value of the corresponding element is the
711 ;;; lowest base in which that character is a digit.
712 (defvar *digit-bases*
713 (make-array 128 ; FIXME
714 :element-type '(unsigned-byte 8)
715 :initial-element 36))
716 (declaim (type (simple-array (unsigned-byte 8) (#.128)) ; FIXME
719 (let ((char (digit-char i 36)))
720 (setf (aref *digit-bases* (char-code char)) i)))
722 ;;; A FSM-like thingie that determines whether a symbol is a potential
723 ;;; number or has evil characters in it.
724 (defun symbol-quotep (name)
725 (declare (simple-string name))
726 (macrolet ((advance (tag &optional (at-end t))
729 ,(if at-end '(go TEST-SIGN) '(return nil)))
730 (setq current (schar name index)
731 code (char-code current)
733 ((< code 160) (aref attributes code))
734 ((upper-case-p current) uppercase-attribute)
735 ((lower-case-p current) lowercase-attribute)
736 (t other-attribute)))
739 (test (&rest attributes)
751 `(and (< code 128) ; FIXME
752 (< (the fixnum (aref bases code)) base))))
754 (prog ((len (length name))
755 (attributes *character-attributes*)
756 (bases *digit-bases*)
759 (case (readtable-case *readtable*)
760 (:upcase uppercase-attribute)
761 (:downcase lowercase-attribute)
762 (t (logior lowercase-attribute uppercase-attribute))))
767 (declare (fixnum len base index bits code))
770 TEST-SIGN ; At end, see whether it is a sign...
771 (return (not (test sign)))
773 OTHER ; not potential number, see whether funny chars...
774 (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
777 (do ((i (1- index) (1+ i)))
778 ((= i len) (return-from symbol-quotep nil))
779 (unless (zerop (logand (let* ((char (schar name i))
780 (code (char-code char)))
782 ((< code 160) (aref attributes code))
783 ((upper-case-p char) uppercase-attribute)
784 ((lower-case-p char) lowercase-attribute)
785 (t other-attribute)))
787 (return-from symbol-quotep t))))
792 (advance LAST-DIGIT-ALPHA)
794 (when (test letter number other slash) (advance OTHER nil))
795 (when (char= current #\.) (advance DOT-FOUND))
796 (when (test sign extension) (advance START-STUFF nil))
799 DOT-FOUND ; leading dots...
800 (when (test letter) (advance START-DOT-MARKER nil))
801 (when (digitp) (advance DOT-DIGIT))
802 (when (test number other) (advance OTHER nil))
803 (when (test extension slash sign) (advance START-DOT-STUFF nil))
804 (when (char= current #\.) (advance DOT-FOUND))
807 START-STUFF ; leading stuff before any dot or digit
810 (advance LAST-DIGIT-ALPHA)
812 (when (test number other) (advance OTHER nil))
813 (when (test letter) (advance START-MARKER nil))
814 (when (char= current #\.) (advance START-DOT-STUFF nil))
815 (when (test sign extension slash) (advance START-STUFF nil))
818 START-MARKER ; number marker in leading stuff...
819 (when (test letter) (advance OTHER nil))
822 START-DOT-STUFF ; leading stuff containing dot without digit...
823 (when (test letter) (advance START-DOT-STUFF nil))
824 (when (digitp) (advance DOT-DIGIT))
825 (when (test sign extension dot slash) (advance START-DOT-STUFF nil))
826 (when (test number other) (advance OTHER nil))
829 START-DOT-MARKER ; number marker in leading stuff with dot..
830 ;; leading stuff containing dot without digit followed by letter...
831 (when (test letter) (advance OTHER nil))
834 DOT-DIGIT ; in a thing with dots...
835 (when (test letter) (advance DOT-MARKER))
836 (when (digitp) (advance DOT-DIGIT))
837 (when (test number other) (advance OTHER nil))
838 (when (test sign extension dot slash) (advance DOT-DIGIT))
841 DOT-MARKER ; number marker in number with dot...
842 (when (test letter) (advance OTHER nil))
845 LAST-DIGIT-ALPHA ; previous char is a letter digit...
846 (when (or (digitp) (test sign slash))
847 (advance ALPHA-DIGIT))
848 (when (test letter number other dot) (advance OTHER nil))
851 ALPHA-DIGIT ; seen a digit which is a letter...
852 (when (or (digitp) (test sign slash))
854 (advance LAST-DIGIT-ALPHA)
855 (advance ALPHA-DIGIT)))
856 (when (test letter) (advance ALPHA-MARKER))
857 (when (test number other dot) (advance OTHER nil))
860 ALPHA-MARKER ; number marker in number with alpha digit...
861 (when (test letter) (advance OTHER nil))
864 DIGIT ; seen only ordinary (non-alphabetic) numeric digits...
867 (advance ALPHA-DIGIT)
869 (when (test number other) (advance OTHER nil))
870 (when (test letter) (advance MARKER))
871 (when (test extension slash sign) (advance DIGIT))
872 (when (char= current #\.) (advance DOT-DIGIT))
875 MARKER ; number marker in a numeric number...
876 ;; ("What," you may ask, "is a 'number marker'?" It's something
877 ;; that a conforming implementation might use in number syntax.
878 ;; See ANSI 2.3.1.1 "Potential Numbers as Tokens".)
879 (when (test letter) (advance OTHER nil))
882 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN*
884 ;;;; case hackery: These functions are stored in
885 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN* according to the values of
886 ;;;; *PRINT-CASE* and READTABLE-CASE.
889 ;;; READTABLE-CASE *PRINT-CASE*
891 ;;; :DOWNCASE :DOWNCASE
893 (defun output-preserve-symbol (pname stream)
894 (declare (simple-string pname))
895 (write-string pname stream))
898 ;;; READTABLE-CASE *PRINT-CASE*
899 ;;; :UPCASE :DOWNCASE
900 (defun output-lowercase-symbol (pname stream)
901 (declare (simple-string pname))
902 (dotimes (index (length pname))
903 (let ((char (schar pname index)))
904 (write-char (char-downcase char) stream))))
907 ;;; READTABLE-CASE *PRINT-CASE*
908 ;;; :DOWNCASE :UPCASE
909 (defun output-uppercase-symbol (pname stream)
910 (declare (simple-string pname))
911 (dotimes (index (length pname))
912 (let ((char (schar pname index)))
913 (write-char (char-upcase char) stream))))
916 ;;; READTABLE-CASE *PRINT-CASE*
917 ;;; :UPCASE :CAPITALIZE
918 ;;; :DOWNCASE :CAPITALIZE
919 (defun output-capitalize-symbol (pname stream)
920 (declare (simple-string pname))
921 (let ((prev-not-alphanum t)
922 (up (eq (readtable-case *readtable*) :upcase)))
923 (dotimes (i (length pname))
924 (let ((char (char pname i)))
926 (if (or prev-not-alphanum (lower-case-p char))
928 (char-downcase char))
929 (if prev-not-alphanum
933 (setq prev-not-alphanum (not (alphanumericp char)))))))
936 ;;; READTABLE-CASE *PRINT-CASE*
938 (defun output-invert-symbol (pname stream)
939 (declare (simple-string pname))
942 (dotimes (i (length pname))
943 (let ((ch (schar pname i)))
944 (when (both-case-p ch)
945 (if (upper-case-p ch)
947 (setq all-upper nil)))))
948 (cond (all-upper (output-lowercase-symbol pname stream))
949 (all-lower (output-uppercase-symbol pname stream))
951 (write-string pname stream)))))
955 (let ((*readtable* (copy-readtable nil)))
956 (format t "READTABLE-CASE Input Symbol-name~@
957 ----------------------------------~%")
958 (dolist (readtable-case '(:upcase :downcase :preserve :invert))
959 (setf (readtable-case *readtable*) readtable-case)
960 (dolist (input '("ZEBRA" "Zebra" "zebra"))
961 (format t "~&:~A~16T~A~24T~A"
962 (string-upcase readtable-case)
964 (symbol-name (read-from-string input)))))))
967 (let ((*readtable* (copy-readtable nil)))
968 (format t "READTABLE-CASE *PRINT-CASE* Symbol-name Output Princ~@
969 --------------------------------------------------------~%")
970 (dolist (readtable-case '(:upcase :downcase :preserve :invert))
971 (setf (readtable-case *readtable*) readtable-case)
972 (dolist (*print-case* '(:upcase :downcase :capitalize))
973 (dolist (symbol '(|ZEBRA| |Zebra| |zebra|))
974 (format t "~&:~A~15T:~A~29T~A~42T~A~50T~A"
975 (string-upcase readtable-case)
976 (string-upcase *print-case*)
978 (prin1-to-string symbol)
979 (princ-to-string symbol)))))))
982 ;;;; recursive objects
984 (defun output-list (list stream)
985 (descend-into (stream)
986 (write-char #\( stream)
990 (punt-print-if-too-long length stream)
991 (output-object (pop list) stream)
994 (when (or (atom list)
995 (check-for-circularity list))
996 (write-string " . " stream)
997 (output-object list stream)
999 (write-char #\space stream)
1001 (write-char #\) stream)))
1003 (defun output-unreadable-vector-readably (vector stream)
1004 (declare (vector vector))
1005 (write-string "#." stream)
1006 (write `(coerce ,(coerce vector '(vector t))
1007 '(simple-array ,(array-element-type vector) (*)))
1010 (defun output-vector (vector stream)
1011 (declare (vector vector))
1012 (cond ((stringp vector)
1013 (cond ((and *print-readably*
1014 (not (eq (array-element-type vector)
1017 (make-array 0 :element-type 'character))))))
1018 (print-not-readable-error vector stream))
1019 ((or *print-escape* *print-readably*)
1020 (write-char #\" stream)
1021 (quote-string vector stream)
1022 (write-char #\" stream))
1024 (write-string vector stream))))
1025 ((not (or *print-array* *print-readably*))
1026 (output-terse-array vector stream))
1027 ((bit-vector-p vector)
1028 (write-string "#*" stream)
1029 (dovector (bit vector)
1030 ;; (Don't use OUTPUT-OBJECT here, since this code
1031 ;; has to work for all possible *PRINT-BASE* values.)
1032 (write-char (if (zerop bit) #\0 #\1) stream)))
1033 ((or (not *print-readably*)
1034 (array-readably-printable-p vector))
1035 (descend-into (stream)
1036 (write-string "#(" stream)
1037 (dotimes (i (length vector))
1039 (write-char #\space stream))
1040 (punt-print-if-too-long i stream)
1041 (output-object (aref vector i) stream))
1042 (write-string ")" stream)))
1044 (output-unreadable-vector-readably vector stream))
1046 (print-not-readable-error vector stream))))
1048 ;;; This function outputs a string quoting characters sufficiently
1049 ;;; so that someone can read it in again. Basically, put a slash in
1050 ;;; front of an character satisfying NEEDS-SLASH-P.
1051 (defun quote-string (string stream)
1052 (macrolet ((needs-slash-p (char)
1053 ;; KLUDGE: We probably should look at the readtable, but just do
1054 ;; this for now. [noted by anonymous long ago] -- WHN 19991130
1055 `(or (char= ,char #\\)
1056 (char= ,char #\"))))
1057 (with-array-data ((data string) (start) (end)
1058 :check-fill-pointer t)
1059 (do ((index start (1+ index)))
1061 (let ((char (schar data index)))
1062 (when (needs-slash-p char) (write-char #\\ stream))
1063 (write-char char stream))))))
1065 (defun array-readably-printable-p (array)
1066 (and (eq (array-element-type array) t)
1067 (let ((zero (position 0 (array-dimensions array)))
1068 (number (position 0 (array-dimensions array)
1069 :test (complement #'eql)
1071 (or (null zero) (null number) (> zero number)))))
1073 ;;; Output the printed representation of any array in either the #< or #A
1075 (defun output-array (array stream)
1076 (if (or *print-array* *print-readably*)
1077 (output-array-guts array stream)
1078 (output-terse-array array stream)))
1080 ;;; Output the abbreviated #< form of an array.
1081 (defun output-terse-array (array stream)
1082 (let ((*print-level* nil)
1083 (*print-length* nil))
1084 (print-unreadable-object (array stream :type t :identity t))))
1086 ;;; Convert an array into a list that can be used with MAKE-ARRAY's
1087 ;;; :INITIAL-CONTENTS keyword argument.
1088 (defun listify-array (array)
1089 (with-array-data ((data array) (start) (end))
1090 (declare (ignore end))
1091 (labels ((listify (dimensions index)
1092 (if (null dimensions)
1094 (let* ((dimension (car dimensions))
1095 (dimensions (cdr dimensions))
1096 (count (reduce #'* dimensions)))
1097 (loop for i below dimension
1098 collect (listify dimensions index)
1099 do (incf index count))))))
1100 (listify (array-dimensions array) start))))
1102 (defun output-unreadable-array-readably (array stream)
1103 (write-string "#." stream)
1104 (write `(make-array ',(array-dimensions array)
1105 :element-type ',(array-element-type array)
1106 :initial-contents ',(listify-array array))
1109 ;;; Output the readable #A form of an array.
1110 (defun output-array-guts (array stream)
1111 (cond ((or (not *print-readably*)
1112 (array-readably-printable-p array))
1113 (write-char #\# stream)
1114 (let ((*print-base* 10)
1115 (*print-radix* nil))
1116 (output-integer (array-rank array) stream))
1117 (write-char #\A stream)
1118 (with-array-data ((data array) (start) (end))
1119 (declare (ignore end))
1120 (sub-output-array-guts data (array-dimensions array) stream start)))
1122 (output-unreadable-array-readably array stream))
1124 (print-not-readable-error array stream))))
1126 (defun sub-output-array-guts (array dimensions stream index)
1127 (declare (type (simple-array * (*)) array) (fixnum index))
1128 (cond ((null dimensions)
1129 (output-object (aref array index) stream))
1131 (descend-into (stream)
1132 (write-char #\( stream)
1133 (let* ((dimension (car dimensions))
1134 (dimensions (cdr dimensions))
1135 (count (reduce #'* dimensions)))
1136 (dotimes (i dimension)
1138 (write-char #\space stream))
1139 (punt-print-if-too-long i stream)
1140 (sub-output-array-guts array dimensions stream index)
1141 (incf index count)))
1142 (write-char #\) stream)))))
1144 ;;; a trivial non-generic-function placeholder for PRINT-OBJECT, for
1145 ;;; use until CLOS is set up (at which time it will be replaced with
1146 ;;; the real generic function implementation)
1147 (defun print-object (instance stream)
1148 (default-structure-print instance stream *current-level-in-print*))
1150 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
1152 (defun %output-radix (base stream)
1153 (write-char #\# stream)
1154 (write-char (case base
1158 (t (%output-reasonable-integer-in-base base 10 stream)
1162 (defun %output-reasonable-integer-in-base (n base stream)
1163 (multiple-value-bind (q r)
1165 ;; Recurse until you have all the digits pushed on
1168 (%output-reasonable-integer-in-base q base stream))
1169 ;; Then as each recursive call unwinds, turn the
1170 ;; digit (in remainder) into a character and output
1173 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r)
1176 ;;; *POWER-CACHE* is an alist mapping bases to power-vectors. It is
1177 ;;; filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
1178 ;;; always prior a GC to drop overly large bignums from the cache.
1180 ;;; It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
1181 ;;; POWERS-FOR-BASE, see that you don't break the assumptions!
1182 (defvar *power-cache* nil)
1184 (defconstant +power-cache-integer-length-limit+ 2048)
1186 (defun scrub-power-cache ()
1187 (let ((cache *power-cache*))
1188 (dolist (cell cache)
1189 (let ((powers (cdr cell)))
1190 (declare (simple-vector powers))
1191 (let ((too-big (position-if
1193 (>= (integer-length x)
1194 +power-cache-integer-length-limit+))
1197 (setf (cdr cell) (subseq powers 0 too-big))))))
1198 ;; Since base 10 is overwhelmingly common, make sure it's at head.
1199 ;; Try to keep other bases in a hopefully sensible order as well.
1200 (if (eql 10 (caar cache))
1201 (setf *power-cache* cache)
1202 ;; If we modify the list destructively we need to copy it, otherwise
1203 ;; an alist lookup in progress might be screwed.
1204 (setf *power-cache* (sort (copy-list cache)
1206 (declare (fixnum a b))
1216 ;;; Compute (and cache) a power vector for a BASE and LIMIT:
1217 ;;; the vector holds integers for which
1218 ;;; (aref powers k) == (expt base (expt 2 k))
1220 (defun powers-for-base (base limit)
1221 (flet ((compute-powers (from)
1223 (do ((p from (* p p)))
1225 ;; We don't actually need this, but we also
1226 ;; prefer not to cons it up a second time...
1229 (nreverse powers))))
1230 ;; Grab a local reference so that we won't stuff consed at the
1231 ;; head by other threads -- or sorting by SCRUB-POWER-CACHE.
1232 (let ((cache *power-cache*))
1233 (let ((cell (assoc base cache)))
1235 (let* ((powers (cdr cell))
1236 (len (length powers))
1237 (max (svref powers (1- len))))
1241 (concatenate 'vector powers
1242 (compute-powers (* max max)))))
1243 (setf (cdr cell) new)
1245 (let ((powers (coerce (compute-powers base) 'vector)))
1246 ;; Add new base to head: SCRUB-POWER-CACHE will later
1247 ;; put it to a better place.
1248 (setf *power-cache* (acons base powers cache))
1251 ;; Algorithm by Harald Hanche-Olsen, sbcl-devel 2005-02-05
1252 (defun %output-huge-integer-in-base (n base stream)
1253 (declare (type bignum n) (type fixnum base))
1254 ;; POWER is a vector for which the following holds:
1255 ;; (aref power k) == (expt base (expt 2 k))
1256 (let* ((power (powers-for-base base n))
1257 (k-start (or (position-if (lambda (x) (> x n)) power)
1258 (bug "power-vector too short"))))
1259 (labels ((bisect (n k exactp)
1260 (declare (fixnum k))
1261 ;; N is the number to bisect
1262 ;; K on initial entry BASE^(2^K) > N
1263 ;; EXACTP is true if 2^K is the exact number of digits
1266 (loop repeat (ash 1 k) do (write-char #\0 stream))))
1269 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n)
1273 (multiple-value-bind (q r) (truncate n (aref power k))
1274 ;; EXACTP is NIL only at the head of the
1275 ;; initial number, as we don't know the number
1276 ;; of digits there, but we do know that it
1277 ;; doesn't get any leading zeros.
1279 (bisect r k (or exactp (plusp q))))))))
1280 (bisect n k-start nil))))
1282 (defun %output-integer-in-base (integer base stream)
1283 (when (minusp integer)
1284 (write-char #\- stream)
1285 (setf integer (- integer)))
1286 ;; The ideal cutoff point between these two algorithms is almost
1287 ;; certainly quite platform dependent: this gives 87 for 32 bit
1288 ;; SBCL, which is about right at least for x86/Darwin.
1289 (if (or (fixnump integer)
1290 (< (integer-length integer) (* 3 sb!vm:n-positive-fixnum-bits)))
1291 (%output-reasonable-integer-in-base integer base stream)
1292 (%output-huge-integer-in-base integer base stream)))
1294 (defun output-integer (integer stream)
1295 (let ((base *print-base*))
1296 (when (and (/= base 10) *print-radix*)
1297 (%output-radix base stream))
1298 (%output-integer-in-base integer base stream)
1299 (when (and *print-radix* (= base 10))
1300 (write-char #\. stream))))
1302 (defun output-ratio (ratio stream)
1303 (let ((base *print-base*))
1305 (%output-radix base stream))
1306 (%output-integer-in-base (numerator ratio) base stream)
1307 (write-char #\/ stream)
1308 (%output-integer-in-base (denominator ratio) base stream)))
1310 (defun output-complex (complex stream)
1311 (write-string "#C(" stream)
1312 ;; FIXME: Could this just be OUTPUT-NUMBER?
1313 (output-object (realpart complex) stream)
1314 (write-char #\space stream)
1315 (output-object (imagpart complex) stream)
1316 (write-char #\) stream))
1320 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1321 ;;; most of the work for all printing of floating point numbers in
1322 ;;; FORMAT. It converts a floating point number to a string in a free
1323 ;;; or fixed format with no exponent. The interpretation of the
1324 ;;; arguments is as follows:
1326 ;;; X - The floating point number to convert, which must not be
1328 ;;; WIDTH - The preferred field width, used to determine the number
1329 ;;; of fraction digits to produce if the FDIGITS parameter
1330 ;;; is unspecified or NIL. If the non-fraction digits and the
1331 ;;; decimal point alone exceed this width, no fraction digits
1332 ;;; will be produced unless a non-NIL value of FDIGITS has been
1333 ;;; specified. Field overflow is not considerd an error at this
1335 ;;; FDIGITS - The number of fractional digits to produce. Insignificant
1336 ;;; trailing zeroes may be introduced as needed. May be
1337 ;;; unspecified or NIL, in which case as many digits as possible
1338 ;;; are generated, subject to the constraint that there are no
1339 ;;; trailing zeroes.
1340 ;;; SCALE - If this parameter is specified or non-NIL, then the number
1341 ;;; printed is (* x (expt 10 scale)). This scaling is exact,
1342 ;;; and cannot lose precision.
1343 ;;; FMIN - This parameter, if specified or non-NIL, is the minimum
1344 ;;; number of fraction digits which will be produced, regardless
1345 ;;; of the value of WIDTH or FDIGITS. This feature is used by
1346 ;;; the ~E format directive to prevent complete loss of
1347 ;;; significance in the printed value due to a bogus choice of
1351 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1352 ;;; where the results have the following interpretation:
1354 ;;; DIGIT-STRING - The decimal representation of X, with decimal point.
1355 ;;; DIGIT-LENGTH - The length of the string DIGIT-STRING.
1356 ;;; LEADING-POINT - True if the first character of DIGIT-STRING is the
1358 ;;; TRAILING-POINT - True if the last character of DIGIT-STRING is the
1360 ;;; POINT-POS - The position of the digit preceding the decimal
1361 ;;; point. Zero indicates point before first digit.
1363 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1364 ;;; accuracy. Specifically, the decimal number printed is the closest
1365 ;;; possible approximation to the true value of the binary number to
1366 ;;; be printed from among all decimal representations with the same
1367 ;;; number of digits. In free-format output, i.e. with the number of
1368 ;;; digits unconstrained, it is guaranteed that all the information is
1369 ;;; preserved, so that a properly- rounding reader can reconstruct the
1370 ;;; original binary number, bit-for-bit, from its printed decimal
1371 ;;; representation. Furthermore, only as many digits as necessary to
1372 ;;; satisfy this condition will be printed.
1374 ;;; FLOAT-DIGITS actually generates the digits for positive numbers;
1375 ;;; see below for comments.
1377 (defun flonum-to-string (x &optional width fdigits scale fmin)
1378 (declare (type float x))
1379 ;; FIXME: I think only FORMAT-DOLLARS calls FLONUM-TO-STRING with
1380 ;; possibly-negative X.
1382 (multiple-value-bind (e string)
1384 (flonum-to-digits x (min (- (+ fdigits (or scale 0)))
1386 (if (and width (> width 1))
1387 (let ((w (multiple-value-list
1391 (if (and scale (minusp scale))
1394 (f (multiple-value-list
1395 (flonum-to-digits x (- (+ (or fmin 0)
1396 (if scale scale 0)))))))
1398 ((>= (length (cadr w)) (length (cadr f)))
1400 (t (values-list f))))
1401 (flonum-to-digits x)))
1402 (let ((e (if (zerop x)
1404 (+ e (or scale 0))))
1405 (stream (make-string-output-stream)))
1408 (write-string string stream :end (min (length string) e))
1409 (dotimes (i (- e (length string)))
1410 (write-char #\0 stream))
1411 (write-char #\. stream)
1412 (write-string string stream :start (min (length string) e))
1414 (dotimes (i (- fdigits
1416 (min (length string) e))))
1417 (write-char #\0 stream))))
1419 (write-string "." stream)
1421 (write-char #\0 stream))
1422 (write-string string stream :end (when fdigits
1423 (min (length string)
1427 (dotimes (i (+ fdigits e (- (length string))))
1428 (write-char #\0 stream)))))
1429 (let ((string (get-output-stream-string stream)))
1430 (values string (length string)
1431 (char= (char string 0) #\.)
1432 (char= (char string (1- (length string))) #\.)
1433 (position #\. string))))))
1435 ;;; implementation of figure 1 from Burger and Dybvig, 1996. It is
1436 ;;; extended in order to handle rounding.
1438 ;;; As the implementation of the Dragon from Classic CMUCL (and
1439 ;;; previously in SBCL above FLONUM-TO-STRING) says: "DO NOT EVEN
1440 ;;; THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE
1441 ;;; PAPER!", and in this case we have to add that even reading the
1442 ;;; paper might not bring immediate illumination as CSR has attempted
1443 ;;; to turn idiomatic Scheme into idiomatic Lisp.
1445 ;;; FIXME: figure 1 from Burger and Dybvig is the unoptimized
1446 ;;; algorithm, noticeably slow at finding the exponent. Figure 2 has
1447 ;;; an improved algorithm, but CSR ran out of energy.
1449 ;;; possible extension for the enthusiastic: printing floats in bases
1450 ;;; other than base 10.
1451 (defconstant single-float-min-e
1452 (- 2 sb!vm:single-float-bias sb!vm:single-float-digits))
1453 (defconstant double-float-min-e
1454 (- 2 sb!vm:double-float-bias sb!vm:double-float-digits))
1456 (defconstant long-float-min-e
1457 (nth-value 1 (decode-float least-positive-long-float)))
1459 (defun flonum-to-digits (v &optional position relativep)
1460 (let ((print-base 10) ; B
1462 (float-digits (float-digits v)) ; p
1463 (digit-characters "0123456789")
1466 (single-float single-float-min-e)
1467 (double-float double-float-min-e)
1469 (long-float long-float-min-e))))
1470 (multiple-value-bind (f e)
1471 (integer-decode-float v)
1472 (let (;; FIXME: these even tests assume normal IEEE rounding
1473 ;; mode. I wonder if we should cater for non-normal?
1476 (with-push-char (:element-type base-char)
1477 (labels ((scale (r s m+ m-)
1479 (s s (* s print-base)))
1480 ((not (or (> (+ r m+) s)
1481 (and high-ok (= (+ r m+) s))))
1483 (r r (* r print-base))
1484 (m+ m+ (* m+ print-base))
1485 (m- m- (* m- print-base)))
1486 ((not (and (plusp (- r m-)) ; Extension to handle zero
1487 (or (< (* (+ r m+) print-base) s)
1489 (= (* (+ r m+) print-base) s)))))
1490 (values k (generate r s m+ m-)))))))
1491 (generate (r s m+ m-)
1495 (setf (values d r) (truncate (* r print-base) s))
1496 (setf m+ (* m+ print-base))
1497 (setf m- (* m- print-base))
1498 (setf tc1 (or (< r m-) (and low-ok (= r m-))))
1499 (setf tc2 (or (> (+ r m+) s)
1500 (and high-ok (= (+ r m+) s))))
1503 (push-char (char digit-characters d))
1507 ((and (not tc1) tc2) (1+ d))
1508 ((and tc1 (not tc2)) d)
1510 (if (< (* r 2) s) d (1+ d))))))
1511 (push-char (char digit-characters d))
1512 (return-from generate (get-pushed-string))))))
1516 (let* ((be (expt float-radix e))
1517 (be1 (* be float-radix)))
1518 (if (/= f (expt float-radix (1- float-digits)))
1528 (/= f (expt float-radix (1- float-digits))))
1530 s (* (expt float-radix (- e)) 2)
1533 (setf r (* f float-radix 2)
1534 s (* (expt float-radix (- 1 e)) 2)
1539 (aver (> position 0))
1541 ;; running out of letters here
1542 (l 1 (* l print-base)))
1543 ((>= (* s l) (+ r m+))
1545 (if (< (+ r (* s (/ (expt print-base (- k position)) 2)))
1546 (* s (expt print-base k)))
1547 (setf position (- k position))
1548 (setf position (- k position 1))))))
1549 (let ((low (max m- (/ (* s (expt print-base position)) 2)))
1550 (high (max m+ (/ (* s (expt print-base position)) 2))))
1557 (values r s m+ m-))))
1558 (multiple-value-bind (r s m+ m-) (initialize)
1559 (scale r s m+ m-))))))))
1561 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns
1562 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1563 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1564 ;;; original number. There may be some loss of precision due the
1565 ;;; floating point representation. The scaling is always done with
1566 ;;; long float arithmetic, which helps printing of lesser precisions
1567 ;;; as well as avoiding generic arithmetic.
1569 ;;; When computing our initial scale factor using EXPT, we pull out
1570 ;;; part of the computation to avoid over/under flow. When
1571 ;;; denormalized, we must pull out a large factor, since there is more
1572 ;;; negative exponent range than positive range.
1574 (eval-when (:compile-toplevel :execute)
1575 (setf *read-default-float-format*
1576 #!+long-float 'long-float #!-long-float 'double-float))
1577 (defun scale-exponent (original-x)
1578 (let* ((x (coerce original-x 'long-float)))
1579 (multiple-value-bind (sig exponent) (decode-float x)
1580 (declare (ignore sig))
1582 (values (float 0.0e0 original-x) 1)
1583 (let* ((ex (locally (declare (optimize (safety 0)))
1586 ;; this is the closest double float
1587 ;; to (log 2 10), but expressed so
1588 ;; that we're not vulnerable to the
1589 ;; host lisp's interpretation of
1590 ;; arithmetic. (FIXME: it turns
1591 ;; out that sbcl itself is off by 1
1592 ;; ulp in this value, which is a
1593 ;; little unfortunate.)
1596 (sb!kernel:make-double-float 1070810131 1352628735)
1598 (error "(log 2 10) not computed")))))))
1600 (if (float-denormalized-p x)
1602 (* x 1.0e16 (expt 10.0e0 (- (- ex) 16)))
1604 (* x 1.0e18 (expt 10.0e0 (- (- ex) 18)))
1605 (* x 10.0e0 (expt 10.0e0 (- (- ex) 1))))
1606 (/ x 10.0e0 (expt 10.0e0 (1- ex))))))
1607 (do ((d 10.0e0 (* d 10.0e0))
1611 (do ((m 10.0e0 (* m 10.0e0))
1615 (values (float z original-x) ex))
1616 (declare (long-float m) (integer ex))))
1617 (declare (long-float d))))))))
1618 (eval-when (:compile-toplevel :execute)
1619 (setf *read-default-float-format* 'single-float))
1621 ;;;; entry point for the float printer
1623 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1624 ;;; argument is printed free-format, in either exponential or
1625 ;;; non-exponential notation, depending on its magnitude.
1627 ;;; NOTE: When a number is to be printed in exponential format, it is
1628 ;;; scaled in floating point. Since precision may be lost in this
1629 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1630 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1631 ;;; extensive computations with integers of similar magnitude to that
1632 ;;; of the number being printed. For large exponents, the bignums
1633 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1634 ;;; fast and the exponent range is not too large, then it might become
1635 ;;; attractive to handle exponential notation with the same accuracy
1636 ;;; as non-exponential notation, using the method described in the
1637 ;;; Steele and White paper.
1639 ;;; NOTE II: this has been bypassed slightly by implementing Burger
1640 ;;; and Dybvig, 1996. When someone has time (KLUDGE) they can
1641 ;;; probably (a) implement the optimizations suggested by Burger and
1642 ;;; Dyvbig, and (b) remove all vestiges of Dragon4, including from
1643 ;;; fixed-format printing.
1645 ;;; Print the appropriate exponent marker for X and the specified exponent.
1646 (defun print-float-exponent (x exp stream)
1647 (declare (type float x) (type integer exp) (type stream stream))
1648 (let ((*print-radix* nil))
1649 (if (typep x *read-default-float-format*)
1651 (format stream "e~D" exp))
1652 (format stream "~C~D"
1660 (defun output-float-infinity (x stream)
1661 (declare (float x) (stream stream))
1663 (write-string "#." stream))
1665 (return-from output-float-infinity
1666 (print-not-readable-error x stream)))
1668 (write-string "#<" stream)))
1669 (write-string "SB-EXT:" stream)
1670 (write-string (symbol-name (float-format-name x)) stream)
1671 (write-string (if (plusp x) "-POSITIVE-" "-NEGATIVE-")
1673 (write-string "INFINITY" stream)
1675 (write-string ">" stream)))
1677 (defun output-float-nan (x stream)
1678 (print-unreadable-object (x stream)
1679 (princ (float-format-name x) stream)
1680 (write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
1681 (write-string " NaN" stream)))
1683 ;;; the function called by OUTPUT-OBJECT to handle floats
1684 (defun output-float (x stream)
1686 ((float-infinity-p x)
1687 (output-float-infinity x stream))
1689 (output-float-nan x stream))
1691 (let ((x (cond ((minusp (float-sign x))
1692 (write-char #\- stream)
1698 (write-string "0.0" stream)
1699 (print-float-exponent x 0 stream))
1701 (output-float-aux x stream -3 8)))))))
1703 (defun output-float-aux (x stream e-min e-max)
1704 (multiple-value-bind (e string)
1705 (flonum-to-digits x)
1710 (write-string string stream :end (min (length string) e))
1711 (dotimes (i (- e (length string)))
1712 (write-char #\0 stream))
1713 (write-char #\. stream)
1714 (write-string string stream :start (min (length string) e))
1715 (when (<= (length string) e)
1716 (write-char #\0 stream))
1717 (print-float-exponent x 0 stream))
1719 (write-string "0." stream)
1721 (write-char #\0 stream))
1722 (write-string string stream)
1723 (print-float-exponent x 0 stream))))
1724 (t (write-string string stream :end 1)
1725 (write-char #\. stream)
1726 (write-string string stream :start 1)
1727 (print-float-exponent x (1- e) stream)))))
1729 ;;;; other leaf objects
1731 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1732 ;;; the character name or the character in the #\char format.
1733 (defun output-character (char stream)
1734 (if (or *print-escape* *print-readably*)
1735 (let ((graphicp (and (graphic-char-p char)
1736 (standard-char-p char)))
1737 (name (char-name char)))
1738 (write-string "#\\" stream)
1739 (if (and name (not graphicp))
1740 (quote-string name stream)
1741 (write-char char stream)))
1742 (write-char char stream)))
1744 (defun output-sap (sap stream)
1745 (declare (type system-area-pointer sap))
1747 (format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
1749 (print-unreadable-object (sap stream)
1750 (format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
1752 (defun output-weak-pointer (weak-pointer stream)
1753 (declare (type weak-pointer weak-pointer))
1754 (print-unreadable-object (weak-pointer stream)
1755 (multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
1757 (write-string "weak pointer: " stream)
1758 (write value :stream stream))
1760 (write-string "broken weak pointer" stream))))))
1762 (defun output-code-component (component stream)
1763 (print-unreadable-object (component stream :identity t)
1764 (let ((dinfo (%code-debug-info component)))
1765 (cond ((eq dinfo :bogus-lra)
1766 (write-string "bogus code object" stream))
1768 (write-string "code object" stream)
1770 (write-char #\space stream)
1771 (output-object (sb!c::debug-info-name dinfo) stream)))))))
1773 (defun output-lra (lra stream)
1774 (print-unreadable-object (lra stream :identity t)
1775 (write-string "return PC object" stream)))
1777 (defun output-fdefn (fdefn stream)
1778 (print-unreadable-object (fdefn stream)
1779 (write-string "FDEFINITION object for " stream)
1780 (output-object (fdefn-name fdefn) stream)))
1783 (defun output-simd-pack (pack stream)
1784 (declare (type simd-pack pack))
1785 (cond ((and *print-readably* *read-eval*)
1787 ((simd-pack double-float)
1788 (multiple-value-call #'format stream
1790 '%make-simd-pack-double
1791 (%simd-pack-doubles pack)))
1792 ((simd-pack single-float)
1793 (multiple-value-call #'format stream
1794 "#.(~S ~S ~S ~S ~S)"
1795 '%make-simd-pack-single
1796 (%simd-pack-singles pack)))
1798 (multiple-value-call #'format stream
1799 "#.(~S #X~16,'0X #X~16,'0X)"
1800 '%make-simd-pack-ub64
1801 (%simd-pack-ub64s pack)))))
1803 (print-unreadable-object (pack stream)
1804 (flet ((all-ones-p (value start end &aux (mask (- (ash 1 end) (ash 1 start))))
1805 (= (logand value mask) mask))
1806 (split-num (value start)
1809 and v = (ash value (- start)) then (ash v -8)
1810 collect (logand v #xFF))))
1811 (multiple-value-bind (low high)
1812 (%simd-pack-ub64s pack)
1814 ((simd-pack double-float)
1815 (multiple-value-bind (v0 v1) (%simd-pack-doubles pack)
1816 (format stream "~S~@{ ~:[~,13E~;~*TRUE~]~}"
1818 (all-ones-p low 0 64) v0
1819 (all-ones-p high 0 64) v1)))
1820 ((simd-pack single-float)
1821 (multiple-value-bind (v0 v1 v2 v3) (%simd-pack-singles pack)
1822 (format stream "~S~@{ ~:[~,7E~;~*TRUE~]~}"
1824 (all-ones-p low 0 32) v0
1825 (all-ones-p low 32 64) v1
1826 (all-ones-p high 0 32) v2
1827 (all-ones-p high 32 64) v3)))
1829 (format stream "~S~@{ ~{ ~2,'0X~}~}"
1831 (split-num low 0) (split-num low 32)
1832 (split-num high 0) (split-num high 32))))))))))
1836 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1837 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1839 ;;; The definition here is a simple temporary placeholder. It will be
1840 ;;; overwritten by a smarter version (capable of calling generic
1841 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1842 (defun printed-as-funcallable-standard-class (object stream)
1843 (declare (ignore object stream))
1846 (defun output-fun (object stream)
1847 (let* ((*print-length* 4) ; in case we have to..
1848 (*print-level* 3) ; ..print an interpreted function definition
1849 (name (%fun-name object))
1850 (proper-name-p (and (legal-fun-name-p name) (fboundp name)
1851 (eq (fdefinition name) object))))
1852 (print-unreadable-object (object stream :identity (not proper-name-p))
1853 (format stream "~:[FUNCTION~;CLOSURE~]~@[ ~S~]"
1857 ;;;; catch-all for unknown things
1859 (defun output-random (object stream)
1860 (print-unreadable-object (object stream :identity t)
1861 (let ((lowtag (lowtag-of object)))
1863 (#.sb!vm:other-pointer-lowtag
1864 (let ((widetag (widetag-of object)))
1866 (#.sb!vm:value-cell-header-widetag
1867 (write-string "value cell " stream)
1868 (output-object (value-cell-ref object) stream))
1870 (write-string "unknown pointer object, widetag=" stream)
1871 (let ((*print-base* 16) (*print-radix* t))
1872 (output-integer widetag stream))))))
1873 ((#.sb!vm:fun-pointer-lowtag
1874 #.sb!vm:instance-pointer-lowtag
1875 #.sb!vm:list-pointer-lowtag)
1876 (write-string "unknown pointer object, lowtag=" stream)
1877 (let ((*print-base* 16) (*print-radix* t))
1878 (output-integer lowtag stream)))
1880 (case (widetag-of object)
1881 (#.sb!vm:unbound-marker-widetag
1882 (write-string "unbound marker" stream))
1884 (write-string "unknown immediate object, lowtag=" stream)
1885 (let ((*print-base* 2) (*print-radix* t))
1886 (output-integer lowtag stream))
1887 (write-string ", widetag=" stream)
1888 (let ((*print-base* 16) (*print-radix* t))
1889 (output-integer (widetag-of object) stream)))))))))