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