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