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