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