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