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