restarts for PRINT-NOT-READABLE errors
[sbcl.git] / src / code / print.lisp
1 ;;;; the printer
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13 \f
14 ;;;; exported printer control variables
15
16 ;;; FIXME: Many of these have nontrivial types, e.g. *PRINT-LEVEL*,
17 ;;; *PRINT-LENGTH*, and *PRINT-LINES* are (OR NULL UNSIGNED-BYTE).
18
19 (defvar *print-readably* nil
20   #!+sb-doc
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
23   *PRINT-ESCAPE*.")
24 (defvar *print-escape* t
25   #!+sb-doc
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)
29   #!+sb-doc
30   "Should pretty printing be used?")
31 (defvar *print-base* 10.
32   #!+sb-doc
33   "The output base for RATIONALs (including integers).")
34 (defvar *print-radix* nil
35   #!+sb-doc
36   "Should base be verified when printing RATIONALs?")
37 (defvar *print-level* nil
38   #!+sb-doc
39   "How many levels should be printed before abbreviating with \"#\"?")
40 (defvar *print-length* nil
41   #!+sb-doc
42   "How many elements at any level should be printed before abbreviating
43   with \"...\"?")
44 (defvar *print-circle* nil
45   #!+sb-doc
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
49   #!+sb-doc
50   "What case should the printer should use default?")
51 (defvar *print-array* t
52   #!+sb-doc
53   "Should the contents of arrays be printed?")
54 (defvar *print-gensym* t
55   #!+sb-doc
56   "Should #: prefixes be used when printing symbols with null SYMBOL-PACKAGE?")
57 (defvar *print-lines* nil
58   #!+sb-doc
59   "The maximum number of lines to print per object.")
60 (defvar *print-right-margin* nil
61   #!+sb-doc
62   "The position of the right margin in ems (for pretty-printing).")
63 (defvar *print-miser-width* nil
64   #!+sb-doc
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*)
70 #!+sb-doc
71 (setf (fdocumentation '*print-pprint-dispatch* 'variable)
72       "The pprint-dispatch-table that controls how to pretty-print objects.")
73
74 (defmacro with-standard-io-syntax (&body body)
75   #!+sb-doc
76   "Bind the reader and printer control variables to values that enable READ
77    to reliably read the results of PRINT. These values are:
78        *PACKAGE*                        the COMMON-LISP-USER package
79        *PRINT-ARRAY*                    T
80        *PRINT-BASE*                     10
81        *PRINT-CASE*                     :UPCASE
82        *PRINT-CIRCLE*                   NIL
83        *PRINT-ESCAPE*                   T
84        *PRINT-GENSYM*                   T
85        *PRINT-LENGTH*                   NIL
86        *PRINT-LEVEL*                    NIL
87        *PRINT-LINES*                    NIL
88        *PRINT-MISER-WIDTH*              NIL
89        *PRINT-PPRINT-DISPATCH*          the standard pprint dispatch table
90        *PRINT-PRETTY*                   NIL
91        *PRINT-RADIX*                    NIL
92        *PRINT-READABLY*                 T
93        *PRINT-RIGHT-MARGIN*             NIL
94        *READ-BASE*                      10
95        *READ-DEFAULT-FLOAT-FORMAT*      SINGLE-FLOAT
96        *READ-EVAL*                      T
97        *READ-SUPPRESS*                  NIL
98        *READTABLE*                      the standard readtable"
99   `(%with-standard-io-syntax (lambda () ,@body)))
100
101 (defun %with-standard-io-syntax (function)
102   (declare (type function function))
103   (let ((*package* (find-package "COMMON-LISP-USER"))
104         (*print-array* t)
105         (*print-base* 10)
106         (*print-case* :upcase)
107         (*print-circle* nil)
108         (*print-escape* t)
109         (*print-gensym* t)
110         (*print-length* nil)
111         (*print-level* nil)
112         (*print-lines* nil)
113         (*print-miser-width* nil)
114         (*print-pprint-dispatch* sb!pretty::*standard-pprint-dispatch-table*)
115         (*print-pretty* nil)
116         (*print-radix* nil)
117         (*print-readably* t)
118         (*print-right-margin* nil)
119         (*read-base* 10)
120         (*read-default-float-format* 'single-float)
121         (*read-eval* t)
122         (*read-suppress* nil)
123         (*readtable* *standard-readtable*))
124     (funcall function)))
125 \f
126 ;;;; routines to print objects
127
128 \f
129 ;;; keyword variables shared by WRITE and WRITE-TO-STRING, and
130 ;;; the bindings they map to.
131 (eval-when (:compile-toplevel :load-toplevel)
132   (defvar *printer-keyword-variables*
133     '(:escape *print-escape*
134       :radix *print-radix*
135       :base *print-base*
136       :circle *print-circle*
137       :pretty *print-pretty*
138       :level *print-level*
139       :length *print-length*
140       :case *print-case*
141       :array *print-array*
142       :gensym *print-gensym*
143       :readably *print-readably*
144       :right-margin *print-right-margin*
145       :miser-width *print-miser-width*
146       :lines *print-lines*
147       :pprint-dispatch *print-pprint-dispatch*)))
148
149 (defun write (object &key
150                      ((:stream stream) *standard-output*)
151                      ((:escape *print-escape*) *print-escape*)
152                      ((:radix *print-radix*) *print-radix*)
153                      ((:base *print-base*) *print-base*)
154                      ((:circle *print-circle*) *print-circle*)
155                      ((:pretty *print-pretty*) *print-pretty*)
156                      ((:level *print-level*) *print-level*)
157                      ((:length *print-length*) *print-length*)
158                      ((:case *print-case*) *print-case*)
159                      ((:array *print-array*) *print-array*)
160                      ((:gensym *print-gensym*) *print-gensym*)
161                      ((:readably *print-readably*) *print-readably*)
162                      ((:right-margin *print-right-margin*)
163                       *print-right-margin*)
164                      ((:miser-width *print-miser-width*)
165                       *print-miser-width*)
166                      ((:lines *print-lines*) *print-lines*)
167                      ((:pprint-dispatch *print-pprint-dispatch*)
168                       *print-pprint-dispatch*))
169   #!+sb-doc
170   "Output OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*."
171   (output-object object (out-synonym-of stream))
172   object)
173
174 ;;; Optimize common case of constant keyword arguments
175 (define-compiler-macro write (&whole form object &rest keys)
176   (let (bind ignore)
177     (do ()
178         ((not (cdr keys))
179          ;; Odd number of keys, punt
180          (when keys
181            (return-from write form)))
182       (let* ((key (pop keys))
183              (value (pop keys))
184              (variable (or (getf *printer-keyword-variables* key)
185                            (when (eq :stream key)
186                              'stream)
187                            (return-from write form))))
188         (when (assoc variable bind)
189           ;; First key has precedence, but we still need to execute the
190           ;; argument, and in the right order.
191           (setf variable (gensym "IGNORE"))
192           (push variable ignore))
193         (push (list variable value) bind)))
194     (unless (assoc 'stream bind)
195       (push (list 'stream '*standard-output*) bind))
196     (once-only ((object object))
197       `(let ,(nreverse bind)
198          ,@(when ignore `((declare (ignore ,@ignore))))
199          (output-object ,object (out-synonym-of stream))
200          ,object))))
201
202 (defun prin1 (object &optional stream)
203   #!+sb-doc
204   "Output a mostly READable printed representation of OBJECT on the specified
205   STREAM."
206   (let ((*print-escape* t))
207     (output-object object (out-synonym-of stream)))
208   object)
209
210 (defun princ (object &optional stream)
211   #!+sb-doc
212   "Output an aesthetic but not necessarily READable printed representation
213   of OBJECT on the specified STREAM."
214   (let ((*print-escape* nil)
215         (*print-readably* nil))
216     (output-object object (out-synonym-of stream)))
217   object)
218
219 (defun print (object &optional stream)
220   #!+sb-doc
221   "Output a newline, the mostly READable printed representation of OBJECT, and
222   space to the specified STREAM."
223   (let ((stream (out-synonym-of stream)))
224     (terpri stream)
225     (prin1 object stream)
226     (write-char #\space stream)
227     object))
228
229 (defun pprint (object &optional stream)
230   #!+sb-doc
231   "Prettily output OBJECT preceded by a newline."
232   (let ((*print-pretty* t)
233         (*print-escape* t)
234         (stream (out-synonym-of stream)))
235     (terpri stream)
236     (output-object object stream))
237   (values))
238
239 (defun write-to-string
240     (object &key
241             ((:escape *print-escape*) *print-escape*)
242             ((:radix *print-radix*) *print-radix*)
243             ((:base *print-base*) *print-base*)
244             ((:circle *print-circle*) *print-circle*)
245             ((:pretty *print-pretty*) *print-pretty*)
246             ((:level *print-level*) *print-level*)
247             ((:length *print-length*) *print-length*)
248             ((:case *print-case*) *print-case*)
249             ((:array *print-array*) *print-array*)
250             ((:gensym *print-gensym*) *print-gensym*)
251             ((:readably *print-readably*) *print-readably*)
252             ((:right-margin *print-right-margin*) *print-right-margin*)
253             ((:miser-width *print-miser-width*) *print-miser-width*)
254             ((:lines *print-lines*) *print-lines*)
255             ((:pprint-dispatch *print-pprint-dispatch*)
256              *print-pprint-dispatch*))
257   #!+sb-doc
258   "Return the printed representation of OBJECT as a string."
259   (stringify-object object))
260
261 ;;; Optimize common case of constant keyword arguments
262 (define-compiler-macro write-to-string (&whole form object &rest keys)
263   (let (bind ignore)
264     (do ()
265         ((not (cdr keys))
266          ;; Odd number of keys, punt
267          (when keys
268            (return-from write-to-string form)))
269       (let* ((key (pop keys))
270              (value (pop keys))
271              (variable (or (getf *printer-keyword-variables* key)
272                            (return-from write-to-string form))))
273         (when (assoc variable bind)
274           ;; First key has precedence, but we still need to execute the
275           ;; argument, and in the right order.
276           (setf variable (gensym "IGNORE"))
277           (push variable ignore))
278         (push (list variable value) bind)))
279     (if bind
280         (once-only ((object object))
281           `(let ,(nreverse bind)
282              ,@(when ignore `((declare (ignore ,@ignore))))
283              (stringify-object ,object)))
284         `(stringify-object ,object))))
285
286 (defun prin1-to-string (object)
287   #!+sb-doc
288   "Return the printed representation of OBJECT as a string with
289    slashification on."
290   (let ((*print-escape* t))
291     (stringify-object object)))
292
293 (defun princ-to-string (object)
294   #!+sb-doc
295   "Return the printed representation of OBJECT as a string with
296   slashification off."
297   (let ((*print-escape* nil)
298         (*print-readably* nil))
299     (stringify-object object)))
300
301 ;;; This produces the printed representation of an object as a string.
302 ;;; The few ...-TO-STRING functions above call this.
303 (defun stringify-object (object)
304   (let ((stream (make-string-output-stream)))
305     (setup-printer-state)
306     (output-object object stream)
307     (get-output-stream-string stream)))
308 \f
309 ;;;; support for the PRINT-UNREADABLE-OBJECT macro
310
311 (defun read-unreadable-replacement ()
312   (format *query-io* "~@<Enter an object (evaluated): ~@:>")
313   (finish-output *query-io*)
314   (list (eval (read *query-io*))))
315
316 ;;; guts of PRINT-UNREADABLE-OBJECT
317 (defun %print-unreadable-object (object stream type identity body)
318   (declare (type (or null function) body))
319   (when *print-readably*
320     (restart-case
321         (error 'print-not-readable :object object)
322       (print-unreadably ()
323         :report "Print unreadably.")
324       (use-value (o)
325         :report "Supply an object to be printed instead."
326         :interactive read-unreadable-replacement
327         (write o :stream stream)
328         (return-from %print-unreadable-object nil))))
329   (flet ((print-description ()
330            (when type
331              (write (type-of object) :stream stream :circle nil
332                     :level nil :length nil)
333              (write-char #\space stream)
334              (pprint-newline :fill stream))
335            (when body
336              (funcall body))
337            (when identity
338              (when (or body (not type))
339                (write-char #\space stream))
340              (pprint-newline :fill stream)
341              (write-char #\{ stream)
342              (write (get-lisp-obj-address object) :stream stream
343                     :radix nil :base 16)
344              (write-char #\} stream))))
345     (cond ((print-pretty-on-stream-p stream)
346            ;; Since we're printing prettily on STREAM, format the
347            ;; object within a logical block. PPRINT-LOGICAL-BLOCK does
348            ;; not rebind the stream when it is already a pretty stream,
349            ;; so output from the body will go to the same stream.
350            (pprint-logical-block (stream nil :prefix "#<" :suffix ">")
351              (print-description)))
352           (t
353            (write-string "#<" stream)
354            (print-description)
355            (write-char #\> stream))))
356   nil)
357 \f
358 ;;;; OUTPUT-OBJECT -- the main entry point
359
360 ;;; Objects whose print representation identifies them EQLly don't
361 ;;; need to be checked for circularity.
362 (defun uniquely-identified-by-print-p (x)
363   (or (numberp x)
364       (characterp x)
365       (and (symbolp x)
366            (symbol-package x))))
367
368 ;;; Output OBJECT to STREAM observing all printer control variables.
369 (defun output-object (object stream)
370   (labels ((print-it (stream)
371              (if *print-pretty*
372                  (sb!pretty:output-pretty-object object stream)
373                  (output-ugly-object object stream)))
374            (check-it (stream)
375              (multiple-value-bind (marker initiate)
376                  (check-for-circularity object t)
377                (if (eq initiate :initiate)
378                    (let ((*circularity-hash-table*
379                           (make-hash-table :test 'eq)))
380                      (check-it (make-broadcast-stream))
381                      (let ((*circularity-counter* 0))
382                        (check-it stream)))
383                    ;; otherwise
384                    (if marker
385                        (when (handle-circularity marker stream)
386                          (print-it stream))
387                        (print-it stream))))))
388     (cond (;; Maybe we don't need to bother with circularity detection.
389            (or (not *print-circle*)
390                (uniquely-identified-by-print-p object))
391            (print-it stream))
392           (;; If we have already started circularity detection, this
393            ;; object might be a shared reference. If we have not, then
394            ;; if it is a compound object it might contain a circular
395            ;; reference to itself or multiple shared references.
396            (or *circularity-hash-table*
397                (compound-object-p object))
398            (check-it stream))
399           (t
400            (print-it stream)))))
401
402 ;;; a hack to work around recurring gotchas with printing while
403 ;;; DEFGENERIC PRINT-OBJECT is being built
404 ;;;
405 ;;; (hopefully will go away naturally when CLOS moves into cold init)
406 (defvar *print-object-is-disabled-p*)
407
408 ;;; Output OBJECT to STREAM observing all printer control variables
409 ;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
410 ;;; then the pretty printer will be used for any components of OBJECT,
411 ;;; just not for OBJECT itself.
412 (defun output-ugly-object (object stream)
413   (typecase object
414     ;; KLUDGE: The TYPECASE approach here is non-ANSI; the ANSI definition of
415     ;; PRINT-OBJECT says it provides printing and we're supposed to provide
416     ;; PRINT-OBJECT methods covering all classes. We deviate from this
417     ;; by using PRINT-OBJECT only when we print instance values. However,
418     ;; ANSI makes it hard to tell that we're deviating from this:
419     ;;   (1) ANSI specifies that the user isn't supposed to call PRINT-OBJECT
420     ;;       directly.
421     ;;   (2) ANSI (section 11.1.2.1.2) says it's undefined to define
422     ;;       a method on an external symbol in the CL package which is
423     ;;       applicable to arg lists containing only direct instances of
424     ;;       standardized classes.
425     ;; Thus, in order for the user to detect our sleaziness in conforming
426     ;; code, he has to do something relatively obscure like
427     ;;   (1) actually use tools like FIND-METHOD to look for PRINT-OBJECT
428     ;;       methods, or
429     ;;   (2) define a PRINT-OBJECT method which is specialized on the stream
430     ;;       value (e.g. a Gray stream object).
431     ;; As long as no one comes up with a non-obscure way of detecting this
432     ;; sleaziness, fixing this nonconformity will probably have a low
433     ;; priority. -- WHN 2001-11-25
434     (list
435      (if (null object)
436          (output-symbol object stream)
437          (output-list object stream)))
438     (instance
439      (cond ((not (and (boundp '*print-object-is-disabled-p*)
440                       *print-object-is-disabled-p*))
441             (print-object object stream))
442            ((typep object 'structure-object)
443             (default-structure-print object stream *current-level-in-print*))
444            (t
445             (write-string "#<INSTANCE but not STRUCTURE-OBJECT>" stream))))
446     (funcallable-instance
447      (cond
448        ((not (and (boundp '*print-object-is-disabled-p*)
449                   *print-object-is-disabled-p*))
450         (print-object object stream))
451        (t (output-fun object stream))))
452     (function
453      (output-fun object stream))
454     (symbol
455      (output-symbol object stream))
456     (number
457      (etypecase object
458        (integer
459         (output-integer object stream))
460        (float
461         (output-float object stream))
462        (ratio
463         (output-ratio object stream))
464        (complex
465         (output-complex object stream))))
466     (character
467      (output-character object stream))
468     (vector
469      (output-vector object stream))
470     (array
471      (output-array object stream))
472     (system-area-pointer
473      (output-sap object stream))
474     (weak-pointer
475      (output-weak-pointer object stream))
476     (lra
477      (output-lra object stream))
478     (code-component
479      (output-code-component object stream))
480     (fdefn
481      (output-fdefn object stream))
482     (t
483      (output-random object stream))))
484 \f
485 ;;;; symbols
486
487 ;;; values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last
488 ;;; time the printer was called
489 (defvar *previous-case* nil)
490 (defvar *previous-readtable-case* nil)
491
492 ;;; This variable contains the current definition of one of three
493 ;;; symbol printers. SETUP-PRINTER-STATE sets this variable.
494 (defvar *internal-symbol-output-fun* nil)
495
496 ;;; This function sets the internal global symbol
497 ;;; *INTERNAL-SYMBOL-OUTPUT-FUN* to the right function depending on
498 ;;; the value of *PRINT-CASE*. See the manual for details. The print
499 ;;; buffer stream is also reset.
500 (defun setup-printer-state ()
501   (unless (and (eq *print-case* *previous-case*)
502                (eq (readtable-case *readtable*) *previous-readtable-case*))
503     (setq *previous-case* *print-case*)
504     (setq *previous-readtable-case* (readtable-case *readtable*))
505     (unless (member *print-case* '(:upcase :downcase :capitalize))
506       (setq *print-case* :upcase)
507       (error "invalid *PRINT-CASE* value: ~S" *previous-case*))
508     (unless (member *previous-readtable-case*
509                     '(:upcase :downcase :invert :preserve))
510       (setf (readtable-case *readtable*) :upcase)
511       (error "invalid READTABLE-CASE value: ~S" *previous-readtable-case*))
512
513     (setq *internal-symbol-output-fun*
514           (case *previous-readtable-case*
515             (:upcase
516              (case *print-case*
517                (:upcase #'output-preserve-symbol)
518                (:downcase #'output-lowercase-symbol)
519                (:capitalize #'output-capitalize-symbol)))
520             (:downcase
521              (case *print-case*
522                (:upcase #'output-uppercase-symbol)
523                (:downcase #'output-preserve-symbol)
524                (:capitalize #'output-capitalize-symbol)))
525             (:preserve #'output-preserve-symbol)
526             (:invert #'output-invert-symbol)))))
527
528 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
529 ;;; and with any embedded |'s or \'s escaped.
530 (defun output-quoted-symbol-name (pname stream)
531   (write-char #\| stream)
532   (dotimes (index (length pname))
533     (let ((char (schar pname index)))
534       (when (or (char= char #\\) (char= char #\|))
535         (write-char #\\ stream))
536       (write-char char stream)))
537   (write-char #\| stream))
538
539 (defun output-symbol (object stream)
540   (if (or *print-escape* *print-readably*)
541       (let ((package (symbol-package object))
542             (name (symbol-name object)))
543         (cond
544          ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
545          ;; requires that keywords be printed with preceding colons
546          ;; always, regardless of the value of *PACKAGE*.
547          ((eq package *keyword-package*)
548           (write-char #\: stream))
549          ;; Otherwise, if the symbol's home package is the current
550          ;; one, then a prefix is never necessary.
551          ((eq package (sane-package)))
552          ;; Uninterned symbols print with a leading #:.
553          ((null package)
554           (when (or *print-gensym* *print-readably*)
555             (write-string "#:" stream)))
556          (t
557           (multiple-value-bind (symbol accessible)
558               (find-symbol name (sane-package))
559             ;; If we can find the symbol by looking it up, it need not
560             ;; be qualified. This can happen if the symbol has been
561             ;; inherited from a package other than its home package.
562             (unless (and accessible (eq symbol object))
563               (output-symbol-name (package-name package) stream)
564               (multiple-value-bind (symbol externalp)
565                   (find-external-symbol name package)
566                 (declare (ignore symbol))
567                 (if externalp
568                     (write-char #\: stream)
569                     (write-string "::" stream)))))))
570         (output-symbol-name name stream))
571       (output-symbol-name (symbol-name object) stream nil)))
572
573 ;;; Output the string NAME as if it were a symbol name. In other
574 ;;; words, diddle its case according to *PRINT-CASE* and
575 ;;; READTABLE-CASE.
576 (defun output-symbol-name (name stream &optional (maybe-quote t))
577   (declare (type simple-string name))
578   (let ((*readtable* (if *print-readably* *standard-readtable* *readtable*)))
579     (setup-printer-state)
580     (if (and maybe-quote (symbol-quotep name))
581         (output-quoted-symbol-name name stream)
582         (funcall *internal-symbol-output-fun* name stream))))
583 \f
584 ;;;; escaping symbols
585
586 ;;; When we print symbols we have to figure out if they need to be
587 ;;; printed with escape characters. This isn't a whole lot easier than
588 ;;; reading symbols in the first place.
589 ;;;
590 ;;; For each character, the value of the corresponding element is a
591 ;;; fixnum with bits set corresponding to attributes that the
592 ;;; character has. At characters have at least one bit set, so we can
593 ;;; search for any character with a positive test.
594 (defvar *character-attributes*
595   (make-array 160 ; FIXME
596               :element-type '(unsigned-byte 16)
597               :initial-element 0))
598 (declaim (type (simple-array (unsigned-byte 16) (#.160)) ; FIXME
599                *character-attributes*))
600
601 ;;; constants which are a bit-mask for each interesting character attribute
602 (defconstant other-attribute            (ash 1 0)) ; Anything else legal.
603 (defconstant number-attribute           (ash 1 1)) ; A numeric digit.
604 (defconstant uppercase-attribute        (ash 1 2)) ; An uppercase letter.
605 (defconstant lowercase-attribute        (ash 1 3)) ; A lowercase letter.
606 (defconstant sign-attribute             (ash 1 4)) ; +-
607 (defconstant extension-attribute        (ash 1 5)) ; ^_
608 (defconstant dot-attribute              (ash 1 6)) ; .
609 (defconstant slash-attribute            (ash 1 7)) ; /
610 (defconstant funny-attribute            (ash 1 8)) ; Anything illegal.
611
612 (eval-when (:compile-toplevel :load-toplevel :execute)
613
614 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
615 ;;; that don't need to be escaped (according to READTABLE-CASE.)
616 (defparameter *attribute-names*
617   `((number . number-attribute) (lowercase . lowercase-attribute)
618     (uppercase . uppercase-attribute) (letter . letter-attribute)
619     (sign . sign-attribute) (extension . extension-attribute)
620     (dot . dot-attribute) (slash . slash-attribute)
621     (other . other-attribute) (funny . funny-attribute)))
622
623 ) ; EVAL-WHEN
624
625 (flet ((set-bit (char bit)
626          (let ((code (char-code char)))
627            (setf (aref *character-attributes* code)
628                  (logior bit (aref *character-attributes* code))))))
629
630   (dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
631                   #\? #\< #\>))
632     (set-bit char other-attribute))
633
634   (dotimes (i 10)
635     (set-bit (digit-char i) number-attribute))
636
637   (do ((code (char-code #\A) (1+ code))
638        (end (char-code #\Z)))
639       ((> code end))
640     (declare (fixnum code end))
641     (set-bit (code-char code) uppercase-attribute)
642     (set-bit (char-downcase (code-char code)) lowercase-attribute))
643
644   (set-bit #\- sign-attribute)
645   (set-bit #\+ sign-attribute)
646   (set-bit #\^ extension-attribute)
647   (set-bit #\_ extension-attribute)
648   (set-bit #\. dot-attribute)
649   (set-bit #\/ slash-attribute)
650
651   ;; Mark anything not explicitly allowed as funny.
652   (dotimes (i 160) ; FIXME
653     (when (zerop (aref *character-attributes* i))
654       (setf (aref *character-attributes* i) funny-attribute))))
655
656 ;;; For each character, the value of the corresponding element is the
657 ;;; lowest base in which that character is a digit.
658 (defvar *digit-bases*
659   (make-array 128 ; FIXME
660               :element-type '(unsigned-byte 8)
661               :initial-element 36))
662 (declaim (type (simple-array (unsigned-byte 8) (#.128)) ; FIXME
663                *digit-bases*))
664 (dotimes (i 36)
665   (let ((char (digit-char i 36)))
666     (setf (aref *digit-bases* (char-code char)) i)))
667
668 ;;; A FSM-like thingie that determines whether a symbol is a potential
669 ;;; number or has evil characters in it.
670 (defun symbol-quotep (name)
671   (declare (simple-string name))
672   (macrolet ((advance (tag &optional (at-end t))
673                `(progn
674                  (when (= index len)
675                    ,(if at-end '(go TEST-SIGN) '(return nil)))
676                  (setq current (schar name index)
677                        code (char-code current)
678                        bits (cond ; FIXME
679                               ((< code 160) (aref attributes code))
680                               ((upper-case-p current) uppercase-attribute)
681                               ((lower-case-p current) lowercase-attribute)
682                               (t other-attribute)))
683                  (incf index)
684                  (go ,tag)))
685              (test (&rest attributes)
686                 `(not (zerop
687                        (the fixnum
688                             (logand
689                              (logior ,@(mapcar
690                                         (lambda (x)
691                                           (or (cdr (assoc x
692                                                           *attribute-names*))
693                                               (error "Blast!")))
694                                         attributes))
695                              bits)))))
696              (digitp ()
697                `(and (< code 128) ; FIXME
698                      (< (the fixnum (aref bases code)) base))))
699
700     (prog ((len (length name))
701            (attributes *character-attributes*)
702            (bases *digit-bases*)
703            (base *print-base*)
704            (letter-attribute
705             (case (readtable-case *readtable*)
706               (:upcase uppercase-attribute)
707               (:downcase lowercase-attribute)
708               (t (logior lowercase-attribute uppercase-attribute))))
709            (index 0)
710            (bits 0)
711            (code 0)
712            current)
713       (declare (fixnum len base index bits code))
714       (advance START t)
715
716      TEST-SIGN ; At end, see whether it is a sign...
717       (return (not (test sign)))
718
719      OTHER ; not potential number, see whether funny chars...
720       (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
721                                   funny-attribute)
722                           letter-attribute)))
723         (do ((i (1- index) (1+ i)))
724             ((= i len) (return-from symbol-quotep nil))
725           (unless (zerop (logand (let* ((char (schar name i))
726                                         (code (char-code char)))
727                                    (cond
728                                      ((< code 160) (aref attributes code))
729                                      ((upper-case-p char) uppercase-attribute)
730                                      ((lower-case-p char) lowercase-attribute)
731                                      (t other-attribute)))
732                                  mask))
733             (return-from symbol-quotep t))))
734
735      START
736       (when (digitp)
737         (if (test letter)
738             (advance LAST-DIGIT-ALPHA)
739             (advance DIGIT)))
740       (when (test letter number other slash) (advance OTHER nil))
741       (when (char= current #\.) (advance DOT-FOUND))
742       (when (test sign extension) (advance START-STUFF nil))
743       (return t)
744
745      DOT-FOUND ; leading dots...
746       (when (test letter) (advance START-DOT-MARKER nil))
747       (when (digitp) (advance DOT-DIGIT))
748       (when (test number other) (advance OTHER nil))
749       (when (test extension slash sign) (advance START-DOT-STUFF nil))
750       (when (char= current #\.) (advance DOT-FOUND))
751       (return t)
752
753      START-STUFF ; leading stuff before any dot or digit
754       (when (digitp)
755         (if (test letter)
756             (advance LAST-DIGIT-ALPHA)
757             (advance DIGIT)))
758       (when (test number other) (advance OTHER nil))
759       (when (test letter) (advance START-MARKER nil))
760       (when (char= current #\.) (advance START-DOT-STUFF nil))
761       (when (test sign extension slash) (advance START-STUFF nil))
762       (return t)
763
764      START-MARKER ; number marker in leading stuff...
765       (when (test letter) (advance OTHER nil))
766       (go START-STUFF)
767
768      START-DOT-STUFF ; leading stuff containing dot without digit...
769       (when (test letter) (advance START-DOT-STUFF nil))
770       (when (digitp) (advance DOT-DIGIT))
771       (when (test sign extension dot slash) (advance START-DOT-STUFF nil))
772       (when (test number other) (advance OTHER nil))
773       (return t)
774
775      START-DOT-MARKER ; number marker in leading stuff with dot..
776       ;; leading stuff containing dot without digit followed by letter...
777       (when (test letter) (advance OTHER nil))
778       (go START-DOT-STUFF)
779
780      DOT-DIGIT ; in a thing with dots...
781       (when (test letter) (advance DOT-MARKER))
782       (when (digitp) (advance DOT-DIGIT))
783       (when (test number other) (advance OTHER nil))
784       (when (test sign extension dot slash) (advance DOT-DIGIT))
785       (return t)
786
787      DOT-MARKER ; number marker in number with dot...
788       (when (test letter) (advance OTHER nil))
789       (go DOT-DIGIT)
790
791      LAST-DIGIT-ALPHA ; previous char is a letter digit...
792       (when (or (digitp) (test sign slash))
793         (advance ALPHA-DIGIT))
794       (when (test letter number other dot) (advance OTHER nil))
795       (return t)
796
797      ALPHA-DIGIT ; seen a digit which is a letter...
798       (when (or (digitp) (test sign slash))
799         (if (test letter)
800             (advance LAST-DIGIT-ALPHA)
801             (advance ALPHA-DIGIT)))
802       (when (test letter) (advance ALPHA-MARKER))
803       (when (test number other dot) (advance OTHER nil))
804       (return t)
805
806      ALPHA-MARKER ; number marker in number with alpha digit...
807       (when (test letter) (advance OTHER nil))
808       (go ALPHA-DIGIT)
809
810      DIGIT ; seen only ordinary (non-alphabetic) numeric digits...
811       (when (digitp)
812         (if (test letter)
813             (advance ALPHA-DIGIT)
814             (advance DIGIT)))
815       (when (test number other) (advance OTHER nil))
816       (when (test letter) (advance MARKER))
817       (when (test extension slash sign) (advance DIGIT))
818       (when (char= current #\.) (advance DOT-DIGIT))
819       (return t)
820
821      MARKER ; number marker in a numeric number...
822       ;; ("What," you may ask, "is a 'number marker'?" It's something
823       ;; that a conforming implementation might use in number syntax.
824       ;; See ANSI 2.3.1.1 "Potential Numbers as Tokens".)
825       (when (test letter) (advance OTHER nil))
826       (go DIGIT))))
827 \f
828 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN*
829 ;;;;
830 ;;;; case hackery: These functions are stored in
831 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN* according to the values of
832 ;;;; *PRINT-CASE* and READTABLE-CASE.
833
834 ;;; called when:
835 ;;; READTABLE-CASE      *PRINT-CASE*
836 ;;; :UPCASE             :UPCASE
837 ;;; :DOWNCASE           :DOWNCASE
838 ;;; :PRESERVE           any
839 (defun output-preserve-symbol (pname stream)
840   (declare (simple-string pname))
841   (write-string pname stream))
842
843 ;;; called when:
844 ;;; READTABLE-CASE      *PRINT-CASE*
845 ;;; :UPCASE             :DOWNCASE
846 (defun output-lowercase-symbol (pname stream)
847   (declare (simple-string pname))
848   (dotimes (index (length pname))
849     (let ((char (schar pname index)))
850       (write-char (char-downcase char) stream))))
851
852 ;;; called when:
853 ;;; READTABLE-CASE      *PRINT-CASE*
854 ;;; :DOWNCASE           :UPCASE
855 (defun output-uppercase-symbol (pname stream)
856   (declare (simple-string pname))
857   (dotimes (index (length pname))
858     (let ((char (schar pname index)))
859       (write-char (char-upcase char) stream))))
860
861 ;;; called when:
862 ;;; READTABLE-CASE      *PRINT-CASE*
863 ;;; :UPCASE             :CAPITALIZE
864 ;;; :DOWNCASE           :CAPITALIZE
865 (defun output-capitalize-symbol (pname stream)
866   (declare (simple-string pname))
867   (let ((prev-not-alphanum t)
868         (up (eq (readtable-case *readtable*) :upcase)))
869     (dotimes (i (length pname))
870       (let ((char (char pname i)))
871         (write-char (if up
872                         (if (or prev-not-alphanum (lower-case-p char))
873                             char
874                             (char-downcase char))
875                         (if prev-not-alphanum
876                             (char-upcase char)
877                             char))
878                     stream)
879         (setq prev-not-alphanum (not (alphanumericp char)))))))
880
881 ;;; called when:
882 ;;; READTABLE-CASE      *PRINT-CASE*
883 ;;; :INVERT             any
884 (defun output-invert-symbol (pname stream)
885   (declare (simple-string pname))
886   (let ((all-upper t)
887         (all-lower t))
888     (dotimes (i (length pname))
889       (let ((ch (schar pname i)))
890         (when (both-case-p ch)
891           (if (upper-case-p ch)
892               (setq all-lower nil)
893               (setq all-upper nil)))))
894     (cond (all-upper (output-lowercase-symbol pname stream))
895           (all-lower (output-uppercase-symbol pname stream))
896           (t
897            (write-string pname stream)))))
898
899 #|
900 (defun test1 ()
901   (let ((*readtable* (copy-readtable nil)))
902     (format t "READTABLE-CASE  Input   Symbol-name~@
903                ----------------------------------~%")
904     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
905       (setf (readtable-case *readtable*) readtable-case)
906       (dolist (input '("ZEBRA" "Zebra" "zebra"))
907         (format t "~&:~A~16T~A~24T~A"
908                 (string-upcase readtable-case)
909                 input
910                 (symbol-name (read-from-string input)))))))
911
912 (defun test2 ()
913   (let ((*readtable* (copy-readtable nil)))
914     (format t "READTABLE-CASE  *PRINT-CASE*  Symbol-name  Output  Princ~@
915                --------------------------------------------------------~%")
916     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
917       (setf (readtable-case *readtable*) readtable-case)
918       (dolist (*print-case* '(:upcase :downcase :capitalize))
919         (dolist (symbol '(|ZEBRA| |Zebra| |zebra|))
920           (format t "~&:~A~15T:~A~29T~A~42T~A~50T~A"
921                   (string-upcase readtable-case)
922                   (string-upcase *print-case*)
923                   (symbol-name symbol)
924                   (prin1-to-string symbol)
925                   (princ-to-string symbol)))))))
926 |#
927 \f
928 ;;;; recursive objects
929
930 (defun output-list (list stream)
931   (descend-into (stream)
932     (write-char #\( stream)
933     (let ((length 0)
934           (list list))
935       (loop
936         (punt-print-if-too-long length stream)
937         (output-object (pop list) stream)
938         (unless list
939           (return))
940         (when (or (atom list)
941                   (check-for-circularity list))
942           (write-string " . " stream)
943           (output-object list stream)
944           (return))
945         (write-char #\space stream)
946         (incf length)))
947     (write-char #\) stream)))
948
949 (defun output-vector (vector stream)
950   (declare (vector vector))
951   (cond ((stringp vector)
952          (cond ((and *print-readably*
953                      (not (eq (array-element-type vector)
954                               (load-time-value
955                                (array-element-type
956                                 (make-array 0 :element-type 'character))))))
957                 (restart-case
958                     (error 'print-not-readable :object vector)
959                   (print-unreadably ()
960                     :report "Print unreadably."
961                     (let ((*print-readably* nil))
962                       (output-vector vector stream)))
963                   (use-value (o)
964                     :report "Supply an object to be printed instead."
965                     :interactive read-unreadable-replacement
966                     (write o :stream stream))))
967                ((or *print-escape* *print-readably*)
968                 (write-char #\" stream)
969                 (quote-string vector stream)
970                 (write-char #\" stream))
971                (t
972                 (write-string vector stream))))
973         ((not (or *print-array* *print-readably*))
974          (output-terse-array vector stream))
975         ((bit-vector-p vector)
976          (write-string "#*" stream)
977          (dovector (bit vector)
978            ;; (Don't use OUTPUT-OBJECT here, since this code
979            ;; has to work for all possible *PRINT-BASE* values.)
980            (write-char (if (zerop bit) #\0 #\1) stream)))
981         (t
982          (when (and *print-readably*
983                     (not (array-readably-printable-p vector)))
984            (restart-case
985                (error 'print-not-readable :object vector)
986              (print-unreadably ()
987                :report "Print unreadably.")
988              (use-value (o)
989                :report "Supply an object to be printed instead."
990                :interactive read-unreadable-replacement
991                (return-from output-vector (write o :stream stream)))))
992          (descend-into (stream)
993                        (write-string "#(" stream)
994                        (dotimes (i (length vector))
995                          (unless (zerop i)
996                            (write-char #\space stream))
997                          (punt-print-if-too-long i stream)
998                          (output-object (aref vector i) stream))
999                        (write-string ")" stream)))))
1000
1001 ;;; This function outputs a string quoting characters sufficiently
1002 ;;; so that someone can read it in again. Basically, put a slash in
1003 ;;; front of an character satisfying NEEDS-SLASH-P.
1004 (defun quote-string (string stream)
1005   (macrolet ((needs-slash-p (char)
1006                ;; KLUDGE: We probably should look at the readtable, but just do
1007                ;; this for now. [noted by anonymous long ago] -- WHN 19991130
1008                `(or (char= ,char #\\)
1009                  (char= ,char #\"))))
1010     (with-array-data ((data string) (start) (end)
1011                       :check-fill-pointer t)
1012       (do ((index start (1+ index)))
1013           ((>= index end))
1014         (let ((char (schar data index)))
1015           (when (needs-slash-p char) (write-char #\\ stream))
1016           (write-char char stream))))))
1017
1018 (defun array-readably-printable-p (array)
1019   (and (eq (array-element-type array) t)
1020        (let ((zero (position 0 (array-dimensions array)))
1021              (number (position 0 (array-dimensions array)
1022                                :test (complement #'eql)
1023                                :from-end t)))
1024          (or (null zero) (null number) (> zero number)))))
1025
1026 ;;; Output the printed representation of any array in either the #< or #A
1027 ;;; form.
1028 (defun output-array (array stream)
1029   (if (or *print-array* *print-readably*)
1030       (output-array-guts array stream)
1031       (output-terse-array array stream)))
1032
1033 ;;; Output the abbreviated #< form of an array.
1034 (defun output-terse-array (array stream)
1035   (let ((*print-level* nil)
1036         (*print-length* nil))
1037     (print-unreadable-object (array stream :type t :identity t))))
1038
1039 ;;; Output the readable #A form of an array.
1040 (defun output-array-guts (array stream)
1041   (when (and *print-readably*
1042              (not (array-readably-printable-p array)))
1043     (restart-case
1044         (error 'print-not-readable :object array)
1045       (print-unreadably ()
1046         :report "Print unreadably.")
1047       (use-value (o)
1048         :report "Supply an object to be printed instead."
1049         :interactive read-unreadable-replacement
1050         (return-from output-array-guts (write o :stream stream)))))
1051   (write-char #\# stream)
1052   (let ((*print-base* 10)
1053         (*print-radix* nil))
1054     (output-integer (array-rank array) stream))
1055   (write-char #\A stream)
1056   (with-array-data ((data array) (start) (end))
1057     (declare (ignore end))
1058     (sub-output-array-guts data (array-dimensions array) stream start)))
1059
1060 (defun sub-output-array-guts (array dimensions stream index)
1061   (declare (type (simple-array * (*)) array) (fixnum index))
1062   (cond ((null dimensions)
1063          (output-object (aref array index) stream))
1064         (t
1065          (descend-into (stream)
1066            (write-char #\( stream)
1067            (let* ((dimension (car dimensions))
1068                   (dimensions (cdr dimensions))
1069                   (count (reduce #'* dimensions)))
1070              (dotimes (i dimension)
1071                (unless (zerop i)
1072                  (write-char #\space stream))
1073                (punt-print-if-too-long i stream)
1074                (sub-output-array-guts array dimensions stream index)
1075                (incf index count)))
1076            (write-char #\) stream)))))
1077
1078 ;;; a trivial non-generic-function placeholder for PRINT-OBJECT, for
1079 ;;; use until CLOS is set up (at which time it will be replaced with
1080 ;;; the real generic function implementation)
1081 (defun print-object (instance stream)
1082   (default-structure-print instance stream *current-level-in-print*))
1083 \f
1084 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
1085
1086 (defun %output-radix (base stream)
1087   (write-char #\# stream)
1088   (write-char (case base
1089                 (2 #\b)
1090                 (8 #\o)
1091                 (16 #\x)
1092                 (t (%output-reasonable-integer-in-base base 10 stream)
1093                    #\r))
1094               stream))
1095
1096 (defun %output-reasonable-integer-in-base (n base stream)
1097   (multiple-value-bind (q r)
1098       (truncate n base)
1099     ;; Recurse until you have all the digits pushed on
1100     ;; the stack.
1101     (unless (zerop q)
1102       (%output-reasonable-integer-in-base q base stream))
1103     ;; Then as each recursive call unwinds, turn the
1104     ;; digit (in remainder) into a character and output
1105     ;; the character.
1106     (write-char
1107      (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r)
1108      stream)))
1109
1110 ;;; *POWER-CACHE* is an alist mapping bases to power-vectors. It is
1111 ;;; filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
1112 ;;; always prior a GC to drop overly large bignums from the cache.
1113 ;;;
1114 ;;; It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
1115 ;;; POWERS-FOR-BASE, see that you don't break the assumptions!
1116 (defvar *power-cache* nil)
1117
1118 (defconstant +power-cache-integer-length-limit+ 2048)
1119
1120 (defun scrub-power-cache ()
1121   (let ((cache *power-cache*))
1122     (dolist (cell cache)
1123       (let ((powers (cdr cell)))
1124         (declare (simple-vector powers))
1125         (let ((too-big (position-if
1126                         (lambda (x)
1127                           (>= (integer-length x)
1128                               +power-cache-integer-length-limit+))
1129                         powers)))
1130           (when too-big
1131             (setf (cdr cell) (subseq powers 0 too-big))))))
1132     ;; Since base 10 is overwhelmingly common, make sure it's at head.
1133     ;; Try to keep other bases in a hopefully sensible order as well.
1134     (if (eql 10 (caar cache))
1135         (setf *power-cache* cache)
1136         ;; If we modify the list destructively we need to copy it, otherwise
1137         ;; an alist lookup in progress might be screwed.
1138         (setf *power-cache* (sort (copy-list cache)
1139                                   (lambda (a b)
1140                                     (declare (fixnum a b))
1141                                     (cond ((= 10 a) t)
1142                                           ((= 10 b) nil)
1143                                           ((= 16 a) t)
1144                                           ((= 16 b) nil)
1145                                           ((= 2 a) t)
1146                                           ((= 2 b) nil)
1147                                           (t (< a b))))
1148                                   :key #'car)))))
1149
1150 ;;; Compute (and cache) a power vector for a BASE and LIMIT:
1151 ;;; the vector holds integers for which
1152 ;;;    (aref powers k) == (expt base (expt 2 k))
1153 ;;; holds.
1154 (defun powers-for-base (base limit)
1155   (flet ((compute-powers (from)
1156            (let (powers)
1157              (do ((p from (* p p)))
1158                  ((> p limit)
1159                   ;; We don't actually need this, but we also
1160                   ;; prefer not to cons it up a second time...
1161                   (push p powers))
1162                (push p powers))
1163              (nreverse powers))))
1164     ;; Grab a local reference so that we won't stuff consed at the
1165     ;; head by other threads -- or sorting by SCRUB-POWER-CACHE.
1166     (let ((cache *power-cache*))
1167       (let ((cell (assoc base cache)))
1168         (if cell
1169             (let* ((powers (cdr cell))
1170                    (len (length powers))
1171                    (max (svref powers (1- len))))
1172               (if (> max limit)
1173                   powers
1174                   (let ((new
1175                          (concatenate 'vector powers
1176                                       (compute-powers (* max max)))))
1177                     (setf (cdr cell) new)
1178                     new)))
1179             (let ((powers (coerce (compute-powers base) 'vector)))
1180               ;; Add new base to head: SCRUB-POWER-CACHE will later
1181               ;; put it to a better place.
1182               (setf *power-cache* (acons base powers cache))
1183               powers))))))
1184
1185 ;; Algorithm by Harald Hanche-Olsen, sbcl-devel 2005-02-05
1186 (defun %output-huge-integer-in-base (n base stream)
1187   (declare (type bignum n) (type fixnum base))
1188   ;; POWER is a vector for which the following holds:
1189   ;;   (aref power k) == (expt base (expt 2 k))
1190   (let* ((power (powers-for-base base n))
1191          (k-start (or (position-if (lambda (x) (> x n)) power)
1192                       (bug "power-vector too short"))))
1193     (labels ((bisect (n k exactp)
1194                (declare (fixnum k))
1195                ;; N is the number to bisect
1196                ;; K on initial entry BASE^(2^K) > N
1197                ;; EXACTP is true if 2^K is the exact number of digits
1198                (cond ((zerop n)
1199                       (when exactp
1200                         (loop repeat (ash 1 k) do (write-char #\0 stream))))
1201                      ((zerop k)
1202                       (write-char
1203                        (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n)
1204                        stream))
1205                      (t
1206                       (setf k (1- k))
1207                       (multiple-value-bind (q r) (truncate n (aref power k))
1208                         ;; EXACTP is NIL only at the head of the
1209                         ;; initial number, as we don't know the number
1210                         ;; of digits there, but we do know that it
1211                         ;; doesn't get any leading zeros.
1212                         (bisect q k exactp)
1213                         (bisect r k (or exactp (plusp q))))))))
1214       (bisect n k-start nil))))
1215
1216 (defun %output-integer-in-base (integer base stream)
1217   (when (minusp integer)
1218     (write-char #\- stream)
1219     (setf integer (- integer)))
1220   ;; The ideal cutoff point between these two algorithms is almost
1221   ;; certainly quite platform dependent: this gives 87 for 32 bit
1222   ;; SBCL, which is about right at least for x86/Darwin.
1223   (if (or (fixnump integer)
1224           (< (integer-length integer) (* 3 sb!vm:n-positive-fixnum-bits)))
1225       (%output-reasonable-integer-in-base integer base stream)
1226       (%output-huge-integer-in-base integer base stream)))
1227
1228 (defun output-integer (integer stream)
1229   (let ((base *print-base*))
1230     (when (and (/= base 10) *print-radix*)
1231       (%output-radix base stream))
1232     (%output-integer-in-base integer base stream)
1233     (when (and *print-radix* (= base 10))
1234       (write-char #\. stream))))
1235
1236 (defun output-ratio (ratio stream)
1237   (let ((base *print-base*))
1238     (when *print-radix*
1239       (%output-radix base stream))
1240     (%output-integer-in-base (numerator ratio) base stream)
1241     (write-char #\/ stream)
1242     (%output-integer-in-base (denominator ratio) base stream)))
1243
1244 (defun output-complex (complex stream)
1245   (write-string "#C(" stream)
1246   ;; FIXME: Could this just be OUTPUT-NUMBER?
1247   (output-object (realpart complex) stream)
1248   (write-char #\space stream)
1249   (output-object (imagpart complex) stream)
1250   (write-char #\) stream))
1251 \f
1252 ;;;; float printing
1253
1254 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1255 ;;; most of the work for all printing of floating point numbers in
1256 ;;; FORMAT.  It converts a floating point number to a string in a free
1257 ;;; or fixed format with no exponent. The interpretation of the
1258 ;;; arguments is as follows:
1259 ;;;
1260 ;;;     X       - The floating point number to convert, which must not be
1261 ;;;             negative.
1262 ;;;     WIDTH    - The preferred field width, used to determine the number
1263 ;;;             of fraction digits to produce if the FDIGITS parameter
1264 ;;;             is unspecified or NIL. If the non-fraction digits and the
1265 ;;;             decimal point alone exceed this width, no fraction digits
1266 ;;;             will be produced unless a non-NIL value of FDIGITS has been
1267 ;;;             specified. Field overflow is not considerd an error at this
1268 ;;;             level.
1269 ;;;     FDIGITS  - The number of fractional digits to produce. Insignificant
1270 ;;;             trailing zeroes may be introduced as needed. May be
1271 ;;;             unspecified or NIL, in which case as many digits as possible
1272 ;;;             are generated, subject to the constraint that there are no
1273 ;;;             trailing zeroes.
1274 ;;;     SCALE    - If this parameter is specified or non-NIL, then the number
1275 ;;;             printed is (* x (expt 10 scale)). This scaling is exact,
1276 ;;;             and cannot lose precision.
1277 ;;;     FMIN     - This parameter, if specified or non-NIL, is the minimum
1278 ;;;             number of fraction digits which will be produced, regardless
1279 ;;;             of the value of WIDTH or FDIGITS. This feature is used by
1280 ;;;             the ~E format directive to prevent complete loss of
1281 ;;;             significance in the printed value due to a bogus choice of
1282 ;;;             scale factor.
1283 ;;;
1284 ;;; Returns:
1285 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1286 ;;; where the results have the following interpretation:
1287 ;;;
1288 ;;;     DIGIT-STRING    - The decimal representation of X, with decimal point.
1289 ;;;     DIGIT-LENGTH    - The length of the string DIGIT-STRING.
1290 ;;;     LEADING-POINT   - True if the first character of DIGIT-STRING is the
1291 ;;;                    decimal point.
1292 ;;;     TRAILING-POINT  - True if the last character of DIGIT-STRING is the
1293 ;;;                    decimal point.
1294 ;;;     POINT-POS       - The position of the digit preceding the decimal
1295 ;;;                    point. Zero indicates point before first digit.
1296 ;;;
1297 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1298 ;;; accuracy. Specifically, the decimal number printed is the closest
1299 ;;; possible approximation to the true value of the binary number to
1300 ;;; be printed from among all decimal representations with the same
1301 ;;; number of digits. In free-format output, i.e. with the number of
1302 ;;; digits unconstrained, it is guaranteed that all the information is
1303 ;;; preserved, so that a properly- rounding reader can reconstruct the
1304 ;;; original binary number, bit-for-bit, from its printed decimal
1305 ;;; representation. Furthermore, only as many digits as necessary to
1306 ;;; satisfy this condition will be printed.
1307 ;;;
1308 ;;; FLOAT-DIGITS actually generates the digits for positive numbers;
1309 ;;; see below for comments.
1310
1311 (defun flonum-to-string (x &optional width fdigits scale fmin)
1312   (declare (type float x))
1313   ;; FIXME: I think only FORMAT-DOLLARS calls FLONUM-TO-STRING with
1314   ;; possibly-negative X.
1315   (setf x (abs x))
1316   (multiple-value-bind (e string)
1317       (if fdigits
1318           (flonum-to-digits x (min (- (+ fdigits (or scale 0)))
1319                                    (- (or fmin 0))))
1320           (if (and width (> width 1))
1321               (let ((w (multiple-value-list
1322                         (flonum-to-digits x
1323                                           (max 1
1324                                                (+ (1- width)
1325                                                   (if (and scale (minusp scale))
1326                                                       scale 0)))
1327                                           t)))
1328                     (f (multiple-value-list
1329                         (flonum-to-digits x (- (+ (or fmin 0)
1330                                                   (if scale scale 0)))))))
1331                 (cond
1332                   ((>= (length (cadr w)) (length (cadr f)))
1333                    (values-list w))
1334                   (t (values-list f))))
1335               (flonum-to-digits x)))
1336     (let ((e (+ e (or scale 0)))
1337           (stream (make-string-output-stream)))
1338       (if (plusp e)
1339           (progn
1340             (write-string string stream :end (min (length string) e))
1341             (dotimes (i (- e (length string)))
1342               (write-char #\0 stream))
1343             (write-char #\. stream)
1344             (write-string string stream :start (min (length string) e))
1345             (when fdigits
1346               (dotimes (i (- fdigits
1347                              (- (length string)
1348                                 (min (length string) e))))
1349                 (write-char #\0 stream))))
1350           (progn
1351             (write-string "." stream)
1352             (dotimes (i (- e))
1353               (write-char #\0 stream))
1354             (write-string string stream)
1355             (when fdigits
1356               (dotimes (i (+ fdigits e (- (length string))))
1357                 (write-char #\0 stream)))))
1358       (let ((string (get-output-stream-string stream)))
1359         (values string (length string)
1360                 (char= (char string 0) #\.)
1361                 (char= (char string (1- (length string))) #\.)
1362                 (position #\. string))))))
1363
1364 ;;; implementation of figure 1 from Burger and Dybvig, 1996. It is
1365 ;;; extended in order to handle rounding.
1366 ;;;
1367 ;;; As the implementation of the Dragon from Classic CMUCL (and
1368 ;;; previously in SBCL above FLONUM-TO-STRING) says: "DO NOT EVEN
1369 ;;; THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE
1370 ;;; PAPER!", and in this case we have to add that even reading the
1371 ;;; paper might not bring immediate illumination as CSR has attempted
1372 ;;; to turn idiomatic Scheme into idiomatic Lisp.
1373 ;;;
1374 ;;; FIXME: figure 1 from Burger and Dybvig is the unoptimized
1375 ;;; algorithm, noticeably slow at finding the exponent.  Figure 2 has
1376 ;;; an improved algorithm, but CSR ran out of energy.
1377 ;;;
1378 ;;; possible extension for the enthusiastic: printing floats in bases
1379 ;;; other than base 10.
1380 (defconstant single-float-min-e
1381   (- 2 sb!vm:single-float-bias sb!vm:single-float-digits))
1382 (defconstant double-float-min-e
1383   (- 2 sb!vm:double-float-bias sb!vm:double-float-digits))
1384 #!+long-float
1385 (defconstant long-float-min-e
1386   (nth-value 1 (decode-float least-positive-long-float)))
1387
1388 (defun flonum-to-digits (v &optional position relativep)
1389   (let ((print-base 10) ; B
1390         (float-radix 2) ; b
1391         (float-digits (float-digits v)) ; p
1392         (digit-characters "0123456789")
1393         (min-e
1394          (etypecase v
1395            (single-float single-float-min-e)
1396            (double-float double-float-min-e)
1397            #!+long-float
1398            (long-float long-float-min-e))))
1399     (multiple-value-bind (f e)
1400         (integer-decode-float v)
1401       (let (;; FIXME: these even tests assume normal IEEE rounding
1402             ;; mode.  I wonder if we should cater for non-normal?
1403             (high-ok (evenp f))
1404             (low-ok (evenp f)))
1405         (with-push-char (:element-type base-char)
1406           (labels ((scale (r s m+ m-)
1407                      (do ((k 0 (1+ k))
1408                           (s s (* s print-base)))
1409                          ((not (or (> (+ r m+) s)
1410                                    (and high-ok (= (+ r m+) s))))
1411                           (do ((k k (1- k))
1412                                (r r (* r print-base))
1413                                (m+ m+ (* m+ print-base))
1414                                (m- m- (* m- print-base)))
1415                               ((not (and (plusp (- r m-)) ; Extension to handle zero
1416                                          (or (< (* (+ r m+) print-base) s)
1417                                              (and (not high-ok)
1418                                                   (= (* (+ r m+) print-base) s)))))
1419                                (values k (generate r s m+ m-)))))))
1420                    (generate (r s m+ m-)
1421                      (let (d tc1 tc2)
1422                        (tagbody
1423                         loop
1424                           (setf (values d r) (truncate (* r print-base) s))
1425                           (setf m+ (* m+ print-base))
1426                           (setf m- (* m- print-base))
1427                           (setf tc1 (or (< r m-) (and low-ok (= r m-))))
1428                           (setf tc2 (or (> (+ r m+) s)
1429                                         (and high-ok (= (+ r m+) s))))
1430                           (when (or tc1 tc2)
1431                             (go end))
1432                           (push-char (char digit-characters d))
1433                           (go loop)
1434                         end
1435                           (let ((d (cond
1436                                      ((and (not tc1) tc2) (1+ d))
1437                                      ((and tc1 (not tc2)) d)
1438                                      (t ; (and tc1 tc2)
1439                                       (if (< (* r 2) s) d (1+ d))))))
1440                             (push-char (char digit-characters d))
1441                             (return-from generate (get-pushed-string))))))
1442                    (initialize ()
1443                      (let (r s m+ m-)
1444                        (if (>= e 0)
1445                            (let* ((be (expt float-radix e))
1446                                   (be1 (* be float-radix)))
1447                              (if (/= f (expt float-radix (1- float-digits)))
1448                                  (setf r (* f be 2)
1449                                        s 2
1450                                        m+ be
1451                                        m- be)
1452                                  (setf r (* f be1 2)
1453                                        s (* float-radix 2)
1454                                        m+ be1
1455                                        m- be)))
1456                            (if (or (= e min-e)
1457                                    (/= f (expt float-radix (1- float-digits))))
1458                                (setf r (* f 2)
1459                                      s (* (expt float-radix (- e)) 2)
1460                                      m+ 1
1461                                      m- 1)
1462                                (setf r (* f float-radix 2)
1463                                      s (* (expt float-radix (- 1 e)) 2)
1464                                      m+ float-radix
1465                                      m- 1)))
1466                        (when position
1467                          (when relativep
1468                            (aver (> position 0))
1469                            (do ((k 0 (1+ k))
1470                                 ;; running out of letters here
1471                                 (l 1 (* l print-base)))
1472                                ((>= (* s l) (+ r m+))
1473                                 ;; k is now \hat{k}
1474                                 (if (< (+ r (* s (/ (expt print-base (- k position)) 2)))
1475                                        (* s (expt print-base k)))
1476                                     (setf position (- k position))
1477                                     (setf position (- k position 1))))))
1478                          (let ((low (max m- (/ (* s (expt print-base position)) 2)))
1479                                (high (max m+ (/ (* s (expt print-base position)) 2))))
1480                            (when (<= m- low)
1481                              (setf m- low)
1482                              (setf low-ok t))
1483                            (when (<= m+ high)
1484                              (setf m+ high)
1485                              (setf high-ok t))))
1486                        (values r s m+ m-))))
1487             (multiple-value-bind (r s m+ m-) (initialize)
1488               (scale r s m+ m-))))))))
1489 \f
1490 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns
1491 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1492 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1493 ;;; original number. There may be some loss of precision due the
1494 ;;; floating point representation. The scaling is always done with
1495 ;;; long float arithmetic, which helps printing of lesser precisions
1496 ;;; as well as avoiding generic arithmetic.
1497 ;;;
1498 ;;; When computing our initial scale factor using EXPT, we pull out
1499 ;;; part of the computation to avoid over/under flow. When
1500 ;;; denormalized, we must pull out a large factor, since there is more
1501 ;;; negative exponent range than positive range.
1502
1503 (eval-when (:compile-toplevel :execute)
1504   (setf *read-default-float-format*
1505         #!+long-float 'long-float #!-long-float 'double-float))
1506 (defun scale-exponent (original-x)
1507   (let* ((x (coerce original-x 'long-float)))
1508     (multiple-value-bind (sig exponent) (decode-float x)
1509       (declare (ignore sig))
1510       (if (= x 0.0e0)
1511           (values (float 0.0e0 original-x) 1)
1512           (let* ((ex (locally (declare (optimize (safety 0)))
1513                        (the fixnum
1514                          (round (* exponent
1515                                    ;; this is the closest double float
1516                                    ;; to (log 2 10), but expressed so
1517                                    ;; that we're not vulnerable to the
1518                                    ;; host lisp's interpretation of
1519                                    ;; arithmetic.  (FIXME: it turns
1520                                    ;; out that sbcl itself is off by 1
1521                                    ;; ulp in this value, which is a
1522                                    ;; little unfortunate.)
1523                                    (load-time-value
1524                                     #!-long-float
1525                                     (sb!kernel:make-double-float 1070810131 1352628735)
1526                                     #!+long-float
1527                                     (error "(log 2 10) not computed")))))))
1528                  (x (if (minusp ex)
1529                         (if (float-denormalized-p x)
1530                             #!-long-float
1531                             (* x 1.0e16 (expt 10.0e0 (- (- ex) 16)))
1532                             #!+long-float
1533                             (* x 1.0e18 (expt 10.0e0 (- (- ex) 18)))
1534                             (* x 10.0e0 (expt 10.0e0 (- (- ex) 1))))
1535                         (/ x 10.0e0 (expt 10.0e0 (1- ex))))))
1536             (do ((d 10.0e0 (* d 10.0e0))
1537                  (y x (/ x d))
1538                  (ex ex (1+ ex)))
1539                 ((< y 1.0e0)
1540                  (do ((m 10.0e0 (* m 10.0e0))
1541                       (z y (* y m))
1542                       (ex ex (1- ex)))
1543                      ((>= z 0.1e0)
1544                       (values (float z original-x) ex))
1545                    (declare (long-float m) (integer ex))))
1546               (declare (long-float d))))))))
1547 (eval-when (:compile-toplevel :execute)
1548   (setf *read-default-float-format* 'single-float))
1549 \f
1550 ;;;; entry point for the float printer
1551
1552 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1553 ;;; argument is printed free-format, in either exponential or
1554 ;;; non-exponential notation, depending on its magnitude.
1555 ;;;
1556 ;;; NOTE: When a number is to be printed in exponential format, it is
1557 ;;; scaled in floating point. Since precision may be lost in this
1558 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1559 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1560 ;;; extensive computations with integers of similar magnitude to that
1561 ;;; of the number being printed. For large exponents, the bignums
1562 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1563 ;;; fast and the exponent range is not too large, then it might become
1564 ;;; attractive to handle exponential notation with the same accuracy
1565 ;;; as non-exponential notation, using the method described in the
1566 ;;; Steele and White paper.
1567 ;;;
1568 ;;; NOTE II: this has been bypassed slightly by implementing Burger
1569 ;;; and Dybvig, 1996.  When someone has time (KLUDGE) they can
1570 ;;; probably (a) implement the optimizations suggested by Burger and
1571 ;;; Dyvbig, and (b) remove all vestiges of Dragon4, including from
1572 ;;; fixed-format printing.
1573
1574 ;;; Print the appropriate exponent marker for X and the specified exponent.
1575 (defun print-float-exponent (x exp stream)
1576   (declare (type float x) (type integer exp) (type stream stream))
1577   (let ((*print-radix* nil))
1578     (if (typep x *read-default-float-format*)
1579         (unless (eql exp 0)
1580           (format stream "e~D" exp))
1581         (format stream "~C~D"
1582                 (etypecase x
1583                   (single-float #\f)
1584                   (double-float #\d)
1585                   (short-float #\s)
1586                   (long-float #\L))
1587                 exp))))
1588
1589 (defun output-float-infinity (x stream)
1590   (declare (float x) (stream stream))
1591   (cond (*read-eval*
1592          (write-string "#." stream))
1593         (*print-readably*
1594          (restart-case
1595              (error 'print-not-readable :object x)
1596            (print-unreadably ()
1597              :report "Print unreadably."
1598              (let ((*print-readably* nil))
1599                (output-float-infinity x stream)))
1600            (use-value (o)
1601              :report "Supply an object to be printed instead."
1602              :interactive read-unreadable-replacement
1603              (write o :stream stream))))
1604         (t
1605          (write-string "#<" stream)))
1606   (write-string "SB-EXT:" stream)
1607   (write-string (symbol-name (float-format-name x)) stream)
1608   (write-string (if (plusp x) "-POSITIVE-" "-NEGATIVE-")
1609                 stream)
1610   (write-string "INFINITY" stream)
1611   (unless *read-eval*
1612     (write-string ">" stream)))
1613
1614 (defun output-float-nan (x stream)
1615   (print-unreadable-object (x stream)
1616     (princ (float-format-name x) stream)
1617     (write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
1618     (write-string " NaN" stream)))
1619
1620 ;;; the function called by OUTPUT-OBJECT to handle floats
1621 (defun output-float (x stream)
1622   (cond
1623    ((float-infinity-p x)
1624     (output-float-infinity x stream))
1625    ((float-nan-p x)
1626     (output-float-nan x stream))
1627    (t
1628     (let ((x (cond ((minusp (float-sign x))
1629                     (write-char #\- stream)
1630                     (- x))
1631                    (t
1632                     x))))
1633       (cond
1634        ((zerop x)
1635         (write-string "0.0" stream)
1636         (print-float-exponent x 0 stream))
1637        (t
1638         (output-float-aux x stream -3 8)))))))
1639
1640 (defun output-float-aux (x stream e-min e-max)
1641   (multiple-value-bind (e string)
1642       (flonum-to-digits x)
1643     (cond
1644       ((< e-min e e-max)
1645        (if (plusp e)
1646            (progn
1647              (write-string string stream :end (min (length string) e))
1648              (dotimes (i (- e (length string)))
1649                (write-char #\0 stream))
1650              (write-char #\. stream)
1651              (write-string string stream :start (min (length string) e))
1652              (when (<= (length string) e)
1653                (write-char #\0 stream))
1654              (print-float-exponent x 0 stream))
1655            (progn
1656              (write-string "0." stream)
1657              (dotimes (i (- e))
1658                (write-char #\0 stream))
1659              (write-string string stream)
1660              (print-float-exponent x 0 stream))))
1661       (t (write-string string stream :end 1)
1662          (write-char #\. stream)
1663          (write-string string stream :start 1)
1664          (print-float-exponent x (1- e) stream)))))
1665 \f
1666 ;;;; other leaf objects
1667
1668 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1669 ;;; the character name or the character in the #\char format.
1670 (defun output-character (char stream)
1671   (if (or *print-escape* *print-readably*)
1672       (let ((graphicp (and (graphic-char-p char)
1673                            (standard-char-p char)))
1674             (name (char-name char)))
1675         (write-string "#\\" stream)
1676         (if (and name (not graphicp))
1677             (quote-string name stream)
1678             (write-char char stream)))
1679       (write-char char stream)))
1680
1681 (defun output-sap (sap stream)
1682   (declare (type system-area-pointer sap))
1683   (cond (*read-eval*
1684          (format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
1685         (t
1686          (print-unreadable-object (sap stream)
1687            (format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
1688
1689 (defun output-weak-pointer (weak-pointer stream)
1690   (declare (type weak-pointer weak-pointer))
1691   (print-unreadable-object (weak-pointer stream)
1692     (multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
1693       (cond (validp
1694              (write-string "weak pointer: " stream)
1695              (write value :stream stream))
1696             (t
1697              (write-string "broken weak pointer" stream))))))
1698
1699 (defun output-code-component (component stream)
1700   (print-unreadable-object (component stream :identity t)
1701     (let ((dinfo (%code-debug-info component)))
1702       (cond ((eq dinfo :bogus-lra)
1703              (write-string "bogus code object" stream))
1704             (t
1705              (write-string "code object" stream)
1706              (when dinfo
1707                (write-char #\space stream)
1708                (output-object (sb!c::debug-info-name dinfo) stream)))))))
1709
1710 (defun output-lra (lra stream)
1711   (print-unreadable-object (lra stream :identity t)
1712     (write-string "return PC object" stream)))
1713
1714 (defun output-fdefn (fdefn stream)
1715   (print-unreadable-object (fdefn stream)
1716     (write-string "FDEFINITION object for " stream)
1717     (output-object (fdefn-name fdefn) stream)))
1718 \f
1719 ;;;; functions
1720
1721 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1722 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1723 ;;;
1724 ;;; The definition here is a simple temporary placeholder. It will be
1725 ;;; overwritten by a smarter version (capable of calling generic
1726 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1727 (defun printed-as-funcallable-standard-class (object stream)
1728   (declare (ignore object stream))
1729   nil)
1730
1731 (defun output-fun (object stream)
1732     (let* ((*print-length* 3)  ; in case we have to..
1733            (*print-level* 3)  ; ..print an interpreted function definition
1734            (name (%fun-name object))
1735            (proper-name-p (and (legal-fun-name-p name) (fboundp name)
1736                                (eq (fdefinition name) object))))
1737       (print-unreadable-object (object stream :identity (not proper-name-p))
1738         (format stream "~:[FUNCTION~;CLOSURE~]~@[ ~S~]"
1739                 (closurep object)
1740                 name))))
1741 \f
1742 ;;;; catch-all for unknown things
1743
1744 (defun output-random (object stream)
1745   (print-unreadable-object (object stream :identity t)
1746     (let ((lowtag (lowtag-of object)))
1747       (case lowtag
1748         (#.sb!vm:other-pointer-lowtag
1749           (let ((widetag (widetag-of object)))
1750             (case widetag
1751               (#.sb!vm:value-cell-header-widetag
1752                (write-string "value cell " stream)
1753                (output-object (value-cell-ref object) stream))
1754               (t
1755                (write-string "unknown pointer object, widetag=" stream)
1756                (let ((*print-base* 16) (*print-radix* t))
1757                  (output-integer widetag stream))))))
1758         ((#.sb!vm:fun-pointer-lowtag
1759           #.sb!vm:instance-pointer-lowtag
1760           #.sb!vm:list-pointer-lowtag)
1761          (write-string "unknown pointer object, lowtag=" stream)
1762          (let ((*print-base* 16) (*print-radix* t))
1763            (output-integer lowtag stream)))
1764         (t
1765          (case (widetag-of object)
1766            (#.sb!vm:unbound-marker-widetag
1767             (write-string "unbound marker" stream))
1768            (t
1769             (write-string "unknown immediate object, lowtag=" stream)
1770             (let ((*print-base* 2) (*print-radix* t))
1771               (output-integer lowtag stream))
1772             (write-string ", widetag=" stream)
1773             (let ((*print-base* 16) (*print-radix* t))
1774               (output-integer (widetag-of object) stream)))))))))