Change code component printer.
[sbcl.git] / src / code / print.lisp
blob5daf11f7faefce97a25c3b1374c8ab1b7eed4494
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 (!defvar *print-readably* nil
17 #!+sb-doc
18 "If true, all objects will be printed readably. If readable printing
19 is impossible, an error will be signalled. This overrides the value of
20 *PRINT-ESCAPE*.")
21 (!defvar *print-escape* t
22 #!+sb-doc
23 "Should we print in a reasonably machine-readable way? (possibly
24 overridden by *PRINT-READABLY*)")
25 (!defvar *print-pretty* nil ; (set later when pretty-printer is initialized)
26 #!+sb-doc
27 "Should pretty printing be used?")
28 (!defvar *print-base* 10.
29 #!+sb-doc
30 "The output base for RATIONALs (including integers).")
31 (!defvar *print-radix* nil
32 #!+sb-doc
33 "Should base be verified when printing RATIONALs?")
34 (!defvar *print-level* nil
35 #!+sb-doc
36 "How many levels should be printed before abbreviating with \"#\"?")
37 (!defvar *print-length* nil
38 #!+sb-doc
39 "How many elements at any level should be printed before abbreviating
40 with \"...\"?")
41 (!defvar *print-circle* nil
42 #!+sb-doc
43 "Should we use #n= and #n# notation to preserve uniqueness in general (and
44 circularity in particular) when printing?")
45 (!defvar *print-case* :upcase
46 #!+sb-doc
47 "What case should the printer should use default?")
48 (!defvar *print-array* t
49 #!+sb-doc
50 "Should the contents of arrays be printed?")
51 (!defvar *print-gensym* t
52 #!+sb-doc
53 "Should #: prefixes be used when printing symbols with null SYMBOL-PACKAGE?")
54 (!defvar *print-lines* nil
55 #!+sb-doc
56 "The maximum number of lines to print per object.")
57 (!defvar *print-right-margin* nil
58 #!+sb-doc
59 "The position of the right margin in ems (for pretty-printing).")
60 (!defvar *print-miser-width* nil
61 #!+sb-doc
62 "If the remaining space between the current column and the right margin
63 is less than this, then print using ``miser-style'' output. Miser
64 style conditional newlines are turned on, and all indentations are
65 turned off. If NIL, never use miser mode.")
66 (defvar *print-pprint-dispatch*
67 (sb!pretty::make-pprint-dispatch-table) ; for type-correctness
68 #!+sb-doc
69 "The pprint-dispatch-table that controls how to pretty-print objects.")
70 (!defvar *suppress-print-errors* nil
71 #!+sb-doc
72 "Suppress printer errors when the condition is of the type designated by this
73 variable: an unreadable object representing the error is printed instead.")
75 ;; duplicate defglobal because this file is compiled before "reader"
76 (defglobal *standard-readtable* nil)
78 (defun %with-standard-io-syntax (function)
79 (declare (type function function))
80 (let ((*package* (find-package "COMMON-LISP-USER"))
81 (*print-array* t)
82 (*print-base* 10)
83 (*print-case* :upcase)
84 (*print-circle* nil)
85 (*print-escape* t)
86 (*print-gensym* t)
87 (*print-length* nil)
88 (*print-level* nil)
89 (*print-lines* nil)
90 (*print-miser-width* nil)
91 (*print-pprint-dispatch* sb!pretty::*standard-pprint-dispatch-table*)
92 (*print-pretty* nil)
93 (*print-radix* nil)
94 (*print-readably* t)
95 (*print-right-margin* nil)
96 (*read-base* 10)
97 (*read-default-float-format* 'single-float)
98 (*read-eval* t)
99 (*read-suppress* nil)
100 (*readtable* *standard-readtable*)
101 (*suppress-print-errors* nil))
102 (funcall function)))
104 ;;;; routines to print objects
106 (macrolet ((def (fn doc &rest forms)
107 (declare (ignorable doc))
108 `(defun ,fn
109 (object
110 &key
111 ,@(if (eq fn 'write) '(stream))
112 ((:escape *print-escape*) *print-escape*)
113 ((:radix *print-radix*) *print-radix*)
114 ((:base *print-base*) *print-base*)
115 ((:circle *print-circle*) *print-circle*)
116 ((:pretty *print-pretty*) *print-pretty*)
117 ((:level *print-level*) *print-level*)
118 ((:length *print-length*) *print-length*)
119 ((:case *print-case*) *print-case*)
120 ((:array *print-array*) *print-array*)
121 ((:gensym *print-gensym*) *print-gensym*)
122 ((:readably *print-readably*) *print-readably*)
123 ((:right-margin *print-right-margin*)
124 *print-right-margin*)
125 ((:miser-width *print-miser-width*)
126 *print-miser-width*)
127 ((:lines *print-lines*) *print-lines*)
128 ((:pprint-dispatch *print-pprint-dispatch*)
129 *print-pprint-dispatch*)
130 ((:suppress-errors *suppress-print-errors*)
131 *suppress-print-errors*))
132 #!+sb-doc ,doc
133 (declare (explicit-check))
134 ,@forms)))
135 (def write
136 "Output OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*."
137 (output-object object (out-synonym-of stream))
138 object)
139 (def write-to-string
140 "Return the printed representation of OBJECT as a string."
141 (stringify-object object)))
143 ;;; Same as a call to (WRITE OBJECT :STREAM STREAM), but returning OBJECT.
144 (defun %write (object stream)
145 (declare (explicit-check))
146 (output-object object (out-synonym-of stream))
147 object)
149 (defun prin1 (object &optional stream)
150 #!+sb-doc
151 "Output a mostly READable printed representation of OBJECT on the specified
152 STREAM."
153 (declare (explicit-check))
154 (let ((*print-escape* t))
155 (output-object object (out-synonym-of stream)))
156 object)
158 (defun princ (object &optional stream)
159 #!+sb-doc
160 "Output an aesthetic but not necessarily READable printed representation
161 of OBJECT on the specified STREAM."
162 (declare (explicit-check))
163 (let ((*print-escape* nil)
164 (*print-readably* nil))
165 (output-object object (out-synonym-of stream)))
166 object)
168 (defun print (object &optional stream)
169 #!+sb-doc
170 "Output a newline, the mostly READable printed representation of OBJECT, and
171 space to the specified STREAM."
172 (declare (explicit-check))
173 (let ((stream (out-synonym-of stream)))
174 (terpri stream)
175 (prin1 object stream)
176 (write-char #\space stream)
177 object))
179 (defun pprint (object &optional stream)
180 #!+sb-doc
181 "Prettily output OBJECT preceded by a newline."
182 (declare (explicit-check))
183 (let ((*print-pretty* t)
184 (*print-escape* t)
185 (stream (out-synonym-of stream)))
186 (terpri stream)
187 (output-object object stream))
188 (values))
190 (defun prin1-to-string (object)
191 #!+sb-doc
192 "Return the printed representation of OBJECT as a string with
193 slashification on."
194 (let ((*print-escape* t))
195 (stringify-object object)))
197 (defun princ-to-string (object)
198 #!+sb-doc
199 "Return the printed representation of OBJECT as a string with
200 slashification off."
201 (let ((*print-escape* nil)
202 (*print-readably* nil))
203 (stringify-object object)))
205 ;;; This produces the printed representation of an object as a string.
206 ;;; The few ...-TO-STRING functions above call this.
207 (defun stringify-object (object)
208 (with-simple-output-to-string (stream)
209 (setup-printer-state)
210 (output-object object stream)))
212 ;;;; support for the PRINT-UNREADABLE-OBJECT macro
214 (defun print-not-readable-error (object stream)
215 (restart-case
216 (error 'print-not-readable :object object)
217 (print-unreadably ()
218 :report "Print unreadably."
219 (let ((*print-readably* nil))
220 (output-object object stream)
221 object))
222 (use-value (o)
223 :report "Supply an object to be printed instead."
224 :interactive
225 (lambda ()
226 (read-evaluated-form "~@<Enter an object (evaluated): ~@:>"))
227 (output-object o stream)
228 o)))
230 ;;; guts of PRINT-UNREADABLE-OBJECT
231 (defun %print-unreadable-object (object stream type identity &optional body)
232 (declare (type (or null function) body))
233 (if *print-readably*
234 (print-not-readable-error object stream)
235 (flet ((print-description ()
236 (when type
237 (write (type-of object) :stream stream :circle nil
238 :level nil :length nil)
239 ;; Do NOT insert a pprint-newline here.
240 ;; See ba34717602d80e5fd74d10e61f4729fb0d019a0c
241 (write-char #\space stream))
242 (when body
243 (funcall body))
244 (when identity
245 (when (or body (not type))
246 (write-char #\space stream))
247 ;; Nor here.
248 (write-char #\{ stream)
249 (write (get-lisp-obj-address object) :stream stream
250 :radix nil :base 16)
251 (write-char #\} stream))))
252 (cond ((print-pretty-on-stream-p stream)
253 ;; Since we're printing prettily on STREAM, format the
254 ;; object within a logical block. PPRINT-LOGICAL-BLOCK does
255 ;; not rebind the stream when it is already a pretty stream,
256 ;; so output from the body will go to the same stream.
257 (pprint-logical-block (stream nil :prefix "#<" :suffix ">")
258 (print-description)))
260 (write-string "#<" stream)
261 (print-description)
262 (write-char #\> stream)))))
263 nil)
265 ;;;; OUTPUT-OBJECT -- the main entry point
267 ;;; Objects whose print representation identifies them EQLly don't
268 ;;; need to be checked for circularity.
269 (defun uniquely-identified-by-print-p (x)
270 (or (numberp x)
271 (characterp x)
272 (and (symbolp x)
273 (symbol-package x))))
275 (defvar *in-print-error* nil)
277 ;;; Output OBJECT to STREAM observing all printer control variables.
278 (defun output-object (object stream)
279 ;; FIXME: this function is declared EXPLICIT-CHECK, so it allows STREAM
280 ;; to be T or NIL (a stream-designator), which is not really right
281 ;; if eventually the call will be to a PRINT-OBJECT method,
282 ;; since the generic function should always receive a stream.
283 (declare (explicit-check))
284 (labels ((print-it (stream)
285 (multiple-value-bind (fun pretty)
286 (and *print-pretty* (pprint-dispatch object))
287 (if pretty
288 (sb!pretty::with-pretty-stream (stream)
289 (funcall fun stream object))
290 (output-ugly-object stream object))))
291 (handle-it (stream)
292 (if *suppress-print-errors*
293 (handler-bind ((condition
294 (lambda (condition) nil
295 (when (typep condition *suppress-print-errors*)
296 (cond (*in-print-error*
297 (write-string "(error printing " stream)
298 (write-string *in-print-error* stream)
299 (write-string ")" stream))
301 ;; Give outer handlers a chance.
302 (with-simple-restart
303 (continue "Suppress the error.")
304 (signal condition))
305 (let ((*print-readably* nil)
306 (*print-escape* t))
307 (write-string
308 "#<error printing a " stream)
309 (let ((*in-print-error* "type"))
310 (output-object (type-of object) stream))
311 (write-string ": " stream)
312 (let ((*in-print-error* "condition"))
313 (output-object condition stream))
314 (write-string ">" stream))))
315 (return-from handle-it object)))))
316 (print-it stream))
317 (print-it stream)))
318 (check-it (stream)
319 (multiple-value-bind (marker initiate)
320 (check-for-circularity object t)
321 (if (eq initiate :initiate)
322 (let ((*circularity-hash-table*
323 (make-hash-table :test 'eq)))
324 (check-it (make-broadcast-stream))
325 (let ((*circularity-counter* 0))
326 (check-it stream)))
327 ;; otherwise
328 (if marker
329 (when (handle-circularity marker stream)
330 (handle-it stream))
331 (handle-it stream))))))
332 (cond (;; Maybe we don't need to bother with circularity detection.
333 (or (not *print-circle*)
334 (uniquely-identified-by-print-p object))
335 (handle-it stream))
336 (;; If we have already started circularity detection, this
337 ;; object might be a shared reference. If we have not, then
338 ;; if it is a compound object it might contain a circular
339 ;; reference to itself or multiple shared references.
340 (or *circularity-hash-table*
341 (compound-object-p object))
342 (check-it stream))
344 (handle-it stream)))))
346 ;;; a hack to work around recurring gotchas with printing while
347 ;;; DEFGENERIC PRINT-OBJECT is being built
349 ;;; (hopefully will go away naturally when CLOS moves into cold init)
350 (defvar *print-object-is-disabled-p* nil) ; real soon now
352 ;;; Output OBJECT to STREAM observing all printer control variables
353 ;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
354 ;;; then the pretty printer will be used for any components of OBJECT,
355 ;;; just not for OBJECT itself.
356 (defun output-ugly-object (stream object)
357 (typecase object
358 ;; KLUDGE: The TYPECASE approach here is non-ANSI; the ANSI definition of
359 ;; PRINT-OBJECT says it provides printing and we're supposed to provide
360 ;; PRINT-OBJECT methods covering all classes. We deviate from this
361 ;; by using PRINT-OBJECT only when we print instance values. However,
362 ;; ANSI makes it hard to tell that we're deviating from this:
363 ;; (1) ANSI specifies that the user isn't supposed to call PRINT-OBJECT
364 ;; directly.
365 ;; (2) ANSI (section 11.1.2.1.2) says it's undefined to define
366 ;; a method on an external symbol in the CL package which is
367 ;; applicable to arg lists containing only direct instances of
368 ;; standardized classes.
369 ;; Thus, in order for the user to detect our sleaziness in conforming
370 ;; code, he has to do something relatively obscure like
371 ;; (1) actually use tools like FIND-METHOD to look for PRINT-OBJECT
372 ;; methods, or
373 ;; (2) define a PRINT-OBJECT method which is specialized on the stream
374 ;; value (e.g. a Gray stream object).
375 ;; As long as no one comes up with a non-obscure way of detecting this
376 ;; sleaziness, fixing this nonconformity will probably have a low
377 ;; priority. -- WHN 2001-11-25
378 (list
379 (if (null object)
380 (output-symbol object stream)
381 (output-list object stream)))
382 (instance
383 ;; The first case takes the above idea one step further: If an instance
384 ;; isn't a citizen yet, it has no right to a print-object method.
385 ;; Additionally, if the object is an obsolete CONDITION, don't crash.
386 ;; (There is no update-instance protocol for conditions)
387 (let* ((layout (layout-of object))
388 (classoid (layout-classoid layout)))
389 (cond ((or (sb!kernel::undefined-classoid-p classoid)
390 (and (layout-invalid layout) (condition-classoid-p classoid)))
391 ;; not only is this unreadable, it's unprintable too.
392 (print-unreadable-object (object stream :identity t)
393 (format stream "UNPRINTABLE instance of ~W" classoid)))
394 ((not (and (boundp '*print-object-is-disabled-p*)
395 *print-object-is-disabled-p*))
396 (print-object object stream))
397 ((typep object 'structure-object)
398 (default-structure-print object stream *current-level-in-print*))
400 (write-string "#<INSTANCE but not STRUCTURE-OBJECT>" stream)))))
401 (funcallable-instance
402 (cond
403 ((not (and (boundp '*print-object-is-disabled-p*)
404 *print-object-is-disabled-p*))
405 (print-object object stream))
406 (t (output-fun object stream))))
407 (function
408 (output-fun object stream))
409 (symbol
410 (output-symbol object stream))
411 (number
412 (etypecase object
413 (integer
414 (output-integer object stream))
415 (float
416 (output-float object stream))
417 (ratio
418 (output-ratio object stream))
419 (complex
420 (output-complex object stream))))
421 (character
422 (output-character object stream))
423 (vector
424 (output-vector object stream))
425 (array
426 (output-array object stream))
427 (system-area-pointer
428 (output-sap object stream))
429 (weak-pointer
430 (output-weak-pointer object stream))
431 (lra
432 (output-lra object stream))
433 (code-component
434 (output-code-component object stream))
435 (fdefn
436 (output-fdefn object stream))
437 #!+sb-simd-pack
438 (simd-pack
439 (print-object object stream))
441 (output-random object stream))))
443 ;;;; symbols
445 ;;; values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last
446 ;;; time the printer was called
447 (defvar *previous-case* nil)
448 (defvar *previous-readtable-case* nil)
450 ;;; This variable contains the current definition of one of three
451 ;;; symbol printers. SETUP-PRINTER-STATE sets this variable.
452 (defvar *internal-symbol-output-fun* nil)
453 (declaim (function *internal-symbol-output-fun*))
455 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
456 ;;; and with any embedded |'s or \'s escaped.
457 (defun output-quoted-symbol-name (pname stream)
458 (declare (string pname))
459 (write-char #\| stream)
460 (dotimes (index (length pname))
461 (let ((char (schar pname index)))
462 (when (or (char= char #\\) (char= char #\|))
463 (write-char #\\ stream))
464 (write-char char stream)))
465 (write-char #\| stream))
467 (defun output-symbol (object stream)
468 (declare (symbol object))
469 (if (or *print-escape* *print-readably*)
470 (let ((package (symbol-package object))
471 (name (symbol-name object))
472 (current (sane-package)))
473 (cond
474 ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
475 ;; requires that keywords be printed with preceding colons
476 ;; always, regardless of the value of *PACKAGE*.
477 ((eq package *keyword-package*)
478 (write-char #\: stream))
479 ;; Otherwise, if the symbol's home package is the current
480 ;; one, then a prefix is never necessary.
481 ((eq package current))
482 ;; Uninterned symbols print with a leading #:.
483 ((null package)
484 (when (or *print-gensym* *print-readably*)
485 (write-string "#:" stream)))
487 (multiple-value-bind (symbol accessible)
488 (find-symbol name current)
489 ;; If we can find the symbol by looking it up, it need not
490 ;; be qualified. This can happen if the symbol has been
491 ;; inherited from a package other than its home package.
493 ;; To preserve print-read consistency, use the local nickname if
494 ;; one exists.
495 (unless (and accessible (eq symbol object))
496 (let ((prefix (or (car (rassoc package (package-%local-nicknames current)))
497 (package-name package))))
498 (output-symbol-name prefix stream))
499 (if (nth-value 1 (find-external-symbol name package))
500 (write-char #\: stream)
501 (write-string "::" stream))))))
502 (output-symbol-name name stream))
503 (output-symbol-name (symbol-name object) stream nil)))
505 ;;; Output the string NAME as if it were a symbol name. In other
506 ;;; words, diddle its case according to *PRINT-CASE* and
507 ;;; READTABLE-CASE.
508 (defun output-symbol-name (name stream &optional (maybe-quote t))
509 (declare (type simple-string name))
510 (let ((*readtable* (if *print-readably* *standard-readtable* *readtable*)))
511 (setup-printer-state)
512 (if (and maybe-quote (or
513 (and (readtable-normalization *readtable*)
514 (not (sb!unicode:normalized-p name :nfkc)))
515 (symbol-quotep name)))
516 (output-quoted-symbol-name name stream)
517 (funcall *internal-symbol-output-fun* name stream))))
519 ;;;; escaping symbols
521 ;;; When we print symbols we have to figure out if they need to be
522 ;;; printed with escape characters. This isn't a whole lot easier than
523 ;;; reading symbols in the first place.
525 ;;; For each character, the value of the corresponding element is a
526 ;;; fixnum with bits set corresponding to attributes that the
527 ;;; character has. At characters have at least one bit set, so we can
528 ;;; search for any character with a positive test.
529 (defvar *character-attributes*
530 (make-array 160 ; FIXME
531 :element-type '(unsigned-byte 16)
532 :initial-element 0))
533 (declaim (type (simple-array (unsigned-byte 16) (#.160)) ; FIXME
534 *character-attributes*))
536 ;;; constants which are a bit-mask for each interesting character attribute
537 (defconstant other-attribute (ash 1 0)) ; Anything else legal.
538 (defconstant number-attribute (ash 1 1)) ; A numeric digit.
539 (defconstant uppercase-attribute (ash 1 2)) ; An uppercase letter.
540 (defconstant lowercase-attribute (ash 1 3)) ; A lowercase letter.
541 (defconstant sign-attribute (ash 1 4)) ; +-
542 (defconstant extension-attribute (ash 1 5)) ; ^_
543 (defconstant dot-attribute (ash 1 6)) ; .
544 (defconstant slash-attribute (ash 1 7)) ; /
545 (defconstant funny-attribute (ash 1 8)) ; Anything illegal.
547 (eval-when (:compile-toplevel :load-toplevel :execute)
549 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
550 ;;; that don't need to be escaped (according to READTABLE-CASE.)
551 (defparameter *attribute-names*
552 `((number . number-attribute) (lowercase . lowercase-attribute)
553 (uppercase . uppercase-attribute) (letter . letter-attribute)
554 (sign . sign-attribute) (extension . extension-attribute)
555 (dot . dot-attribute) (slash . slash-attribute)
556 (other . other-attribute) (funny . funny-attribute)))
558 ) ; EVAL-WHEN
560 ;;; For each character, the value of the corresponding element is the
561 ;;; lowest base in which that character is a digit.
562 (declaim (type (simple-array (unsigned-byte 8) (128)) ; FIXME: range?
563 *digit-bases*))
564 (defvar *digit-bases*
565 (make-array 128 ; FIXME
566 :element-type '(unsigned-byte 8)))
568 (defun !printer-cold-init ()
569 ;; The dispatch table will be changed later, so this doesn't really matter
570 ;; except if a full call to WRITE wants to read the current binding.
571 (setq *print-pprint-dispatch* (sb!pretty::make-pprint-dispatch-table))
572 (setq *digit-bases* (make-array 128 ; FIXME
573 :element-type '(unsigned-byte 8)
574 :initial-element 36)
575 *character-attributes* (make-array 160 ; FIXME
576 :element-type '(unsigned-byte 16)
577 :initial-element 0))
578 (dotimes (i 36)
579 (let ((char (digit-char i 36)))
580 (setf (aref *digit-bases* (char-code char)) i)))
582 (flet ((set-bit (char bit)
583 (let ((code (char-code char)))
584 (setf (aref *character-attributes* code)
585 (logior bit (aref *character-attributes* code))))))
587 (dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
588 #\? #\< #\>))
589 (set-bit char other-attribute))
591 (dotimes (i 10)
592 (set-bit (digit-char i) number-attribute))
594 (do ((code (char-code #\A) (1+ code))
595 (end (char-code #\Z)))
596 ((> code end))
597 (declare (fixnum code end))
598 (set-bit (code-char code) uppercase-attribute)
599 (set-bit (char-downcase (code-char code)) lowercase-attribute))
601 (set-bit #\- sign-attribute)
602 (set-bit #\+ sign-attribute)
603 (set-bit #\^ extension-attribute)
604 (set-bit #\_ extension-attribute)
605 (set-bit #\. dot-attribute)
606 (set-bit #\/ slash-attribute)
608 ;; Mark anything not explicitly allowed as funny.
609 (dotimes (i 160) ; FIXME
610 (when (zerop (aref *character-attributes* i))
611 (setf (aref *character-attributes* i) funny-attribute))))
612 ) ; end !COLD-PRINT-INIT
614 ;;; A FSM-like thingie that determines whether a symbol is a potential
615 ;;; number or has evil characters in it.
616 (defun symbol-quotep (name)
617 (declare (simple-string name))
618 (macrolet ((advance (tag &optional (at-end t))
619 `(progn
620 (when (= index len)
621 ,(if at-end '(go TEST-SIGN) '(return nil)))
622 (setq current (schar name index)
623 code (char-code current)
624 bits (cond ; FIXME
625 ((< code 160) (aref attributes code))
626 ((upper-case-p current) uppercase-attribute)
627 ((lower-case-p current) lowercase-attribute)
628 (t other-attribute)))
629 (incf index)
630 (go ,tag)))
631 (test (&rest attributes)
632 `(not (zerop
633 (the fixnum
634 (logand
635 (logior ,@(mapcar
636 (lambda (x)
637 (or (cdr (assoc x
638 *attribute-names*))
639 (error "Blast!")))
640 attributes))
641 bits)))))
642 (digitp ()
643 `(and (< code 128) ; FIXME
644 (< (the fixnum (aref bases code)) base))))
646 (prog ((len (length name))
647 (attributes *character-attributes*)
648 (bases *digit-bases*)
649 (base *print-base*)
650 (letter-attribute
651 (case (%readtable-case *readtable*)
652 (:upcase uppercase-attribute)
653 (:downcase lowercase-attribute)
654 (t (logior lowercase-attribute uppercase-attribute))))
655 (index 0)
656 (bits 0)
657 (code 0)
658 current)
659 (declare (fixnum len base index bits code))
660 (advance START t)
662 TEST-SIGN ; At end, see whether it is a sign...
663 (return (not (test sign)))
665 OTHER ; not potential number, see whether funny chars...
666 (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
667 funny-attribute)
668 letter-attribute)))
669 (do ((i (1- index) (1+ i)))
670 ((= i len) (return-from symbol-quotep nil))
671 (unless (zerop (logand (let* ((char (schar name i))
672 (code (char-code char)))
673 (cond
674 ((< code 160) (aref attributes code))
675 ((upper-case-p char) uppercase-attribute)
676 ((lower-case-p char) lowercase-attribute)
677 (t other-attribute)))
678 mask))
679 (return-from symbol-quotep t))))
681 START
682 (when (digitp)
683 (if (test letter)
684 (advance LAST-DIGIT-ALPHA)
685 (advance DIGIT)))
686 (when (test letter number other slash) (advance OTHER nil))
687 (when (char= current #\.) (advance DOT-FOUND))
688 (when (test sign extension) (advance START-STUFF nil))
689 (return t)
691 DOT-FOUND ; leading dots...
692 (when (test letter) (advance START-DOT-MARKER nil))
693 (when (digitp) (advance DOT-DIGIT))
694 (when (test number other) (advance OTHER nil))
695 (when (test extension slash sign) (advance START-DOT-STUFF nil))
696 (when (char= current #\.) (advance DOT-FOUND))
697 (return t)
699 START-STUFF ; leading stuff before any dot or digit
700 (when (digitp)
701 (if (test letter)
702 (advance LAST-DIGIT-ALPHA)
703 (advance DIGIT)))
704 (when (test number other) (advance OTHER nil))
705 (when (test letter) (advance START-MARKER nil))
706 (when (char= current #\.) (advance START-DOT-STUFF nil))
707 (when (test sign extension slash) (advance START-STUFF nil))
708 (return t)
710 START-MARKER ; number marker in leading stuff...
711 (when (test letter) (advance OTHER nil))
712 (go START-STUFF)
714 START-DOT-STUFF ; leading stuff containing dot without digit...
715 (when (test letter) (advance START-DOT-STUFF nil))
716 (when (digitp) (advance DOT-DIGIT))
717 (when (test sign extension dot slash) (advance START-DOT-STUFF nil))
718 (when (test number other) (advance OTHER nil))
719 (return t)
721 START-DOT-MARKER ; number marker in leading stuff with dot..
722 ;; leading stuff containing dot without digit followed by letter...
723 (when (test letter) (advance OTHER nil))
724 (go START-DOT-STUFF)
726 DOT-DIGIT ; in a thing with dots...
727 (when (test letter) (advance DOT-MARKER))
728 (when (digitp) (advance DOT-DIGIT))
729 (when (test number other) (advance OTHER nil))
730 (when (test sign extension dot slash) (advance DOT-DIGIT))
731 (return t)
733 DOT-MARKER ; number marker in number with dot...
734 (when (test letter) (advance OTHER nil))
735 (go DOT-DIGIT)
737 LAST-DIGIT-ALPHA ; previous char is a letter digit...
738 (when (or (digitp) (test sign slash))
739 (advance ALPHA-DIGIT))
740 (when (test letter number other dot) (advance OTHER nil))
741 (return t)
743 ALPHA-DIGIT ; seen a digit which is a letter...
744 (when (or (digitp) (test sign slash))
745 (if (test letter)
746 (advance LAST-DIGIT-ALPHA)
747 (advance ALPHA-DIGIT)))
748 (when (test letter) (advance ALPHA-MARKER))
749 (when (test number other dot) (advance OTHER nil))
750 (return t)
752 ALPHA-MARKER ; number marker in number with alpha digit...
753 (when (test letter) (advance OTHER nil))
754 (go ALPHA-DIGIT)
756 DIGIT ; seen only ordinary (non-alphabetic) numeric digits...
757 (when (digitp)
758 (if (test letter)
759 (advance ALPHA-DIGIT)
760 (advance DIGIT)))
761 (when (test number other) (advance OTHER nil))
762 (when (test letter) (advance MARKER))
763 (when (test extension slash sign) (advance DIGIT))
764 (when (char= current #\.) (advance DOT-DIGIT))
765 (return t)
767 MARKER ; number marker in a numeric number...
768 ;; ("What," you may ask, "is a 'number marker'?" It's something
769 ;; that a conforming implementation might use in number syntax.
770 ;; See ANSI 2.3.1.1 "Potential Numbers as Tokens".)
771 (when (test letter) (advance OTHER nil))
772 (go DIGIT))))
774 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN*
775 ;;;;
776 ;;;; case hackery: These functions are stored in
777 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUN* according to the values of
778 ;;;; *PRINT-CASE* and READTABLE-CASE.
780 ;;; called when:
781 ;;; READTABLE-CASE *PRINT-CASE*
782 ;;; :UPCASE :UPCASE
783 ;;; :DOWNCASE :DOWNCASE
784 ;;; :PRESERVE any
785 (defun output-preserve-symbol (pname stream)
786 (declare (simple-string pname))
787 (write-string pname stream))
789 ;;; called when:
790 ;;; READTABLE-CASE *PRINT-CASE*
791 ;;; :UPCASE :DOWNCASE
792 (defun output-lowercase-symbol (pname stream)
793 (declare (simple-string pname))
794 (dotimes (index (length pname))
795 (let ((char (schar pname index)))
796 (write-char (char-downcase char) stream))))
798 ;;; called when:
799 ;;; READTABLE-CASE *PRINT-CASE*
800 ;;; :DOWNCASE :UPCASE
801 (defun output-uppercase-symbol (pname stream)
802 (declare (simple-string pname))
803 (dotimes (index (length pname))
804 (let ((char (schar pname index)))
805 (write-char (char-upcase char) stream))))
807 ;;; called when:
808 ;;; READTABLE-CASE *PRINT-CASE*
809 ;;; :UPCASE :CAPITALIZE
810 ;;; :DOWNCASE :CAPITALIZE
811 (defun output-capitalize-symbol (pname stream)
812 (declare (simple-string pname))
813 (let ((prev-not-alphanum t)
814 (up (eq (%readtable-case *readtable*) :upcase)))
815 (dotimes (i (length pname))
816 (let ((char (char pname i)))
817 (write-char (if up
818 (if (or prev-not-alphanum (lower-case-p char))
819 char
820 (char-downcase char))
821 (if prev-not-alphanum
822 (char-upcase char)
823 char))
824 stream)
825 (setq prev-not-alphanum (not (alphanumericp char)))))))
827 ;;; called when:
828 ;;; READTABLE-CASE *PRINT-CASE*
829 ;;; :INVERT any
830 (defun output-invert-symbol (pname stream)
831 (declare (simple-string pname))
832 (let ((all-upper t)
833 (all-lower t))
834 (dotimes (i (length pname))
835 (let ((ch (schar pname i)))
836 (when (both-case-p ch)
837 (if (upper-case-p ch)
838 (setq all-lower nil)
839 (setq all-upper nil)))))
840 (cond (all-upper (output-lowercase-symbol pname stream))
841 (all-lower (output-uppercase-symbol pname stream))
843 (write-string pname stream)))))
845 ;;; Set the internal global symbol *INTERNAL-SYMBOL-OUTPUT-FUN*
846 ;;; to the right function depending on the values of *PRINT-CASE*
847 ;;; and (%READTABLE-CASE *READTABLE*).
848 (defun setup-printer-state ()
849 (let ((readtable-case (%readtable-case *readtable*))
850 (print-case *print-case*))
851 (unless (and (eq print-case *previous-case*)
852 (eq readtable-case *previous-readtable-case*))
853 (setq *previous-case* print-case)
854 (setq *previous-readtable-case* readtable-case)
855 (setq *internal-symbol-output-fun*
856 ;; a morally equivalent reformulation of FOP-KNOWN-FUN
857 (macrolet ((load-time-fn (name) `(load-time-value #',name t)))
858 (case readtable-case
859 (:upcase
860 (case print-case
861 (:upcase (load-time-fn output-preserve-symbol))
862 (:downcase (load-time-fn output-lowercase-symbol))
863 (:capitalize (load-time-fn output-capitalize-symbol))))
864 (:downcase
865 (case print-case
866 (:upcase (load-time-fn output-uppercase-symbol))
867 (:downcase (load-time-fn output-preserve-symbol))
868 (:capitalize (load-time-fn output-capitalize-symbol))))
869 (:preserve (load-time-fn output-preserve-symbol))
870 (:invert (load-time-fn output-invert-symbol))))))))
873 (defun test1 ()
874 (let ((*readtable* (copy-readtable nil)))
875 (format t "READTABLE-CASE Input Symbol-name~@
876 ----------------------------------~%")
877 (dolist (readtable-case '(:upcase :downcase :preserve :invert))
878 (setf (readtable-case *readtable*) readtable-case)
879 (dolist (input '("ZEBRA" "Zebra" "zebra"))
880 (format t "~&:~A~16T~A~24T~A"
881 (string-upcase readtable-case)
882 input
883 (symbol-name (read-from-string input)))))))
885 (defun test2 ()
886 (let ((*readtable* (copy-readtable nil)))
887 (format t "READTABLE-CASE *PRINT-CASE* Symbol-name Output Princ~@
888 --------------------------------------------------------~%")
889 (dolist (readtable-case '(:upcase :downcase :preserve :invert))
890 (setf (readtable-case *readtable*) readtable-case)
891 (dolist (*print-case* '(:upcase :downcase :capitalize))
892 (dolist (symbol '(|ZEBRA| |Zebra| |zebra|))
893 (format t "~&:~A~15T:~A~29T~A~42T~A~50T~A"
894 (string-upcase readtable-case)
895 (string-upcase *print-case*)
896 (symbol-name symbol)
897 (prin1-to-string symbol)
898 (princ-to-string symbol)))))))
901 ;;;; recursive objects
903 (defun output-list (list stream)
904 (descend-into (stream)
905 (write-char #\( stream)
906 (let ((length 0)
907 (list list))
908 (loop
909 (punt-print-if-too-long length stream)
910 (output-object (pop list) stream)
911 (unless list
912 (return))
913 (when (or (atom list)
914 (check-for-circularity list))
915 (write-string " . " stream)
916 (output-object list stream)
917 (return))
918 (write-char #\space stream)
919 (incf length)))
920 (write-char #\) stream)))
922 (defun output-unreadable-vector-readably (vector stream)
923 (declare (vector vector))
924 (write-string "#." stream)
925 (write `(coerce ,(coerce vector '(vector t))
926 '(simple-array ,(array-element-type vector) (*)))
927 :stream stream))
929 (defun output-vector (vector stream &aux (readably *print-readably*))
930 (declare (vector vector))
931 (cond ((stringp vector)
932 (let ((coerce-p
933 (and readably (not (typep vector '(vector character))))))
934 (cond ((and coerce-p (not *read-eval*))
935 (print-not-readable-error vector stream))
936 ((or *print-escape* readably)
937 (when coerce-p
938 ;; OUTPUT-UNREADABLE-VECTOR-READABLY would output each char
939 ;; in #\c syntax. In addition to wasting time coercing to a
940 ;; general vector, it's not nice looking.
941 (write-string "#.(" stream)
942 (write 'coerce :stream stream) ; package-qualify / casify as needed
943 (write-char #\Space stream))
944 (write-char #\" stream)
945 (quote-string vector stream)
946 (write-char #\" stream)
947 (when coerce-p
948 (write-char #\Space stream)
949 (write `'(vector ,(array-element-type vector)) :stream stream)
950 (write-char #\) stream)))
952 (write-string vector stream)))))
953 ((not (or *print-array* readably))
954 (output-terse-array vector stream))
955 ((bit-vector-p vector)
956 (write-string "#*" stream)
957 (dovector (bit vector)
958 ;; (Don't use OUTPUT-OBJECT here, since this code
959 ;; has to work for all possible *PRINT-BASE* values.)
960 (write-char (if (zerop bit) #\0 #\1) stream)))
961 ((or (not readably) (array-readably-printable-p vector))
962 (descend-into (stream)
963 (write-string "#(" stream)
964 (dotimes (i (length vector))
965 (unless (zerop i)
966 (write-char #\space stream))
967 (punt-print-if-too-long i stream)
968 (output-object (aref vector i) stream))
969 (write-string ")" stream)))
970 (*read-eval*
971 (output-unreadable-vector-readably vector stream))
973 (print-not-readable-error vector stream))))
975 ;;; This function outputs a string quoting characters sufficiently
976 ;;; so that someone can read it in again. Basically, put a slash in
977 ;;; front of an character satisfying NEEDS-SLASH-P.
978 (defun quote-string (string stream)
979 (macrolet ((needs-slash-p (char)
980 ;; KLUDGE: We probably should look at the readtable, but just do
981 ;; this for now. [noted by anonymous long ago] -- WHN 19991130
982 `(or (char= ,char #\\)
983 (char= ,char #\"))))
984 (with-array-data ((data string) (start) (end)
985 :check-fill-pointer t)
986 (do ((index start (1+ index)))
987 ((>= index end))
988 (let ((char (schar data index)))
989 (when (needs-slash-p char) (write-char #\\ stream))
990 (write-char char stream))))))
992 (defun array-readably-printable-p (array)
993 (and (eq (array-element-type array) t)
994 (let ((zero (position 0 (array-dimensions array)))
995 (number (position 0 (array-dimensions array)
996 :test (complement #'eql)
997 :from-end t)))
998 (or (null zero) (null number) (> zero number)))))
1000 ;;; Output the printed representation of any array in either the #< or #A
1001 ;;; form.
1002 (defun output-array (array stream)
1003 (if (or *print-array* *print-readably*)
1004 (output-array-guts array stream)
1005 (output-terse-array array stream)))
1007 ;;; Output the abbreviated #< form of an array.
1008 (defun output-terse-array (array stream)
1009 (let ((*print-level* nil)
1010 (*print-length* nil))
1011 (print-unreadable-object (array stream :type t :identity t))))
1013 ;;; Convert an array into a list that can be used with MAKE-ARRAY's
1014 ;;; :INITIAL-CONTENTS keyword argument.
1015 (defun listify-array (array)
1016 (with-array-data ((data array) (start) (end))
1017 (declare (ignore end))
1018 (labels ((listify (dimensions index)
1019 (if (null dimensions)
1020 (aref data index)
1021 (let* ((dimension (car dimensions))
1022 (dimensions (cdr dimensions))
1023 (count (reduce #'* dimensions)))
1024 (loop for i below dimension
1025 collect (listify dimensions index)
1026 do (incf index count))))))
1027 (listify (array-dimensions array) start))))
1029 (defun output-unreadable-array-readably (array stream)
1030 (write-string "#." stream)
1031 (write `(make-array ',(array-dimensions array)
1032 :element-type ',(array-element-type array)
1033 :initial-contents ',(listify-array array))
1034 :stream stream))
1036 ;;; Output the readable #A form of an array.
1037 (defun output-array-guts (array stream)
1038 (cond ((or (not *print-readably*)
1039 (array-readably-printable-p array))
1040 (write-char #\# stream)
1041 (let ((*print-base* 10)
1042 (*print-radix* nil))
1043 (output-integer (array-rank array) stream))
1044 (write-char #\A stream)
1045 (with-array-data ((data array) (start) (end))
1046 (declare (ignore end))
1047 (sub-output-array-guts data (array-dimensions array) stream start)))
1048 (*read-eval*
1049 (output-unreadable-array-readably array stream))
1051 (print-not-readable-error array stream))))
1053 (defun sub-output-array-guts (array dimensions stream index)
1054 (declare (type (simple-array * (*)) array) (fixnum index))
1055 (cond ((null dimensions)
1056 (output-object (aref array index) stream))
1058 (descend-into (stream)
1059 (write-char #\( stream)
1060 (let* ((dimension (car dimensions))
1061 (dimensions (cdr dimensions))
1062 (count (reduce #'* dimensions)))
1063 (dotimes (i dimension)
1064 (unless (zerop i)
1065 (write-char #\space stream))
1066 (punt-print-if-too-long i stream)
1067 (sub-output-array-guts array dimensions stream index)
1068 (incf index count)))
1069 (write-char #\) stream)))))
1072 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
1074 (defun %output-radix (base stream)
1075 (write-char #\# stream)
1076 (write-char (case base
1077 (2 #\b)
1078 (8 #\o)
1079 (16 #\x)
1080 (t (%output-reasonable-integer-in-base base 10 stream)
1081 #\r))
1082 stream))
1084 (defun %output-reasonable-integer-in-base (n base stream)
1085 (multiple-value-bind (q r)
1086 (truncate n base)
1087 ;; Recurse until you have all the digits pushed on
1088 ;; the stack.
1089 (unless (zerop q)
1090 (%output-reasonable-integer-in-base q base stream))
1091 ;; Then as each recursive call unwinds, turn the
1092 ;; digit (in remainder) into a character and output
1093 ;; the character.
1094 (write-char
1095 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r)
1096 stream)))
1098 ;;; *POWER-CACHE* is an alist mapping bases to power-vectors. It is
1099 ;;; filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
1100 ;;; always prior a GC to drop overly large bignums from the cache.
1102 ;;; It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
1103 ;;; POWERS-FOR-BASE, see that you don't break the assumptions!
1104 (defglobal *power-cache* (make-array 37 :initial-element nil))
1105 (declaim (type (simple-vector 37) *power-cache*))
1107 (defconstant +power-cache-integer-length-limit+ 2048)
1109 (defun scrub-power-cache (&aux (cache *power-cache*))
1110 (dotimes (i (length cache))
1111 (let ((powers (aref cache i)))
1112 (when powers
1113 (let ((too-big (position-if
1114 (lambda (x)
1115 (>= (integer-length x)
1116 +power-cache-integer-length-limit+))
1117 (the simple-vector powers))))
1118 (when too-big
1119 (setf (aref cache i) (subseq powers 0 too-big))))))))
1121 ;;; Compute (and cache) a power vector for a BASE and LIMIT:
1122 ;;; the vector holds integers for which
1123 ;;; (aref powers k) == (expt base (expt 2 k))
1124 ;;; holds.
1125 (defun powers-for-base (base limit)
1126 (flet ((compute-powers (from)
1127 (let (powers)
1128 (do ((p from (* p p)))
1129 ((> p limit)
1130 ;; We don't actually need this, but we also
1131 ;; prefer not to cons it up a second time...
1132 (push p powers))
1133 (push p powers))
1134 (nreverse powers))))
1135 (let* ((cache *power-cache*)
1136 (powers (aref cache base)))
1137 (setf (aref cache base)
1138 (concatenate 'vector powers
1139 (compute-powers
1140 (if powers
1141 (let* ((len (length powers))
1142 (max (svref powers (1- len))))
1143 (if (> max limit)
1144 (return-from powers-for-base powers)
1145 (* max max)))
1146 base)))))))
1148 ;; Algorithm by Harald Hanche-Olsen, sbcl-devel 2005-02-05
1149 (defun %output-huge-integer-in-base (n base stream)
1150 (declare (type bignum n) (type fixnum base))
1151 ;; POWER is a vector for which the following holds:
1152 ;; (aref power k) == (expt base (expt 2 k))
1153 (let* ((power (powers-for-base base n))
1154 (k-start (or (position-if (lambda (x) (> x n)) power)
1155 (bug "power-vector too short"))))
1156 (labels ((bisect (n k exactp)
1157 (declare (fixnum k))
1158 ;; N is the number to bisect
1159 ;; K on initial entry BASE^(2^K) > N
1160 ;; EXACTP is true if 2^K is the exact number of digits
1161 (cond ((zerop n)
1162 (when exactp
1163 (loop repeat (ash 1 k) do (write-char #\0 stream))))
1164 ((zerop k)
1165 (write-char
1166 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n)
1167 stream))
1169 (setf k (1- k))
1170 (multiple-value-bind (q r) (truncate n (aref power k))
1171 ;; EXACTP is NIL only at the head of the
1172 ;; initial number, as we don't know the number
1173 ;; of digits there, but we do know that it
1174 ;; doesn't get any leading zeros.
1175 (bisect q k exactp)
1176 (bisect r k (or exactp (plusp q))))))))
1177 (bisect n k-start nil))))
1179 (defun %output-integer-in-base (integer base stream)
1180 (when (minusp integer)
1181 (write-char #\- stream)
1182 (setf integer (- integer)))
1183 ;; The ideal cutoff point between these two algorithms is almost
1184 ;; certainly quite platform dependent: this gives 87 for 32 bit
1185 ;; SBCL, which is about right at least for x86/Darwin.
1186 (if (or (fixnump integer)
1187 (< (integer-length integer) (* 3 sb!vm:n-positive-fixnum-bits)))
1188 (%output-reasonable-integer-in-base integer base stream)
1189 (%output-huge-integer-in-base integer base stream)))
1191 (defun output-integer (integer stream)
1192 (let ((base *print-base*))
1193 (when (and (/= base 10) *print-radix*)
1194 (%output-radix base stream))
1195 (%output-integer-in-base integer base stream)
1196 (when (and *print-radix* (= base 10))
1197 (write-char #\. stream))))
1199 (defun output-ratio (ratio stream)
1200 (let ((base *print-base*))
1201 (when *print-radix*
1202 (%output-radix base stream))
1203 (%output-integer-in-base (numerator ratio) base stream)
1204 (write-char #\/ stream)
1205 (%output-integer-in-base (denominator ratio) base stream)))
1207 (defun output-complex (complex stream)
1208 (write-string "#C(" stream)
1209 ;; FIXME: Could this just be OUTPUT-NUMBER?
1210 (output-object (realpart complex) stream)
1211 (write-char #\space stream)
1212 (output-object (imagpart complex) stream)
1213 (write-char #\) stream))
1215 ;;;; float printing
1217 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1218 ;;; most of the work for all printing of floating point numbers in
1219 ;;; FORMAT. It converts a floating point number to a string in a free
1220 ;;; or fixed format with no exponent. The interpretation of the
1221 ;;; arguments is as follows:
1223 ;;; X - The floating point number to convert, which must not be
1224 ;;; negative.
1225 ;;; WIDTH - The preferred field width, used to determine the number
1226 ;;; of fraction digits to produce if the FDIGITS parameter
1227 ;;; is unspecified or NIL. If the non-fraction digits and the
1228 ;;; decimal point alone exceed this width, no fraction digits
1229 ;;; will be produced unless a non-NIL value of FDIGITS has been
1230 ;;; specified. Field overflow is not considerd an error at this
1231 ;;; level.
1232 ;;; FDIGITS - The number of fractional digits to produce. Insignificant
1233 ;;; trailing zeroes may be introduced as needed. May be
1234 ;;; unspecified or NIL, in which case as many digits as possible
1235 ;;; are generated, subject to the constraint that there are no
1236 ;;; trailing zeroes.
1237 ;;; SCALE - If this parameter is specified or non-NIL, then the number
1238 ;;; printed is (* x (expt 10 scale)). This scaling is exact,
1239 ;;; and cannot lose precision.
1240 ;;; FMIN - This parameter, if specified or non-NIL, is the minimum
1241 ;;; number of fraction digits which will be produced, regardless
1242 ;;; of the value of WIDTH or FDIGITS. This feature is used by
1243 ;;; the ~E format directive to prevent complete loss of
1244 ;;; significance in the printed value due to a bogus choice of
1245 ;;; scale factor.
1247 ;;; Returns:
1248 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1249 ;;; where the results have the following interpretation:
1251 ;;; DIGIT-STRING - The decimal representation of X, with decimal point.
1252 ;;; DIGIT-LENGTH - The length of the string DIGIT-STRING.
1253 ;;; LEADING-POINT - True if the first character of DIGIT-STRING is the
1254 ;;; decimal point.
1255 ;;; TRAILING-POINT - True if the last character of DIGIT-STRING is the
1256 ;;; decimal point.
1257 ;;; POINT-POS - The position of the digit preceding the decimal
1258 ;;; point. Zero indicates point before first digit.
1260 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1261 ;;; accuracy. Specifically, the decimal number printed is the closest
1262 ;;; possible approximation to the true value of the binary number to
1263 ;;; be printed from among all decimal representations with the same
1264 ;;; number of digits. In free-format output, i.e. with the number of
1265 ;;; digits unconstrained, it is guaranteed that all the information is
1266 ;;; preserved, so that a properly- rounding reader can reconstruct the
1267 ;;; original binary number, bit-for-bit, from its printed decimal
1268 ;;; representation. Furthermore, only as many digits as necessary to
1269 ;;; satisfy this condition will be printed.
1271 ;;; FLOAT-DIGITS actually generates the digits for positive numbers;
1272 ;;; see below for comments.
1274 (defun flonum-to-string (x &optional width fdigits scale fmin)
1275 (declare (type float x))
1276 ;; FIXME: I think only FORMAT-DOLLARS calls FLONUM-TO-STRING with
1277 ;; possibly-negative X.
1278 (setf x (abs x))
1279 (multiple-value-bind (e string)
1280 (if fdigits
1281 (flonum-to-digits x (min (- (+ fdigits (or scale 0)))
1282 (- (or fmin 0))))
1283 (if (and width (> width 1))
1284 (let ((w (multiple-value-list
1285 (flonum-to-digits x
1286 (max 1
1287 (+ (1- width)
1288 (if (and scale (minusp scale))
1289 scale 0)))
1290 t)))
1291 (f (multiple-value-list
1292 (flonum-to-digits x (- (+ (or fmin 0)
1293 (if scale scale 0)))))))
1294 (cond
1295 ((>= (length (cadr w)) (length (cadr f)))
1296 (values-list w))
1297 (t (values-list f))))
1298 (flonum-to-digits x)))
1299 (let ((e (if (zerop x)
1301 (+ e (or scale 0))))
1302 (stream (make-string-output-stream)))
1303 (if (plusp e)
1304 (progn
1305 (write-string string stream :end (min (length string) e))
1306 (dotimes (i (- e (length string)))
1307 (write-char #\0 stream))
1308 (write-char #\. stream)
1309 (write-string string stream :start (min (length string) e))
1310 (when fdigits
1311 (dotimes (i (- fdigits
1312 (- (length string)
1313 (min (length string) e))))
1314 (write-char #\0 stream))))
1315 (progn
1316 (write-string "." stream)
1317 (dotimes (i (- e))
1318 (write-char #\0 stream))
1319 (write-string string stream :end (when fdigits
1320 (min (length string)
1321 (max (or fmin 0)
1322 (+ fdigits e)))))
1323 (when fdigits
1324 (dotimes (i (+ fdigits e (- (length string))))
1325 (write-char #\0 stream)))))
1326 (let ((string (get-output-stream-string stream)))
1327 (values string (length string)
1328 (char= (char string 0) #\.)
1329 (char= (char string (1- (length string))) #\.)
1330 (position #\. string))))))
1332 ;;; implementation of figure 1 from Burger and Dybvig, 1996. It is
1333 ;;; extended in order to handle rounding.
1335 ;;; As the implementation of the Dragon from Classic CMUCL (and
1336 ;;; previously in SBCL above FLONUM-TO-STRING) says: "DO NOT EVEN
1337 ;;; THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE
1338 ;;; PAPER!", and in this case we have to add that even reading the
1339 ;;; paper might not bring immediate illumination as CSR has attempted
1340 ;;; to turn idiomatic Scheme into idiomatic Lisp.
1342 ;;; FIXME: figure 1 from Burger and Dybvig is the unoptimized
1343 ;;; algorithm, noticeably slow at finding the exponent. Figure 2 has
1344 ;;; an improved algorithm, but CSR ran out of energy.
1346 ;;; possible extension for the enthusiastic: printing floats in bases
1347 ;;; other than base 10.
1348 (defconstant single-float-min-e
1349 (- 2 sb!vm:single-float-bias sb!vm:single-float-digits))
1350 (defconstant double-float-min-e
1351 (- 2 sb!vm:double-float-bias sb!vm:double-float-digits))
1352 #!+long-float
1353 (defconstant long-float-min-e
1354 (nth-value 1 (decode-float least-positive-long-float)))
1356 (defun flonum-to-digits (v &optional position relativep)
1357 (let ((print-base 10) ; B
1358 (float-radix 2) ; b
1359 (float-digits (float-digits v)) ; p
1360 (digit-characters "0123456789")
1361 (min-e
1362 (etypecase v
1363 (single-float single-float-min-e)
1364 (double-float double-float-min-e)
1365 #!+long-float
1366 (long-float long-float-min-e))))
1367 (multiple-value-bind (f e)
1368 (integer-decode-float v)
1369 (let ( ;; FIXME: these even tests assume normal IEEE rounding
1370 ;; mode. I wonder if we should cater for non-normal?
1371 (high-ok (evenp f))
1372 (low-ok (evenp f)))
1373 (with-push-char (:element-type base-char)
1374 (labels ((scale (r s m+ m-)
1375 (do ((r+m+ (+ r m+))
1376 (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 (and (> r m-) ; Extension to handle zero
1385 (let ((x (* (+ r m+) print-base)))
1386 (or (< x s)
1387 (and (not high-ok)
1388 (= x s))))))
1389 (values k (generate r s m+ m-)))))))
1390 (generate (r s m+ m-)
1391 (let (d tc1 tc2)
1392 (tagbody
1393 loop
1394 (setf (values d r) (truncate (* r print-base) s))
1395 (setf m+ (* m+ print-base))
1396 (setf m- (* m- print-base))
1397 (setf tc1 (or (< r m-) (and low-ok (= r m-))))
1398 (setf tc2 (let ((r+m+ (+ r m+)))
1399 (or (> r+m+ s)
1400 (and high-ok (= r+m+ s)))))
1401 (when (or tc1 tc2)
1402 (go end))
1403 (push-char (char digit-characters d))
1404 (go loop)
1406 (let ((d (cond
1407 ((and (not tc1) tc2) (1+ d))
1408 ((and tc1 (not tc2)) d)
1409 ((< (* r 2) s)
1412 (1+ d)))))
1413 (push-char (char digit-characters d))
1414 (return-from generate (get-pushed-string))))))
1415 (initialize ()
1416 (let (r s m+ m-)
1417 (cond ((>= e 0)
1418 (let ((be (expt float-radix e)))
1419 (if (/= f (expt float-radix (1- float-digits)))
1420 (setf r (* f be 2)
1422 m+ be
1423 m- be)
1424 (setf m- be
1425 m+ (* be float-radix)
1426 r (* f m+ 2)
1427 s (* float-radix 2)))))
1428 ((or (= e min-e)
1429 (/= f (expt float-radix (1- float-digits))))
1430 (setf r (* f 2)
1431 s (expt float-radix (- 1 e))
1432 m+ 1
1433 m- 1))
1435 (setf r (* f float-radix 2)
1436 s (expt float-radix (- 2 e))
1437 m+ float-radix
1438 m- 1)))
1439 (when position
1440 (when relativep
1441 (aver (> position 0))
1442 (do ((k 0 (1+ k))
1443 ;; running out of letters here
1444 (l 1 (* l print-base)))
1445 ((>= (* s l) (+ r m+))
1446 ;; k is now \hat{k}
1447 (if (< (+ r (* s (/ (expt print-base (- k position)) 2)))
1448 (* s l))
1449 (setf position (- k position))
1450 (setf position (- k position 1))))))
1451 (let* ((x (/ (* s (expt print-base position)) 2))
1452 (low (max m- x))
1453 (high (max m+ x)))
1454 (when (<= m- low)
1455 (setf m- low)
1456 (setf low-ok t))
1457 (when (<= m+ high)
1458 (setf m+ high)
1459 (setf high-ok t))))
1460 (values r s m+ m-))))
1461 (multiple-value-bind (r s m+ m-) (initialize)
1462 (scale r s m+ m-))))))))
1464 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns
1465 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1466 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1467 ;;; original number. There may be some loss of precision due the
1468 ;;; floating point representation. The scaling is always done with
1469 ;;; long float arithmetic, which helps printing of lesser precisions
1470 ;;; as well as avoiding generic arithmetic.
1472 ;;; When computing our initial scale factor using EXPT, we pull out
1473 ;;; part of the computation to avoid over/under flow. When
1474 ;;; denormalized, we must pull out a large factor, since there is more
1475 ;;; negative exponent range than positive range.
1477 (eval-when (:compile-toplevel :execute)
1478 (setf *read-default-float-format*
1479 #!+long-float 'long-float #!-long-float 'double-float))
1480 (defun scale-exponent (original-x)
1481 (let* ((x (coerce original-x 'long-float)))
1482 (multiple-value-bind (sig exponent) (decode-float x)
1483 (declare (ignore sig))
1484 (if (= x 0.0e0)
1485 (values (float 0.0e0 original-x) 1)
1486 (let* ((ex (locally (declare (optimize (safety 0)))
1487 (the fixnum
1488 (round (* exponent
1489 ;; this is the closest double float
1490 ;; to (log 2 10), but expressed so
1491 ;; that we're not vulnerable to the
1492 ;; host lisp's interpretation of
1493 ;; arithmetic. (FIXME: it turns
1494 ;; out that sbcl itself is off by 1
1495 ;; ulp in this value, which is a
1496 ;; little unfortunate.)
1497 (load-time-value
1498 #!-long-float
1499 (make-double-float 1070810131 1352628735)
1500 #!+long-float
1501 (error "(log 2 10) not computed")))))))
1502 (x (if (minusp ex)
1503 (if (float-denormalized-p x)
1504 #!-long-float
1505 (* x 1.0e16 (expt 10.0e0 (- (- ex) 16)))
1506 #!+long-float
1507 (* x 1.0e18 (expt 10.0e0 (- (- ex) 18)))
1508 (* x 10.0e0 (expt 10.0e0 (- (- ex) 1))))
1509 (/ x 10.0e0 (expt 10.0e0 (1- ex))))))
1510 (do ((d 10.0e0 (* d 10.0e0))
1511 (y x (/ x d))
1512 (ex ex (1+ ex)))
1513 ((< y 1.0e0)
1514 (do ((m 10.0e0 (* m 10.0e0))
1515 (z y (* y m))
1516 (ex ex (1- ex)))
1517 ((>= z 0.1e0)
1518 (values (float z original-x) ex))
1519 (declare (long-float m) (integer ex))))
1520 (declare (long-float d))))))))
1521 (eval-when (:compile-toplevel :execute)
1522 (setf *read-default-float-format* 'single-float))
1524 ;;;; entry point for the float printer
1526 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1527 ;;; argument is printed free-format, in either exponential or
1528 ;;; non-exponential notation, depending on its magnitude.
1530 ;;; NOTE: When a number is to be printed in exponential format, it is
1531 ;;; scaled in floating point. Since precision may be lost in this
1532 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1533 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1534 ;;; extensive computations with integers of similar magnitude to that
1535 ;;; of the number being printed. For large exponents, the bignums
1536 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1537 ;;; fast and the exponent range is not too large, then it might become
1538 ;;; attractive to handle exponential notation with the same accuracy
1539 ;;; as non-exponential notation, using the method described in the
1540 ;;; Steele and White paper.
1542 ;;; NOTE II: this has been bypassed slightly by implementing Burger
1543 ;;; and Dybvig, 1996. When someone has time (KLUDGE) they can
1544 ;;; probably (a) implement the optimizations suggested by Burger and
1545 ;;; Dyvbig, and (b) remove all vestiges of Dragon4, including from
1546 ;;; fixed-format printing.
1548 ;;; Print the appropriate exponent marker for X and the specified exponent.
1549 (defun print-float-exponent (x exp stream)
1550 (declare (type float x) (type integer exp) (type stream stream))
1551 (cond ((case *read-default-float-format*
1552 ((short-float single-float)
1553 (typep x 'single-float))
1554 ((double-float #!-long-float long-float)
1555 (typep x 'double-float))
1556 #!+long-float
1557 (long-float
1558 (typep x 'long-float)))
1559 (unless (eql exp 0)
1560 (write-char #\e stream)
1561 (%output-integer-in-base exp 10 stream)))
1563 (write-char
1564 (etypecase x
1565 (single-float #\f)
1566 (double-float #\d)
1567 (short-float #\s)
1568 (long-float #\L))
1569 stream)
1570 (%output-integer-in-base exp 10 stream))))
1572 (defun output-float-infinity (x stream)
1573 (declare (float x) (stream stream))
1574 (cond (*read-eval*
1575 (write-string "#." stream))
1576 (*print-readably*
1577 (return-from output-float-infinity
1578 (print-not-readable-error x stream)))
1580 (write-string "#<" stream)))
1581 (write-string "SB-EXT:" stream)
1582 (write-string (symbol-name (float-format-name x)) stream)
1583 (write-string (if (plusp x) "-POSITIVE-" "-NEGATIVE-")
1584 stream)
1585 (write-string "INFINITY" stream)
1586 (unless *read-eval*
1587 (write-string ">" stream)))
1589 (defun output-float-nan (x stream)
1590 (print-unreadable-object (x stream)
1591 (princ (float-format-name x) stream)
1592 (write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
1593 (write-string " NaN" stream)))
1595 ;;; the function called by OUTPUT-OBJECT to handle floats
1596 (defun output-float (x stream)
1597 (cond
1598 ((float-infinity-p x)
1599 (output-float-infinity x stream))
1600 ((float-nan-p x)
1601 (output-float-nan x stream))
1603 (let ((x (cond ((minusp (float-sign x))
1604 (write-char #\- stream)
1605 (- x))
1607 x))))
1608 (cond
1609 ((zerop x)
1610 (write-string "0.0" stream)
1611 (print-float-exponent x 0 stream))
1613 (output-float-aux x stream -3 8)))))))
1615 (defun output-float-aux (x stream e-min e-max)
1616 (multiple-value-bind (e string)
1617 (flonum-to-digits x)
1618 (cond
1619 ((< e-min e e-max)
1620 (if (plusp e)
1621 (progn
1622 (write-string string stream :end (min (length string) e))
1623 (dotimes (i (- e (length string)))
1624 (write-char #\0 stream))
1625 (write-char #\. stream)
1626 (write-string string stream :start (min (length string) e))
1627 (when (<= (length string) e)
1628 (write-char #\0 stream))
1629 (print-float-exponent x 0 stream))
1630 (progn
1631 (write-string "0." stream)
1632 (dotimes (i (- e))
1633 (write-char #\0 stream))
1634 (write-string string stream)
1635 (print-float-exponent x 0 stream))))
1636 (t (write-string string stream :end 1)
1637 (write-char #\. stream)
1638 (write-string string stream :start 1)
1639 (print-float-exponent x (1- e) stream)))))
1641 ;;;; other leaf objects
1643 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1644 ;;; the character name or the character in the #\char format.
1645 (defun output-character (char stream)
1646 (if (or *print-escape* *print-readably*)
1647 (let ((graphicp (and (graphic-char-p char)
1648 (standard-char-p char)))
1649 (name (char-name char)))
1650 (write-string "#\\" stream)
1651 (if (and name (or (not graphicp) *print-readably*))
1652 (quote-string name stream)
1653 (write-char char stream)))
1654 (write-char char stream)))
1656 (defun output-sap (sap stream)
1657 (declare (type system-area-pointer sap))
1658 (cond (*read-eval*
1659 (format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
1661 (print-unreadable-object (sap stream)
1662 (format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
1664 (defun output-weak-pointer (weak-pointer stream)
1665 (declare (type weak-pointer weak-pointer))
1666 (print-unreadable-object (weak-pointer stream)
1667 (multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
1668 (cond (validp
1669 (write-string "weak pointer: " stream)
1670 (write value :stream stream))
1672 (write-string "broken weak pointer" stream))))))
1674 (defun output-code-component (component stream)
1675 (print-unreadable-object (component stream :identity t)
1676 (let ((dinfo (%code-debug-info component)))
1677 (cond ((eq dinfo :bogus-lra)
1678 (write-string "bogus code object" stream))
1680 (write-string "code object" stream)
1681 (do ((n 0 (1+ n))
1682 (f (%code-entry-points component) (%simple-fun-next f)))
1683 ((null f) (format stream " [~D]" n)))
1684 (let ((fun-name (awhen (%code-entry-points component)
1685 (%simple-fun-name it))))
1686 (when fun-name
1687 (write-char #\Space stream)
1688 (write fun-name :stream stream))
1689 (cond ((not (typep dinfo 'sb!c::debug-info)))
1690 ((neq (sb!c::debug-info-name dinfo) fun-name)
1691 (write-string ", " stream)
1692 (output-object (sb!c::debug-info-name dinfo) stream)))))))))
1694 (defun output-lra (lra stream)
1695 (print-unreadable-object (lra stream :identity t)
1696 (write-string "return PC object" stream)))
1698 (defun output-fdefn (fdefn stream)
1699 (print-unreadable-object (fdefn stream :type t)
1700 (let ((name (fdefn-name fdefn)))
1701 ;; It's somewhat unhelpful to print as <FDEFINITION for (SETF #)>
1702 ;; Generalized function names are indivisible.
1703 (if (proper-list-p name)
1704 (format stream "(~{~S~^ ~})" name)
1705 (output-object name stream)))))
1707 ;;; Making this a DEFMETHOD defers its compilation until after the inline
1708 ;;; functions %SIMD-PACK-{SINGLES,DOUBLES,UB64S} get defined.
1709 #!+sb-simd-pack
1710 (defmethod print-object ((pack simd-pack) stream)
1711 (cond ((and *print-readably* *read-eval*)
1712 (multiple-value-bind (format maker extractor)
1713 (etypecase pack
1714 ((simd-pack double-float)
1715 (values "#.(~S ~S ~S)"
1716 '%make-simd-pack-double #'%simd-pack-doubles))
1717 ((simd-pack single-float)
1718 (values "#.(~S ~S ~S ~S ~S)"
1719 '%make-simd-pack-single #'%simd-pack-singles))
1721 (values "#.(~S #X~16,'0X #X~16,'0X)"
1722 '%make-simd-pack-ub64 #'%simd-pack-ub64s)))
1723 (multiple-value-call
1724 #'format stream format maker (funcall extractor pack))))
1726 (print-unreadable-object (pack stream)
1727 (flet ((all-ones-p (value start end &aux (mask (- (ash 1 end) (ash 1 start))))
1728 (= (logand value mask) mask))
1729 (split-num (value start)
1730 (loop
1731 for i from 0 to 3
1732 and v = (ash value (- start)) then (ash v -8)
1733 collect (logand v #xFF))))
1734 (multiple-value-bind (low high)
1735 (%simd-pack-ub64s pack)
1736 (etypecase pack
1737 ((simd-pack double-float)
1738 (multiple-value-bind (v0 v1) (%simd-pack-doubles pack)
1739 (format stream "~S~@{ ~:[~,13E~;~*TRUE~]~}"
1740 'simd-pack
1741 (all-ones-p low 0 64) v0
1742 (all-ones-p high 0 64) v1)))
1743 ((simd-pack single-float)
1744 (multiple-value-bind (v0 v1 v2 v3) (%simd-pack-singles pack)
1745 (format stream "~S~@{ ~:[~,7E~;~*TRUE~]~}"
1746 'simd-pack
1747 (all-ones-p low 0 32) v0
1748 (all-ones-p low 32 64) v1
1749 (all-ones-p high 0 32) v2
1750 (all-ones-p high 32 64) v3)))
1752 (format stream "~S~@{ ~{ ~2,'0X~}~}"
1753 'simd-pack
1754 (split-num low 0) (split-num low 32)
1755 (split-num high 0) (split-num high 32))))))))))
1757 ;;;; functions
1759 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1760 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1762 ;;; The definition here is a simple temporary placeholder. It will be
1763 ;;; overwritten by a smarter version (capable of calling generic
1764 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1765 (defun printed-as-funcallable-standard-class (object stream)
1766 (declare (ignore object stream))
1767 nil)
1769 (defun output-fun (object stream)
1770 (let* ((name (%fun-name object))
1771 (proper-name-p (and (legal-fun-name-p name) (fboundp name)
1772 (eq (fdefinition name) object))))
1773 (print-unreadable-object (object stream :identity (not proper-name-p))
1774 (format stream "~:[FUNCTION~;CLOSURE~]~@[ ~S~]"
1775 (closurep object)
1776 name))))
1778 ;;;; catch-all for unknown things
1780 (defun output-random (object stream)
1781 (print-unreadable-object (object stream :identity t)
1782 (let ((lowtag (lowtag-of object)))
1783 (case lowtag
1784 (#.sb!vm:other-pointer-lowtag
1785 (let ((widetag (widetag-of object)))
1786 (case widetag
1787 (#.sb!vm:value-cell-header-widetag
1788 (write-string "value cell " stream)
1789 (output-object (value-cell-ref object) stream))
1791 (write-string "unknown pointer object, widetag=" stream)
1792 (let ((*print-base* 16) (*print-radix* t))
1793 (output-integer widetag stream))))))
1794 ((#.sb!vm:fun-pointer-lowtag
1795 #.sb!vm:instance-pointer-lowtag
1796 #.sb!vm:list-pointer-lowtag)
1797 (write-string "unknown pointer object, lowtag=" stream)
1798 (let ((*print-base* 16) (*print-radix* t))
1799 (output-integer lowtag stream)))
1801 (case (widetag-of object)
1802 (#.sb!vm:unbound-marker-widetag
1803 (write-string "unbound marker" stream))
1805 (write-string "unknown immediate object, lowtag=" stream)
1806 (let ((*print-base* 2) (*print-radix* t))
1807 (output-integer lowtag stream))
1808 (write-string ", widetag=" stream)
1809 (let ((*print-base* 16) (*print-radix* t))
1810 (output-integer (widetag-of object) stream)))))))))