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