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