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