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