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