1.0.33.6: prettier PRINT-OBJECT default method
[sbcl/llvm.git] / src / code / print.lisp
blob8e6e0c8d050274675d9af8313c98e398c063b747
1 ;;;; the printer
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.
12 (in-package "SB!IMPL")
14 ;;;; exported printer control variables
16 ;;; FIXME: Many of these have nontrivial types, e.g. *PRINT-LEVEL*,
17 ;;; *PRINT-LENGTH*, and *PRINT-LINES* are (OR NULL UNSIGNED-BYTE).
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")
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-PPRINT-DISPATCH* the standard pprint dispatch table
90 *PRINT-PRETTY* NIL
91 *PRINT-RADIX* NIL
92 *PRINT-READABLY* T
93 *PRINT-RIGHT-MARGIN* NIL
94 *READ-BASE* 10
95 *READ-DEFAULT-FLOAT-FORMAT* SINGLE-FLOAT
96 *READ-EVAL* T
97 *READ-SUPPRESS* NIL
98 *READTABLE* the standard readtable"
99 `(%with-standard-io-syntax (lambda () ,@body)))
101 (defun %with-standard-io-syntax (function)
102 (declare (type function function))
103 (let ((*package* (find-package "COMMON-LISP-USER"))
104 (*print-array* t)
105 (*print-base* 10)
106 (*print-case* :upcase)
107 (*print-circle* nil)
108 (*print-escape* t)
109 (*print-gensym* t)
110 (*print-length* nil)
111 (*print-level* nil)
112 (*print-lines* nil)
113 (*print-miser-width* nil)
114 (*print-pprint-dispatch* sb!pretty::*standard-pprint-dispatch-table*)
115 (*print-pretty* nil)
116 (*print-radix* nil)
117 (*print-readably* t)
118 (*print-right-margin* nil)
119 (*read-base* 10)
120 (*read-default-float-format* 'single-float)
121 (*read-eval* t)
122 (*read-suppress* nil)
123 (*readtable* *standard-readtable*))
124 (funcall function)))
126 ;;;; routines to print objects
129 ;;; keyword variables shared by WRITE and WRITE-TO-STRING, and
130 ;;; the bindings they map to.
131 (eval-when (:compile-toplevel :load-toplevel)
132 (defvar *printer-keyword-variables*
133 '(:escape *print-escape*
134 :radix *print-radix*
135 :base *print-base*
136 :circle *print-circle*
137 :pretty *print-pretty*
138 :level *print-level*
139 :length *print-length*
140 :case *print-case*
141 :array *print-array*
142 :gensym *print-gensym*
143 :readably *print-readably*
144 :right-margin *print-right-margin*
145 :miser-width *print-miser-width*
146 :lines *print-lines*
147 :pprint-dispatch *print-pprint-dispatch*)))
149 (defun write (object &key
150 ((:stream stream) *standard-output*)
151 ((:escape *print-escape*) *print-escape*)
152 ((:radix *print-radix*) *print-radix*)
153 ((:base *print-base*) *print-base*)
154 ((:circle *print-circle*) *print-circle*)
155 ((:pretty *print-pretty*) *print-pretty*)
156 ((:level *print-level*) *print-level*)
157 ((:length *print-length*) *print-length*)
158 ((:case *print-case*) *print-case*)
159 ((:array *print-array*) *print-array*)
160 ((:gensym *print-gensym*) *print-gensym*)
161 ((:readably *print-readably*) *print-readably*)
162 ((:right-margin *print-right-margin*)
163 *print-right-margin*)
164 ((:miser-width *print-miser-width*)
165 *print-miser-width*)
166 ((:lines *print-lines*) *print-lines*)
167 ((:pprint-dispatch *print-pprint-dispatch*)
168 *print-pprint-dispatch*))
169 #!+sb-doc
170 "Output OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*"
171 (output-object object (out-synonym-of stream))
172 object)
174 ;;; Optimize common case of constant keyword arguments
175 (define-compiler-macro write (&whole form object &rest keys)
176 (let (bind ignore)
177 (do ()
178 ((not (cdr keys))
179 ;; Odd number of keys, punt
180 (when keys
181 (return-from write form)))
182 (let* ((key (pop keys))
183 (value (pop keys))
184 (variable (or (getf *printer-keyword-variables* key)
185 (when (eq :stream key)
186 'stream)
187 (return-from write form))))
188 (when (assoc variable bind)
189 ;; First key has precedence, but we still need to execute the
190 ;; argument, and in the right order.
191 (setf variable (gensym "IGNORE"))
192 (push variable ignore))
193 (push (list variable value) bind)))
194 (unless (assoc 'stream bind)
195 (push (list 'stream '*standard-output*) bind))
196 `(let ,(nreverse bind)
197 ,@(when ignore `((declare (ignore ,@ignore))))
198 (output-object ,object stream))))
200 (defun prin1 (object &optional stream)
201 #!+sb-doc
202 "Output a mostly READable printed representation of OBJECT on the specified
203 STREAM."
204 (let ((*print-escape* t))
205 (output-object object (out-synonym-of stream)))
206 object)
208 (defun princ (object &optional stream)
209 #!+sb-doc
210 "Output an aesthetic but not necessarily READable printed representation
211 of OBJECT on the specified STREAM."
212 (let ((*print-escape* nil)
213 (*print-readably* nil))
214 (output-object object (out-synonym-of stream)))
215 object)
217 (defun print (object &optional stream)
218 #!+sb-doc
219 "Output a newline, the mostly READable printed representation of OBJECT, and
220 space to the specified STREAM."
221 (let ((stream (out-synonym-of stream)))
222 (terpri stream)
223 (prin1 object stream)
224 (write-char #\space stream)
225 object))
227 (defun pprint (object &optional stream)
228 #!+sb-doc
229 "Prettily output OBJECT preceded by a newline."
230 (let ((*print-pretty* t)
231 (*print-escape* t)
232 (stream (out-synonym-of stream)))
233 (terpri stream)
234 (output-object object stream))
235 (values))
237 (defun write-to-string
238 (object &key
239 ((:escape *print-escape*) *print-escape*)
240 ((:radix *print-radix*) *print-radix*)
241 ((:base *print-base*) *print-base*)
242 ((:circle *print-circle*) *print-circle*)
243 ((:pretty *print-pretty*) *print-pretty*)
244 ((:level *print-level*) *print-level*)
245 ((:length *print-length*) *print-length*)
246 ((:case *print-case*) *print-case*)
247 ((:array *print-array*) *print-array*)
248 ((:gensym *print-gensym*) *print-gensym*)
249 ((:readably *print-readably*) *print-readably*)
250 ((:right-margin *print-right-margin*) *print-right-margin*)
251 ((:miser-width *print-miser-width*) *print-miser-width*)
252 ((:lines *print-lines*) *print-lines*)
253 ((:pprint-dispatch *print-pprint-dispatch*)
254 *print-pprint-dispatch*))
255 #!+sb-doc
256 "Return the printed representation of OBJECT as a string."
257 (stringify-object object))
259 ;;; Optimize common case of constant keyword arguments
260 (define-compiler-macro write-to-string (&whole form object &rest keys)
261 (let (bind ignore)
262 (do ()
263 ((not (cdr keys))
264 ;; Odd number of keys, punt
265 (when keys
266 (return-from write-to-string form)))
267 (let* ((key (pop keys))
268 (value (pop keys))
269 (variable (or (getf *printer-keyword-variables* key)
270 (return-from write-to-string form))))
271 (when (assoc variable bind)
272 ;; First key has precedence, but we still need to execute the
273 ;; argument, and in the right order.
274 (setf variable (gensym "IGNORE"))
275 (push variable ignore))
276 (push (list variable value) bind)))
277 (if bind
278 `(let ,(nreverse bind)
279 ,@(when ignore `((declare (ignore ,@ignore))))
280 (stringify-object ,object))
281 `(stringify-object ,object))))
283 (defun prin1-to-string (object)
284 #!+sb-doc
285 "Return the printed representation of OBJECT as a string with
286 slashification on."
287 (let ((*print-escape* t))
288 (stringify-object object)))
290 (defun princ-to-string (object)
291 #!+sb-doc
292 "Return the printed representation of OBJECT as a string with
293 slashification off."
294 (let ((*print-escape* nil)
295 (*print-readably* nil))
296 (stringify-object object)))
298 ;;; This produces the printed representation of an object as a string.
299 ;;; The few ...-TO-STRING functions above call this.
300 (defun stringify-object (object)
301 (let ((stream (make-string-output-stream)))
302 (setup-printer-state)
303 (output-object object stream)
304 (get-output-stream-string stream)))
306 ;;;; support for the PRINT-UNREADABLE-OBJECT macro
308 ;;; guts of PRINT-UNREADABLE-OBJECT
309 (defun %print-unreadable-object (object stream type identity body)
310 (declare (type (or null function) body))
311 (when *print-readably*
312 (error 'print-not-readable :object object))
313 (flet ((print-description ()
314 (when type
315 (write (type-of object) :stream stream :circle nil
316 :level nil :length nil)
317 (write-char #\space stream))
318 (when body
319 (pprint-newline :fill stream)
320 (funcall body))
321 (when identity
322 (when (or body (not type))
323 (write-char #\space stream))
324 (pprint-newline :fill stream)
325 (write-char #\{ stream)
326 (write (get-lisp-obj-address object) :stream stream
327 :radix nil :base 16)
328 (write-char #\} stream))))
329 (cond ((print-pretty-on-stream-p stream)
330 ;; Since we're printing prettily on STREAM, format the
331 ;; object within a logical block. PPRINT-LOGICAL-BLOCK does
332 ;; not rebind the stream when it is already a pretty stream,
333 ;; so output from the body will go to the same stream.
334 (pprint-logical-block (stream nil :prefix "#<" :suffix ">")
335 (print-description)))
337 (write-string "#<" stream)
338 (print-description)
339 (write-char #\> stream))))
340 nil)
342 ;;;; OUTPUT-OBJECT -- the main entry point
344 ;;; Objects whose print representation identifies them EQLly don't
345 ;;; need to be checked for circularity.
346 (defun uniquely-identified-by-print-p (x)
347 (or (numberp x)
348 (characterp x)
349 (and (symbolp x)
350 (symbol-package x))))
352 ;;; Output OBJECT to STREAM observing all printer control variables.
353 (defun output-object (object stream)
354 (labels ((print-it (stream)
355 (if *print-pretty*
356 (sb!pretty:output-pretty-object object stream)
357 (output-ugly-object object stream)))
358 (check-it (stream)
359 (multiple-value-bind (marker initiate)
360 (check-for-circularity object t)
361 (if (eq initiate :initiate)
362 (let ((*circularity-hash-table*
363 (make-hash-table :test 'eq)))
364 (check-it (make-broadcast-stream))
365 (let ((*circularity-counter* 0))
366 (check-it stream)))
367 ;; otherwise
368 (if marker
369 (when (handle-circularity marker stream)
370 (print-it stream))
371 (print-it stream))))))
372 (cond (;; Maybe we don't need to bother with circularity detection.
373 (or (not *print-circle*)
374 (uniquely-identified-by-print-p object))
375 (print-it stream))
376 (;; If we have already started circularity detection, this
377 ;; object might be a shared reference. If we have not, then
378 ;; if it is a compound object it might contain a circular
379 ;; reference to itself or multiple shared references.
380 (or *circularity-hash-table*
381 (compound-object-p object))
382 (check-it stream))
384 (print-it stream)))))
386 ;;; a hack to work around recurring gotchas with printing while
387 ;;; DEFGENERIC PRINT-OBJECT is being built
389 ;;; (hopefully will go away naturally when CLOS moves into cold init)
390 (defvar *print-object-is-disabled-p*)
392 ;;; Output OBJECT to STREAM observing all printer control variables
393 ;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
394 ;;; then the pretty printer will be used for any components of OBJECT,
395 ;;; just not for OBJECT itself.
396 (defun output-ugly-object (object stream)
397 (typecase object
398 ;; KLUDGE: The TYPECASE approach here is non-ANSI; the ANSI definition of
399 ;; PRINT-OBJECT says it provides printing and we're supposed to provide
400 ;; PRINT-OBJECT methods covering all classes. We deviate from this
401 ;; by using PRINT-OBJECT only when we print instance values. However,
402 ;; ANSI makes it hard to tell that we're deviating from this:
403 ;; (1) ANSI specifies that the user isn't supposed to call PRINT-OBJECT
404 ;; directly.
405 ;; (2) ANSI (section 11.1.2.1.2) says it's undefined to define
406 ;; a method on an external symbol in the CL package which is
407 ;; applicable to arg lists containing only direct instances of
408 ;; standardized classes.
409 ;; Thus, in order for the user to detect our sleaziness in conforming
410 ;; code, he has to do something relatively obscure like
411 ;; (1) actually use tools like FIND-METHOD to look for PRINT-OBJECT
412 ;; methods, or
413 ;; (2) define a PRINT-OBJECT method which is specialized on the stream
414 ;; value (e.g. a Gray stream object).
415 ;; As long as no one comes up with a non-obscure way of detecting this
416 ;; sleaziness, fixing this nonconformity will probably have a low
417 ;; priority. -- WHN 2001-11-25
418 (list
419 (if (null object)
420 (output-symbol object stream)
421 (output-list object stream)))
422 (instance
423 (cond ((not (and (boundp '*print-object-is-disabled-p*)
424 *print-object-is-disabled-p*))
425 (print-object object stream))
426 ((typep object 'structure-object)
427 (default-structure-print object stream *current-level-in-print*))
429 (write-string "#<INSTANCE but not STRUCTURE-OBJECT>" stream))))
430 (funcallable-instance
431 (cond
432 ((not (and (boundp '*print-object-is-disabled-p*)
433 *print-object-is-disabled-p*))
434 (print-object object stream))
435 (t (output-fun object stream))))
436 (function
437 (output-fun object stream))
438 (symbol
439 (output-symbol object stream))
440 (number
441 (etypecase object
442 (integer
443 (output-integer object stream))
444 (float
445 (output-float object stream))
446 (ratio
447 (output-ratio object stream))
448 (complex
449 (output-complex object stream))))
450 (character
451 (output-character object stream))
452 (vector
453 (output-vector object stream))
454 (array
455 (output-array object stream))
456 (system-area-pointer
457 (output-sap object stream))
458 (weak-pointer
459 (output-weak-pointer object stream))
460 (lra
461 (output-lra object stream))
462 (code-component
463 (output-code-component object stream))
464 (fdefn
465 (output-fdefn object stream))
467 (output-random object stream))))
469 ;;;; symbols
471 ;;; values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last
472 ;;; time the printer was called
473 (defvar *previous-case* nil)
474 (defvar *previous-readtable-case* nil)
476 ;;; This variable contains the current definition of one of three
477 ;;; symbol printers. SETUP-PRINTER-STATE sets this variable.
478 (defvar *internal-symbol-output-fun* nil)
480 ;;; This function sets the internal global symbol
481 ;;; *INTERNAL-SYMBOL-OUTPUT-FUN* to the right function depending on
482 ;;; the value of *PRINT-CASE*. See the manual for details. The print
483 ;;; buffer stream is also reset.
484 (defun setup-printer-state ()
485 (unless (and (eq *print-case* *previous-case*)
486 (eq (readtable-case *readtable*) *previous-readtable-case*))
487 (setq *previous-case* *print-case*)
488 (setq *previous-readtable-case* (readtable-case *readtable*))
489 (unless (member *print-case* '(:upcase :downcase :capitalize))
490 (setq *print-case* :upcase)
491 (error "invalid *PRINT-CASE* value: ~S" *previous-case*))
492 (unless (member *previous-readtable-case*
493 '(:upcase :downcase :invert :preserve))
494 (setf (readtable-case *readtable*) :upcase)
495 (error "invalid READTABLE-CASE value: ~S" *previous-readtable-case*))
497 (setq *internal-symbol-output-fun*
498 (case *previous-readtable-case*
499 (:upcase
500 (case *print-case*
501 (:upcase #'output-preserve-symbol)
502 (:downcase #'output-lowercase-symbol)
503 (:capitalize #'output-capitalize-symbol)))
504 (:downcase
505 (case *print-case*
506 (:upcase #'output-uppercase-symbol)
507 (:downcase #'output-preserve-symbol)
508 (:capitalize #'output-capitalize-symbol)))
509 (:preserve #'output-preserve-symbol)
510 (:invert #'output-invert-symbol)))))
512 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
513 ;;; and with any embedded |'s or \'s escaped.
514 (defun output-quoted-symbol-name (pname stream)
515 (write-char #\| stream)
516 (dotimes (index (length pname))
517 (let ((char (schar pname index)))
518 (when (or (char= char #\\) (char= char #\|))
519 (write-char #\\ stream))
520 (write-char char stream)))
521 (write-char #\| stream))
523 (defun output-symbol (object stream)
524 (if (or *print-escape* *print-readably*)
525 (let ((package (symbol-package object))
526 (name (symbol-name object)))
527 (cond
528 ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
529 ;; requires that keywords be printed with preceding colons
530 ;; always, regardless of the value of *PACKAGE*.
531 ((eq package *keyword-package*)
532 (write-char #\: stream))
533 ;; Otherwise, if the symbol's home package is the current
534 ;; one, then a prefix is never necessary.
535 ((eq package (sane-package)))
536 ;; Uninterned symbols print with a leading #:.
537 ((null package)
538 (when (or *print-gensym* *print-readably*)
539 (write-string "#:" stream)))
541 (multiple-value-bind (symbol accessible)
542 (find-symbol name (sane-package))
543 ;; If we can find the symbol by looking it up, it need not
544 ;; be qualified. This can happen if the symbol has been
545 ;; inherited from a package other than its home package.
546 (unless (and accessible (eq symbol object))
547 (output-symbol-name (package-name package) stream)
548 (multiple-value-bind (symbol externalp)
549 (find-external-symbol name package)
550 (declare (ignore symbol))
551 (if externalp
552 (write-char #\: stream)
553 (write-string "::" stream)))))))
554 (output-symbol-name name stream))
555 (output-symbol-name (symbol-name object) stream nil)))
557 ;;; Output the string NAME as if it were a symbol name. In other
558 ;;; words, diddle its case according to *PRINT-CASE* and
559 ;;; READTABLE-CASE.
560 (defun output-symbol-name (name stream &optional (maybe-quote t))
561 (declare (type simple-string name))
562 (let ((*readtable* (if *print-readably* *standard-readtable* *readtable*)))
563 (setup-printer-state)
564 (if (and maybe-quote (symbol-quotep name))
565 (output-quoted-symbol-name name stream)
566 (funcall *internal-symbol-output-fun* name stream))))
568 ;;;; escaping symbols
570 ;;; When we print symbols we have to figure out if they need to be
571 ;;; printed with escape characters. This isn't a whole lot easier than
572 ;;; reading symbols in the first place.
574 ;;; For each character, the value of the corresponding element is a
575 ;;; fixnum with bits set corresponding to attributes that the
576 ;;; character has. At characters have at least one bit set, so we can
577 ;;; search for any character with a positive test.
578 (defvar *character-attributes*
579 (make-array 160 ; FIXME
580 :element-type '(unsigned-byte 16)
581 :initial-element 0))
582 (declaim (type (simple-array (unsigned-byte 16) (#.160)) ; FIXME
583 *character-attributes*))
585 ;;; constants which are a bit-mask for each interesting character attribute
586 (defconstant other-attribute (ash 1 0)) ; Anything else legal.
587 (defconstant number-attribute (ash 1 1)) ; A numeric digit.
588 (defconstant uppercase-attribute (ash 1 2)) ; An uppercase letter.
589 (defconstant lowercase-attribute (ash 1 3)) ; A lowercase letter.
590 (defconstant sign-attribute (ash 1 4)) ; +-
591 (defconstant extension-attribute (ash 1 5)) ; ^_
592 (defconstant dot-attribute (ash 1 6)) ; .
593 (defconstant slash-attribute (ash 1 7)) ; /
594 (defconstant funny-attribute (ash 1 8)) ; Anything illegal.
596 (eval-when (:compile-toplevel :load-toplevel :execute)
598 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
599 ;;; that don't need to be escaped (according to READTABLE-CASE.)
600 (defparameter *attribute-names*
601 `((number . number-attribute) (lowercase . lowercase-attribute)
602 (uppercase . uppercase-attribute) (letter . letter-attribute)
603 (sign . sign-attribute) (extension . extension-attribute)
604 (dot . dot-attribute) (slash . slash-attribute)
605 (other . other-attribute) (funny . funny-attribute)))
607 ) ; EVAL-WHEN
609 (flet ((set-bit (char bit)
610 (let ((code (char-code char)))
611 (setf (aref *character-attributes* code)
612 (logior bit (aref *character-attributes* code))))))
614 (dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
615 #\? #\< #\>))
616 (set-bit char other-attribute))
618 (dotimes (i 10)
619 (set-bit (digit-char i) number-attribute))
621 (do ((code (char-code #\A) (1+ code))
622 (end (char-code #\Z)))
623 ((> code end))
624 (declare (fixnum code end))
625 (set-bit (code-char code) uppercase-attribute)
626 (set-bit (char-downcase (code-char code)) lowercase-attribute))
628 (set-bit #\- sign-attribute)
629 (set-bit #\+ sign-attribute)
630 (set-bit #\^ extension-attribute)
631 (set-bit #\_ extension-attribute)
632 (set-bit #\. dot-attribute)
633 (set-bit #\/ slash-attribute)
635 ;; Mark anything not explicitly allowed as funny.
636 (dotimes (i 160) ; FIXME
637 (when (zerop (aref *character-attributes* i))
638 (setf (aref *character-attributes* i) funny-attribute))))
640 ;;; For each character, the value of the corresponding element is the
641 ;;; lowest base in which that character is a digit.
642 (defvar *digit-bases*
643 (make-array 128 ; FIXME
644 :element-type '(unsigned-byte 8)
645 :initial-element 36))
646 (declaim (type (simple-array (unsigned-byte 8) (#.128)) ; FIXME
647 *digit-bases*))
648 (dotimes (i 36)
649 (let ((char (digit-char i 36)))
650 (setf (aref *digit-bases* (char-code char)) i)))
652 ;;; A FSM-like thingie that determines whether a symbol is a potential
653 ;;; number or has evil characters in it.
654 (defun symbol-quotep (name)
655 (declare (simple-string name))
656 (macrolet ((advance (tag &optional (at-end t))
657 `(progn
658 (when (= index len)
659 ,(if at-end '(go TEST-SIGN) '(return nil)))
660 (setq current (schar name index)
661 code (char-code current)
662 bits (cond ; FIXME
663 ((< code 160) (aref attributes code))
664 ((upper-case-p current) uppercase-attribute)
665 ((lower-case-p current) lowercase-attribute)
666 (t other-attribute)))
667 (incf index)
668 (go ,tag)))
669 (test (&rest attributes)
670 `(not (zerop
671 (the fixnum
672 (logand
673 (logior ,@(mapcar
674 (lambda (x)
675 (or (cdr (assoc x
676 *attribute-names*))
677 (error "Blast!")))
678 attributes))
679 bits)))))
680 (digitp ()
681 `(and (< code 128) ; FIXME
682 (< (the fixnum (aref bases code)) base))))
684 (prog ((len (length name))
685 (attributes *character-attributes*)
686 (bases *digit-bases*)
687 (base *print-base*)
688 (letter-attribute
689 (case (readtable-case *readtable*)
690 (:upcase uppercase-attribute)
691 (:downcase lowercase-attribute)
692 (t (logior lowercase-attribute uppercase-attribute))))
693 (index 0)
694 (bits 0)
695 (code 0)
696 current)
697 (declare (fixnum len base index bits code))
698 (advance START t)
700 TEST-SIGN ; At end, see whether it is a sign...
701 (return (not (test sign)))
703 OTHER ; not potential number, see whether funny chars...
704 (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
705 funny-attribute)
706 letter-attribute)))
707 (do ((i (1- index) (1+ i)))
708 ((= i len) (return-from symbol-quotep nil))
709 (unless (zerop (logand (let* ((char (schar name i))
710 (code (char-code char)))
711 (cond
712 ((< code 160) (aref attributes code))
713 ((upper-case-p char) uppercase-attribute)
714 ((lower-case-p char) lowercase-attribute)
715 (t other-attribute)))
716 mask))
717 (return-from symbol-quotep t))))
719 START
720 (when (digitp)
721 (if (test letter)
722 (advance LAST-DIGIT-ALPHA)
723 (advance DIGIT)))
724 (when (test letter number other slash) (advance OTHER nil))
725 (when (char= current #\.) (advance DOT-FOUND))
726 (when (test sign extension) (advance START-STUFF nil))
727 (return t)
729 DOT-FOUND ; leading dots...
730 (when (test letter) (advance START-DOT-MARKER nil))
731 (when (digitp) (advance DOT-DIGIT))
732 (when (test number other) (advance OTHER nil))
733 (when (test extension slash sign) (advance START-DOT-STUFF nil))
734 (when (char= current #\.) (advance DOT-FOUND))
735 (return t)
737 START-STUFF ; leading stuff before any dot or digit
738 (when (digitp)
739 (if (test letter)
740 (advance LAST-DIGIT-ALPHA)
741 (advance DIGIT)))
742 (when (test number other) (advance OTHER nil))
743 (when (test letter) (advance START-MARKER nil))
744 (when (char= current #\.) (advance START-DOT-STUFF nil))
745 (when (test sign extension slash) (advance START-STUFF nil))
746 (return t)
748 START-MARKER ; number marker in leading stuff...
749 (when (test letter) (advance OTHER nil))
750 (go START-STUFF)
752 START-DOT-STUFF ; leading stuff containing dot without digit...
753 (when (test letter) (advance START-DOT-STUFF nil))
754 (when (digitp) (advance DOT-DIGIT))
755 (when (test sign extension dot slash) (advance START-DOT-STUFF nil))
756 (when (test number other) (advance OTHER nil))
757 (return t)
759 START-DOT-MARKER ; number marker in leading stuff with dot..
760 ;; leading stuff containing dot without digit followed by letter...
761 (when (test letter) (advance OTHER nil))
762 (go START-DOT-STUFF)
764 DOT-DIGIT ; in a thing with dots...
765 (when (test letter) (advance DOT-MARKER))
766 (when (digitp) (advance DOT-DIGIT))
767 (when (test number other) (advance OTHER nil))
768 (when (test sign extension dot slash) (advance DOT-DIGIT))
769 (return t)
771 DOT-MARKER ; number marker in number with dot...
772 (when (test letter) (advance OTHER nil))
773 (go DOT-DIGIT)
775 LAST-DIGIT-ALPHA ; previous char is a letter digit...
776 (when (or (digitp) (test sign slash))
777 (advance ALPHA-DIGIT))
778 (when (test letter number other dot) (advance OTHER nil))
779 (return t)
781 ALPHA-DIGIT ; seen a digit which is a letter...
782 (when (or (digitp) (test sign slash))
783 (if (test letter)
784 (advance LAST-DIGIT-ALPHA)
785 (advance ALPHA-DIGIT)))
786 (when (test letter) (advance ALPHA-MARKER))
787 (when (test number other dot) (advance OTHER nil))
788 (return t)
790 ALPHA-MARKER ; number marker in number with alpha digit...
791 (when (test letter) (advance OTHER nil))
792 (go ALPHA-DIGIT)
794 DIGIT ; seen only ordinary (non-alphabetic) numeric digits...
795 (when (digitp)
796 (if (test letter)
797 (advance ALPHA-DIGIT)
798 (advance DIGIT)))
799 (when (test number other) (advance OTHER nil))
800 (when (test letter) (advance MARKER))
801 (when (test extension slash sign) (advance DIGIT))
802 (when (char= current #\.) (advance DOT-DIGIT))
803 (return t)
805 MARKER ; number marker in a numeric number...
806 ;; ("What," you may ask, "is a 'number marker'?" It's something
807 ;; that a conforming implementation might use in number syntax.
808 ;; See ANSI 2.3.1.1 "Potential Numbers as Tokens".)
809 (when (test letter) (advance OTHER nil))
810 (go DIGIT))))
812 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN*
813 ;;;;
814 ;;;; case hackery: These functions are stored in
815 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN* according to the values of
816 ;;;; *PRINT-CASE* and READTABLE-CASE.
818 ;;; called when:
819 ;;; READTABLE-CASE *PRINT-CASE*
820 ;;; :UPCASE :UPCASE
821 ;;; :DOWNCASE :DOWNCASE
822 ;;; :PRESERVE any
823 (defun output-preserve-symbol (pname stream)
824 (declare (simple-string pname))
825 (write-string pname stream))
827 ;;; called when:
828 ;;; READTABLE-CASE *PRINT-CASE*
829 ;;; :UPCASE :DOWNCASE
830 (defun output-lowercase-symbol (pname stream)
831 (declare (simple-string pname))
832 (dotimes (index (length pname))
833 (let ((char (schar pname index)))
834 (write-char (char-downcase char) stream))))
836 ;;; called when:
837 ;;; READTABLE-CASE *PRINT-CASE*
838 ;;; :DOWNCASE :UPCASE
839 (defun output-uppercase-symbol (pname stream)
840 (declare (simple-string pname))
841 (dotimes (index (length pname))
842 (let ((char (schar pname index)))
843 (write-char (char-upcase char) stream))))
845 ;;; called when:
846 ;;; READTABLE-CASE *PRINT-CASE*
847 ;;; :UPCASE :CAPITALIZE
848 ;;; :DOWNCASE :CAPITALIZE
849 (defun output-capitalize-symbol (pname stream)
850 (declare (simple-string pname))
851 (let ((prev-not-alphanum t)
852 (up (eq (readtable-case *readtable*) :upcase)))
853 (dotimes (i (length pname))
854 (let ((char (char pname i)))
855 (write-char (if up
856 (if (or prev-not-alphanum (lower-case-p char))
857 char
858 (char-downcase char))
859 (if prev-not-alphanum
860 (char-upcase char)
861 char))
862 stream)
863 (setq prev-not-alphanum (not (alphanumericp char)))))))
865 ;;; called when:
866 ;;; READTABLE-CASE *PRINT-CASE*
867 ;;; :INVERT any
868 (defun output-invert-symbol (pname stream)
869 (declare (simple-string pname))
870 (let ((all-upper t)
871 (all-lower t))
872 (dotimes (i (length pname))
873 (let ((ch (schar pname i)))
874 (when (both-case-p ch)
875 (if (upper-case-p ch)
876 (setq all-lower nil)
877 (setq all-upper nil)))))
878 (cond (all-upper (output-lowercase-symbol pname stream))
879 (all-lower (output-uppercase-symbol pname stream))
881 (write-string pname stream)))))
884 (defun test1 ()
885 (let ((*readtable* (copy-readtable nil)))
886 (format t "READTABLE-CASE Input Symbol-name~@
887 ----------------------------------~%")
888 (dolist (readtable-case '(:upcase :downcase :preserve :invert))
889 (setf (readtable-case *readtable*) readtable-case)
890 (dolist (input '("ZEBRA" "Zebra" "zebra"))
891 (format t "~&:~A~16T~A~24T~A"
892 (string-upcase readtable-case)
893 input
894 (symbol-name (read-from-string input)))))))
896 (defun test2 ()
897 (let ((*readtable* (copy-readtable nil)))
898 (format t "READTABLE-CASE *PRINT-CASE* Symbol-name Output Princ~@
899 --------------------------------------------------------~%")
900 (dolist (readtable-case '(:upcase :downcase :preserve :invert))
901 (setf (readtable-case *readtable*) readtable-case)
902 (dolist (*print-case* '(:upcase :downcase :capitalize))
903 (dolist (symbol '(|ZEBRA| |Zebra| |zebra|))
904 (format t "~&:~A~15T:~A~29T~A~42T~A~50T~A"
905 (string-upcase readtable-case)
906 (string-upcase *print-case*)
907 (symbol-name symbol)
908 (prin1-to-string symbol)
909 (princ-to-string symbol)))))))
912 ;;;; recursive objects
914 (defun output-list (list stream)
915 (descend-into (stream)
916 (write-char #\( stream)
917 (let ((length 0)
918 (list list))
919 (loop
920 (punt-print-if-too-long length stream)
921 (output-object (pop list) stream)
922 (unless list
923 (return))
924 (when (or (atom list)
925 (check-for-circularity list))
926 (write-string " . " stream)
927 (output-object list stream)
928 (return))
929 (write-char #\space stream)
930 (incf length)))
931 (write-char #\) stream)))
933 (defun output-vector (vector stream)
934 (declare (vector vector))
935 (cond ((stringp vector)
936 (cond ((and *print-readably*
937 (not (eq (array-element-type vector)
938 (load-time-value
939 (array-element-type
940 (make-array 0 :element-type 'character))))))
941 (error 'print-not-readable :object vector))
942 ((or *print-escape* *print-readably*)
943 (write-char #\" stream)
944 (quote-string vector stream)
945 (write-char #\" stream))
947 (write-string vector stream))))
948 ((not (or *print-array* *print-readably*))
949 (output-terse-array vector stream))
950 ((bit-vector-p vector)
951 (write-string "#*" stream)
952 (dovector (bit vector)
953 ;; (Don't use OUTPUT-OBJECT here, since this code
954 ;; has to work for all possible *PRINT-BASE* values.)
955 (write-char (if (zerop bit) #\0 #\1) stream)))
957 (when (and *print-readably*
958 (not (array-readably-printable-p vector)))
959 (error 'print-not-readable :object vector))
960 (descend-into (stream)
961 (write-string "#(" stream)
962 (dotimes (i (length vector))
963 (unless (zerop i)
964 (write-char #\space stream))
965 (punt-print-if-too-long i stream)
966 (output-object (aref vector i) stream))
967 (write-string ")" stream)))))
969 ;;; This function outputs a string quoting characters sufficiently
970 ;;; so that someone can read it in again. Basically, put a slash in
971 ;;; front of an character satisfying NEEDS-SLASH-P.
972 (defun quote-string (string stream)
973 (macrolet ((needs-slash-p (char)
974 ;; KLUDGE: We probably should look at the readtable, but just do
975 ;; this for now. [noted by anonymous long ago] -- WHN 19991130
976 `(or (char= ,char #\\)
977 (char= ,char #\"))))
978 (with-array-data ((data string) (start) (end)
979 :check-fill-pointer t)
980 (do ((index start (1+ index)))
981 ((>= index end))
982 (let ((char (schar data index)))
983 (when (needs-slash-p char) (write-char #\\ stream))
984 (write-char char stream))))))
986 (defun array-readably-printable-p (array)
987 (and (eq (array-element-type array) t)
988 (let ((zero (position 0 (array-dimensions array)))
989 (number (position 0 (array-dimensions array)
990 :test (complement #'eql)
991 :from-end t)))
992 (or (null zero) (null number) (> zero number)))))
994 ;;; Output the printed representation of any array in either the #< or #A
995 ;;; form.
996 (defun output-array (array stream)
997 (if (or *print-array* *print-readably*)
998 (output-array-guts array stream)
999 (output-terse-array array stream)))
1001 ;;; Output the abbreviated #< form of an array.
1002 (defun output-terse-array (array stream)
1003 (let ((*print-level* nil)
1004 (*print-length* nil))
1005 (print-unreadable-object (array stream :type t :identity t))))
1007 ;;; Output the readable #A form of an array.
1008 (defun output-array-guts (array stream)
1009 (when (and *print-readably*
1010 (not (array-readably-printable-p array)))
1011 (error 'print-not-readable :object array))
1012 (write-char #\# stream)
1013 (let ((*print-base* 10)
1014 (*print-radix* nil))
1015 (output-integer (array-rank array) stream))
1016 (write-char #\A stream)
1017 (with-array-data ((data array) (start) (end))
1018 (declare (ignore end))
1019 (sub-output-array-guts data (array-dimensions array) stream start)))
1021 (defun sub-output-array-guts (array dimensions stream index)
1022 (declare (type (simple-array * (*)) array) (fixnum index))
1023 (cond ((null dimensions)
1024 (output-object (aref array index) stream))
1026 (descend-into (stream)
1027 (write-char #\( stream)
1028 (let* ((dimension (car dimensions))
1029 (dimensions (cdr dimensions))
1030 (count (reduce #'* dimensions)))
1031 (dotimes (i dimension)
1032 (unless (zerop i)
1033 (write-char #\space stream))
1034 (punt-print-if-too-long i stream)
1035 (sub-output-array-guts array dimensions stream index)
1036 (incf index count)))
1037 (write-char #\) stream)))))
1039 ;;; a trivial non-generic-function placeholder for PRINT-OBJECT, for
1040 ;;; use until CLOS is set up (at which time it will be replaced with
1041 ;;; the real generic function implementation)
1042 (defun print-object (instance stream)
1043 (default-structure-print instance stream *current-level-in-print*))
1045 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
1047 (defun %output-radix (base stream)
1048 (write-char #\# stream)
1049 (write-char (case base
1050 (2 #\b)
1051 (8 #\o)
1052 (16 #\x)
1053 (t (%output-reasonable-integer-in-base base 10 stream)
1054 #\r))
1055 stream))
1057 (defun %output-reasonable-integer-in-base (n base stream)
1058 (multiple-value-bind (q r)
1059 (truncate n base)
1060 ;; Recurse until you have all the digits pushed on
1061 ;; the stack.
1062 (unless (zerop q)
1063 (%output-reasonable-integer-in-base q base stream))
1064 ;; Then as each recursive call unwinds, turn the
1065 ;; digit (in remainder) into a character and output
1066 ;; the character.
1067 (write-char
1068 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r)
1069 stream)))
1071 ;;; *POWER-CACHE* is an alist mapping bases to power-vectors. It is
1072 ;;; filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
1073 ;;; always prior a GC to drop overly large bignums from the cache.
1075 ;;; It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
1076 ;;; POWERS-FOR-BASE, see that you don't break the assumptions!
1077 (defvar *power-cache* nil)
1079 (defconstant +power-cache-integer-length-limit+ 2048)
1081 (defun scrub-power-cache ()
1082 (let ((cache *power-cache*))
1083 (dolist (cell cache)
1084 (let ((powers (cdr cell)))
1085 (declare (simple-vector powers))
1086 (let ((too-big (position-if
1087 (lambda (x)
1088 (>= (integer-length x)
1089 +power-cache-integer-length-limit+))
1090 powers)))
1091 (when too-big
1092 (setf (cdr cell) (subseq powers 0 too-big))))))
1093 ;; Since base 10 is overwhelmingly common, make sure it's at head.
1094 ;; Try to keep other bases in a hopefully sensible order as well.
1095 (if (eql 10 (caar cache))
1096 (setf *power-cache* cache)
1097 ;; If we modify the list destructively we need to copy it, otherwise
1098 ;; an alist lookup in progress might be screwed.
1099 (setf *power-cache* (sort (copy-list cache)
1100 (lambda (a b)
1101 (declare (fixnum a b))
1102 (cond ((= 10 a) t)
1103 ((= 10 b) nil)
1104 ((= 16 a) t)
1105 ((= 16 b) nil)
1106 ((= 2 a) t)
1107 ((= 2 b) nil)
1108 (t (< a b))))
1109 :key #'car)))))
1111 ;;; Compute (and cache) a power vector for a BASE and LIMIT:
1112 ;;; the vector holds integers for which
1113 ;;; (aref powers k) == (expt base (expt 2 k))
1114 ;;; holds.
1115 (defun powers-for-base (base limit)
1116 (flet ((compute-powers (from)
1117 (let (powers)
1118 (do ((p from (* p p)))
1119 ((> p limit)
1120 ;; We don't actually need this, but we also
1121 ;; prefer not to cons it up a second time...
1122 (push p powers))
1123 (push p powers))
1124 (nreverse powers))))
1125 ;; Grab a local reference so that we won't stuff consed at the
1126 ;; head by other threads -- or sorting by SCRUB-POWER-CACHE.
1127 (let ((cache *power-cache*))
1128 (let ((cell (assoc base cache)))
1129 (if cell
1130 (let* ((powers (cdr cell))
1131 (len (length powers))
1132 (max (svref powers (1- len))))
1133 (if (> max limit)
1134 powers
1135 (let ((new
1136 (concatenate 'vector powers
1137 (compute-powers (* max max)))))
1138 (setf (cdr cell) new)
1139 new)))
1140 (let ((powers (coerce (compute-powers base) 'vector)))
1141 ;; Add new base to head: SCRUB-POWER-CACHE will later
1142 ;; put it to a better place.
1143 (setf *power-cache* (acons base powers cache))
1144 powers))))))
1146 ;; Algorithm by Harald Hanche-Olsen, sbcl-devel 2005-02-05
1147 (defun %output-huge-integer-in-base (n base stream)
1148 (declare (type bignum n) (type fixnum base))
1149 ;; POWER is a vector for which the following holds:
1150 ;; (aref power k) == (expt base (expt 2 k))
1151 (let* ((power (powers-for-base base n))
1152 (k-start (or (position-if (lambda (x) (> x n)) power)
1153 (bug "power-vector too short"))))
1154 (labels ((bisect (n k exactp)
1155 (declare (fixnum k))
1156 ;; N is the number to bisect
1157 ;; K on initial entry BASE^(2^K) > N
1158 ;; EXACTP is true if 2^K is the exact number of digits
1159 (cond ((zerop n)
1160 (when exactp
1161 (loop repeat (ash 1 k) do (write-char #\0 stream))))
1162 ((zerop k)
1163 (write-char
1164 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n)
1165 stream))
1167 (setf k (1- k))
1168 (multiple-value-bind (q r) (truncate n (aref power k))
1169 ;; EXACTP is NIL only at the head of the
1170 ;; initial number, as we don't know the number
1171 ;; of digits there, but we do know that it
1172 ;; doesn't get any leading zeros.
1173 (bisect q k exactp)
1174 (bisect r k (or exactp (plusp q))))))))
1175 (bisect n k-start nil))))
1177 (defun %output-integer-in-base (integer base stream)
1178 (when (minusp integer)
1179 (write-char #\- stream)
1180 (setf integer (- integer)))
1181 ;; The ideal cutoff point between these two algorithms is almost
1182 ;; certainly quite platform dependent: this gives 87 for 32 bit
1183 ;; SBCL, which is about right at least for x86/Darwin.
1184 (if (or (fixnump integer)
1185 (< (integer-length integer) (* 3 sb!vm:n-positive-fixnum-bits)))
1186 (%output-reasonable-integer-in-base integer base stream)
1187 (%output-huge-integer-in-base integer base stream)))
1189 (defun output-integer (integer stream)
1190 (let ((base *print-base*))
1191 (when (and (/= base 10) *print-radix*)
1192 (%output-radix base stream))
1193 (%output-integer-in-base integer base stream)
1194 (when (and *print-radix* (= base 10))
1195 (write-char #\. stream))))
1197 (defun output-ratio (ratio stream)
1198 (let ((base *print-base*))
1199 (when *print-radix*
1200 (%output-radix base stream))
1201 (%output-integer-in-base (numerator ratio) base stream)
1202 (write-char #\/ stream)
1203 (%output-integer-in-base (denominator ratio) base stream)))
1205 (defun output-complex (complex stream)
1206 (write-string "#C(" stream)
1207 ;; FIXME: Could this just be OUTPUT-NUMBER?
1208 (output-object (realpart complex) stream)
1209 (write-char #\space stream)
1210 (output-object (imagpart complex) stream)
1211 (write-char #\) stream))
1213 ;;;; float printing
1215 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1216 ;;; most of the work for all printing of floating point numbers in
1217 ;;; FORMAT. It converts a floating point number to a string in a free
1218 ;;; or fixed format with no exponent. The interpretation of the
1219 ;;; arguments is as follows:
1221 ;;; X - The floating point number to convert, which must not be
1222 ;;; negative.
1223 ;;; WIDTH - The preferred field width, used to determine the number
1224 ;;; of fraction digits to produce if the FDIGITS parameter
1225 ;;; is unspecified or NIL. If the non-fraction digits and the
1226 ;;; decimal point alone exceed this width, no fraction digits
1227 ;;; will be produced unless a non-NIL value of FDIGITS has been
1228 ;;; specified. Field overflow is not considerd an error at this
1229 ;;; level.
1230 ;;; FDIGITS - The number of fractional digits to produce. Insignificant
1231 ;;; trailing zeroes may be introduced as needed. May be
1232 ;;; unspecified or NIL, in which case as many digits as possible
1233 ;;; are generated, subject to the constraint that there are no
1234 ;;; trailing zeroes.
1235 ;;; SCALE - If this parameter is specified or non-NIL, then the number
1236 ;;; printed is (* x (expt 10 scale)). This scaling is exact,
1237 ;;; and cannot lose precision.
1238 ;;; FMIN - This parameter, if specified or non-NIL, is the minimum
1239 ;;; number of fraction digits which will be produced, regardless
1240 ;;; of the value of WIDTH or FDIGITS. This feature is used by
1241 ;;; the ~E format directive to prevent complete loss of
1242 ;;; significance in the printed value due to a bogus choice of
1243 ;;; scale factor.
1245 ;;; Returns:
1246 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1247 ;;; where the results have the following interpretation:
1249 ;;; DIGIT-STRING - The decimal representation of X, with decimal point.
1250 ;;; DIGIT-LENGTH - The length of the string DIGIT-STRING.
1251 ;;; LEADING-POINT - True if the first character of DIGIT-STRING is the
1252 ;;; decimal point.
1253 ;;; TRAILING-POINT - True if the last character of DIGIT-STRING is the
1254 ;;; decimal point.
1255 ;;; POINT-POS - The position of the digit preceding the decimal
1256 ;;; point. Zero indicates point before first digit.
1258 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1259 ;;; accuracy. Specifically, the decimal number printed is the closest
1260 ;;; possible approximation to the true value of the binary number to
1261 ;;; be printed from among all decimal representations with the same
1262 ;;; number of digits. In free-format output, i.e. with the number of
1263 ;;; digits unconstrained, it is guaranteed that all the information is
1264 ;;; preserved, so that a properly- rounding reader can reconstruct the
1265 ;;; original binary number, bit-for-bit, from its printed decimal
1266 ;;; representation. Furthermore, only as many digits as necessary to
1267 ;;; satisfy this condition will be printed.
1269 ;;; FLOAT-DIGITS actually generates the digits for positive numbers;
1270 ;;; see below for comments.
1272 (defun flonum-to-string (x &optional width fdigits scale fmin)
1273 (declare (type float x))
1274 ;; FIXME: I think only FORMAT-DOLLARS calls FLONUM-TO-STRING with
1275 ;; possibly-negative X.
1276 (setf x (abs x))
1277 (cond ((zerop x)
1278 ;; Zero is a special case which FLOAT-STRING cannot handle.
1279 (if fdigits
1280 (let ((s (make-string (1+ fdigits) :initial-element #\0)))
1281 (setf (schar s 0) #\.)
1282 (values s (length s) t (zerop fdigits) 0))
1283 (values "." 1 t t 0)))
1285 (multiple-value-bind (e string)
1286 (if fdigits
1287 (flonum-to-digits x (min (- (+ fdigits (or scale 0)))
1288 (- (or fmin 0))))
1289 (if (and width (> width 1))
1290 (let ((w (multiple-value-list
1291 (flonum-to-digits x
1292 (max 1
1293 (+ (1- width)
1294 (if (and scale (minusp scale))
1295 scale 0)))
1296 t)))
1297 (f (multiple-value-list
1298 (flonum-to-digits x (- (+ (or fmin 0)
1299 (if scale scale 0)))))))
1300 (cond
1301 ((>= (length (cadr w)) (length (cadr f)))
1302 (values-list w))
1303 (t (values-list f))))
1304 (flonum-to-digits x)))
1305 (let ((e (+ e (or scale 0)))
1306 (stream (make-string-output-stream)))
1307 (if (plusp e)
1308 (progn
1309 (write-string string stream :end (min (length string)
1311 (dotimes (i (- e (length string)))
1312 (write-char #\0 stream))
1313 (write-char #\. stream)
1314 (write-string string stream :start (min (length
1315 string) e))
1316 (when fdigits
1317 (dotimes (i (- fdigits
1318 (- (length string)
1319 (min (length string) e))))
1320 (write-char #\0 stream))))
1321 (progn
1322 (write-string "." stream)
1323 (dotimes (i (- e))
1324 (write-char #\0 stream))
1325 (write-string string stream)
1326 (when fdigits
1327 (dotimes (i (+ fdigits e (- (length string))))
1328 (write-char #\0 stream)))))
1329 (let ((string (get-output-stream-string stream)))
1330 (values string (length string)
1331 (char= (char string 0) #\.)
1332 (char= (char string (1- (length string))) #\.)
1333 (position #\. string))))))))
1335 ;;; implementation of figure 1 from Burger and Dybvig, 1996. As the
1336 ;;; implementation of the Dragon from Classic CMUCL (and previously in
1337 ;;; SBCL above FLONUM-TO-STRING) says: "DO NOT EVEN THINK OF
1338 ;;; ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE PAPER!",
1339 ;;; and in this case we have to add that even reading the paper might
1340 ;;; not bring immediate illumination as CSR has attempted to turn
1341 ;;; idiomatic Scheme into idiomatic Lisp.
1343 ;;; FIXME: figure 1 from Burger and Dybvig is the unoptimized
1344 ;;; algorithm, noticeably slow at finding the exponent. Figure 2 has
1345 ;;; an improved algorithm, but CSR ran out of energy.
1347 ;;; possible extension for the enthusiastic: printing floats in bases
1348 ;;; other than base 10.
1349 (defconstant single-float-min-e
1350 (- 2 sb!vm:single-float-bias sb!vm:single-float-digits))
1351 (defconstant double-float-min-e
1352 (- 2 sb!vm:double-float-bias sb!vm:double-float-digits))
1353 #!+long-float
1354 (defconstant long-float-min-e
1355 (nth-value 1 (decode-float least-positive-long-float)))
1357 (defun flonum-to-digits (v &optional position relativep)
1358 (let ((print-base 10) ; B
1359 (float-radix 2) ; b
1360 (float-digits (float-digits v)) ; p
1361 (digit-characters "0123456789")
1362 (min-e
1363 (etypecase v
1364 (single-float single-float-min-e)
1365 (double-float double-float-min-e)
1366 #!+long-float
1367 (long-float long-float-min-e))))
1368 (multiple-value-bind (f e)
1369 (integer-decode-float v)
1370 (let (;; FIXME: these even tests assume normal IEEE rounding
1371 ;; mode. I wonder if we should cater for non-normal?
1372 (high-ok (evenp f))
1373 (low-ok (evenp f)))
1374 (with-push-char (:element-type base-char)
1375 (labels ((scale (r s m+ m-)
1376 (do ((k 0 (1+ k))
1377 (s s (* s print-base)))
1378 ((not (or (> (+ r m+) s)
1379 (and high-ok (= (+ r m+) s))))
1380 (do ((k k (1- k))
1381 (r r (* r print-base))
1382 (m+ m+ (* m+ print-base))
1383 (m- m- (* m- print-base)))
1384 ((not (or (< (* (+ r m+) print-base) s)
1385 (and (not high-ok)
1386 (= (* (+ r m+) print-base) s))))
1387 (values k (generate r s m+ m-)))))))
1388 (generate (r s m+ m-)
1389 (let (d tc1 tc2)
1390 (tagbody
1391 loop
1392 (setf (values d r) (truncate (* r print-base) s))
1393 (setf m+ (* m+ print-base))
1394 (setf m- (* m- print-base))
1395 (setf tc1 (or (< r m-) (and low-ok (= r m-))))
1396 (setf tc2 (or (> (+ r m+) s)
1397 (and high-ok (= (+ r m+) s))))
1398 (when (or tc1 tc2)
1399 (go end))
1400 (push-char (char digit-characters d))
1401 (go loop)
1403 (let ((d (cond
1404 ((and (not tc1) tc2) (1+ d))
1405 ((and tc1 (not tc2)) d)
1406 (t ; (and tc1 tc2)
1407 (if (< (* r 2) s) d (1+ d))))))
1408 (push-char (char digit-characters d))
1409 (return-from generate (get-pushed-string))))))
1410 (initialize ()
1411 (let (r s m+ m-)
1412 (if (>= e 0)
1413 (let* ((be (expt float-radix e))
1414 (be1 (* be float-radix)))
1415 (if (/= f (expt float-radix (1- float-digits)))
1416 (setf r (* f be 2)
1418 m+ be
1419 m- be)
1420 (setf r (* f be1 2)
1421 s (* float-radix 2)
1422 m+ be1
1423 m- be)))
1424 (if (or (= e min-e)
1425 (/= f (expt float-radix (1- float-digits))))
1426 (setf r (* f 2)
1427 s (* (expt float-radix (- e)) 2)
1428 m+ 1
1429 m- 1)
1430 (setf r (* f float-radix 2)
1431 s (* (expt float-radix (- 1 e)) 2)
1432 m+ float-radix
1433 m- 1)))
1434 (when position
1435 (when relativep
1436 (aver (> position 0))
1437 (do ((k 0 (1+ k))
1438 ;; running out of letters here
1439 (l 1 (* l print-base)))
1440 ((>= (* s l) (+ r m+))
1441 ;; k is now \hat{k}
1442 (if (< (+ r (* s (/ (expt print-base (- k position)) 2)))
1443 (* s (expt print-base k)))
1444 (setf position (- k position))
1445 (setf position (- k position 1))))))
1446 (let ((low (max m- (/ (* s (expt print-base position)) 2)))
1447 (high (max m+ (/ (* s (expt print-base position)) 2))))
1448 (when (<= m- low)
1449 (setf m- low)
1450 (setf low-ok t))
1451 (when (<= m+ high)
1452 (setf m+ high)
1453 (setf high-ok t))))
1454 (values r s m+ m-))))
1455 (multiple-value-bind (r s m+ m-) (initialize)
1456 (scale r s m+ m-))))))))
1458 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns
1459 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1460 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1461 ;;; original number. There may be some loss of precision due the
1462 ;;; floating point representation. The scaling is always done with
1463 ;;; long float arithmetic, which helps printing of lesser precisions
1464 ;;; as well as avoiding generic arithmetic.
1466 ;;; When computing our initial scale factor using EXPT, we pull out
1467 ;;; part of the computation to avoid over/under flow. When
1468 ;;; denormalized, we must pull out a large factor, since there is more
1469 ;;; negative exponent range than positive range.
1471 (eval-when (:compile-toplevel :execute)
1472 (setf *read-default-float-format*
1473 #!+long-float 'long-float #!-long-float 'double-float))
1474 (defun scale-exponent (original-x)
1475 (let* ((x (coerce original-x 'long-float)))
1476 (multiple-value-bind (sig exponent) (decode-float x)
1477 (declare (ignore sig))
1478 (if (= x 0.0e0)
1479 (values (float 0.0e0 original-x) 1)
1480 (let* ((ex (locally (declare (optimize (safety 0)))
1481 (the fixnum
1482 (round (* exponent
1483 ;; this is the closest double float
1484 ;; to (log 2 10), but expressed so
1485 ;; that we're not vulnerable to the
1486 ;; host lisp's interpretation of
1487 ;; arithmetic. (FIXME: it turns
1488 ;; out that sbcl itself is off by 1
1489 ;; ulp in this value, which is a
1490 ;; little unfortunate.)
1491 (load-time-value
1492 #!-long-float
1493 (sb!kernel:make-double-float 1070810131 1352628735)
1494 #!+long-float
1495 (error "(log 2 10) not computed")))))))
1496 (x (if (minusp ex)
1497 (if (float-denormalized-p x)
1498 #!-long-float
1499 (* x 1.0e16 (expt 10.0e0 (- (- ex) 16)))
1500 #!+long-float
1501 (* x 1.0e18 (expt 10.0e0 (- (- ex) 18)))
1502 (* x 10.0e0 (expt 10.0e0 (- (- ex) 1))))
1503 (/ x 10.0e0 (expt 10.0e0 (1- ex))))))
1504 (do ((d 10.0e0 (* d 10.0e0))
1505 (y x (/ x d))
1506 (ex ex (1+ ex)))
1507 ((< y 1.0e0)
1508 (do ((m 10.0e0 (* m 10.0e0))
1509 (z y (* y m))
1510 (ex ex (1- ex)))
1511 ((>= z 0.1e0)
1512 (values (float z original-x) ex))
1513 (declare (long-float m) (integer ex))))
1514 (declare (long-float d))))))))
1515 (eval-when (:compile-toplevel :execute)
1516 (setf *read-default-float-format* 'single-float))
1518 ;;;; entry point for the float printer
1520 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1521 ;;; argument is printed free-format, in either exponential or
1522 ;;; non-exponential notation, depending on its magnitude.
1524 ;;; NOTE: When a number is to be printed in exponential format, it is
1525 ;;; scaled in floating point. Since precision may be lost in this
1526 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1527 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1528 ;;; extensive computations with integers of similar magnitude to that
1529 ;;; of the number being printed. For large exponents, the bignums
1530 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1531 ;;; fast and the exponent range is not too large, then it might become
1532 ;;; attractive to handle exponential notation with the same accuracy
1533 ;;; as non-exponential notation, using the method described in the
1534 ;;; Steele and White paper.
1536 ;;; NOTE II: this has been bypassed slightly by implementing Burger
1537 ;;; and Dybvig, 1996. When someone has time (KLUDGE) they can
1538 ;;; probably (a) implement the optimizations suggested by Burger and
1539 ;;; Dyvbig, and (b) remove all vestiges of Dragon4, including from
1540 ;;; fixed-format printing.
1542 ;;; Print the appropriate exponent marker for X and the specified exponent.
1543 (defun print-float-exponent (x exp stream)
1544 (declare (type float x) (type integer exp) (type stream stream))
1545 (let ((*print-radix* nil))
1546 (if (typep x *read-default-float-format*)
1547 (unless (eql exp 0)
1548 (format stream "e~D" exp))
1549 (format stream "~C~D"
1550 (etypecase x
1551 (single-float #\f)
1552 (double-float #\d)
1553 (short-float #\s)
1554 (long-float #\L))
1555 exp))))
1557 (defun output-float-infinity (x stream)
1558 (declare (float x) (stream stream))
1559 (cond (*read-eval*
1560 (write-string "#." stream))
1561 (*print-readably*
1562 (error 'print-not-readable :object x))
1564 (write-string "#<" stream)))
1565 (write-string "SB-EXT:" stream)
1566 (write-string (symbol-name (float-format-name x)) stream)
1567 (write-string (if (plusp x) "-POSITIVE-" "-NEGATIVE-")
1568 stream)
1569 (write-string "INFINITY" stream)
1570 (unless *read-eval*
1571 (write-string ">" stream)))
1573 (defun output-float-nan (x stream)
1574 (print-unreadable-object (x stream)
1575 (princ (float-format-name x) stream)
1576 (write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
1577 (write-string " NaN" stream)))
1579 ;;; the function called by OUTPUT-OBJECT to handle floats
1580 (defun output-float (x stream)
1581 (cond
1582 ((float-infinity-p x)
1583 (output-float-infinity x stream))
1584 ((float-nan-p x)
1585 (output-float-nan x stream))
1587 (let ((x (cond ((minusp (float-sign x))
1588 (write-char #\- stream)
1589 (- x))
1591 x))))
1592 (cond
1593 ((zerop x)
1594 (write-string "0.0" stream)
1595 (print-float-exponent x 0 stream))
1597 (output-float-aux x stream -3 8)))))))
1599 (defun output-float-aux (x stream e-min e-max)
1600 (multiple-value-bind (e string)
1601 (flonum-to-digits x)
1602 (cond
1603 ((< e-min e e-max)
1604 (if (plusp e)
1605 (progn
1606 (write-string string stream :end (min (length string) e))
1607 (dotimes (i (- e (length string)))
1608 (write-char #\0 stream))
1609 (write-char #\. stream)
1610 (write-string string stream :start (min (length string) e))
1611 (when (<= (length string) e)
1612 (write-char #\0 stream))
1613 (print-float-exponent x 0 stream))
1614 (progn
1615 (write-string "0." stream)
1616 (dotimes (i (- e))
1617 (write-char #\0 stream))
1618 (write-string string stream)
1619 (print-float-exponent x 0 stream))))
1620 (t (write-string string stream :end 1)
1621 (write-char #\. stream)
1622 (write-string string stream :start 1)
1623 (print-float-exponent x (1- e) stream)))))
1625 ;;;; other leaf objects
1627 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1628 ;;; the character name or the character in the #\char format.
1629 (defun output-character (char stream)
1630 (if (or *print-escape* *print-readably*)
1631 (let ((graphicp (and (graphic-char-p char)
1632 (standard-char-p char)))
1633 (name (char-name char)))
1634 (write-string "#\\" stream)
1635 (if (and name (not graphicp))
1636 (quote-string name stream)
1637 (write-char char stream)))
1638 (write-char char stream)))
1640 (defun output-sap (sap stream)
1641 (declare (type system-area-pointer sap))
1642 (cond (*read-eval*
1643 (format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
1645 (print-unreadable-object (sap stream)
1646 (format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
1648 (defun output-weak-pointer (weak-pointer stream)
1649 (declare (type weak-pointer weak-pointer))
1650 (print-unreadable-object (weak-pointer stream)
1651 (multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
1652 (cond (validp
1653 (write-string "weak pointer: " stream)
1654 (write value :stream stream))
1656 (write-string "broken weak pointer" stream))))))
1658 (defun output-code-component (component stream)
1659 (print-unreadable-object (component stream :identity t)
1660 (let ((dinfo (%code-debug-info component)))
1661 (cond ((eq dinfo :bogus-lra)
1662 (write-string "bogus code object" stream))
1664 (write-string "code object" stream)
1665 (when dinfo
1666 (write-char #\space stream)
1667 (output-object (sb!c::debug-info-name dinfo) stream)))))))
1669 (defun output-lra (lra stream)
1670 (print-unreadable-object (lra stream :identity t)
1671 (write-string "return PC object" stream)))
1673 (defun output-fdefn (fdefn stream)
1674 (print-unreadable-object (fdefn stream)
1675 (write-string "FDEFINITION object for " stream)
1676 (output-object (fdefn-name fdefn) stream)))
1678 ;;;; functions
1680 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1681 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1683 ;;; The definition here is a simple temporary placeholder. It will be
1684 ;;; overwritten by a smarter version (capable of calling generic
1685 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1686 (defun printed-as-funcallable-standard-class (object stream)
1687 (declare (ignore object stream))
1688 nil)
1690 (defun output-fun (object stream)
1691 (let* ((*print-length* 3) ; in case we have to..
1692 (*print-level* 3) ; ..print an interpreted function definition
1693 (name (%fun-name object))
1694 (proper-name-p (and (legal-fun-name-p name) (fboundp name)
1695 (eq (fdefinition name) object))))
1696 (print-unreadable-object (object stream :identity (not proper-name-p))
1697 (format stream "~:[FUNCTION~;CLOSURE~]~@[ ~S~]"
1698 (closurep object)
1699 name))))
1701 ;;;; catch-all for unknown things
1703 (defun output-random (object stream)
1704 (print-unreadable-object (object stream :identity t)
1705 (let ((lowtag (lowtag-of object)))
1706 (case lowtag
1707 (#.sb!vm:other-pointer-lowtag
1708 (let ((widetag (widetag-of object)))
1709 (case widetag
1710 (#.sb!vm:value-cell-header-widetag
1711 (write-string "value cell " stream)
1712 (output-object (value-cell-ref object) stream))
1714 (write-string "unknown pointer object, widetag=" stream)
1715 (let ((*print-base* 16) (*print-radix* t))
1716 (output-integer widetag stream))))))
1717 ((#.sb!vm:fun-pointer-lowtag
1718 #.sb!vm:instance-pointer-lowtag
1719 #.sb!vm:list-pointer-lowtag)
1720 (write-string "unknown pointer object, lowtag=" stream)
1721 (let ((*print-base* 16) (*print-radix* t))
1722 (output-integer lowtag stream)))
1724 (case (widetag-of object)
1725 (#.sb!vm:unbound-marker-widetag
1726 (write-string "unbound marker" stream))
1728 (write-string "unknown immediate object, lowtag=" stream)
1729 (let ((*print-base* 2) (*print-radix* t))
1730 (output-integer lowtag stream))
1731 (write-string ", widetag=" stream)
1732 (let ((*print-base* 16) (*print-radix* t))
1733 (output-integer (widetag-of object) stream)))))))))