Additional niceties and middle end support for short vector SIMD packs
[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     #!+sb-simd-pack
528     (simd-pack
529      (output-simd-pack object stream))
530     (t
531      (output-random object stream))))
532 \f
533 ;;;; symbols
534
535 ;;; values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last
536 ;;; time the printer was called
537 (defvar *previous-case* nil)
538 (defvar *previous-readtable-case* nil)
539
540 ;;; This variable contains the current definition of one of three
541 ;;; symbol printers. SETUP-PRINTER-STATE sets this variable.
542 (defvar *internal-symbol-output-fun* nil)
543
544 ;;; This function sets the internal global symbol
545 ;;; *INTERNAL-SYMBOL-OUTPUT-FUN* to the right function depending on
546 ;;; the value of *PRINT-CASE*. See the manual for details. The print
547 ;;; buffer stream is also reset.
548 (defun setup-printer-state ()
549   (unless (and (eq *print-case* *previous-case*)
550                (eq (readtable-case *readtable*) *previous-readtable-case*))
551     (setq *previous-case* *print-case*)
552     (setq *previous-readtable-case* (readtable-case *readtable*))
553     (unless (member *print-case* '(:upcase :downcase :capitalize))
554       (setq *print-case* :upcase)
555       (error "invalid *PRINT-CASE* value: ~S" *previous-case*))
556     (unless (member *previous-readtable-case*
557                     '(:upcase :downcase :invert :preserve))
558       (setf (readtable-case *readtable*) :upcase)
559       (error "invalid READTABLE-CASE value: ~S" *previous-readtable-case*))
560
561     (setq *internal-symbol-output-fun*
562           (case *previous-readtable-case*
563             (:upcase
564              (case *print-case*
565                (:upcase #'output-preserve-symbol)
566                (:downcase #'output-lowercase-symbol)
567                (:capitalize #'output-capitalize-symbol)))
568             (:downcase
569              (case *print-case*
570                (:upcase #'output-uppercase-symbol)
571                (:downcase #'output-preserve-symbol)
572                (:capitalize #'output-capitalize-symbol)))
573             (:preserve #'output-preserve-symbol)
574             (:invert #'output-invert-symbol)))))
575
576 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
577 ;;; and with any embedded |'s or \'s escaped.
578 (defun output-quoted-symbol-name (pname stream)
579   (write-char #\| stream)
580   (dotimes (index (length pname))
581     (let ((char (schar pname index)))
582       (when (or (char= char #\\) (char= char #\|))
583         (write-char #\\ stream))
584       (write-char char stream)))
585   (write-char #\| stream))
586
587 (defun output-symbol (object stream)
588   (if (or *print-escape* *print-readably*)
589       (let ((package (symbol-package object))
590             (name (symbol-name object))
591             (current (sane-package)))
592         (cond
593          ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
594          ;; requires that keywords be printed with preceding colons
595          ;; always, regardless of the value of *PACKAGE*.
596          ((eq package *keyword-package*)
597           (write-char #\: stream))
598          ;; Otherwise, if the symbol's home package is the current
599          ;; one, then a prefix is never necessary.
600          ((eq package current))
601          ;; Uninterned symbols print with a leading #:.
602          ((null package)
603           (when (or *print-gensym* *print-readably*)
604             (write-string "#:" stream)))
605          (t
606           (multiple-value-bind (symbol accessible)
607               (find-symbol name current)
608             ;; If we can find the symbol by looking it up, it need not
609             ;; be qualified. This can happen if the symbol has been
610             ;; inherited from a package other than its home package.
611             ;;
612             ;; To preserve print-read consistency, use the local nickname if
613             ;; one exists.
614             (unless (and accessible (eq symbol object))
615               (let ((prefix (or (car (rassoc package (package-%local-nicknames current)))
616                                 (package-name package))))
617                 (output-symbol-name prefix stream))
618               (multiple-value-bind (symbol externalp)
619                   (find-external-symbol name package)
620                 (declare (ignore symbol))
621                 (if externalp
622                     (write-char #\: stream)
623                     (write-string "::" stream)))))))
624         (output-symbol-name name stream))
625       (output-symbol-name (symbol-name object) stream nil)))
626
627 ;;; Output the string NAME as if it were a symbol name. In other
628 ;;; words, diddle its case according to *PRINT-CASE* and
629 ;;; READTABLE-CASE.
630 (defun output-symbol-name (name stream &optional (maybe-quote t))
631   (declare (type simple-string name))
632   (let ((*readtable* (if *print-readably* *standard-readtable* *readtable*)))
633     (setup-printer-state)
634     (if (and maybe-quote (symbol-quotep name))
635         (output-quoted-symbol-name name stream)
636         (funcall *internal-symbol-output-fun* name stream))))
637 \f
638 ;;;; escaping symbols
639
640 ;;; When we print symbols we have to figure out if they need to be
641 ;;; printed with escape characters. This isn't a whole lot easier than
642 ;;; reading symbols in the first place.
643 ;;;
644 ;;; For each character, the value of the corresponding element is a
645 ;;; fixnum with bits set corresponding to attributes that the
646 ;;; character has. At characters have at least one bit set, so we can
647 ;;; search for any character with a positive test.
648 (defvar *character-attributes*
649   (make-array 160 ; FIXME
650               :element-type '(unsigned-byte 16)
651               :initial-element 0))
652 (declaim (type (simple-array (unsigned-byte 16) (#.160)) ; FIXME
653                *character-attributes*))
654
655 ;;; constants which are a bit-mask for each interesting character attribute
656 (defconstant other-attribute            (ash 1 0)) ; Anything else legal.
657 (defconstant number-attribute           (ash 1 1)) ; A numeric digit.
658 (defconstant uppercase-attribute        (ash 1 2)) ; An uppercase letter.
659 (defconstant lowercase-attribute        (ash 1 3)) ; A lowercase letter.
660 (defconstant sign-attribute             (ash 1 4)) ; +-
661 (defconstant extension-attribute        (ash 1 5)) ; ^_
662 (defconstant dot-attribute              (ash 1 6)) ; .
663 (defconstant slash-attribute            (ash 1 7)) ; /
664 (defconstant funny-attribute            (ash 1 8)) ; Anything illegal.
665
666 (eval-when (:compile-toplevel :load-toplevel :execute)
667
668 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
669 ;;; that don't need to be escaped (according to READTABLE-CASE.)
670 (defparameter *attribute-names*
671   `((number . number-attribute) (lowercase . lowercase-attribute)
672     (uppercase . uppercase-attribute) (letter . letter-attribute)
673     (sign . sign-attribute) (extension . extension-attribute)
674     (dot . dot-attribute) (slash . slash-attribute)
675     (other . other-attribute) (funny . funny-attribute)))
676
677 ) ; EVAL-WHEN
678
679 (flet ((set-bit (char bit)
680          (let ((code (char-code char)))
681            (setf (aref *character-attributes* code)
682                  (logior bit (aref *character-attributes* code))))))
683
684   (dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
685                   #\? #\< #\>))
686     (set-bit char other-attribute))
687
688   (dotimes (i 10)
689     (set-bit (digit-char i) number-attribute))
690
691   (do ((code (char-code #\A) (1+ code))
692        (end (char-code #\Z)))
693       ((> code end))
694     (declare (fixnum code end))
695     (set-bit (code-char code) uppercase-attribute)
696     (set-bit (char-downcase (code-char code)) lowercase-attribute))
697
698   (set-bit #\- sign-attribute)
699   (set-bit #\+ sign-attribute)
700   (set-bit #\^ extension-attribute)
701   (set-bit #\_ extension-attribute)
702   (set-bit #\. dot-attribute)
703   (set-bit #\/ slash-attribute)
704
705   ;; Mark anything not explicitly allowed as funny.
706   (dotimes (i 160) ; FIXME
707     (when (zerop (aref *character-attributes* i))
708       (setf (aref *character-attributes* i) funny-attribute))))
709
710 ;;; For each character, the value of the corresponding element is the
711 ;;; lowest base in which that character is a digit.
712 (defvar *digit-bases*
713   (make-array 128 ; FIXME
714               :element-type '(unsigned-byte 8)
715               :initial-element 36))
716 (declaim (type (simple-array (unsigned-byte 8) (#.128)) ; FIXME
717                *digit-bases*))
718 (dotimes (i 36)
719   (let ((char (digit-char i 36)))
720     (setf (aref *digit-bases* (char-code char)) i)))
721
722 ;;; A FSM-like thingie that determines whether a symbol is a potential
723 ;;; number or has evil characters in it.
724 (defun symbol-quotep (name)
725   (declare (simple-string name))
726   (macrolet ((advance (tag &optional (at-end t))
727                `(progn
728                  (when (= index len)
729                    ,(if at-end '(go TEST-SIGN) '(return nil)))
730                  (setq current (schar name index)
731                        code (char-code current)
732                        bits (cond ; FIXME
733                               ((< code 160) (aref attributes code))
734                               ((upper-case-p current) uppercase-attribute)
735                               ((lower-case-p current) lowercase-attribute)
736                               (t other-attribute)))
737                  (incf index)
738                  (go ,tag)))
739              (test (&rest attributes)
740                 `(not (zerop
741                        (the fixnum
742                             (logand
743                              (logior ,@(mapcar
744                                         (lambda (x)
745                                           (or (cdr (assoc x
746                                                           *attribute-names*))
747                                               (error "Blast!")))
748                                         attributes))
749                              bits)))))
750              (digitp ()
751                `(and (< code 128) ; FIXME
752                      (< (the fixnum (aref bases code)) base))))
753
754     (prog ((len (length name))
755            (attributes *character-attributes*)
756            (bases *digit-bases*)
757            (base *print-base*)
758            (letter-attribute
759             (case (readtable-case *readtable*)
760               (:upcase uppercase-attribute)
761               (:downcase lowercase-attribute)
762               (t (logior lowercase-attribute uppercase-attribute))))
763            (index 0)
764            (bits 0)
765            (code 0)
766            current)
767       (declare (fixnum len base index bits code))
768       (advance START t)
769
770      TEST-SIGN ; At end, see whether it is a sign...
771       (return (not (test sign)))
772
773      OTHER ; not potential number, see whether funny chars...
774       (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
775                                   funny-attribute)
776                           letter-attribute)))
777         (do ((i (1- index) (1+ i)))
778             ((= i len) (return-from symbol-quotep nil))
779           (unless (zerop (logand (let* ((char (schar name i))
780                                         (code (char-code char)))
781                                    (cond
782                                      ((< code 160) (aref attributes code))
783                                      ((upper-case-p char) uppercase-attribute)
784                                      ((lower-case-p char) lowercase-attribute)
785                                      (t other-attribute)))
786                                  mask))
787             (return-from symbol-quotep t))))
788
789      START
790       (when (digitp)
791         (if (test letter)
792             (advance LAST-DIGIT-ALPHA)
793             (advance DIGIT)))
794       (when (test letter number other slash) (advance OTHER nil))
795       (when (char= current #\.) (advance DOT-FOUND))
796       (when (test sign extension) (advance START-STUFF nil))
797       (return t)
798
799      DOT-FOUND ; leading dots...
800       (when (test letter) (advance START-DOT-MARKER nil))
801       (when (digitp) (advance DOT-DIGIT))
802       (when (test number other) (advance OTHER nil))
803       (when (test extension slash sign) (advance START-DOT-STUFF nil))
804       (when (char= current #\.) (advance DOT-FOUND))
805       (return t)
806
807      START-STUFF ; leading stuff before any dot or digit
808       (when (digitp)
809         (if (test letter)
810             (advance LAST-DIGIT-ALPHA)
811             (advance DIGIT)))
812       (when (test number other) (advance OTHER nil))
813       (when (test letter) (advance START-MARKER nil))
814       (when (char= current #\.) (advance START-DOT-STUFF nil))
815       (when (test sign extension slash) (advance START-STUFF nil))
816       (return t)
817
818      START-MARKER ; number marker in leading stuff...
819       (when (test letter) (advance OTHER nil))
820       (go START-STUFF)
821
822      START-DOT-STUFF ; leading stuff containing dot without digit...
823       (when (test letter) (advance START-DOT-STUFF nil))
824       (when (digitp) (advance DOT-DIGIT))
825       (when (test sign extension dot slash) (advance START-DOT-STUFF nil))
826       (when (test number other) (advance OTHER nil))
827       (return t)
828
829      START-DOT-MARKER ; number marker in leading stuff with dot..
830       ;; leading stuff containing dot without digit followed by letter...
831       (when (test letter) (advance OTHER nil))
832       (go START-DOT-STUFF)
833
834      DOT-DIGIT ; in a thing with dots...
835       (when (test letter) (advance DOT-MARKER))
836       (when (digitp) (advance DOT-DIGIT))
837       (when (test number other) (advance OTHER nil))
838       (when (test sign extension dot slash) (advance DOT-DIGIT))
839       (return t)
840
841      DOT-MARKER ; number marker in number with dot...
842       (when (test letter) (advance OTHER nil))
843       (go DOT-DIGIT)
844
845      LAST-DIGIT-ALPHA ; previous char is a letter digit...
846       (when (or (digitp) (test sign slash))
847         (advance ALPHA-DIGIT))
848       (when (test letter number other dot) (advance OTHER nil))
849       (return t)
850
851      ALPHA-DIGIT ; seen a digit which is a letter...
852       (when (or (digitp) (test sign slash))
853         (if (test letter)
854             (advance LAST-DIGIT-ALPHA)
855             (advance ALPHA-DIGIT)))
856       (when (test letter) (advance ALPHA-MARKER))
857       (when (test number other dot) (advance OTHER nil))
858       (return t)
859
860      ALPHA-MARKER ; number marker in number with alpha digit...
861       (when (test letter) (advance OTHER nil))
862       (go ALPHA-DIGIT)
863
864      DIGIT ; seen only ordinary (non-alphabetic) numeric digits...
865       (when (digitp)
866         (if (test letter)
867             (advance ALPHA-DIGIT)
868             (advance DIGIT)))
869       (when (test number other) (advance OTHER nil))
870       (when (test letter) (advance MARKER))
871       (when (test extension slash sign) (advance DIGIT))
872       (when (char= current #\.) (advance DOT-DIGIT))
873       (return t)
874
875      MARKER ; number marker in a numeric number...
876       ;; ("What," you may ask, "is a 'number marker'?" It's something
877       ;; that a conforming implementation might use in number syntax.
878       ;; See ANSI 2.3.1.1 "Potential Numbers as Tokens".)
879       (when (test letter) (advance OTHER nil))
880       (go DIGIT))))
881 \f
882 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN*
883 ;;;;
884 ;;;; case hackery: These functions are stored in
885 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN* according to the values of
886 ;;;; *PRINT-CASE* and READTABLE-CASE.
887
888 ;;; called when:
889 ;;; READTABLE-CASE      *PRINT-CASE*
890 ;;; :UPCASE             :UPCASE
891 ;;; :DOWNCASE           :DOWNCASE
892 ;;; :PRESERVE           any
893 (defun output-preserve-symbol (pname stream)
894   (declare (simple-string pname))
895   (write-string pname stream))
896
897 ;;; called when:
898 ;;; READTABLE-CASE      *PRINT-CASE*
899 ;;; :UPCASE             :DOWNCASE
900 (defun output-lowercase-symbol (pname stream)
901   (declare (simple-string pname))
902   (dotimes (index (length pname))
903     (let ((char (schar pname index)))
904       (write-char (char-downcase char) stream))))
905
906 ;;; called when:
907 ;;; READTABLE-CASE      *PRINT-CASE*
908 ;;; :DOWNCASE           :UPCASE
909 (defun output-uppercase-symbol (pname stream)
910   (declare (simple-string pname))
911   (dotimes (index (length pname))
912     (let ((char (schar pname index)))
913       (write-char (char-upcase char) stream))))
914
915 ;;; called when:
916 ;;; READTABLE-CASE      *PRINT-CASE*
917 ;;; :UPCASE             :CAPITALIZE
918 ;;; :DOWNCASE           :CAPITALIZE
919 (defun output-capitalize-symbol (pname stream)
920   (declare (simple-string pname))
921   (let ((prev-not-alphanum t)
922         (up (eq (readtable-case *readtable*) :upcase)))
923     (dotimes (i (length pname))
924       (let ((char (char pname i)))
925         (write-char (if up
926                         (if (or prev-not-alphanum (lower-case-p char))
927                             char
928                             (char-downcase char))
929                         (if prev-not-alphanum
930                             (char-upcase char)
931                             char))
932                     stream)
933         (setq prev-not-alphanum (not (alphanumericp char)))))))
934
935 ;;; called when:
936 ;;; READTABLE-CASE      *PRINT-CASE*
937 ;;; :INVERT             any
938 (defun output-invert-symbol (pname stream)
939   (declare (simple-string pname))
940   (let ((all-upper t)
941         (all-lower t))
942     (dotimes (i (length pname))
943       (let ((ch (schar pname i)))
944         (when (both-case-p ch)
945           (if (upper-case-p ch)
946               (setq all-lower nil)
947               (setq all-upper nil)))))
948     (cond (all-upper (output-lowercase-symbol pname stream))
949           (all-lower (output-uppercase-symbol pname stream))
950           (t
951            (write-string pname stream)))))
952
953 #|
954 (defun test1 ()
955   (let ((*readtable* (copy-readtable nil)))
956     (format t "READTABLE-CASE  Input   Symbol-name~@
957                ----------------------------------~%")
958     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
959       (setf (readtable-case *readtable*) readtable-case)
960       (dolist (input '("ZEBRA" "Zebra" "zebra"))
961         (format t "~&:~A~16T~A~24T~A"
962                 (string-upcase readtable-case)
963                 input
964                 (symbol-name (read-from-string input)))))))
965
966 (defun test2 ()
967   (let ((*readtable* (copy-readtable nil)))
968     (format t "READTABLE-CASE  *PRINT-CASE*  Symbol-name  Output  Princ~@
969                --------------------------------------------------------~%")
970     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
971       (setf (readtable-case *readtable*) readtable-case)
972       (dolist (*print-case* '(:upcase :downcase :capitalize))
973         (dolist (symbol '(|ZEBRA| |Zebra| |zebra|))
974           (format t "~&:~A~15T:~A~29T~A~42T~A~50T~A"
975                   (string-upcase readtable-case)
976                   (string-upcase *print-case*)
977                   (symbol-name symbol)
978                   (prin1-to-string symbol)
979                   (princ-to-string symbol)))))))
980 |#
981 \f
982 ;;;; recursive objects
983
984 (defun output-list (list stream)
985   (descend-into (stream)
986     (write-char #\( stream)
987     (let ((length 0)
988           (list list))
989       (loop
990         (punt-print-if-too-long length stream)
991         (output-object (pop list) stream)
992         (unless list
993           (return))
994         (when (or (atom list)
995                   (check-for-circularity list))
996           (write-string " . " stream)
997           (output-object list stream)
998           (return))
999         (write-char #\space stream)
1000         (incf length)))
1001     (write-char #\) stream)))
1002
1003 (defun output-unreadable-vector-readably (vector stream)
1004   (declare (vector vector))
1005   (write-string "#." stream)
1006   (write `(coerce ,(coerce vector '(vector t))
1007                   '(simple-array ,(array-element-type vector) (*)))
1008          :stream stream))
1009
1010 (defun output-vector (vector stream)
1011   (declare (vector vector))
1012   (cond ((stringp vector)
1013          (cond ((and *print-readably*
1014                      (not (eq (array-element-type vector)
1015                               (load-time-value
1016                                (array-element-type
1017                                 (make-array 0 :element-type 'character))))))
1018                 (print-not-readable-error vector stream))
1019                ((or *print-escape* *print-readably*)
1020                 (write-char #\" stream)
1021                 (quote-string vector stream)
1022                 (write-char #\" stream))
1023                (t
1024                 (write-string vector stream))))
1025         ((not (or *print-array* *print-readably*))
1026          (output-terse-array vector stream))
1027         ((bit-vector-p vector)
1028          (write-string "#*" stream)
1029          (dovector (bit vector)
1030            ;; (Don't use OUTPUT-OBJECT here, since this code
1031            ;; has to work for all possible *PRINT-BASE* values.)
1032            (write-char (if (zerop bit) #\0 #\1) stream)))
1033         ((or (not *print-readably*)
1034              (array-readably-printable-p vector))
1035          (descend-into (stream)
1036                        (write-string "#(" stream)
1037                        (dotimes (i (length vector))
1038                          (unless (zerop i)
1039                            (write-char #\space stream))
1040                          (punt-print-if-too-long i stream)
1041                          (output-object (aref vector i) stream))
1042                        (write-string ")" stream)))
1043         (*read-eval*
1044          (output-unreadable-vector-readably vector stream))
1045         (t
1046          (print-not-readable-error vector stream))))
1047
1048 ;;; This function outputs a string quoting characters sufficiently
1049 ;;; so that someone can read it in again. Basically, put a slash in
1050 ;;; front of an character satisfying NEEDS-SLASH-P.
1051 (defun quote-string (string stream)
1052   (macrolet ((needs-slash-p (char)
1053                ;; KLUDGE: We probably should look at the readtable, but just do
1054                ;; this for now. [noted by anonymous long ago] -- WHN 19991130
1055                `(or (char= ,char #\\)
1056                  (char= ,char #\"))))
1057     (with-array-data ((data string) (start) (end)
1058                       :check-fill-pointer t)
1059       (do ((index start (1+ index)))
1060           ((>= index end))
1061         (let ((char (schar data index)))
1062           (when (needs-slash-p char) (write-char #\\ stream))
1063           (write-char char stream))))))
1064
1065 (defun array-readably-printable-p (array)
1066   (and (eq (array-element-type array) t)
1067        (let ((zero (position 0 (array-dimensions array)))
1068              (number (position 0 (array-dimensions array)
1069                                :test (complement #'eql)
1070                                :from-end t)))
1071          (or (null zero) (null number) (> zero number)))))
1072
1073 ;;; Output the printed representation of any array in either the #< or #A
1074 ;;; form.
1075 (defun output-array (array stream)
1076   (if (or *print-array* *print-readably*)
1077       (output-array-guts array stream)
1078       (output-terse-array array stream)))
1079
1080 ;;; Output the abbreviated #< form of an array.
1081 (defun output-terse-array (array stream)
1082   (let ((*print-level* nil)
1083         (*print-length* nil))
1084     (print-unreadable-object (array stream :type t :identity t))))
1085
1086 ;;; Convert an array into a list that can be used with MAKE-ARRAY's
1087 ;;; :INITIAL-CONTENTS keyword argument.
1088 (defun listify-array (array)
1089   (with-array-data ((data array) (start) (end))
1090     (declare (ignore end))
1091     (labels ((listify (dimensions index)
1092                (if (null dimensions)
1093                    (aref data index)
1094                    (let* ((dimension (car dimensions))
1095                           (dimensions (cdr dimensions))
1096                           (count (reduce #'* dimensions)))
1097                      (loop for i below dimension
1098                            collect (listify dimensions index)
1099                            do (incf index count))))))
1100       (listify (array-dimensions array) start))))
1101
1102 (defun output-unreadable-array-readably (array stream)
1103   (write-string "#." stream)
1104   (write `(make-array ',(array-dimensions array)
1105                       :element-type ',(array-element-type array)
1106                       :initial-contents ',(listify-array array))
1107          :stream stream))
1108
1109 ;;; Output the readable #A form of an array.
1110 (defun output-array-guts (array stream)
1111   (cond ((or (not *print-readably*)
1112              (array-readably-printable-p array))
1113          (write-char #\# stream)
1114          (let ((*print-base* 10)
1115                (*print-radix* nil))
1116            (output-integer (array-rank array) stream))
1117          (write-char #\A stream)
1118          (with-array-data ((data array) (start) (end))
1119            (declare (ignore end))
1120            (sub-output-array-guts data (array-dimensions array) stream start)))
1121         (*read-eval*
1122          (output-unreadable-array-readably array stream))
1123         (t
1124          (print-not-readable-error array stream))))
1125
1126 (defun sub-output-array-guts (array dimensions stream index)
1127   (declare (type (simple-array * (*)) array) (fixnum index))
1128   (cond ((null dimensions)
1129          (output-object (aref array index) stream))
1130         (t
1131          (descend-into (stream)
1132            (write-char #\( stream)
1133            (let* ((dimension (car dimensions))
1134                   (dimensions (cdr dimensions))
1135                   (count (reduce #'* dimensions)))
1136              (dotimes (i dimension)
1137                (unless (zerop i)
1138                  (write-char #\space stream))
1139                (punt-print-if-too-long i stream)
1140                (sub-output-array-guts array dimensions stream index)
1141                (incf index count)))
1142            (write-char #\) stream)))))
1143
1144 ;;; a trivial non-generic-function placeholder for PRINT-OBJECT, for
1145 ;;; use until CLOS is set up (at which time it will be replaced with
1146 ;;; the real generic function implementation)
1147 (defun print-object (instance stream)
1148   (default-structure-print instance stream *current-level-in-print*))
1149 \f
1150 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
1151
1152 (defun %output-radix (base stream)
1153   (write-char #\# stream)
1154   (write-char (case base
1155                 (2 #\b)
1156                 (8 #\o)
1157                 (16 #\x)
1158                 (t (%output-reasonable-integer-in-base base 10 stream)
1159                    #\r))
1160               stream))
1161
1162 (defun %output-reasonable-integer-in-base (n base stream)
1163   (multiple-value-bind (q r)
1164       (truncate n base)
1165     ;; Recurse until you have all the digits pushed on
1166     ;; the stack.
1167     (unless (zerop q)
1168       (%output-reasonable-integer-in-base q base stream))
1169     ;; Then as each recursive call unwinds, turn the
1170     ;; digit (in remainder) into a character and output
1171     ;; the character.
1172     (write-char
1173      (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r)
1174      stream)))
1175
1176 ;;; *POWER-CACHE* is an alist mapping bases to power-vectors. It is
1177 ;;; filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
1178 ;;; always prior a GC to drop overly large bignums from the cache.
1179 ;;;
1180 ;;; It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
1181 ;;; POWERS-FOR-BASE, see that you don't break the assumptions!
1182 (defvar *power-cache* nil)
1183
1184 (defconstant +power-cache-integer-length-limit+ 2048)
1185
1186 (defun scrub-power-cache ()
1187   (let ((cache *power-cache*))
1188     (dolist (cell cache)
1189       (let ((powers (cdr cell)))
1190         (declare (simple-vector powers))
1191         (let ((too-big (position-if
1192                         (lambda (x)
1193                           (>= (integer-length x)
1194                               +power-cache-integer-length-limit+))
1195                         powers)))
1196           (when too-big
1197             (setf (cdr cell) (subseq powers 0 too-big))))))
1198     ;; Since base 10 is overwhelmingly common, make sure it's at head.
1199     ;; Try to keep other bases in a hopefully sensible order as well.
1200     (if (eql 10 (caar cache))
1201         (setf *power-cache* cache)
1202         ;; If we modify the list destructively we need to copy it, otherwise
1203         ;; an alist lookup in progress might be screwed.
1204         (setf *power-cache* (sort (copy-list cache)
1205                                   (lambda (a b)
1206                                     (declare (fixnum a b))
1207                                     (cond ((= 10 a) t)
1208                                           ((= 10 b) nil)
1209                                           ((= 16 a) t)
1210                                           ((= 16 b) nil)
1211                                           ((= 2 a) t)
1212                                           ((= 2 b) nil)
1213                                           (t (< a b))))
1214                                   :key #'car)))))
1215
1216 ;;; Compute (and cache) a power vector for a BASE and LIMIT:
1217 ;;; the vector holds integers for which
1218 ;;;    (aref powers k) == (expt base (expt 2 k))
1219 ;;; holds.
1220 (defun powers-for-base (base limit)
1221   (flet ((compute-powers (from)
1222            (let (powers)
1223              (do ((p from (* p p)))
1224                  ((> p limit)
1225                   ;; We don't actually need this, but we also
1226                   ;; prefer not to cons it up a second time...
1227                   (push p powers))
1228                (push p powers))
1229              (nreverse powers))))
1230     ;; Grab a local reference so that we won't stuff consed at the
1231     ;; head by other threads -- or sorting by SCRUB-POWER-CACHE.
1232     (let ((cache *power-cache*))
1233       (let ((cell (assoc base cache)))
1234         (if cell
1235             (let* ((powers (cdr cell))
1236                    (len (length powers))
1237                    (max (svref powers (1- len))))
1238               (if (> max limit)
1239                   powers
1240                   (let ((new
1241                          (concatenate 'vector powers
1242                                       (compute-powers (* max max)))))
1243                     (setf (cdr cell) new)
1244                     new)))
1245             (let ((powers (coerce (compute-powers base) 'vector)))
1246               ;; Add new base to head: SCRUB-POWER-CACHE will later
1247               ;; put it to a better place.
1248               (setf *power-cache* (acons base powers cache))
1249               powers))))))
1250
1251 ;; Algorithm by Harald Hanche-Olsen, sbcl-devel 2005-02-05
1252 (defun %output-huge-integer-in-base (n base stream)
1253   (declare (type bignum n) (type fixnum base))
1254   ;; POWER is a vector for which the following holds:
1255   ;;   (aref power k) == (expt base (expt 2 k))
1256   (let* ((power (powers-for-base base n))
1257          (k-start (or (position-if (lambda (x) (> x n)) power)
1258                       (bug "power-vector too short"))))
1259     (labels ((bisect (n k exactp)
1260                (declare (fixnum k))
1261                ;; N is the number to bisect
1262                ;; K on initial entry BASE^(2^K) > N
1263                ;; EXACTP is true if 2^K is the exact number of digits
1264                (cond ((zerop n)
1265                       (when exactp
1266                         (loop repeat (ash 1 k) do (write-char #\0 stream))))
1267                      ((zerop k)
1268                       (write-char
1269                        (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n)
1270                        stream))
1271                      (t
1272                       (setf k (1- k))
1273                       (multiple-value-bind (q r) (truncate n (aref power k))
1274                         ;; EXACTP is NIL only at the head of the
1275                         ;; initial number, as we don't know the number
1276                         ;; of digits there, but we do know that it
1277                         ;; doesn't get any leading zeros.
1278                         (bisect q k exactp)
1279                         (bisect r k (or exactp (plusp q))))))))
1280       (bisect n k-start nil))))
1281
1282 (defun %output-integer-in-base (integer base stream)
1283   (when (minusp integer)
1284     (write-char #\- stream)
1285     (setf integer (- integer)))
1286   ;; The ideal cutoff point between these two algorithms is almost
1287   ;; certainly quite platform dependent: this gives 87 for 32 bit
1288   ;; SBCL, which is about right at least for x86/Darwin.
1289   (if (or (fixnump integer)
1290           (< (integer-length integer) (* 3 sb!vm:n-positive-fixnum-bits)))
1291       (%output-reasonable-integer-in-base integer base stream)
1292       (%output-huge-integer-in-base integer base stream)))
1293
1294 (defun output-integer (integer stream)
1295   (let ((base *print-base*))
1296     (when (and (/= base 10) *print-radix*)
1297       (%output-radix base stream))
1298     (%output-integer-in-base integer base stream)
1299     (when (and *print-radix* (= base 10))
1300       (write-char #\. stream))))
1301
1302 (defun output-ratio (ratio stream)
1303   (let ((base *print-base*))
1304     (when *print-radix*
1305       (%output-radix base stream))
1306     (%output-integer-in-base (numerator ratio) base stream)
1307     (write-char #\/ stream)
1308     (%output-integer-in-base (denominator ratio) base stream)))
1309
1310 (defun output-complex (complex stream)
1311   (write-string "#C(" stream)
1312   ;; FIXME: Could this just be OUTPUT-NUMBER?
1313   (output-object (realpart complex) stream)
1314   (write-char #\space stream)
1315   (output-object (imagpart complex) stream)
1316   (write-char #\) stream))
1317 \f
1318 ;;;; float printing
1319
1320 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1321 ;;; most of the work for all printing of floating point numbers in
1322 ;;; FORMAT.  It converts a floating point number to a string in a free
1323 ;;; or fixed format with no exponent. The interpretation of the
1324 ;;; arguments is as follows:
1325 ;;;
1326 ;;;     X       - The floating point number to convert, which must not be
1327 ;;;             negative.
1328 ;;;     WIDTH    - The preferred field width, used to determine the number
1329 ;;;             of fraction digits to produce if the FDIGITS parameter
1330 ;;;             is unspecified or NIL. If the non-fraction digits and the
1331 ;;;             decimal point alone exceed this width, no fraction digits
1332 ;;;             will be produced unless a non-NIL value of FDIGITS has been
1333 ;;;             specified. Field overflow is not considerd an error at this
1334 ;;;             level.
1335 ;;;     FDIGITS  - The number of fractional digits to produce. Insignificant
1336 ;;;             trailing zeroes may be introduced as needed. May be
1337 ;;;             unspecified or NIL, in which case as many digits as possible
1338 ;;;             are generated, subject to the constraint that there are no
1339 ;;;             trailing zeroes.
1340 ;;;     SCALE    - If this parameter is specified or non-NIL, then the number
1341 ;;;             printed is (* x (expt 10 scale)). This scaling is exact,
1342 ;;;             and cannot lose precision.
1343 ;;;     FMIN     - This parameter, if specified or non-NIL, is the minimum
1344 ;;;             number of fraction digits which will be produced, regardless
1345 ;;;             of the value of WIDTH or FDIGITS. This feature is used by
1346 ;;;             the ~E format directive to prevent complete loss of
1347 ;;;             significance in the printed value due to a bogus choice of
1348 ;;;             scale factor.
1349 ;;;
1350 ;;; Returns:
1351 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1352 ;;; where the results have the following interpretation:
1353 ;;;
1354 ;;;     DIGIT-STRING    - The decimal representation of X, with decimal point.
1355 ;;;     DIGIT-LENGTH    - The length of the string DIGIT-STRING.
1356 ;;;     LEADING-POINT   - True if the first character of DIGIT-STRING is the
1357 ;;;                    decimal point.
1358 ;;;     TRAILING-POINT  - True if the last character of DIGIT-STRING is the
1359 ;;;                    decimal point.
1360 ;;;     POINT-POS       - The position of the digit preceding the decimal
1361 ;;;                    point. Zero indicates point before first digit.
1362 ;;;
1363 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1364 ;;; accuracy. Specifically, the decimal number printed is the closest
1365 ;;; possible approximation to the true value of the binary number to
1366 ;;; be printed from among all decimal representations with the same
1367 ;;; number of digits. In free-format output, i.e. with the number of
1368 ;;; digits unconstrained, it is guaranteed that all the information is
1369 ;;; preserved, so that a properly- rounding reader can reconstruct the
1370 ;;; original binary number, bit-for-bit, from its printed decimal
1371 ;;; representation. Furthermore, only as many digits as necessary to
1372 ;;; satisfy this condition will be printed.
1373 ;;;
1374 ;;; FLOAT-DIGITS actually generates the digits for positive numbers;
1375 ;;; see below for comments.
1376
1377 (defun flonum-to-string (x &optional width fdigits scale fmin)
1378   (declare (type float x))
1379   ;; FIXME: I think only FORMAT-DOLLARS calls FLONUM-TO-STRING with
1380   ;; possibly-negative X.
1381   (setf x (abs x))
1382   (multiple-value-bind (e string)
1383       (if fdigits
1384           (flonum-to-digits x (min (- (+ fdigits (or scale 0)))
1385                                    (- (or fmin 0))))
1386           (if (and width (> width 1))
1387               (let ((w (multiple-value-list
1388                         (flonum-to-digits x
1389                                           (max 1
1390                                                (+ (1- width)
1391                                                   (if (and scale (minusp scale))
1392                                                       scale 0)))
1393                                           t)))
1394                     (f (multiple-value-list
1395                         (flonum-to-digits x (- (+ (or fmin 0)
1396                                                   (if scale scale 0)))))))
1397                 (cond
1398                   ((>= (length (cadr w)) (length (cadr f)))
1399                    (values-list w))
1400                   (t (values-list f))))
1401               (flonum-to-digits x)))
1402     (let ((e (if (zerop x)
1403                  e
1404                  (+ e (or scale 0))))
1405           (stream (make-string-output-stream)))
1406       (if (plusp e)
1407           (progn
1408             (write-string string stream :end (min (length string) e))
1409             (dotimes (i (- e (length string)))
1410               (write-char #\0 stream))
1411             (write-char #\. stream)
1412             (write-string string stream :start (min (length string) e))
1413             (when fdigits
1414               (dotimes (i (- fdigits
1415                              (- (length string)
1416                                 (min (length string) e))))
1417                 (write-char #\0 stream))))
1418           (progn
1419             (write-string "." stream)
1420             (dotimes (i (- e))
1421               (write-char #\0 stream))
1422             (write-string string stream :end (when fdigits
1423                                                (min (length string)
1424                                                     (max (or fmin 0)
1425                                                          (+ fdigits e)))))
1426             (when fdigits
1427               (dotimes (i (+ fdigits e (- (length string))))
1428                 (write-char #\0 stream)))))
1429       (let ((string (get-output-stream-string stream)))
1430         (values string (length string)
1431                 (char= (char string 0) #\.)
1432                 (char= (char string (1- (length string))) #\.)
1433                 (position #\. string))))))
1434
1435 ;;; implementation of figure 1 from Burger and Dybvig, 1996. It is
1436 ;;; extended in order to handle rounding.
1437 ;;;
1438 ;;; As the implementation of the Dragon from Classic CMUCL (and
1439 ;;; previously in SBCL above FLONUM-TO-STRING) says: "DO NOT EVEN
1440 ;;; THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE
1441 ;;; PAPER!", and in this case we have to add that even reading the
1442 ;;; paper might not bring immediate illumination as CSR has attempted
1443 ;;; to turn idiomatic Scheme into idiomatic Lisp.
1444 ;;;
1445 ;;; FIXME: figure 1 from Burger and Dybvig is the unoptimized
1446 ;;; algorithm, noticeably slow at finding the exponent.  Figure 2 has
1447 ;;; an improved algorithm, but CSR ran out of energy.
1448 ;;;
1449 ;;; possible extension for the enthusiastic: printing floats in bases
1450 ;;; other than base 10.
1451 (defconstant single-float-min-e
1452   (- 2 sb!vm:single-float-bias sb!vm:single-float-digits))
1453 (defconstant double-float-min-e
1454   (- 2 sb!vm:double-float-bias sb!vm:double-float-digits))
1455 #!+long-float
1456 (defconstant long-float-min-e
1457   (nth-value 1 (decode-float least-positive-long-float)))
1458
1459 (defun flonum-to-digits (v &optional position relativep)
1460   (let ((print-base 10) ; B
1461         (float-radix 2) ; b
1462         (float-digits (float-digits v)) ; p
1463         (digit-characters "0123456789")
1464         (min-e
1465          (etypecase v
1466            (single-float single-float-min-e)
1467            (double-float double-float-min-e)
1468            #!+long-float
1469            (long-float long-float-min-e))))
1470     (multiple-value-bind (f e)
1471         (integer-decode-float v)
1472       (let (;; FIXME: these even tests assume normal IEEE rounding
1473             ;; mode.  I wonder if we should cater for non-normal?
1474             (high-ok (evenp f))
1475             (low-ok (evenp f)))
1476         (with-push-char (:element-type base-char)
1477           (labels ((scale (r s m+ m-)
1478                      (do ((k 0 (1+ k))
1479                           (s s (* s print-base)))
1480                          ((not (or (> (+ r m+) s)
1481                                    (and high-ok (= (+ r m+) s))))
1482                           (do ((k k (1- k))
1483                                (r r (* r print-base))
1484                                (m+ m+ (* m+ print-base))
1485                                (m- m- (* m- print-base)))
1486                               ((not (and (plusp (- r m-)) ; Extension to handle zero
1487                                          (or (< (* (+ r m+) print-base) s)
1488                                              (and (not high-ok)
1489                                                   (= (* (+ r m+) print-base) s)))))
1490                                (values k (generate r s m+ m-)))))))
1491                    (generate (r s m+ m-)
1492                      (let (d tc1 tc2)
1493                        (tagbody
1494                         loop
1495                           (setf (values d r) (truncate (* r print-base) s))
1496                           (setf m+ (* m+ print-base))
1497                           (setf m- (* m- print-base))
1498                           (setf tc1 (or (< r m-) (and low-ok (= r m-))))
1499                           (setf tc2 (or (> (+ r m+) s)
1500                                         (and high-ok (= (+ r m+) s))))
1501                           (when (or tc1 tc2)
1502                             (go end))
1503                           (push-char (char digit-characters d))
1504                           (go loop)
1505                         end
1506                           (let ((d (cond
1507                                      ((and (not tc1) tc2) (1+ d))
1508                                      ((and tc1 (not tc2)) d)
1509                                      (t ; (and tc1 tc2)
1510                                       (if (< (* r 2) s) d (1+ d))))))
1511                             (push-char (char digit-characters d))
1512                             (return-from generate (get-pushed-string))))))
1513                    (initialize ()
1514                      (let (r s m+ m-)
1515                        (if (>= e 0)
1516                            (let* ((be (expt float-radix e))
1517                                   (be1 (* be float-radix)))
1518                              (if (/= f (expt float-radix (1- float-digits)))
1519                                  (setf r (* f be 2)
1520                                        s 2
1521                                        m+ be
1522                                        m- be)
1523                                  (setf r (* f be1 2)
1524                                        s (* float-radix 2)
1525                                        m+ be1
1526                                        m- be)))
1527                            (if (or (= e min-e)
1528                                    (/= f (expt float-radix (1- float-digits))))
1529                                (setf r (* f 2)
1530                                      s (* (expt float-radix (- e)) 2)
1531                                      m+ 1
1532                                      m- 1)
1533                                (setf r (* f float-radix 2)
1534                                      s (* (expt float-radix (- 1 e)) 2)
1535                                      m+ float-radix
1536                                      m- 1)))
1537                        (when position
1538                          (when relativep
1539                            (aver (> position 0))
1540                            (do ((k 0 (1+ k))
1541                                 ;; running out of letters here
1542                                 (l 1 (* l print-base)))
1543                                ((>= (* s l) (+ r m+))
1544                                 ;; k is now \hat{k}
1545                                 (if (< (+ r (* s (/ (expt print-base (- k position)) 2)))
1546                                        (* s (expt print-base k)))
1547                                     (setf position (- k position))
1548                                     (setf position (- k position 1))))))
1549                          (let ((low (max m- (/ (* s (expt print-base position)) 2)))
1550                                (high (max m+ (/ (* s (expt print-base position)) 2))))
1551                            (when (<= m- low)
1552                              (setf m- low)
1553                              (setf low-ok t))
1554                            (when (<= m+ high)
1555                              (setf m+ high)
1556                              (setf high-ok t))))
1557                        (values r s m+ m-))))
1558             (multiple-value-bind (r s m+ m-) (initialize)
1559               (scale r s m+ m-))))))))
1560 \f
1561 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns
1562 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1563 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1564 ;;; original number. There may be some loss of precision due the
1565 ;;; floating point representation. The scaling is always done with
1566 ;;; long float arithmetic, which helps printing of lesser precisions
1567 ;;; as well as avoiding generic arithmetic.
1568 ;;;
1569 ;;; When computing our initial scale factor using EXPT, we pull out
1570 ;;; part of the computation to avoid over/under flow. When
1571 ;;; denormalized, we must pull out a large factor, since there is more
1572 ;;; negative exponent range than positive range.
1573
1574 (eval-when (:compile-toplevel :execute)
1575   (setf *read-default-float-format*
1576         #!+long-float 'long-float #!-long-float 'double-float))
1577 (defun scale-exponent (original-x)
1578   (let* ((x (coerce original-x 'long-float)))
1579     (multiple-value-bind (sig exponent) (decode-float x)
1580       (declare (ignore sig))
1581       (if (= x 0.0e0)
1582           (values (float 0.0e0 original-x) 1)
1583           (let* ((ex (locally (declare (optimize (safety 0)))
1584                        (the fixnum
1585                          (round (* exponent
1586                                    ;; this is the closest double float
1587                                    ;; to (log 2 10), but expressed so
1588                                    ;; that we're not vulnerable to the
1589                                    ;; host lisp's interpretation of
1590                                    ;; arithmetic.  (FIXME: it turns
1591                                    ;; out that sbcl itself is off by 1
1592                                    ;; ulp in this value, which is a
1593                                    ;; little unfortunate.)
1594                                    (load-time-value
1595                                     #!-long-float
1596                                     (sb!kernel:make-double-float 1070810131 1352628735)
1597                                     #!+long-float
1598                                     (error "(log 2 10) not computed")))))))
1599                  (x (if (minusp ex)
1600                         (if (float-denormalized-p x)
1601                             #!-long-float
1602                             (* x 1.0e16 (expt 10.0e0 (- (- ex) 16)))
1603                             #!+long-float
1604                             (* x 1.0e18 (expt 10.0e0 (- (- ex) 18)))
1605                             (* x 10.0e0 (expt 10.0e0 (- (- ex) 1))))
1606                         (/ x 10.0e0 (expt 10.0e0 (1- ex))))))
1607             (do ((d 10.0e0 (* d 10.0e0))
1608                  (y x (/ x d))
1609                  (ex ex (1+ ex)))
1610                 ((< y 1.0e0)
1611                  (do ((m 10.0e0 (* m 10.0e0))
1612                       (z y (* y m))
1613                       (ex ex (1- ex)))
1614                      ((>= z 0.1e0)
1615                       (values (float z original-x) ex))
1616                    (declare (long-float m) (integer ex))))
1617               (declare (long-float d))))))))
1618 (eval-when (:compile-toplevel :execute)
1619   (setf *read-default-float-format* 'single-float))
1620 \f
1621 ;;;; entry point for the float printer
1622
1623 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1624 ;;; argument is printed free-format, in either exponential or
1625 ;;; non-exponential notation, depending on its magnitude.
1626 ;;;
1627 ;;; NOTE: When a number is to be printed in exponential format, it is
1628 ;;; scaled in floating point. Since precision may be lost in this
1629 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1630 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1631 ;;; extensive computations with integers of similar magnitude to that
1632 ;;; of the number being printed. For large exponents, the bignums
1633 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1634 ;;; fast and the exponent range is not too large, then it might become
1635 ;;; attractive to handle exponential notation with the same accuracy
1636 ;;; as non-exponential notation, using the method described in the
1637 ;;; Steele and White paper.
1638 ;;;
1639 ;;; NOTE II: this has been bypassed slightly by implementing Burger
1640 ;;; and Dybvig, 1996.  When someone has time (KLUDGE) they can
1641 ;;; probably (a) implement the optimizations suggested by Burger and
1642 ;;; Dyvbig, and (b) remove all vestiges of Dragon4, including from
1643 ;;; fixed-format printing.
1644
1645 ;;; Print the appropriate exponent marker for X and the specified exponent.
1646 (defun print-float-exponent (x exp stream)
1647   (declare (type float x) (type integer exp) (type stream stream))
1648   (let ((*print-radix* nil))
1649     (if (typep x *read-default-float-format*)
1650         (unless (eql exp 0)
1651           (format stream "e~D" exp))
1652         (format stream "~C~D"
1653                 (etypecase x
1654                   (single-float #\f)
1655                   (double-float #\d)
1656                   (short-float #\s)
1657                   (long-float #\L))
1658                 exp))))
1659
1660 (defun output-float-infinity (x stream)
1661   (declare (float x) (stream stream))
1662   (cond (*read-eval*
1663          (write-string "#." stream))
1664         (*print-readably*
1665          (return-from output-float-infinity
1666            (print-not-readable-error x stream)))
1667         (t
1668          (write-string "#<" stream)))
1669   (write-string "SB-EXT:" stream)
1670   (write-string (symbol-name (float-format-name x)) stream)
1671   (write-string (if (plusp x) "-POSITIVE-" "-NEGATIVE-")
1672                 stream)
1673   (write-string "INFINITY" stream)
1674   (unless *read-eval*
1675     (write-string ">" stream)))
1676
1677 (defun output-float-nan (x stream)
1678   (print-unreadable-object (x stream)
1679     (princ (float-format-name x) stream)
1680     (write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
1681     (write-string " NaN" stream)))
1682
1683 ;;; the function called by OUTPUT-OBJECT to handle floats
1684 (defun output-float (x stream)
1685   (cond
1686    ((float-infinity-p x)
1687     (output-float-infinity x stream))
1688    ((float-nan-p x)
1689     (output-float-nan x stream))
1690    (t
1691     (let ((x (cond ((minusp (float-sign x))
1692                     (write-char #\- stream)
1693                     (- x))
1694                    (t
1695                     x))))
1696       (cond
1697        ((zerop x)
1698         (write-string "0.0" stream)
1699         (print-float-exponent x 0 stream))
1700        (t
1701         (output-float-aux x stream -3 8)))))))
1702
1703 (defun output-float-aux (x stream e-min e-max)
1704   (multiple-value-bind (e string)
1705       (flonum-to-digits x)
1706     (cond
1707       ((< e-min e e-max)
1708        (if (plusp e)
1709            (progn
1710              (write-string string stream :end (min (length string) e))
1711              (dotimes (i (- e (length string)))
1712                (write-char #\0 stream))
1713              (write-char #\. stream)
1714              (write-string string stream :start (min (length string) e))
1715              (when (<= (length string) e)
1716                (write-char #\0 stream))
1717              (print-float-exponent x 0 stream))
1718            (progn
1719              (write-string "0." stream)
1720              (dotimes (i (- e))
1721                (write-char #\0 stream))
1722              (write-string string stream)
1723              (print-float-exponent x 0 stream))))
1724       (t (write-string string stream :end 1)
1725          (write-char #\. stream)
1726          (write-string string stream :start 1)
1727          (print-float-exponent x (1- e) stream)))))
1728 \f
1729 ;;;; other leaf objects
1730
1731 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1732 ;;; the character name or the character in the #\char format.
1733 (defun output-character (char stream)
1734   (if (or *print-escape* *print-readably*)
1735       (let ((graphicp (and (graphic-char-p char)
1736                            (standard-char-p char)))
1737             (name (char-name char)))
1738         (write-string "#\\" stream)
1739         (if (and name (not graphicp))
1740             (quote-string name stream)
1741             (write-char char stream)))
1742       (write-char char stream)))
1743
1744 (defun output-sap (sap stream)
1745   (declare (type system-area-pointer sap))
1746   (cond (*read-eval*
1747          (format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
1748         (t
1749          (print-unreadable-object (sap stream)
1750            (format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
1751
1752 (defun output-weak-pointer (weak-pointer stream)
1753   (declare (type weak-pointer weak-pointer))
1754   (print-unreadable-object (weak-pointer stream)
1755     (multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
1756       (cond (validp
1757              (write-string "weak pointer: " stream)
1758              (write value :stream stream))
1759             (t
1760              (write-string "broken weak pointer" stream))))))
1761
1762 (defun output-code-component (component stream)
1763   (print-unreadable-object (component stream :identity t)
1764     (let ((dinfo (%code-debug-info component)))
1765       (cond ((eq dinfo :bogus-lra)
1766              (write-string "bogus code object" stream))
1767             (t
1768              (write-string "code object" stream)
1769              (when dinfo
1770                (write-char #\space stream)
1771                (output-object (sb!c::debug-info-name dinfo) stream)))))))
1772
1773 (defun output-lra (lra stream)
1774   (print-unreadable-object (lra stream :identity t)
1775     (write-string "return PC object" stream)))
1776
1777 (defun output-fdefn (fdefn stream)
1778   (print-unreadable-object (fdefn stream)
1779     (write-string "FDEFINITION object for " stream)
1780     (output-object (fdefn-name fdefn) stream)))
1781
1782 #!+sb-simd-pack
1783 (defun output-simd-pack (pack stream)
1784   (declare (type simd-pack pack))
1785   (cond ((and *print-readably* *read-eval*)
1786          (etypecase pack
1787            ((simd-pack double-float)
1788             (multiple-value-call #'format stream
1789               "#.(~S ~S ~S)"
1790               '%make-simd-pack-double
1791               (%simd-pack-doubles pack)))
1792            ((simd-pack single-float)
1793             (multiple-value-call #'format stream
1794               "#.(~S ~S ~S ~S ~S)"
1795               '%make-simd-pack-single
1796               (%simd-pack-singles pack)))
1797            (t
1798             (multiple-value-call #'format stream
1799               "#.(~S #X~16,'0X #X~16,'0X)"
1800               '%make-simd-pack-ub64
1801               (%simd-pack-ub64s pack)))))
1802         (t
1803          (print-unreadable-object (pack stream)
1804            (flet ((all-ones-p (value start end &aux (mask (- (ash 1 end) (ash 1 start))))
1805                       (= (logand value mask) mask))
1806                     (split-num (value start)
1807                       (loop
1808                          for i from 0 to 3
1809                          and v = (ash value (- start)) then (ash v -8)
1810                          collect (logand v #xFF))))
1811              (multiple-value-bind (low high)
1812                  (%simd-pack-ub64s pack)
1813                (etypecase pack
1814                  ((simd-pack double-float)
1815                   (multiple-value-bind (v0 v1) (%simd-pack-doubles pack)
1816                     (format stream "~S~@{ ~:[~,13E~;~*TRUE~]~}"
1817                             'simd-pack
1818                             (all-ones-p low 0 64) v0
1819                             (all-ones-p high 0 64) v1)))
1820                  ((simd-pack single-float)
1821                   (multiple-value-bind (v0 v1 v2 v3) (%simd-pack-singles pack)
1822                     (format stream "~S~@{ ~:[~,7E~;~*TRUE~]~}"
1823                             'simd-pack
1824                             (all-ones-p low 0 32) v0
1825                             (all-ones-p low 32 64) v1
1826                             (all-ones-p high 0 32) v2
1827                             (all-ones-p high 32 64) v3)))
1828                  (t
1829                   (format stream "~S~@{ ~{ ~2,'0X~}~}"
1830                           'simd-pack
1831                           (split-num low 0) (split-num low 32)
1832                           (split-num high 0) (split-num high 32))))))))))
1833 \f
1834 ;;;; functions
1835
1836 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1837 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1838 ;;;
1839 ;;; The definition here is a simple temporary placeholder. It will be
1840 ;;; overwritten by a smarter version (capable of calling generic
1841 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1842 (defun printed-as-funcallable-standard-class (object stream)
1843   (declare (ignore object stream))
1844   nil)
1845
1846 (defun output-fun (object stream)
1847   (let* ((*print-length* 4)  ; in case we have to..
1848          (*print-level* 3)  ; ..print an interpreted function definition
1849          (name (%fun-name object))
1850          (proper-name-p (and (legal-fun-name-p name) (fboundp name)
1851                              (eq (fdefinition name) object))))
1852     (print-unreadable-object (object stream :identity (not proper-name-p))
1853       (format stream "~:[FUNCTION~;CLOSURE~]~@[ ~S~]"
1854               (closurep object)
1855               name))))
1856 \f
1857 ;;;; catch-all for unknown things
1858
1859 (defun output-random (object stream)
1860   (print-unreadable-object (object stream :identity t)
1861     (let ((lowtag (lowtag-of object)))
1862       (case lowtag
1863         (#.sb!vm:other-pointer-lowtag
1864           (let ((widetag (widetag-of object)))
1865             (case widetag
1866               (#.sb!vm:value-cell-header-widetag
1867                (write-string "value cell " stream)
1868                (output-object (value-cell-ref object) stream))
1869               (t
1870                (write-string "unknown pointer object, widetag=" stream)
1871                (let ((*print-base* 16) (*print-radix* t))
1872                  (output-integer widetag stream))))))
1873         ((#.sb!vm:fun-pointer-lowtag
1874           #.sb!vm:instance-pointer-lowtag
1875           #.sb!vm:list-pointer-lowtag)
1876          (write-string "unknown pointer object, lowtag=" stream)
1877          (let ((*print-base* 16) (*print-radix* t))
1878            (output-integer lowtag stream)))
1879         (t
1880          (case (widetag-of object)
1881            (#.sb!vm:unbound-marker-widetag
1882             (write-string "unbound marker" stream))
1883            (t
1884             (write-string "unknown immediate object, lowtag=" stream)
1885             (let ((*print-base* 2) (*print-radix* t))
1886               (output-integer lowtag stream))
1887             (write-string ", widetag=" stream)
1888             (let ((*print-base* 16) (*print-radix* t))
1889               (output-integer (widetag-of object) stream)))))))))