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