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