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