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