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