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