0.pre7.14.flaky4:
[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   "Output 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   "Output 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   "Output 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   "Output a newline, the mostly READable printed representation 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 output 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   "Return the printed representation of OBJECT as a string."
212   (stringify-object object))
213
214 (defun prin1-to-string (object)
215   #!+sb-doc
216   "Return 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   "Return 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 ;;; 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 (defun check-for-circularity (object &optional assign)
302   (cond ((null *print-circle*)
303          ;; Don't bother, nobody cares.
304          nil)
305         ((null *circularity-hash-table*)
306          :initiate)
307         ((null *circularity-counter*)
308          (ecase (gethash object *circularity-hash-table*)
309            ((nil)
310             ;; First encounter.
311             (setf (gethash object *circularity-hash-table*) t)
312             ;; We need to keep looking.
313             nil)
314            ((t)
315             ;; Second encounter.
316             (setf (gethash object *circularity-hash-table*) 0)
317             ;; It's a circular reference.
318             t)
319            (0
320             ;; It's a circular reference.
321             t)))
322         (t
323          (let ((value (gethash object *circularity-hash-table*)))
324            (case value
325              ((nil t)
326               ;; If NIL, we found an object that wasn't there the first time
327               ;; around. If T, exactly one occurance of this object appears.
328               ;; Either way, just print the thing without any special
329               ;; processing. Note: you might argue that finding a new object
330               ;; means that something is broken, but this can happen. If
331               ;; someone uses the ~@<...~:> format directive, it conses a
332               ;; new list each time though format (i.e. the &REST list), so
333               ;; we will have different cdrs.
334               nil)
335              (0
336               (if assign
337                   (let ((value (incf *circularity-counter*)))
338                     ;; First occurance of this object. Set the counter.
339                     (setf (gethash object *circularity-hash-table*) value)
340                     value)
341                   t))
342              (t
343               ;; Second or later occurance.
344               (- value)))))))
345
346 ;;; Handle the results of CHECK-FOR-CIRCULARITY. If this returns T then
347 ;;; you should go ahead and print the object. If it returns NIL, then
348 ;;; you should blow it off.
349 (defun handle-circularity (marker stream)
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 ;;; the current pretty printer. This should be either a function that
375 ;;; takes two arguments (the object and the stream) or NIL to indicate
376 ;;; that there is no pretty printer installed.
377 (defvar *pretty-printer* nil)
378
379 ;;; Output OBJECT to STREAM observing all printer control variables.
380 (defun output-object (object stream)
381   (labels ((print-it (stream)
382              (if *print-pretty*
383                  (if *pretty-printer*
384                      (funcall *pretty-printer* object stream)
385                      (let ((*print-pretty* nil))
386                        (output-ugly-object object stream)))
387                  (output-ugly-object object stream)))
388            (check-it (stream)
389              (let ((marker (check-for-circularity object t)))
390                (case marker
391                  (:initiate
392                   (let ((*circularity-hash-table*
393                          (make-hash-table :test 'eq)))
394                     (check-it (make-broadcast-stream))
395                     (let ((*circularity-counter* 0))
396                       (check-it stream))))
397                  ((nil)
398                   (print-it stream))
399                  (t
400                   (when (handle-circularity marker stream)
401                     (print-it stream)))))))
402     (cond ((or (not *print-circle*)
403                (numberp object)
404                (characterp object)
405                (and (symbolp object) (symbol-package object) t))
406            ;; If it a number, character, or interned symbol, we do not
407            ;; want to check for circularity/sharing.
408            (print-it stream))
409           ((or *circularity-hash-table*
410                (consp object)
411                (typep object 'instance)
412                (typep object '(array t *)))
413            ;; If we have already started circularity detection, this
414            ;; object might be a sharded reference. If we have not,
415            ;; then if it is a cons, a instance, or an array of element
416            ;; type t it might contain a circular reference to itself
417            ;; or multiple shared references.
418            (check-it stream))
419           (t
420            (print-it stream)))))
421
422 ;;; Output OBJECT to STREAM observing all printer control variables
423 ;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
424 ;;; then the pretty printer will be used for any components of OBJECT,
425 ;;; just not for OBJECT itself.
426 (defun output-ugly-object (object stream)
427   (typecase object
428     ;; KLUDGE: The TYPECASE approach here is non-ANSI; the ANSI definition of
429     ;; PRINT-OBJECT says it provides printing and we're supposed to provide
430     ;; PRINT-OBJECT methods covering all classes. We deviate from this
431     ;; by using PRINT-OBJECT only when we print instance values. However,
432     ;; ANSI makes it hard to tell that we're deviating from this:
433     ;;   (1) ANSI specifies that the user isn't supposed to call PRINT-OBJECT
434     ;;       directly.
435     ;;   (2) ANSI (section 11.1.2.1.2) says it's undefined to define
436     ;;       a method on an external symbol in the CL package which is
437     ;;       applicable to arg lists containing only direct instances of
438     ;;       standardized classes.
439     ;; Thus, in order for the user to detect our sleaziness, he has to do
440     ;; something relatively obscure like
441     ;;   (1) actually use tools like FIND-METHOD to look for PRINT-OBJECT
442     ;;       methods, or
443     ;;   (2) define a PRINT-OBJECT method which is specialized on the stream
444     ;;       value (e.g. a Gray stream object).
445     ;; As long as no one comes up with a non-obscure way of detecting this
446     ;; sleaziness, fixing this nonconformity will probably have a low
447     ;; priority. -- WHN 20000121
448     (fixnum
449      (output-integer object stream))
450     (list
451      (if (null object)
452          (output-symbol object stream)
453          (output-list object stream)))
454     (instance
455      (print-object object stream))
456     (function
457      (unless (and (funcallable-instance-p object)
458                   (printed-as-funcallable-standard-class object stream))
459        (output-function object stream)))
460     (symbol
461      (output-symbol object stream))
462     (number
463      (etypecase object
464        (integer
465         (output-integer object stream))
466        (float
467         (output-float object stream))
468        (ratio
469         (output-ratio object stream))
470        (ratio
471         (output-ratio object stream))
472        (complex
473         (output-complex object stream))))
474     (character
475      (output-character object stream))
476     (vector
477      (output-vector object stream))
478     (array
479      (output-array object stream))
480     (system-area-pointer
481      (output-sap object stream))
482     (weak-pointer
483      (output-weak-pointer object stream))
484     (lra
485      (output-lra object stream))
486     (code-component
487      (output-code-component object stream))
488     (fdefn
489      (output-fdefn object stream))
490     (t
491      (output-random object stream))))
492 \f
493 ;;;; symbols
494
495 ;;; Values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last
496 ;;; time the printer was called.
497 (defvar *previous-case* nil)
498 (defvar *previous-readtable-case* nil)
499
500 ;;; This variable contains the current definition of one of three
501 ;;; symbol printers. SETUP-PRINTER-STATE sets this variable.
502 (defvar *internal-symbol-output-function* nil)
503
504 ;;; This function sets the internal global symbol
505 ;;; *INTERNAL-SYMBOL-OUTPUT-FUNCTION* to the right function depending
506 ;;; on the value of *PRINT-CASE*. See the manual for details. The
507 ;;; print buffer stream is also reset.
508 (defun setup-printer-state ()
509   (unless (and (eq *print-case* *previous-case*)
510                (eq (readtable-case *readtable*) *previous-readtable-case*))
511     (setq *previous-case* *print-case*)
512     (setq *previous-readtable-case* (readtable-case *readtable*))
513     (unless (member *print-case* '(:upcase :downcase :capitalize))
514       (setq *print-case* :upcase)
515       (error "invalid *PRINT-CASE* value: ~S" *previous-case*))
516     (unless (member *previous-readtable-case*
517                     '(:upcase :downcase :invert :preserve))
518       (setf (readtable-case *readtable*) :upcase)
519       (error "invalid READTABLE-CASE value: ~S" *previous-readtable-case*))
520
521     (setq *internal-symbol-output-function*
522           (case *previous-readtable-case*
523             (:upcase
524              (case *print-case*
525                (:upcase #'output-preserve-symbol)
526                (:downcase #'output-lowercase-symbol)
527                (:capitalize #'output-capitalize-symbol)))
528             (:downcase
529              (case *print-case*
530                (:upcase #'output-uppercase-symbol)
531                (:downcase #'output-preserve-symbol)
532                (:capitalize #'output-capitalize-symbol)))
533             (:preserve #'output-preserve-symbol)
534             (:invert #'output-invert-symbol)))))
535
536 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
537 ;;; and with any embedded |'s or \'s escaped.
538 (defun output-quoted-symbol-name (pname stream)
539   (write-char #\| stream)
540   (dotimes (index (length pname))
541     (let ((char (schar pname index)))
542       (when (or (char= char #\\) (char= char #\|))
543         (write-char #\\ stream))
544       (write-char char stream)))
545   (write-char #\| stream))
546
547 (defun output-symbol (object stream)
548   (if (or *print-escape* *print-readably*)
549       (let ((package (symbol-package object))
550             (name (symbol-name object)))
551         (cond
552          ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
553          ;; requires that keywords be printed with preceding colons
554          ;; always, regardless of the value of *PACKAGE*.
555          ((eq package *keyword-package*)
556           (write-char #\: stream))
557          ;; Otherwise, if the symbol's home package is the current
558          ;; one, then a prefix is never necessary.
559          ((eq package (sane-package)))
560          ;; Uninterned symbols print with a leading #:.
561          ((null package)
562           (when (or *print-gensym* *print-readably*)
563             (write-string "#:" stream)))
564          (t
565           (multiple-value-bind (symbol accessible)
566               (find-symbol name (sane-package))
567             ;; If we can find the symbol by looking it up, it need not
568             ;; be qualified. This can happen if the symbol has been
569             ;; inherited from a package other than its home package.
570             (unless (and accessible (eq symbol object))
571               (output-symbol-name (package-name package) stream)
572               (multiple-value-bind (symbol externalp)
573                   (find-external-symbol name package)
574                 (declare (ignore symbol))
575                 (if externalp
576                     (write-char #\: stream)
577                     (write-string "::" stream)))))))
578         (output-symbol-name name stream))
579       (output-symbol-name (symbol-name object) stream nil)))
580
581 ;;; Output the string NAME as if it were a symbol name. In other
582 ;;; words, diddle its case according to *PRINT-CASE* and
583 ;;; READTABLE-CASE.
584 (defun output-symbol-name (name stream &optional (maybe-quote t))
585   (declare (type simple-base-string name))
586   (setup-printer-state)
587   (if (and maybe-quote (symbol-quotep name))
588       (output-quoted-symbol-name name stream)
589       (funcall *internal-symbol-output-function* name stream)))
590 \f
591 ;;;; escaping symbols
592
593 ;;; When we print symbols we have to figure out if they need to be
594 ;;; printed with escape characters. This isn't a whole lot easier than
595 ;;; reading symbols in the first place.
596 ;;;
597 ;;; For each character, the value of the corresponding element is a
598 ;;; fixnum with bits set corresponding to attributes that the
599 ;;; character has. At characters have at least one bit set, so we can
600 ;;; search for any character with a positive test.
601 (defvar *character-attributes*
602   (make-array char-code-limit
603               :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 ;;; constants which are a bit-mask for each interesting character attribute
609 (defconstant other-attribute            (ash 1 0)) ; Anything else legal.
610 (defconstant number-attribute           (ash 1 1)) ; A numeric digit.
611 (defconstant uppercase-attribute        (ash 1 2)) ; An uppercase letter.
612 (defconstant lowercase-attribute        (ash 1 3)) ; A lowercase letter.
613 (defconstant sign-attribute             (ash 1 4)) ; +-
614 (defconstant extension-attribute        (ash 1 5)) ; ^_
615 (defconstant dot-attribute              (ash 1 6)) ; .
616 (defconstant slash-attribute            (ash 1 7)) ; /
617 (defconstant funny-attribute            (ash 1 8)) ; Anything illegal.
618
619 (eval-when (:compile-toplevel :load-toplevel :execute)
620
621 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
622 ;;; that don't need to be escaped (according to READTABLE-CASE.)
623 (defparameter *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
664 ;;; lowest 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
696                                                           *attribute-names*))
697                                               (error "Blast!")))
698                                         attributes))
699                              bits)))))
700              (digitp ()
701                `(< (the fixnum (aref bases code)) base)))
702
703     (prog ((len (length name))
704            (attributes *character-attributes*)
705            (bases *digit-bases*)
706            (base *print-base*)
707            (letter-attribute
708             (case (readtable-case *readtable*)
709               (:upcase uppercase-attribute)
710               (:downcase lowercase-attribute)
711               (t (logior lowercase-attribute uppercase-attribute))))
712            (index 0)
713            (bits 0)
714            (code 0)
715            current)
716       (declare (fixnum len base index bits code))
717       (advance START t)
718
719      TEST-SIGN ; At end, see whether it is a sign...
720       (return (not (test sign)))
721
722      OTHER ; not potential number, see whether funny chars...
723       (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
724                                   funny-attribute)
725                           letter-attribute)))
726         (do ((i (1- index) (1+ i)))
727             ((= i len) (return-from symbol-quotep nil))
728           (unless (zerop (logand (aref attributes (char-code (schar name i)))
729                                  mask))
730             (return-from symbol-quotep t))))
731
732      START
733       (when (digitp)
734         (if (test letter)
735             (advance LAST-DIGIT-ALPHA)
736             (advance DIGIT)))
737       (when (test letter number other slash) (advance OTHER nil))
738       (when (char= current #\.) (advance DOT-FOUND))
739       (when (test sign extension) (advance START-STUFF nil))
740       (return t)
741
742      DOT-FOUND ; leading dots...
743       (when (test letter) (advance START-DOT-MARKER nil))
744       (when (digitp) (advance DOT-DIGIT))
745       (when (test number other) (advance OTHER nil))
746       (when (test extension slash sign) (advance START-DOT-STUFF nil))
747       (when (char= current #\.) (advance DOT-FOUND))
748       (return t)
749
750      START-STUFF ; leading stuff before any dot or digit
751       (when (digitp)
752         (if (test letter)
753             (advance LAST-DIGIT-ALPHA)
754             (advance DIGIT)))
755       (when (test number other) (advance OTHER nil))
756       (when (test letter) (advance START-MARKER nil))
757       (when (char= current #\.) (advance START-DOT-STUFF nil))
758       (when (test sign extension slash) (advance START-STUFF nil))
759       (return t)
760
761      START-MARKER ; number marker in leading stuff...
762       (when (test letter) (advance OTHER nil))
763       (go START-STUFF)
764
765      START-DOT-STUFF ; leading stuff containing dot without digit...
766       (when (test letter) (advance START-DOT-STUFF nil))
767       (when (digitp) (advance DOT-DIGIT))
768       (when (test sign extension dot slash) (advance START-DOT-STUFF nil))
769       (when (test number other) (advance OTHER nil))
770       (return t)
771
772      START-DOT-MARKER ; number marker in leading stuff with dot..
773       ;; leading stuff containing dot without digit followed by letter...
774       (when (test letter) (advance OTHER nil))
775       (go START-DOT-STUFF)
776
777      DOT-DIGIT ; in a thing with dots...
778       (when (test letter) (advance DOT-MARKER))
779       (when (digitp) (advance DOT-DIGIT))
780       (when (test number other) (advance OTHER nil))
781       (when (test sign extension dot slash) (advance DOT-DIGIT))
782       (return t)
783
784      DOT-MARKER ; number marker in number with dot...
785       (when (test letter) (advance OTHER nil))
786       (go DOT-DIGIT)
787
788      LAST-DIGIT-ALPHA ; previous char is a letter digit...
789       (when (or (digitp) (test sign slash))
790         (advance ALPHA-DIGIT))
791       (when (test letter number other dot) (advance OTHER nil))
792       (return t)
793
794      ALPHA-DIGIT ; seen a digit which is a letter...
795       (when (or (digitp) (test sign slash))
796         (if (test letter)
797             (advance LAST-DIGIT-ALPHA)
798             (advance ALPHA-DIGIT)))
799       (when (test letter) (advance ALPHA-MARKER))
800       (when (test number other dot) (advance OTHER nil))
801       (return t)
802
803      ALPHA-MARKER ; number marker in number with alpha digit...
804       (when (test letter) (advance OTHER nil))
805       (go ALPHA-DIGIT)
806
807      DIGIT ; seen only ordinary (non-alphabetic) numeric digits...
808       (when (digitp)
809         (if (test letter)
810             (advance ALPHA-DIGIT)
811             (advance DIGIT)))
812       (when (test number other) (advance OTHER nil))
813       (when (test letter) (advance MARKER))
814       (when (test extension slash sign) (advance DIGIT))
815       (when (char= current #\.) (advance DOT-DIGIT))
816       (return t)
817
818      MARKER ; number marker in a numeric number...
819       (when (test letter) (advance OTHER nil))
820       (go DIGIT))))
821 \f
822 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUNCTION*
823 ;;;;
824 ;;;; Case hackery. These functions are stored in
825 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUNCTION* according to the values of
826 ;;;; *PRINT-CASE* and READTABLE-CASE.
827
828 ;;; called when:
829 ;;; READTABLE-CASE      *PRINT-CASE*
830 ;;; :UPCASE             :UPCASE
831 ;;; :DOWNCASE           :DOWNCASE
832 ;;; :PRESERVE           any
833 (defun output-preserve-symbol (pname stream)
834   (declare (simple-string pname))
835   (write-string pname stream))
836
837 ;;; called when:
838 ;;; READTABLE-CASE      *PRINT-CASE*
839 ;;; :UPCASE             :DOWNCASE
840 (defun output-lowercase-symbol (pname stream)
841   (declare (simple-string pname))
842   (dotimes (index (length pname))
843     (let ((char (schar pname index)))
844       (write-char (char-downcase char) stream))))
845
846 ;;; called when:
847 ;;; READTABLE-CASE      *PRINT-CASE*
848 ;;; :DOWNCASE           :UPCASE
849 (defun output-uppercase-symbol (pname stream)
850   (declare (simple-string pname))
851   (dotimes (index (length pname))
852     (let ((char (schar pname index)))
853       (write-char (char-upcase char) stream))))
854
855 ;;; called when:
856 ;;; READTABLE-CASE      *PRINT-CASE*
857 ;;; :UPCASE             :CAPITALIZE
858 ;;; :DOWNCASE           :CAPITALIZE
859 (defun output-capitalize-symbol (pname stream)
860   (declare (simple-string pname))
861   (let ((prev-not-alpha t)
862         (up (eq (readtable-case *readtable*) :upcase)))
863     (dotimes (i (length pname))
864       (let ((char (char pname i)))
865         (write-char (if up
866                         (if (or prev-not-alpha (lower-case-p char))
867                             char
868                             (char-downcase char))
869                         (if prev-not-alpha
870                             (char-upcase char)
871                             char))
872                     stream)
873         (setq prev-not-alpha (not (alpha-char-p char)))))))
874
875 ;;; called when:
876 ;;; READTABLE-CASE      *PRINT-CASE*
877 ;;; :INVERT             any
878 (defun output-invert-symbol (pname stream)
879   (declare (simple-string pname))
880   (let ((all-upper t)
881         (all-lower t))
882     (dotimes (i (length pname))
883       (let ((ch (schar pname i)))
884         (when (both-case-p ch)
885           (if (upper-case-p ch)
886               (setq all-lower nil)
887               (setq all-upper nil)))))
888     (cond (all-upper (output-lowercase-symbol pname stream))
889           (all-lower (output-uppercase-symbol pname stream))
890           (t
891            (write-string pname stream)))))
892
893 #|
894 (defun test1 ()
895   (let ((*readtable* (copy-readtable nil)))
896     (format t "READTABLE-CASE  Input   Symbol-name~@
897                ----------------------------------~%")
898     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
899       (setf (readtable-case *readtable*) readtable-case)
900       (dolist (input '("ZEBRA" "Zebra" "zebra"))
901         (format t "~&:~A~16T~A~24T~A"
902                 (string-upcase readtable-case)
903                 input
904                 (symbol-name (read-from-string input)))))))
905
906 (defun test2 ()
907   (let ((*readtable* (copy-readtable nil)))
908     (format t "READTABLE-CASE  *PRINT-CASE*  Symbol-name  Output  Princ~@
909                --------------------------------------------------------~%")
910     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
911       (setf (readtable-case *readtable*) readtable-case)
912       (dolist (*print-case* '(:upcase :downcase :capitalize))
913         (dolist (symbol '(|ZEBRA| |Zebra| |zebra|))
914           (format t "~&:~A~15T:~A~29T~A~42T~A~50T~A"
915                   (string-upcase readtable-case)
916                   (string-upcase *print-case*)
917                   (symbol-name symbol)
918                   (prin1-to-string symbol)
919                   (princ-to-string symbol)))))))
920 |#
921 \f
922 ;;;; recursive objects
923
924 (defun output-list (list stream)
925   (descend-into (stream)
926     (write-char #\( stream)
927     (let ((length 0)
928           (list list))
929       (loop
930         (punt-print-if-too-long length stream)
931         (output-object (pop list) stream)
932         (unless list
933           (return))
934         (when (or (atom list) (check-for-circularity list))
935           (write-string " . " stream)
936           (output-object list stream)
937           (return))
938         (write-char #\space stream)
939         (incf length)))
940     (write-char #\) stream)))
941
942 (defun output-vector (vector stream)
943   (declare (vector vector))
944   (cond ((stringp vector)
945          (cond ((or *print-escape* *print-readably*)
946                 (write-char #\" stream)
947                 (quote-string vector stream)
948                 (write-char #\" stream))
949                (t
950                 (write-string vector stream))))
951         ((not (or *print-array* *print-readably*))
952          (output-terse-array vector stream))
953         ((bit-vector-p vector)
954          (write-string "#*" stream)
955          (dovector (bit vector)
956            ;; (Don't use OUTPUT-OBJECT here, since this code
957            ;; has to work for all possible *PRINT-BASE* values.)
958            (write-char (if (zerop bit) #\0 #\1) stream)))
959         (t
960          (when (and *print-readably*
961                     (not (eq (array-element-type vector) t)))
962            (error 'print-not-readable :object vector))
963          (descend-into (stream)
964                        (write-string "#(" stream)
965                        (dotimes (i (length vector))
966                          (unless (zerop i)
967                            (write-char #\space stream))
968                          (punt-print-if-too-long i stream)
969                          (output-object (aref vector i) stream))
970                        (write-string ")" stream)))))
971
972 ;;; This function outputs a string quoting characters sufficiently
973 ;;; so that someone can read it in again. Basically, put a slash in
974 ;;; front of an character satisfying NEEDS-SLASH-P.
975 (defun quote-string (string stream)
976   (macrolet ((needs-slash-p (char)
977                ;; KLUDGE: We probably should look at the readtable, but just do
978                ;; this for now. [noted by anonymous long ago] -- WHN 19991130
979                `(or (char= ,char #\\)
980                  (char= ,char #\"))))
981     (with-array-data ((data string) (start) (end (length string)))
982       (do ((index start (1+ index)))
983           ((>= index end))
984         (let ((char (schar data index)))
985           (when (needs-slash-p char) (write-char #\\ stream))
986           (write-char char stream))))))
987
988 ;;; Output the printed representation of any array in either the #< or #A
989 ;;; form.
990 (defun output-array (array stream)
991   (if (or *print-array* *print-readably*)
992       (output-array-guts array stream)
993       (output-terse-array array stream)))
994
995 ;;; Output the abbreviated #< form of an array.
996 (defun output-terse-array (array stream)
997   (let ((*print-level* nil)
998         (*print-length* nil))
999     (print-unreadable-object (array stream :type t :identity t))))
1000
1001 ;;; Output the readable #A form of an array.
1002 (defun output-array-guts (array stream)
1003   (when (and *print-readably*
1004              (not (eq (array-element-type array) t)))
1005     (error 'print-not-readable :object array))
1006   (write-char #\# stream)
1007   (let ((*print-base* 10))
1008     (output-integer (array-rank array) stream))
1009   (write-char #\A stream)
1010   (with-array-data ((data array) (start) (end))
1011     (declare (ignore end))
1012     (sub-output-array-guts data (array-dimensions array) stream start)))
1013
1014 (defun sub-output-array-guts (array dimensions stream index)
1015   (declare (type (simple-array * (*)) array) (fixnum index))
1016   (cond ((null dimensions)
1017          (output-object (aref array index) stream))
1018         (t
1019          (descend-into (stream)
1020            (write-char #\( stream)
1021            (let* ((dimension (car dimensions))
1022                   (dimensions (cdr dimensions))
1023                   (count (reduce #'* dimensions)))
1024              (dotimes (i dimension)
1025                (unless (zerop i)
1026                  (write-char #\space stream))
1027                (punt-print-if-too-long i stream)
1028                (sub-output-array-guts array dimensions stream index)
1029                (incf index count)))
1030            (write-char #\) stream)))))
1031
1032 ;;; a trivial non-generic-function placeholder for PRINT-OBJECT, for
1033 ;;; use until CLOS is set up (at which time it will be replaced with
1034 ;;; the real generic function implementation)
1035 (defun print-object (instance stream)
1036   (default-structure-print instance stream *current-level*))
1037 \f
1038 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
1039
1040 (defun output-integer (integer stream)
1041   ;; FIXME: This UNLESS form should be pulled out into something like
1042   ;; (SANE-PRINT-BASE), along the lines of (SANE-PACKAGE) for the
1043   ;; *PACKAGE* variable.
1044   (unless (and (fixnump *print-base*)
1045                (< 1 *print-base* 37))
1046     (let ((obase *print-base*))
1047       (setq *print-base* 10.)
1048       (error "~A is not a reasonable value for *PRINT-BASE*." obase)))
1049   (when (and (not (= *print-base* 10.))
1050              *print-radix*)
1051     ;; First print leading base information, if any.
1052     (write-char #\# stream)
1053     (write-char (case *print-base*
1054                   (2. #\b)
1055                   (8. #\o)
1056                   (16. #\x)
1057                   (T (let ((fixbase *print-base*)
1058                            (*print-base* 10.)
1059                            (*print-radix* ()))
1060                        (sub-output-integer fixbase stream))
1061                      #\r))
1062                 stream))
1063   ;; Then output a minus sign if the number is negative, then output
1064   ;; the absolute value of the number.
1065   (cond ((bignump integer) (print-bignum integer stream))
1066         ((< integer 0)
1067          (write-char #\- stream)
1068          (sub-output-integer (- integer) stream))
1069         (t
1070          (sub-output-integer integer stream)))
1071   ;; Print any trailing base information, if any.
1072   (if (and (= *print-base* 10.) *print-radix*)
1073       (write-char #\. stream)))
1074
1075 (defun sub-output-integer (integer stream)
1076   (let ((quotient ())
1077         (remainder ()))
1078     ;; Recurse until you have all the digits pushed on the stack.
1079     (if (not (zerop (multiple-value-setq (quotient remainder)
1080                       (truncate integer *print-base*))))
1081         (sub-output-integer quotient stream))
1082     ;; Then as each recursive call unwinds, turn the digit (in remainder)
1083     ;; into a character and output the character.
1084     (write-char (code-char (if (and (> remainder 9.)
1085                                     (> *print-base* 10.))
1086                                (+ (char-code #\A) (- remainder 10.))
1087                                (+ (char-code #\0) remainder)))
1088                 stream)))
1089 \f
1090 ;;;; bignum printing
1091
1092 ;;; *BASE-POWER* holds the number that we keep dividing into the
1093 ;;; bignum for each *print-base*. We want this number as close to
1094 ;;; *most-positive-fixnum* as possible, i.e. (floor (log
1095 ;;; most-positive-fixnum *print-base*)).
1096 (defparameter *base-power* (make-array 37 :initial-element nil))
1097
1098 ;;; *FIXNUM-POWER--1* holds the number of digits for each *PRINT-BASE*
1099 ;;; that fit in the corresponding *base-power*.
1100 (defparameter *fixnum-power--1* (make-array 37 :initial-element nil))
1101
1102 ;;; Print the bignum to the stream. We first generate the correct
1103 ;;; value for *base-power* and *fixnum-power--1* if we have not
1104 ;;; already. Then we call bignum-print-aux to do the printing.
1105 (defun print-bignum (big stream)
1106   (unless (aref *base-power* *print-base*)
1107     (do ((power-1 -1 (1+ power-1))
1108          (new-divisor *print-base* (* new-divisor *print-base*))
1109          (divisor 1 new-divisor))
1110         ((not (fixnump new-divisor))
1111          (setf (aref *base-power* *print-base*) divisor)
1112          (setf (aref *fixnum-power--1* *print-base*) power-1))))
1113   (bignum-print-aux (cond ((minusp big)
1114                            (write-char #\- stream)
1115                            (- big))
1116                           (t big))
1117                     (aref *base-power* *print-base*)
1118                     (aref *fixnum-power--1* *print-base*)
1119                     stream)
1120   big)
1121
1122 (defun bignum-print-aux (big divisor power-1 stream)
1123   (multiple-value-bind (newbig fix) (truncate big divisor)
1124     (if (fixnump newbig)
1125         (sub-output-integer newbig stream)
1126         (bignum-print-aux newbig divisor power-1 stream))
1127     (do ((zeros power-1 (1- zeros))
1128          (base-power *print-base* (* base-power *print-base*)))
1129         ((> base-power fix)
1130          (dotimes (i zeros) (write-char #\0 stream))
1131          (sub-output-integer fix stream)))))
1132
1133 (defun output-ratio (ratio stream)
1134   (when *print-radix*
1135     (write-char #\# stream)
1136     (case *print-base*
1137       (2 (write-char #\b stream))
1138       (8 (write-char #\o stream))
1139       (16 (write-char #\x stream))
1140       (t (write *print-base* :stream stream :radix nil :base 10)))
1141     (write-char #\r stream))
1142   (let ((*print-radix* nil))
1143     (output-integer (numerator ratio) stream)
1144     (write-char #\/ stream)
1145     (output-integer (denominator ratio) stream)))
1146
1147 (defun output-complex (complex stream)
1148   (write-string "#C(" stream)
1149   (output-object (realpart complex) stream)
1150   (write-char #\space stream)
1151   (output-object (imagpart complex) stream)
1152   (write-char #\) stream))
1153 \f
1154 ;;;; float printing
1155
1156 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1157 ;;; most of the work for all printing of floating point numbers in the
1158 ;;; printer and in FORMAT. It converts a floating point number to a
1159 ;;; string in a free or fixed format with no exponent. The
1160 ;;; interpretation of the arguments is as follows:
1161 ;;;
1162 ;;;     X       - The floating point number to convert, which must not be
1163 ;;;             negative.
1164 ;;;     WIDTH    - The preferred field width, used to determine the number
1165 ;;;             of fraction digits to produce if the FDIGITS parameter
1166 ;;;             is unspecified or NIL. If the non-fraction digits and the
1167 ;;;             decimal point alone exceed this width, no fraction digits
1168 ;;;             will be produced unless a non-NIL value of FDIGITS has been
1169 ;;;             specified. Field overflow is not considerd an error at this
1170 ;;;             level.
1171 ;;;     FDIGITS  - The number of fractional digits to produce. Insignificant
1172 ;;;             trailing zeroes may be introduced as needed. May be
1173 ;;;             unspecified or NIL, in which case as many digits as possible
1174 ;;;             are generated, subject to the constraint that there are no
1175 ;;;             trailing zeroes.
1176 ;;;     SCALE    - If this parameter is specified or non-NIL, then the number
1177 ;;;             printed is (* x (expt 10 scale)). This scaling is exact,
1178 ;;;             and cannot lose precision.
1179 ;;;     FMIN     - This parameter, if specified or non-NIL, is the minimum
1180 ;;;             number of fraction digits which will be produced, regardless
1181 ;;;             of the value of WIDTH or FDIGITS. This feature is used by
1182 ;;;             the ~E format directive to prevent complete loss of
1183 ;;;             significance in the printed value due to a bogus choice of
1184 ;;;             scale factor.
1185 ;;;
1186 ;;; Most of the optional arguments are for the benefit for FORMAT and are not
1187 ;;; used by the printer.
1188 ;;;
1189 ;;; Returns:
1190 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1191 ;;; where the results have the following interpretation:
1192 ;;;
1193 ;;;     DIGIT-STRING    - The decimal representation of X, with decimal point.
1194 ;;;     DIGIT-LENGTH    - The length of the string DIGIT-STRING.
1195 ;;;     LEADING-POINT   - True if the first character of DIGIT-STRING is the
1196 ;;;                    decimal point.
1197 ;;;     TRAILING-POINT  - True if the last character of DIGIT-STRING is the
1198 ;;;                    decimal point.
1199 ;;;     POINT-POS       - The position of the digit preceding the decimal
1200 ;;;                    point. Zero indicates point before first digit.
1201 ;;;
1202 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1203 ;;; accuracy. Specifically, the decimal number printed is the closest
1204 ;;; possible approximation to the true value of the binary number to
1205 ;;; be printed from among all decimal representations with the same
1206 ;;; number of digits. In free-format output, i.e. with the number of
1207 ;;; digits unconstrained, it is guaranteed that all the information is
1208 ;;; preserved, so that a properly- rounding reader can reconstruct the
1209 ;;; original binary number, bit-for-bit, from its printed decimal
1210 ;;; representation. Furthermore, only as many digits as necessary to
1211 ;;; satisfy this condition will be printed.
1212 ;;;
1213 ;;; FLOAT-STRING actually generates the digits for positive numbers.
1214 ;;; The algorithm is essentially that of algorithm Dragon4 in "How to
1215 ;;; Print Floating-Point Numbers Accurately" by Steele and White. The
1216 ;;; current (draft) version of this paper may be found in
1217 ;;; [CMUC]<steele>tradix.press. DO NOT EVEN THINK OF ATTEMPTING TO
1218 ;;; UNDERSTAND THIS CODE WITHOUT READING THE PAPER!
1219
1220 (defvar *digits* "0123456789")
1221
1222 (defun flonum-to-string (x &optional width fdigits scale fmin)
1223   (cond ((zerop x)
1224          ;; Zero is a special case which FLOAT-STRING cannot handle.
1225          (if fdigits
1226              (let ((s (make-string (1+ fdigits) :initial-element #\0)))
1227                (setf (schar s 0) #\.)
1228                (values s (length s) t (zerop fdigits) 0))
1229              (values "." 1 t t 0)))
1230         (t
1231          (multiple-value-bind (sig exp) (integer-decode-float x)
1232            (let* ((precision (float-precision x))
1233                   (digits (float-digits x))
1234                   (fudge (- digits precision))
1235                   (width (if width (max width 1) nil)))
1236            (float-string (ash sig (- fudge)) (+ exp fudge) precision width
1237                          fdigits scale fmin))))))
1238
1239 (defun float-string (fraction exponent precision width fdigits scale fmin)
1240   (let ((r fraction) (s 1) (m- 1) (m+ 1) (k 0)
1241         (digits 0) (decpnt 0) (cutoff nil) (roundup nil) u low high
1242         (digit-string (make-array 50
1243                                   :element-type 'base-char
1244                                   :fill-pointer 0
1245                                   :adjustable t)))
1246     ;; Represent fraction as r/s, error bounds as m+/s and m-/s.
1247     ;; Rational arithmetic avoids loss of precision in subsequent
1248     ;; calculations.
1249     (cond ((> exponent 0)
1250            (setq r (ash fraction exponent))
1251            (setq m- (ash 1 exponent))
1252            (setq m+ m-))
1253           ((< exponent 0)
1254            (setq s (ash 1 (- exponent)))))
1255     ;; Adjust the error bounds m+ and m- for unequal gaps.
1256     (when (= fraction (ash 1 precision))
1257       (setq m+ (ash m+ 1))
1258       (setq r (ash r 1))
1259       (setq s (ash s 1)))
1260     ;; Scale value by requested amount, and update error bounds.
1261     (when scale
1262       (if (minusp scale)
1263           (let ((scale-factor (expt 10 (- scale))))
1264             (setq s (* s scale-factor)))
1265           (let ((scale-factor (expt 10 scale)))
1266             (setq r (* r scale-factor))
1267             (setq m+ (* m+ scale-factor))
1268             (setq m- (* m- scale-factor)))))
1269     ;; Scale r and s and compute initial k, the base 10 logarithm of r.
1270     (do ()
1271         ((>= r (ceiling s 10)))
1272       (decf k)
1273       (setq r (* r 10))
1274       (setq m- (* m- 10))
1275       (setq m+ (* m+ 10)))
1276     (do ()(nil)
1277       (do ()
1278           ((< (+ (ash r 1) m+) (ash s 1)))
1279         (setq s (* s 10))
1280         (incf k))
1281       ;; Determine number of fraction digits to generate.
1282       (cond (fdigits
1283              ;; Use specified number of fraction digits.
1284              (setq cutoff (- fdigits))
1285              ;;don't allow less than fmin fraction digits
1286              (if (and fmin (> cutoff (- fmin))) (setq cutoff (- fmin))))
1287             (width
1288              ;; Use as many fraction digits as width will permit but
1289              ;; force at least fmin digits even if width will be
1290              ;; 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
1296       ;; has been exhausted, rounding the last digit may cause a carry
1297       ;; propagation. We can prevent this, preserving left-to-right
1298       ;; digit generation, with a few magical adjustments to m- and
1299       ;; m+. Of course, correct rounding 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
1330       ;; many 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
1358 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1359 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1360 ;;; original number. There may be some loss of precision due the
1361 ;;; floating point representation. The scaling is always done with
1362 ;;; long float arithmetic, which helps printing of lesser precisions
1363 ;;; as well as avoiding generic arithmetic.
1364 ;;;
1365 ;;; When computing our initial scale factor using EXPT, we pull out
1366 ;;; part of the computation to avoid over/under flow. When
1367 ;;; denormalized, we must pull out a large factor, since there is more
1368 ;;; negative exponent range than positive range.
1369 (defun scale-exponent (original-x)
1370   (let* ((x (coerce original-x 'long-float)))
1371     (multiple-value-bind (sig exponent) (decode-float x)
1372       (declare (ignore sig))
1373       (if (= x 0.0l0)
1374           (values (float 0.0l0 original-x) 1)
1375           (let* ((ex (round (* exponent (log 2l0 10))))
1376                  (x (if (minusp ex)
1377                         (if (float-denormalized-p x)
1378                             #!-long-float
1379                             (* x 1.0l16 (expt 10.0l0 (- (- ex) 16)))
1380                             #!+long-float
1381                             (* x 1.0l18 (expt 10.0l0 (- (- ex) 18)))
1382                             (* x 10.0l0 (expt 10.0l0 (- (- ex) 1))))
1383                         (/ x 10.0l0 (expt 10.0l0 (1- ex))))))
1384             (do ((d 10.0l0 (* d 10.0l0))
1385                  (y x (/ x d))
1386                  (ex ex (1+ ex)))
1387                 ((< y 1.0l0)
1388                  (do ((m 10.0l0 (* m 10.0l0))
1389                       (z y (* y m))
1390                       (ex ex (1- ex)))
1391                      ((>= z 0.1l0)
1392                       (values (float z original-x) ex))))))))))
1393 \f
1394 ;;;; entry point for the float printer
1395
1396 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1397 ;;; argument is printed free-format, in either exponential or
1398 ;;; non-exponential notation, depending on its magnitude.
1399 ;;;
1400 ;;; NOTE: When a number is to be printed in exponential format, it is
1401 ;;; scaled in floating point. Since precision may be lost in this
1402 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1403 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1404 ;;; extensive computations with integers of similar magnitude to that
1405 ;;; of the number being printed. For large exponents, the bignums
1406 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1407 ;;; fast and the exponent range is not too large, then it might become
1408 ;;; attractive to handle exponential notation with the same accuracy
1409 ;;; as non-exponential notation, using the method described in the
1410 ;;; Steele and White paper.
1411
1412 ;;; Print the appropriate exponent marker for X and the specified exponent.
1413 (defun print-float-exponent (x exp stream)
1414   (declare (type float x) (type integer exp) (type stream stream))
1415   (let ((*print-radix* nil)
1416         (plusp (plusp exp)))
1417     (if (typep x *read-default-float-format*)
1418         (unless (eql exp 0)
1419           (format stream "e~:[~;+~]~D" plusp exp))
1420         (format stream "~C~:[~;+~]~D"
1421                 (etypecase x
1422                   (single-float #\f)
1423                   (double-float #\d)
1424                   (short-float #\s)
1425                   (long-float #\L))
1426                 plusp exp))))
1427
1428 (defun output-float-infinity (x stream)
1429   (declare (float x) (stream stream))
1430   (cond (*read-eval*
1431          (write-string "#." stream))
1432         (*print-readably*
1433          (error 'print-not-readable :object x))
1434         (t
1435          (write-string "#<" stream)))
1436   (write-string "SB-EXT:" stream)
1437   (write-string (symbol-name (float-format-name x)) stream)
1438   (write-string (if (plusp x) "-POSITIVE-" "-NEGATIVE-")
1439                 stream)
1440   (write-string "INFINITY" stream)
1441   (unless *read-eval*
1442     (write-string ">" stream)))
1443
1444 (defun output-float-nan (x stream)
1445   (print-unreadable-object (x stream)
1446     (princ (float-format-name x) stream)
1447     (write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
1448     (write-string " NaN" stream)))
1449
1450 ;;; the function called by OUTPUT-OBJECT to handle floats
1451 (defun output-float (x stream)
1452   (cond
1453    ((float-infinity-p x)
1454     (output-float-infinity x stream))
1455    ((float-nan-p x)
1456     (output-float-nan x stream))
1457    (t
1458     (let ((x (cond ((minusp (float-sign x))
1459                     (write-char #\- stream)
1460                     (- x))
1461                    (t
1462                     x))))
1463       (cond
1464        ((zerop x)
1465         (write-string "0.0" stream)
1466         (print-float-exponent x 0 stream))
1467        (t
1468         (output-float-aux x stream (float 1/1000 x) (float 10000000 x))))))))
1469 (defun output-float-aux (x stream e-min e-max)
1470   (if (and (>= x e-min) (< x e-max))
1471       ;; free format
1472       (multiple-value-bind (str len lpoint tpoint) (flonum-to-string x)
1473         (declare (ignore len))
1474         (when lpoint (write-char #\0 stream))
1475         (write-string str stream)
1476         (when tpoint (write-char #\0 stream))
1477         (print-float-exponent x 0 stream))
1478       ;; exponential format
1479       (multiple-value-bind (f ex) (scale-exponent x)
1480         (multiple-value-bind (str len lpoint tpoint)
1481             (flonum-to-string f nil nil 1)
1482           (declare (ignore len))
1483           (when lpoint (write-char #\0 stream))
1484           (write-string str stream)
1485           (when tpoint (write-char #\0 stream))
1486           ;; Subtract out scale factor of 1 passed to FLONUM-TO-STRING.
1487           (print-float-exponent x (1- ex) stream)))))
1488 \f
1489 ;;;; other leaf objects
1490
1491 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1492 ;;; the character name or the character in the #\char format.
1493 (defun output-character (char stream)
1494   (if (or *print-escape* *print-readably*)
1495       (let ((name (char-name char)))
1496         (write-string "#\\" stream)
1497         (if name
1498             (quote-string name stream)
1499             (write-char char stream)))
1500       (write-char char stream)))
1501
1502 (defun output-sap (sap stream)
1503   (declare (type system-area-pointer sap))
1504   (cond (*read-eval*
1505          (format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
1506         (t
1507          (print-unreadable-object (sap stream)
1508            (format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
1509
1510 (defun output-weak-pointer (weak-pointer stream)
1511   (declare (type weak-pointer weak-pointer))
1512   (print-unreadable-object (weak-pointer stream)
1513     (multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
1514       (cond (validp
1515              (write-string "weak pointer: " stream)
1516              (write value :stream stream))
1517             (t
1518              (write-string "broken weak pointer" stream))))))
1519
1520 (defun output-code-component (component stream)
1521   (print-unreadable-object (component stream :identity t)
1522     (let ((dinfo (%code-debug-info component)))
1523       (cond ((eq dinfo :bogus-lra)
1524              (write-string "bogus code object" stream))
1525             (t
1526              (write-string "code object" stream)
1527              (when dinfo
1528                (write-char #\space stream)
1529                (output-object (sb!c::debug-info-name dinfo) stream)))))))
1530
1531 (defun output-lra (lra stream)
1532   (print-unreadable-object (lra stream :identity t)
1533     (write-string "return PC object" stream)))
1534
1535 (defun output-fdefn (fdefn stream)
1536   (print-unreadable-object (fdefn stream)
1537     (write-string "FDEFINITION object for " stream)
1538     (output-object (fdefn-name fdefn) stream)))
1539 \f
1540 ;;;; functions
1541
1542 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1543 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1544 ;;;
1545 ;;; The definition here is a simple temporary placeholder. It will be
1546 ;;; overwritten by a smarter version (capable of calling generic
1547 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1548 (defun printed-as-clos-funcallable-standard-class (object stream)
1549   (declare (ignore object stream))
1550   nil)
1551
1552 (defun output-function (object stream)
1553   (let* ((*print-length* 3) ; in case we have to..
1554          (*print-level* 3)  ; ..print an interpreted function definition
1555          (name (cond ((find (function-subtype object)
1556                             #(#.sb!vm:closure-header-type
1557                               #.sb!vm:byte-code-closure-type))
1558                       "CLOSURE")
1559                      #!+sb-interpreter
1560                      ((sb!eval::interpreted-function-p object)
1561                       (or (sb!eval::interpreted-function-%name object)
1562                           (sb!eval:interpreted-function-lambda-expression
1563                            object)))
1564                      ((find (function-subtype object)
1565                             #(#.sb!vm:function-header-type
1566                               #.sb!vm:closure-function-header-type))
1567                       (%function-name object))
1568                      (t 'no-name-available)))
1569          (identified-by-name-p (and (symbolp name)
1570                                     (fboundp name)
1571                                     (eq (fdefinition name) object))))
1572       (print-unreadable-object (object
1573                                 stream
1574                                 :identity (not identified-by-name-p))
1575         (prin1 'function stream)
1576         (unless (eq name 'no-name-available)
1577           (format stream " ~S" name)))))
1578 \f
1579 ;;;; catch-all for unknown things
1580
1581 (defun output-random (object stream)
1582   (print-unreadable-object (object stream :identity t)
1583     (let ((lowtag (get-lowtag object)))
1584       (case lowtag
1585         (#.sb!vm:other-pointer-type
1586           (let ((type (get-type object)))
1587             (case type
1588               (#.sb!vm:value-cell-header-type
1589                (write-string "value cell " stream)
1590                (output-object (sb!c:value-cell-ref object) stream))
1591               (t
1592                (write-string "unknown pointer object, type=" stream)
1593                (let ((*print-base* 16) (*print-radix* t))
1594                  (output-integer type stream))))))
1595         ((#.sb!vm:function-pointer-type
1596           #.sb!vm:instance-pointer-type
1597           #.sb!vm:list-pointer-type)
1598          (write-string "unknown pointer object, type=" stream))
1599         (t
1600          (case (get-type object)
1601            (#.sb!vm:unbound-marker-type
1602             (write-string "unbound marker" stream))
1603            (t
1604             (write-string "unknown immediate object, lowtag=" stream)
1605             (let ((*print-base* 2) (*print-radix* t))
1606               (output-integer lowtag stream))
1607             (write-string ", type=" stream)
1608             (let ((*print-base* 16) (*print-radix* t))
1609               (output-integer (get-type object) stream)))))))))