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