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