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