0.9.5.62: trivial PCL cleanups
[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 (defun stringify-object (object)
234   (let ((stream (make-string-output-stream)))
235     (setup-printer-state)
236     (output-object object stream)
237     (get-output-stream-string stream)))
238 \f
239 ;;;; support for the PRINT-UNREADABLE-OBJECT macro
240
241 ;;; guts of PRINT-UNREADABLE-OBJECT
242 (defun %print-unreadable-object (object stream type identity body)
243   (declare (type (or null function) body))
244   (when *print-readably*
245     (error 'print-not-readable :object object))
246   (flet ((print-description ()
247            (when type
248              (write (type-of object) :stream stream :circle nil
249                     :level nil :length nil)
250              (write-char #\space stream))
251            (when body
252              (funcall body))
253            (when identity
254              (when (or body (not type))
255                (write-char #\space stream))
256              (write-char #\{ stream)
257              (write (get-lisp-obj-address object) :stream stream
258                     :radix nil :base 16)
259              (write-char #\} stream))))
260     (cond ((print-pretty-on-stream-p stream)
261            ;; Since we're printing prettily on STREAM, format the
262            ;; object within a logical block. PPRINT-LOGICAL-BLOCK does
263            ;; not rebind the stream when it is already a pretty stream,
264            ;; so output from the body will go to the same stream.
265            (pprint-logical-block (stream nil :prefix "#<" :suffix ">")
266              (print-description)))
267           (t
268             (write-string "#<" stream)
269             (print-description)
270             (write-char #\> stream))))
271   nil)
272 \f
273 ;;;; OUTPUT-OBJECT -- the main entry point
274
275 ;;; Objects whose print representation identifies them EQLly don't
276 ;;; need to be checked for circularity.
277 (defun uniquely-identified-by-print-p (x)
278   (or (numberp x)
279       (characterp x)
280       (and (symbolp x)
281            (symbol-package x))))
282
283 ;;; Output OBJECT to STREAM observing all printer control variables.
284 (defun output-object (object stream)
285   (labels ((print-it (stream)
286              (if *print-pretty*
287                  (sb!pretty:output-pretty-object object stream)
288                  (output-ugly-object object stream)))
289            (check-it (stream)
290              (multiple-value-bind (marker initiate)
291                  (check-for-circularity object t)
292                (if (eq initiate :initiate)
293                    (let ((*circularity-hash-table*
294                           (make-hash-table :test 'eq)))
295                      (check-it (make-broadcast-stream))
296                      (let ((*circularity-counter* 0))
297                        (check-it stream)))
298                    ;; otherwise
299                    (if marker
300                        (when (handle-circularity marker stream)
301                          (print-it stream))
302                        (print-it stream))))))
303     (cond (;; Maybe we don't need to bother with circularity detection.
304            (or (not *print-circle*)
305                (uniquely-identified-by-print-p object))
306            (print-it stream))
307           (;; If we have already started circularity detection, this
308            ;; object might be a shared reference. If we have not, then
309            ;; if it is a compound object it might contain a circular
310            ;; reference to itself or multiple shared references.
311            (or *circularity-hash-table*
312                (compound-object-p object))
313            (check-it stream))
314           (t
315            (print-it stream)))))
316
317 ;;; a hack to work around recurring gotchas with printing while
318 ;;; DEFGENERIC PRINT-OBJECT is being built
319 ;;;
320 ;;; (hopefully will go away naturally when CLOS moves into cold init)
321 (defvar *print-object-is-disabled-p*)
322
323 ;;; Output OBJECT to STREAM observing all printer control variables
324 ;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
325 ;;; then the pretty printer will be used for any components of OBJECT,
326 ;;; just not for OBJECT itself.
327 (defun output-ugly-object (object stream)
328   (typecase object
329     ;; KLUDGE: The TYPECASE approach here is non-ANSI; the ANSI definition of
330     ;; PRINT-OBJECT says it provides printing and we're supposed to provide
331     ;; PRINT-OBJECT methods covering all classes. We deviate from this
332     ;; by using PRINT-OBJECT only when we print instance values. However,
333     ;; ANSI makes it hard to tell that we're deviating from this:
334     ;;   (1) ANSI specifies that the user isn't supposed to call PRINT-OBJECT
335     ;;       directly.
336     ;;   (2) ANSI (section 11.1.2.1.2) says it's undefined to define
337     ;;       a method on an external symbol in the CL package which is
338     ;;       applicable to arg lists containing only direct instances of
339     ;;       standardized classes.
340     ;; Thus, in order for the user to detect our sleaziness in conforming
341     ;; code, he has to do something relatively obscure like
342     ;;   (1) actually use tools like FIND-METHOD to look for PRINT-OBJECT
343     ;;       methods, or
344     ;;   (2) define a PRINT-OBJECT method which is specialized on the stream
345     ;;       value (e.g. a Gray stream object).
346     ;; As long as no one comes up with a non-obscure way of detecting this
347     ;; sleaziness, fixing this nonconformity will probably have a low
348     ;; priority. -- WHN 2001-11-25
349     (list
350      (if (null object)
351          (output-symbol object stream)
352          (output-list object stream)))
353     (instance
354      (cond ((not (and (boundp '*print-object-is-disabled-p*)
355                       *print-object-is-disabled-p*))
356             (print-object object stream))
357            ((typep object 'structure-object)
358             (default-structure-print object stream *current-level-in-print*))
359            (t
360             (write-string "#<INSTANCE but not STRUCTURE-OBJECT>" stream))))
361     (function
362      (unless (and (funcallable-instance-p object)
363                   (printed-as-funcallable-standard-class object stream))
364        (output-fun object stream)))
365     (symbol
366      (output-symbol object stream))
367     (number
368      (etypecase object
369        (integer
370         (output-integer object stream))
371        (float
372         (output-float object stream))
373        (ratio
374         (output-ratio object stream))
375        (ratio
376         (output-ratio object stream))
377        (complex
378         (output-complex object stream))))
379     (character
380      (output-character object stream))
381     (vector
382      (output-vector object stream))
383     (array
384      (output-array object stream))
385     (system-area-pointer
386      (output-sap object stream))
387     (weak-pointer
388      (output-weak-pointer object stream))
389     (lra
390      (output-lra object stream))
391     (code-component
392      (output-code-component object stream))
393     (fdefn
394      (output-fdefn object stream))
395     (t
396      (output-random object stream))))
397 \f
398 ;;;; symbols
399
400 ;;; values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last
401 ;;; time the printer was called
402 (defvar *previous-case* nil)
403 (defvar *previous-readtable-case* nil)
404
405 ;;; This variable contains the current definition of one of three
406 ;;; symbol printers. SETUP-PRINTER-STATE sets this variable.
407 (defvar *internal-symbol-output-fun* nil)
408
409 ;;; This function sets the internal global symbol
410 ;;; *INTERNAL-SYMBOL-OUTPUT-FUN* to the right function depending on
411 ;;; the value of *PRINT-CASE*. See the manual for details. The print
412 ;;; buffer stream is also reset.
413 (defun setup-printer-state ()
414   (unless (and (eq *print-case* *previous-case*)
415                (eq (readtable-case *readtable*) *previous-readtable-case*))
416     (setq *previous-case* *print-case*)
417     (setq *previous-readtable-case* (readtable-case *readtable*))
418     (unless (member *print-case* '(:upcase :downcase :capitalize))
419       (setq *print-case* :upcase)
420       (error "invalid *PRINT-CASE* value: ~S" *previous-case*))
421     (unless (member *previous-readtable-case*
422                     '(:upcase :downcase :invert :preserve))
423       (setf (readtable-case *readtable*) :upcase)
424       (error "invalid READTABLE-CASE value: ~S" *previous-readtable-case*))
425
426     (setq *internal-symbol-output-fun*
427           (case *previous-readtable-case*
428             (:upcase
429              (case *print-case*
430                (:upcase #'output-preserve-symbol)
431                (:downcase #'output-lowercase-symbol)
432                (:capitalize #'output-capitalize-symbol)))
433             (:downcase
434              (case *print-case*
435                (:upcase #'output-uppercase-symbol)
436                (:downcase #'output-preserve-symbol)
437                (:capitalize #'output-capitalize-symbol)))
438             (:preserve #'output-preserve-symbol)
439             (:invert #'output-invert-symbol)))))
440
441 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
442 ;;; and with any embedded |'s or \'s escaped.
443 (defun output-quoted-symbol-name (pname stream)
444   (write-char #\| stream)
445   (dotimes (index (length pname))
446     (let ((char (schar pname index)))
447       (when (or (char= char #\\) (char= char #\|))
448         (write-char #\\ stream))
449       (write-char char stream)))
450   (write-char #\| stream))
451
452 (defun output-symbol (object stream)
453   (if (or *print-escape* *print-readably*)
454       (let ((package (symbol-package object))
455             (name (symbol-name object)))
456         (cond
457          ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
458          ;; requires that keywords be printed with preceding colons
459          ;; always, regardless of the value of *PACKAGE*.
460          ((eq package *keyword-package*)
461           (write-char #\: stream))
462          ;; Otherwise, if the symbol's home package is the current
463          ;; one, then a prefix is never necessary.
464          ((eq package (sane-package)))
465          ;; Uninterned symbols print with a leading #:.
466          ((null package)
467           (when (or *print-gensym* *print-readably*)
468             (write-string "#:" stream)))
469          (t
470           (multiple-value-bind (symbol accessible)
471               (find-symbol name (sane-package))
472             ;; If we can find the symbol by looking it up, it need not
473             ;; be qualified. This can happen if the symbol has been
474             ;; inherited from a package other than its home package.
475             (unless (and accessible (eq symbol object))
476               (output-symbol-name (package-name package) stream)
477               (multiple-value-bind (symbol externalp)
478                   (find-external-symbol name package)
479                 (declare (ignore symbol))
480                 (if externalp
481                     (write-char #\: stream)
482                     (write-string "::" stream)))))))
483         (output-symbol-name name stream))
484       (output-symbol-name (symbol-name object) stream nil)))
485
486 ;;; Output the string NAME as if it were a symbol name. In other
487 ;;; words, diddle its case according to *PRINT-CASE* and
488 ;;; READTABLE-CASE.
489 (defun output-symbol-name (name stream &optional (maybe-quote t))
490   (declare (type simple-string name))
491   (let ((*readtable* (if *print-readably* *standard-readtable* *readtable*)))
492     (setup-printer-state)
493     (if (and maybe-quote (symbol-quotep name))
494         (output-quoted-symbol-name name stream)
495         (funcall *internal-symbol-output-fun* name stream))))
496 \f
497 ;;;; escaping symbols
498
499 ;;; When we print symbols we have to figure out if they need to be
500 ;;; printed with escape characters. This isn't a whole lot easier than
501 ;;; reading symbols in the first place.
502 ;;;
503 ;;; For each character, the value of the corresponding element is a
504 ;;; fixnum with bits set corresponding to attributes that the
505 ;;; character has. At characters have at least one bit set, so we can
506 ;;; search for any character with a positive test.
507 (defvar *character-attributes*
508   (make-array 160 ; FIXME
509               :element-type '(unsigned-byte 16)
510               :initial-element 0))
511 (declaim (type (simple-array (unsigned-byte 16) (#.160)) ; FIXME
512                *character-attributes*))
513
514 ;;; constants which are a bit-mask for each interesting character attribute
515 (defconstant other-attribute            (ash 1 0)) ; Anything else legal.
516 (defconstant number-attribute           (ash 1 1)) ; A numeric digit.
517 (defconstant uppercase-attribute        (ash 1 2)) ; An uppercase letter.
518 (defconstant lowercase-attribute        (ash 1 3)) ; A lowercase letter.
519 (defconstant sign-attribute             (ash 1 4)) ; +-
520 (defconstant extension-attribute        (ash 1 5)) ; ^_
521 (defconstant dot-attribute              (ash 1 6)) ; .
522 (defconstant slash-attribute            (ash 1 7)) ; /
523 (defconstant funny-attribute            (ash 1 8)) ; Anything illegal.
524
525 (eval-when (:compile-toplevel :load-toplevel :execute)
526
527 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
528 ;;; that don't need to be escaped (according to READTABLE-CASE.)
529 (defparameter *attribute-names*
530   `((number . number-attribute) (lowercase . lowercase-attribute)
531     (uppercase . uppercase-attribute) (letter . letter-attribute)
532     (sign . sign-attribute) (extension . extension-attribute)
533     (dot . dot-attribute) (slash . slash-attribute)
534     (other . other-attribute) (funny . funny-attribute)))
535
536 ) ; EVAL-WHEN
537
538 (flet ((set-bit (char bit)
539          (let ((code (char-code char)))
540            (setf (aref *character-attributes* code)
541                  (logior bit (aref *character-attributes* code))))))
542
543   (dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
544                   #\? #\< #\>))
545     (set-bit char other-attribute))
546
547   (dotimes (i 10)
548     (set-bit (digit-char i) number-attribute))
549
550   (do ((code (char-code #\A) (1+ code))
551        (end (char-code #\Z)))
552       ((> code end))
553     (declare (fixnum code end))
554     (set-bit (code-char code) uppercase-attribute)
555     (set-bit (char-downcase (code-char code)) lowercase-attribute))
556
557   (set-bit #\- sign-attribute)
558   (set-bit #\+ sign-attribute)
559   (set-bit #\^ extension-attribute)
560   (set-bit #\_ extension-attribute)
561   (set-bit #\. dot-attribute)
562   (set-bit #\/ slash-attribute)
563
564   ;; Mark anything not explicitly allowed as funny.
565   (dotimes (i 160) ; FIXME
566     (when (zerop (aref *character-attributes* i))
567       (setf (aref *character-attributes* i) funny-attribute))))
568
569 ;;; For each character, the value of the corresponding element is the
570 ;;; lowest base in which that character is a digit.
571 (defvar *digit-bases*
572   (make-array 128 ; FIXME
573               :element-type '(unsigned-byte 8)
574               :initial-element 36))
575 (declaim (type (simple-array (unsigned-byte 8) (#.128)) ; FIXME
576                *digit-bases*))
577 (dotimes (i 36)
578   (let ((char (digit-char i 36)))
579     (setf (aref *digit-bases* (char-code char)) i)))
580
581 ;;; A FSM-like thingie that determines whether a symbol is a potential
582 ;;; number or has evil characters in it.
583 (defun symbol-quotep (name)
584   (declare (simple-string name))
585   (macrolet ((advance (tag &optional (at-end t))
586                `(progn
587                  (when (= index len)
588                    ,(if at-end '(go TEST-SIGN) '(return nil)))
589                  (setq current (schar name index)
590                        code (char-code current)
591                        bits (cond ; FIXME
592                               ((< code 160) (aref attributes code))
593                               ((upper-case-p current) uppercase-attribute)
594                               ((lower-case-p current) lowercase-attribute)
595                               (t other-attribute)))
596                  (incf index)
597                  (go ,tag)))
598              (test (&rest attributes)
599                 `(not (zerop
600                        (the fixnum
601                             (logand
602                              (logior ,@(mapcar
603                                         (lambda (x)
604                                           (or (cdr (assoc x
605                                                           *attribute-names*))
606                                               (error "Blast!")))
607                                         attributes))
608                              bits)))))
609              (digitp ()
610                `(and (< code 128) ; FIXME
611                      (< (the fixnum (aref bases code)) base))))
612
613     (prog ((len (length name))
614            (attributes *character-attributes*)
615            (bases *digit-bases*)
616            (base *print-base*)
617            (letter-attribute
618             (case (readtable-case *readtable*)
619               (:upcase uppercase-attribute)
620               (:downcase lowercase-attribute)
621               (t (logior lowercase-attribute uppercase-attribute))))
622            (index 0)
623            (bits 0)
624            (code 0)
625            current)
626       (declare (fixnum len base index bits code))
627       (advance START t)
628
629      TEST-SIGN ; At end, see whether it is a sign...
630       (return (not (test sign)))
631
632      OTHER ; not potential number, see whether funny chars...
633       (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
634                                   funny-attribute)
635                           letter-attribute)))
636         (do ((i (1- index) (1+ i)))
637             ((= i len) (return-from symbol-quotep nil))
638           (unless (zerop (logand (let* ((char (schar name i))
639                                         (code (char-code char)))
640                                    (cond
641                                      ((< code 160) (aref attributes code))
642                                      ((upper-case-p char) uppercase-attribute)
643                                      ((lower-case-p char) lowercase-attribute)
644                                      (t other-attribute)))
645                                  mask))
646             (return-from symbol-quotep t))))
647
648      START
649       (when (digitp)
650         (if (test letter)
651             (advance LAST-DIGIT-ALPHA)
652             (advance DIGIT)))
653       (when (test letter number other slash) (advance OTHER nil))
654       (when (char= current #\.) (advance DOT-FOUND))
655       (when (test sign extension) (advance START-STUFF nil))
656       (return t)
657
658      DOT-FOUND ; leading dots...
659       (when (test letter) (advance START-DOT-MARKER nil))
660       (when (digitp) (advance DOT-DIGIT))
661       (when (test number other) (advance OTHER nil))
662       (when (test extension slash sign) (advance START-DOT-STUFF nil))
663       (when (char= current #\.) (advance DOT-FOUND))
664       (return t)
665
666      START-STUFF ; leading stuff before any dot or digit
667       (when (digitp)
668         (if (test letter)
669             (advance LAST-DIGIT-ALPHA)
670             (advance DIGIT)))
671       (when (test number other) (advance OTHER nil))
672       (when (test letter) (advance START-MARKER nil))
673       (when (char= current #\.) (advance START-DOT-STUFF nil))
674       (when (test sign extension slash) (advance START-STUFF nil))
675       (return t)
676
677      START-MARKER ; number marker in leading stuff...
678       (when (test letter) (advance OTHER nil))
679       (go START-STUFF)
680
681      START-DOT-STUFF ; leading stuff containing dot without digit...
682       (when (test letter) (advance START-DOT-STUFF nil))
683       (when (digitp) (advance DOT-DIGIT))
684       (when (test sign extension dot slash) (advance START-DOT-STUFF nil))
685       (when (test number other) (advance OTHER nil))
686       (return t)
687
688      START-DOT-MARKER ; number marker in leading stuff with dot..
689       ;; leading stuff containing dot without digit followed by letter...
690       (when (test letter) (advance OTHER nil))
691       (go START-DOT-STUFF)
692
693      DOT-DIGIT ; in a thing with dots...
694       (when (test letter) (advance DOT-MARKER))
695       (when (digitp) (advance DOT-DIGIT))
696       (when (test number other) (advance OTHER nil))
697       (when (test sign extension dot slash) (advance DOT-DIGIT))
698       (return t)
699
700      DOT-MARKER ; number marker in number with dot...
701       (when (test letter) (advance OTHER nil))
702       (go DOT-DIGIT)
703
704      LAST-DIGIT-ALPHA ; previous char is a letter digit...
705       (when (or (digitp) (test sign slash))
706         (advance ALPHA-DIGIT))
707       (when (test letter number other dot) (advance OTHER nil))
708       (return t)
709
710      ALPHA-DIGIT ; seen a digit which is a letter...
711       (when (or (digitp) (test sign slash))
712         (if (test letter)
713             (advance LAST-DIGIT-ALPHA)
714             (advance ALPHA-DIGIT)))
715       (when (test letter) (advance ALPHA-MARKER))
716       (when (test number other dot) (advance OTHER nil))
717       (return t)
718
719      ALPHA-MARKER ; number marker in number with alpha digit...
720       (when (test letter) (advance OTHER nil))
721       (go ALPHA-DIGIT)
722
723      DIGIT ; seen only ordinary (non-alphabetic) numeric digits...
724       (when (digitp)
725         (if (test letter)
726             (advance ALPHA-DIGIT)
727             (advance DIGIT)))
728       (when (test number other) (advance OTHER nil))
729       (when (test letter) (advance MARKER))
730       (when (test extension slash sign) (advance DIGIT))
731       (when (char= current #\.) (advance DOT-DIGIT))
732       (return t)
733
734      MARKER ; number marker in a numeric number...
735       ;; ("What," you may ask, "is a 'number marker'?" It's something
736       ;; that a conforming implementation might use in number syntax.
737       ;; See ANSI 2.3.1.1 "Potential Numbers as Tokens".)
738       (when (test letter) (advance OTHER nil))
739       (go DIGIT))))
740 \f
741 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN*
742 ;;;;
743 ;;;; case hackery: These functions are stored in
744 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN* according to the values of
745 ;;;; *PRINT-CASE* and READTABLE-CASE.
746
747 ;;; called when:
748 ;;; READTABLE-CASE      *PRINT-CASE*
749 ;;; :UPCASE             :UPCASE
750 ;;; :DOWNCASE           :DOWNCASE
751 ;;; :PRESERVE           any
752 (defun output-preserve-symbol (pname stream)
753   (declare (simple-string pname))
754   (write-string pname stream))
755
756 ;;; called when:
757 ;;; READTABLE-CASE      *PRINT-CASE*
758 ;;; :UPCASE             :DOWNCASE
759 (defun output-lowercase-symbol (pname stream)
760   (declare (simple-string pname))
761   (dotimes (index (length pname))
762     (let ((char (schar pname index)))
763       (write-char (char-downcase char) stream))))
764
765 ;;; called when:
766 ;;; READTABLE-CASE      *PRINT-CASE*
767 ;;; :DOWNCASE           :UPCASE
768 (defun output-uppercase-symbol (pname stream)
769   (declare (simple-string pname))
770   (dotimes (index (length pname))
771     (let ((char (schar pname index)))
772       (write-char (char-upcase char) stream))))
773
774 ;;; called when:
775 ;;; READTABLE-CASE      *PRINT-CASE*
776 ;;; :UPCASE             :CAPITALIZE
777 ;;; :DOWNCASE           :CAPITALIZE
778 (defun output-capitalize-symbol (pname stream)
779   (declare (simple-string pname))
780   (let ((prev-not-alphanum t)
781         (up (eq (readtable-case *readtable*) :upcase)))
782     (dotimes (i (length pname))
783       (let ((char (char pname i)))
784         (write-char (if up
785                         (if (or prev-not-alphanum (lower-case-p char))
786                             char
787                             (char-downcase char))
788                         (if prev-not-alphanum
789                             (char-upcase char)
790                             char))
791                     stream)
792         (setq prev-not-alphanum (not (alphanumericp char)))))))
793
794 ;;; called when:
795 ;;; READTABLE-CASE      *PRINT-CASE*
796 ;;; :INVERT             any
797 (defun output-invert-symbol (pname stream)
798   (declare (simple-string pname))
799   (let ((all-upper t)
800         (all-lower t))
801     (dotimes (i (length pname))
802       (let ((ch (schar pname i)))
803         (when (both-case-p ch)
804           (if (upper-case-p ch)
805               (setq all-lower nil)
806               (setq all-upper nil)))))
807     (cond (all-upper (output-lowercase-symbol pname stream))
808           (all-lower (output-uppercase-symbol pname stream))
809           (t
810            (write-string pname stream)))))
811
812 #|
813 (defun test1 ()
814   (let ((*readtable* (copy-readtable nil)))
815     (format t "READTABLE-CASE  Input   Symbol-name~@
816                ----------------------------------~%")
817     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
818       (setf (readtable-case *readtable*) readtable-case)
819       (dolist (input '("ZEBRA" "Zebra" "zebra"))
820         (format t "~&:~A~16T~A~24T~A"
821                 (string-upcase readtable-case)
822                 input
823                 (symbol-name (read-from-string input)))))))
824
825 (defun test2 ()
826   (let ((*readtable* (copy-readtable nil)))
827     (format t "READTABLE-CASE  *PRINT-CASE*  Symbol-name  Output  Princ~@
828                --------------------------------------------------------~%")
829     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
830       (setf (readtable-case *readtable*) readtable-case)
831       (dolist (*print-case* '(:upcase :downcase :capitalize))
832         (dolist (symbol '(|ZEBRA| |Zebra| |zebra|))
833           (format t "~&:~A~15T:~A~29T~A~42T~A~50T~A"
834                   (string-upcase readtable-case)
835                   (string-upcase *print-case*)
836                   (symbol-name symbol)
837                   (prin1-to-string symbol)
838                   (princ-to-string symbol)))))))
839 |#
840 \f
841 ;;;; recursive objects
842
843 (defun output-list (list stream)
844   (descend-into (stream)
845     (write-char #\( stream)
846     (let ((length 0)
847           (list list))
848       (loop
849         (punt-print-if-too-long length stream)
850         (output-object (pop list) stream)
851         (unless list
852           (return))
853         (when (or (atom list)
854                   (check-for-circularity list))
855           (write-string " . " stream)
856           (output-object list stream)
857           (return))
858         (write-char #\space stream)
859         (incf length)))
860     (write-char #\) stream)))
861
862 (defun output-vector (vector stream)
863   (declare (vector vector))
864   (cond ((stringp vector)
865          (cond ((and *print-readably*
866                      (not (eq (array-element-type vector)
867                               (load-time-value
868                                (array-element-type
869                                 (make-array 0 :element-type 'character))))))
870                 (error 'print-not-readable :object vector))
871                ((or *print-escape* *print-readably*)
872                 (write-char #\" stream)
873                 (quote-string vector stream)
874                 (write-char #\" stream))
875                (t
876                 (write-string vector stream))))
877         ((not (or *print-array* *print-readably*))
878          (output-terse-array vector stream))
879         ((bit-vector-p vector)
880          (write-string "#*" stream)
881          (dovector (bit vector)
882            ;; (Don't use OUTPUT-OBJECT here, since this code
883            ;; has to work for all possible *PRINT-BASE* values.)
884            (write-char (if (zerop bit) #\0 #\1) stream)))
885         (t
886          (when (and *print-readably*
887                     (not (array-readably-printable-p vector)))
888            (error 'print-not-readable :object vector))
889          (descend-into (stream)
890                        (write-string "#(" stream)
891                        (dotimes (i (length vector))
892                          (unless (zerop i)
893                            (write-char #\space stream))
894                          (punt-print-if-too-long i stream)
895                          (output-object (aref vector i) stream))
896                        (write-string ")" stream)))))
897
898 ;;; This function outputs a string quoting characters sufficiently
899 ;;; so that someone can read it in again. Basically, put a slash in
900 ;;; front of an character satisfying NEEDS-SLASH-P.
901 (defun quote-string (string stream)
902   (macrolet ((needs-slash-p (char)
903                ;; KLUDGE: We probably should look at the readtable, but just do
904                ;; this for now. [noted by anonymous long ago] -- WHN 19991130
905                `(or (char= ,char #\\)
906                  (char= ,char #\"))))
907     (with-array-data ((data string) (start) (end (length string)))
908       (do ((index start (1+ index)))
909           ((>= index end))
910         (let ((char (schar data index)))
911           (when (needs-slash-p char) (write-char #\\ stream))
912           (write-char char stream))))))
913
914 (defun array-readably-printable-p (array)
915   (and (eq (array-element-type array) t)
916        (let ((zero (position 0 (array-dimensions array)))
917              (number (position 0 (array-dimensions array)
918                                :test (complement #'eql)
919                                :from-end t)))
920          (or (null zero) (null number) (> zero number)))))
921
922 ;;; Output the printed representation of any array in either the #< or #A
923 ;;; form.
924 (defun output-array (array stream)
925   (if (or *print-array* *print-readably*)
926       (output-array-guts array stream)
927       (output-terse-array array stream)))
928
929 ;;; Output the abbreviated #< form of an array.
930 (defun output-terse-array (array stream)
931   (let ((*print-level* nil)
932         (*print-length* nil))
933     (print-unreadable-object (array stream :type t :identity t))))
934
935 ;;; Output the readable #A form of an array.
936 (defun output-array-guts (array stream)
937   (when (and *print-readably*
938              (not (array-readably-printable-p array)))
939     (error 'print-not-readable :object array))
940   (write-char #\# stream)
941   (let ((*print-base* 10)
942         (*print-radix* nil))
943     (output-integer (array-rank array) stream))
944   (write-char #\A stream)
945   (with-array-data ((data array) (start) (end))
946     (declare (ignore end))
947     (sub-output-array-guts data (array-dimensions array) stream start)))
948
949 (defun sub-output-array-guts (array dimensions stream index)
950   (declare (type (simple-array * (*)) array) (fixnum index))
951   (cond ((null dimensions)
952          (output-object (aref array index) stream))
953         (t
954          (descend-into (stream)
955            (write-char #\( stream)
956            (let* ((dimension (car dimensions))
957                   (dimensions (cdr dimensions))
958                   (count (reduce #'* dimensions)))
959              (dotimes (i dimension)
960                (unless (zerop i)
961                  (write-char #\space stream))
962                (punt-print-if-too-long i stream)
963                (sub-output-array-guts array dimensions stream index)
964                (incf index count)))
965            (write-char #\) stream)))))
966
967 ;;; a trivial non-generic-function placeholder for PRINT-OBJECT, for
968 ;;; use until CLOS is set up (at which time it will be replaced with
969 ;;; the real generic function implementation)
970 (defun print-object (instance stream)
971   (default-structure-print instance stream *current-level-in-print*))
972 \f
973 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
974
975 (defun %output-radix (base stream)
976   (write-char #\# stream)
977   (write-char (case base
978                 (2 #\b)
979                 (8 #\o)
980                 (16 #\x)
981                 (t (%output-fixnum-in-base base 10 stream)
982                    #\r))
983               stream))
984
985 (defun %output-fixnum-in-base (n base stream)
986   (multiple-value-bind (q r)
987       (truncate n base)
988     ;; Recurse until you have all the digits pushed on
989     ;; the stack.
990     (unless (zerop q)
991       (%output-fixnum-in-base q base stream))
992     ;; Then as each recursive call unwinds, turn the
993     ;; digit (in remainder) into a character and output
994     ;; the character.
995     (write-char
996      (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r)
997      stream)))
998
999 ;; Algorithm by Harald Hanche-Olsen, sbcl-devel 2005-02-05
1000 (defun %output-bignum-in-base (n base stream)
1001   (declare (type bignum n) (type fixnum base))
1002   (let ((power (make-array 10 :adjustable t :fill-pointer 0)))
1003     ;; Here there be the bottleneck for big bignums, in the (* p p).
1004     ;; A special purpose SQUARE-BIGNUM might help a bit. See eg: Dan
1005     ;; Zuras, "On Squaring and Multiplying Large Integers", ARITH-11:
1006     ;; IEEE Symposium on Computer Arithmetic, 1993, pp. 260 to 271.
1007     ;; Reprinted as "More on Multiplying and Squaring Large Integers",
1008     ;; IEEE Transactions on Computers, volume 43, number 8, August
1009     ;; 1994, pp. 899-908.
1010     (do ((p base (* p p)))
1011         ((> p n))
1012       (vector-push-extend p power))
1013     ;; (aref power k) == (expt base (expt 2 k))
1014     (labels ((bisect (n k exactp)
1015                (declare (fixnum k))
1016                ;; N is the number to bisect
1017                ;; K on initial entry BASE^(2^K) > N
1018                ;; EXACTP is true if 2^K is the exact number of digits
1019                (cond ((zerop n)
1020                       (when exactp
1021                         (loop repeat (ash 1 k) do (write-char #\0 stream))))
1022                      ((zerop k)
1023                       (write-char
1024                        (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n)
1025                        stream))
1026                      (t
1027                       (setf k (1- k))
1028                       (multiple-value-bind (q r) (truncate n (aref power k))
1029                         ;; EXACTP is NIL only at the head of the
1030                         ;; initial number, as we don't know the number
1031                         ;; of digits there, but we do know that it
1032                         ;; doesn't get any leading zeros.
1033                         (bisect q k exactp)
1034                         (bisect r k (or exactp (plusp q))))))))
1035       (bisect n (fill-pointer power) nil))))
1036
1037 (defun %output-integer-in-base (integer base stream)
1038   (when (minusp integer)
1039     (write-char #\- stream)
1040     (setf integer (- integer)))
1041   (if (fixnump integer)
1042       (%output-fixnum-in-base integer base stream)
1043       (%output-bignum-in-base integer base stream)))
1044
1045 (defun output-integer (integer stream)
1046   (let ((base *print-base*))
1047     (when (and (/= base 10) *print-radix*)
1048       (%output-radix base stream))
1049     (%output-integer-in-base integer base stream)
1050     (when (and *print-radix* (= base 10))
1051       (write-char #\. stream))))
1052
1053 (defun output-ratio (ratio stream)
1054   (let ((base *print-base*))
1055     (when *print-radix*
1056       (%output-radix base stream))
1057     (%output-integer-in-base (numerator ratio) base stream)
1058     (write-char #\/ stream)
1059     (%output-integer-in-base (denominator ratio) base stream)))
1060
1061 (defun output-complex (complex stream)
1062   (write-string "#C(" stream)
1063   ;; FIXME: Could this just be OUTPUT-NUMBER?
1064   (output-object (realpart complex) stream)
1065   (write-char #\space stream)
1066   (output-object (imagpart complex) stream)
1067   (write-char #\) stream))
1068 \f
1069 ;;;; float printing
1070
1071 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1072 ;;; most of the work for all printing of floating point numbers in
1073 ;;; FORMAT.  It converts a floating point number to a string in a free
1074 ;;; or fixed format with no exponent. The interpretation of the
1075 ;;; arguments is as follows:
1076 ;;;
1077 ;;;     X       - The floating point number to convert, which must not be
1078 ;;;             negative.
1079 ;;;     WIDTH    - The preferred field width, used to determine the number
1080 ;;;             of fraction digits to produce if the FDIGITS parameter
1081 ;;;             is unspecified or NIL. If the non-fraction digits and the
1082 ;;;             decimal point alone exceed this width, no fraction digits
1083 ;;;             will be produced unless a non-NIL value of FDIGITS has been
1084 ;;;             specified. Field overflow is not considerd an error at this
1085 ;;;             level.
1086 ;;;     FDIGITS  - The number of fractional digits to produce. Insignificant
1087 ;;;             trailing zeroes may be introduced as needed. May be
1088 ;;;             unspecified or NIL, in which case as many digits as possible
1089 ;;;             are generated, subject to the constraint that there are no
1090 ;;;             trailing zeroes.
1091 ;;;     SCALE    - If this parameter is specified or non-NIL, then the number
1092 ;;;             printed is (* x (expt 10 scale)). This scaling is exact,
1093 ;;;             and cannot lose precision.
1094 ;;;     FMIN     - This parameter, if specified or non-NIL, is the minimum
1095 ;;;             number of fraction digits which will be produced, regardless
1096 ;;;             of the value of WIDTH or FDIGITS. This feature is used by
1097 ;;;             the ~E format directive to prevent complete loss of
1098 ;;;             significance in the printed value due to a bogus choice of
1099 ;;;             scale factor.
1100 ;;;
1101 ;;; Returns:
1102 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1103 ;;; where the results have the following interpretation:
1104 ;;;
1105 ;;;     DIGIT-STRING    - The decimal representation of X, with decimal point.
1106 ;;;     DIGIT-LENGTH    - The length of the string DIGIT-STRING.
1107 ;;;     LEADING-POINT   - True if the first character of DIGIT-STRING is the
1108 ;;;                    decimal point.
1109 ;;;     TRAILING-POINT  - True if the last character of DIGIT-STRING is the
1110 ;;;                    decimal point.
1111 ;;;     POINT-POS       - The position of the digit preceding the decimal
1112 ;;;                    point. Zero indicates point before first digit.
1113 ;;;
1114 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1115 ;;; accuracy. Specifically, the decimal number printed is the closest
1116 ;;; possible approximation to the true value of the binary number to
1117 ;;; be printed from among all decimal representations with the same
1118 ;;; number of digits. In free-format output, i.e. with the number of
1119 ;;; digits unconstrained, it is guaranteed that all the information is
1120 ;;; preserved, so that a properly- rounding reader can reconstruct the
1121 ;;; original binary number, bit-for-bit, from its printed decimal
1122 ;;; representation. Furthermore, only as many digits as necessary to
1123 ;;; satisfy this condition will be printed.
1124 ;;;
1125 ;;; FLOAT-DIGITS actually generates the digits for positive numbers;
1126 ;;; see below for comments.
1127
1128 (defun flonum-to-string (x &optional width fdigits scale fmin)
1129   (declare (type float x))
1130   ;; FIXME: I think only FORMAT-DOLLARS calls FLONUM-TO-STRING with
1131   ;; possibly-negative X.
1132   (setf x (abs x))
1133   (cond ((zerop x)
1134          ;; Zero is a special case which FLOAT-STRING cannot handle.
1135          (if fdigits
1136              (let ((s (make-string (1+ fdigits) :initial-element #\0)))
1137                (setf (schar s 0) #\.)
1138                (values s (length s) t (zerop fdigits) 0))
1139              (values "." 1 t t 0)))
1140         (t
1141          (multiple-value-bind (e string)
1142              (if fdigits
1143                  (flonum-to-digits x (min (- fdigits) (- (or fmin 0))))
1144                  (if (and width (> width 1))
1145                      (let ((w (multiple-value-list (flonum-to-digits x (1- width) t)))
1146                            (f (multiple-value-list (flonum-to-digits x (- (or fmin 0))))))
1147                        (cond
1148                          ((>= (length (cadr w)) (length (cadr f)))
1149                           (values-list w))
1150                          (t (values-list f))))
1151                      (flonum-to-digits x)))
1152            (let ((e (+ e (or scale 0)))
1153                  (stream (make-string-output-stream)))
1154              (if (plusp e)
1155                  (progn
1156                    (write-string string stream :end (min (length string) e))
1157                    (dotimes (i (- e (length string)))
1158                      (write-char #\0 stream))
1159                    (write-char #\. stream)
1160                    (write-string string stream :start (min (length string) e))
1161                    (when fdigits
1162                      (dotimes (i (- fdigits
1163                                     (- (length string)
1164                                        (min (length string) e))))
1165                        (write-char #\0 stream))))
1166                  (progn
1167                    (write-string "." stream)
1168                    (dotimes (i (- e))
1169                      (write-char #\0 stream))
1170                    (write-string string stream)
1171                    (when fdigits
1172                      (dotimes (i (+ fdigits e (- (length string))))
1173                        (write-char #\0 stream)))))
1174              (let ((string (get-output-stream-string stream)))
1175                (values string (length string)
1176                        (char= (char string 0) #\.)
1177                        (char= (char string (1- (length string))) #\.)
1178                        (position #\. string))))))))
1179
1180 ;;; implementation of figure 1 from Burger and Dybvig, 1996.  As the
1181 ;;; implementation of the Dragon from Classic CMUCL (and previously in
1182 ;;; SBCL above FLONUM-TO-STRING) says: "DO NOT EVEN THINK OF
1183 ;;; ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE PAPER!",
1184 ;;; and in this case we have to add that even reading the paper might
1185 ;;; not bring immediate illumination as CSR has attempted to turn
1186 ;;; idiomatic Scheme into idiomatic Lisp.
1187 ;;;
1188 ;;; FIXME: figure 1 from Burger and Dybvig is the unoptimized
1189 ;;; algorithm, noticeably slow at finding the exponent.  Figure 2 has
1190 ;;; an improved algorithm, but CSR ran out of energy.
1191 ;;;
1192 ;;; possible extension for the enthusiastic: printing floats in bases
1193 ;;; other than base 10.
1194 (defconstant single-float-min-e
1195   (nth-value 1 (decode-float least-positive-single-float)))
1196 (defconstant double-float-min-e
1197   (nth-value 1 (decode-float least-positive-double-float)))
1198 #!+long-float
1199 (defconstant long-float-min-e
1200   (nth-value 1 (decode-float least-positive-long-float)))
1201
1202 (defun flonum-to-digits (v &optional position relativep)
1203   (let ((print-base 10) ; B
1204         (float-radix 2) ; b
1205         (float-digits (float-digits v)) ; p
1206         (digit-characters "0123456789")
1207         (min-e
1208          (etypecase v
1209            (single-float single-float-min-e)
1210            (double-float double-float-min-e)
1211            #!+long-float
1212            (long-float long-float-min-e))))
1213     (multiple-value-bind (f e)
1214         (integer-decode-float v)
1215       (let (;; FIXME: these even tests assume normal IEEE rounding
1216             ;; mode.  I wonder if we should cater for non-normal?
1217             (high-ok (evenp f))
1218             (low-ok (evenp f))
1219             (result (make-array 50 :element-type 'base-char
1220                                 :fill-pointer 0 :adjustable t)))
1221         (labels ((scale (r s m+ m-)
1222                    (do ((k 0 (1+ k))
1223                         (s s (* s print-base)))
1224                        ((not (or (> (+ r m+) s)
1225                                  (and high-ok (= (+ r m+) s))))
1226                         (do ((k k (1- k))
1227                              (r r (* r print-base))
1228                              (m+ m+ (* m+ print-base))
1229                              (m- m- (* m- print-base)))
1230                             ((not (or (< (* (+ r m+) print-base) s)
1231                                       (and (not high-ok)
1232                                            (= (* (+ r m+) print-base) s))))
1233                              (values k (generate r s m+ m-)))))))
1234                  (generate (r s m+ m-)
1235                    (let (d tc1 tc2)
1236                      (tagbody
1237                       loop
1238                         (setf (values d r) (truncate (* r print-base) s))
1239                         (setf m+ (* m+ print-base))
1240                         (setf m- (* m- print-base))
1241                         (setf tc1 (or (< r m-) (and low-ok (= r m-))))
1242                         (setf tc2 (or (> (+ r m+) s)
1243                                       (and high-ok (= (+ r m+) s))))
1244                         (when (or tc1 tc2)
1245                           (go end))
1246                         (vector-push-extend (char digit-characters d) result)
1247                         (go loop)
1248                       end
1249                         (let ((d (cond
1250                                    ((and (not tc1) tc2) (1+ d))
1251                                    ((and tc1 (not tc2)) d)
1252                                    (t ; (and tc1 tc2)
1253                                     (if (< (* r 2) s) d (1+ d))))))
1254                           (vector-push-extend (char digit-characters d) result)
1255                           (return-from generate result)))))
1256                  (initialize ()
1257                    (let (r s m+ m-)
1258                      (if (>= e 0)
1259                          (let* ((be (expt float-radix e))
1260                                 (be1 (* be float-radix)))
1261                            (if (/= f (expt float-radix (1- float-digits)))
1262                                (setf r (* f be 2)
1263                                      s 2
1264                                      m+ be
1265                                      m- be)
1266                                (setf r (* f be1 2)
1267                                      s (* float-radix 2)
1268                                      m+ be1
1269                                      m- be)))
1270                          (if (or (= e min-e)
1271                                  (/= f (expt float-radix (1- float-digits))))
1272                              (setf r (* f 2)
1273                                    s (* (expt float-radix (- e)) 2)
1274                                    m+ 1
1275                                    m- 1)
1276                              (setf r (* f float-radix 2)
1277                                    s (* (expt float-radix (- 1 e)) 2)
1278                                    m+ float-radix
1279                                    m- 1)))
1280                      (when position
1281                        (when relativep
1282                          (aver (> position 0))
1283                          (do ((k 0 (1+ k))
1284                               ;; running out of letters here
1285                               (l 1 (* l print-base)))
1286                              ((>= (* s l) (+ r m+))
1287                               ;; k is now \hat{k}
1288                               (if (< (+ r (* s (/ (expt print-base (- k position)) 2)))
1289                                      (* s (expt print-base k)))
1290                                   (setf position (- k position))
1291                                   (setf position (- k position 1))))))
1292                        (let ((low (max m- (/ (* s (expt print-base position)) 2)))
1293                              (high (max m+ (/ (* s (expt print-base position)) 2))))
1294                          (when (<= m- low)
1295                            (setf m- low)
1296                            (setf low-ok t))
1297                          (when (<= m+ high)
1298                            (setf m+ high)
1299                            (setf high-ok t))))
1300                      (values r s m+ m-))))
1301           (multiple-value-bind (r s m+ m-) (initialize)
1302             (scale r s m+ m-)))))))
1303 \f
1304 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns
1305 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1306 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1307 ;;; original number. There may be some loss of precision due the
1308 ;;; floating point representation. The scaling is always done with
1309 ;;; long float arithmetic, which helps printing of lesser precisions
1310 ;;; as well as avoiding generic arithmetic.
1311 ;;;
1312 ;;; When computing our initial scale factor using EXPT, we pull out
1313 ;;; part of the computation to avoid over/under flow. When
1314 ;;; denormalized, we must pull out a large factor, since there is more
1315 ;;; negative exponent range than positive range.
1316
1317 (eval-when (:compile-toplevel :execute)
1318   (setf *read-default-float-format*
1319         #!+long-float 'long-float #!-long-float 'double-float))
1320 (defun scale-exponent (original-x)
1321   (let* ((x (coerce original-x 'long-float)))
1322     (multiple-value-bind (sig exponent) (decode-float x)
1323       (declare (ignore sig))
1324       (if (= x 0.0e0)
1325           (values (float 0.0e0 original-x) 1)
1326           (let* ((ex (locally (declare (optimize (safety 0)))
1327                        (the fixnum
1328                          (round (* exponent (log 2e0 10))))))
1329                  (x (if (minusp ex)
1330                         (if (float-denormalized-p x)
1331                             #!-long-float
1332                             (* x 1.0e16 (expt 10.0e0 (- (- ex) 16)))
1333                             #!+long-float
1334                             (* x 1.0e18 (expt 10.0e0 (- (- ex) 18)))
1335                             (* x 10.0e0 (expt 10.0e0 (- (- ex) 1))))
1336                         (/ x 10.0e0 (expt 10.0e0 (1- ex))))))
1337             (do ((d 10.0e0 (* d 10.0e0))
1338                  (y x (/ x d))
1339                  (ex ex (1+ ex)))
1340                 ((< y 1.0e0)
1341                  (do ((m 10.0e0 (* m 10.0e0))
1342                       (z y (* y m))
1343                       (ex ex (1- ex)))
1344                      ((>= z 0.1e0)
1345                       (values (float z original-x) ex))
1346                    (declare (long-float m) (integer ex))))
1347               (declare (long-float d))))))))
1348 (eval-when (:compile-toplevel :execute)
1349   (setf *read-default-float-format* 'single-float))
1350 \f
1351 ;;;; entry point for the float printer
1352
1353 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1354 ;;; argument is printed free-format, in either exponential or
1355 ;;; non-exponential notation, depending on its magnitude.
1356 ;;;
1357 ;;; NOTE: When a number is to be printed in exponential format, it is
1358 ;;; scaled in floating point. Since precision may be lost in this
1359 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1360 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1361 ;;; extensive computations with integers of similar magnitude to that
1362 ;;; of the number being printed. For large exponents, the bignums
1363 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1364 ;;; fast and the exponent range is not too large, then it might become
1365 ;;; attractive to handle exponential notation with the same accuracy
1366 ;;; as non-exponential notation, using the method described in the
1367 ;;; Steele and White paper.
1368 ;;;
1369 ;;; NOTE II: this has been bypassed slightly by implementing Burger
1370 ;;; and Dybvig, 1996.  When someone has time (KLUDGE) they can
1371 ;;; probably (a) implement the optimizations suggested by Burger and
1372 ;;; Dyvbig, and (b) remove all vestiges of Dragon4, including from
1373 ;;; fixed-format printing.
1374
1375 ;;; Print the appropriate exponent marker for X and the specified exponent.
1376 (defun print-float-exponent (x exp stream)
1377   (declare (type float x) (type integer exp) (type stream stream))
1378   (let ((*print-radix* nil)
1379         (plusp (plusp exp)))
1380     (if (typep x *read-default-float-format*)
1381         (unless (eql exp 0)
1382           (format stream "e~:[~;+~]~D" plusp exp))
1383         (format stream "~C~:[~;+~]~D"
1384                 (etypecase x
1385                   (single-float #\f)
1386                   (double-float #\d)
1387                   (short-float #\s)
1388                   (long-float #\L))
1389                 plusp exp))))
1390
1391 (defun output-float-infinity (x stream)
1392   (declare (float x) (stream stream))
1393   (cond (*read-eval*
1394          (write-string "#." stream))
1395         (*print-readably*
1396          (error 'print-not-readable :object x))
1397         (t
1398          (write-string "#<" stream)))
1399   (write-string "SB-EXT:" stream)
1400   (write-string (symbol-name (float-format-name x)) stream)
1401   (write-string (if (plusp x) "-POSITIVE-" "-NEGATIVE-")
1402                 stream)
1403   (write-string "INFINITY" stream)
1404   (unless *read-eval*
1405     (write-string ">" stream)))
1406
1407 (defun output-float-nan (x stream)
1408   (print-unreadable-object (x stream)
1409     (princ (float-format-name x) stream)
1410     (write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
1411     (write-string " NaN" stream)))
1412
1413 ;;; the function called by OUTPUT-OBJECT to handle floats
1414 (defun output-float (x stream)
1415   (cond
1416    ((float-infinity-p x)
1417     (output-float-infinity x stream))
1418    ((float-nan-p x)
1419     (output-float-nan x stream))
1420    (t
1421     (let ((x (cond ((minusp (float-sign x))
1422                     (write-char #\- stream)
1423                     (- x))
1424                    (t
1425                     x))))
1426       (cond
1427        ((zerop x)
1428         (write-string "0.0" stream)
1429         (print-float-exponent x 0 stream))
1430        (t
1431         (output-float-aux x stream -3 8)))))))
1432 (defun output-float-aux (x stream e-min e-max)
1433   (multiple-value-bind (e string)
1434       (flonum-to-digits x)
1435     (cond
1436       ((< e-min e e-max)
1437        (if (plusp e)
1438            (progn
1439              (write-string string stream :end (min (length string) e))
1440              (dotimes (i (- e (length string)))
1441                (write-char #\0 stream))
1442              (write-char #\. stream)
1443              (write-string string stream :start (min (length string) e))
1444              (when (<= (length string) e)
1445                (write-char #\0 stream))
1446              (print-float-exponent x 0 stream))
1447            (progn
1448              (write-string "0." stream)
1449              (dotimes (i (- e))
1450                (write-char #\0 stream))
1451              (write-string string stream)
1452              (print-float-exponent x 0 stream))))
1453       (t (write-string string stream :end 1)
1454          (write-char #\. stream)
1455          (write-string string stream :start 1)
1456          (when (= (length string) 1)
1457            (write-char #\0 stream))
1458          (print-float-exponent x (1- e) stream)))))
1459 \f
1460 ;;;; other leaf objects
1461
1462 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1463 ;;; the character name or the character in the #\char format.
1464 (defun output-character (char stream)
1465   (if (or *print-escape* *print-readably*)
1466       (let ((graphicp (graphic-char-p char))
1467             (name (char-name char)))
1468         (write-string "#\\" stream)
1469         (if (and name (not graphicp))
1470             (quote-string name stream)
1471             (write-char char stream)))
1472       (write-char char stream)))
1473
1474 (defun output-sap (sap stream)
1475   (declare (type system-area-pointer sap))
1476   (cond (*read-eval*
1477          (format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
1478         (t
1479          (print-unreadable-object (sap stream)
1480            (format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
1481
1482 (defun output-weak-pointer (weak-pointer stream)
1483   (declare (type weak-pointer weak-pointer))
1484   (print-unreadable-object (weak-pointer stream)
1485     (multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
1486       (cond (validp
1487              (write-string "weak pointer: " stream)
1488              (write value :stream stream))
1489             (t
1490              (write-string "broken weak pointer" stream))))))
1491
1492 (defun output-code-component (component stream)
1493   (print-unreadable-object (component stream :identity t)
1494     (let ((dinfo (%code-debug-info component)))
1495       (cond ((eq dinfo :bogus-lra)
1496              (write-string "bogus code object" stream))
1497             (t
1498              (write-string "code object" stream)
1499              (when dinfo
1500                (write-char #\space stream)
1501                (output-object (sb!c::debug-info-name dinfo) stream)))))))
1502
1503 (defun output-lra (lra stream)
1504   (print-unreadable-object (lra stream :identity t)
1505     (write-string "return PC object" stream)))
1506
1507 (defun output-fdefn (fdefn stream)
1508   (print-unreadable-object (fdefn stream)
1509     (write-string "FDEFINITION object for " stream)
1510     (output-object (fdefn-name fdefn) stream)))
1511 \f
1512 ;;;; functions
1513
1514 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1515 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1516 ;;;
1517 ;;; The definition here is a simple temporary placeholder. It will be
1518 ;;; overwritten by a smarter version (capable of calling generic
1519 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1520 (defun printed-as-funcallable-standard-class (object stream)
1521   (declare (ignore object stream))
1522   nil)
1523
1524 (defun output-fun (object stream)
1525     (let* ((*print-length* 3)  ; in case we have to..
1526            (*print-level* 3)  ; ..print an interpreted function definition
1527            (name (%fun-name object))
1528            (proper-name-p (and (legal-fun-name-p name) (fboundp name)
1529                                (eq (fdefinition name) object))))
1530       (print-unreadable-object (object stream :identity (not proper-name-p))
1531         (format stream "~:[FUNCTION~;CLOSURE~]~@[ ~S~]"
1532                 (closurep object)
1533                 name))))
1534 \f
1535 ;;;; catch-all for unknown things
1536
1537 (defun output-random (object stream)
1538   (print-unreadable-object (object stream :identity t)
1539     (let ((lowtag (lowtag-of object)))
1540       (case lowtag
1541         (#.sb!vm:other-pointer-lowtag
1542           (let ((widetag (widetag-of object)))
1543             (case widetag
1544               (#.sb!vm:value-cell-header-widetag
1545                (write-string "value cell " stream)
1546                (output-object (value-cell-ref object) stream))
1547               (t
1548                (write-string "unknown pointer object, widetag=" stream)
1549                (let ((*print-base* 16) (*print-radix* t))
1550                  (output-integer widetag stream))))))
1551         ((#.sb!vm:fun-pointer-lowtag
1552           #.sb!vm:instance-pointer-lowtag
1553           #.sb!vm:list-pointer-lowtag)
1554          (write-string "unknown pointer object, lowtag=" stream)
1555          (let ((*print-base* 16) (*print-radix* t))
1556            (output-integer lowtag stream)))
1557         (t
1558          (case (widetag-of object)
1559            (#.sb!vm:unbound-marker-widetag
1560             (write-string "unbound marker" stream))
1561            (t
1562             (write-string "unknown immediate object, lowtag=" stream)
1563             (let ((*print-base* 2) (*print-radix* t))
1564               (output-integer lowtag stream))
1565             (write-string ", widetag=" stream)
1566             (let ((*print-base* 16) (*print-radix* t))
1567               (output-integer (widetag-of object) stream)))))))))