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