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