Tolerate non-simple strings when checking arguments to CERROR.
[sbcl.git] / src / code / print.lisp
blobd610de4e94e25a6edbe8b50f1ae54236b1a1cb76
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 "If true, all objects will be printed readably. If readable printing
18 is impossible, an error will be signalled. This overrides the value of
19 *PRINT-ESCAPE*.")
20 (!defvar *print-escape* t
21 "Should we print in a reasonably machine-readable way? (possibly
22 overridden by *PRINT-READABLY*)")
23 (!defvar *print-pretty* nil ; (set later when pretty-printer is initialized)
24 "Should pretty printing be used?")
25 (!defvar *print-base* 10.
26 "The output base for RATIONALs (including integers).")
27 (!defvar *print-radix* nil
28 "Should base be verified when printing RATIONALs?")
29 (!defvar *print-level* nil
30 "How many levels should be printed before abbreviating with \"#\"?")
31 (!defvar *print-length* nil
32 "How many elements at any level should be printed before abbreviating
33 with \"...\"?")
34 (!defvar *print-circle* nil
35 "Should we use #n= and #n# notation to preserve uniqueness in general (and
36 circularity in particular) when printing?")
37 (!defvar *print-case* :upcase
38 "What case should the printer should use default?")
39 (!defvar *print-array* t
40 "Should the contents of arrays be printed?")
41 (!defvar *print-gensym* t
42 "Should #: prefixes be used when printing symbols with null SYMBOL-PACKAGE?")
43 (!defvar *print-lines* nil
44 "The maximum number of lines to print per object.")
45 (!defvar *print-right-margin* nil
46 "The position of the right margin in ems (for pretty-printing).")
47 (!defvar *print-miser-width* nil
48 "If the remaining space between the current column and the right margin
49 is less than this, then print using ``miser-style'' output. Miser
50 style conditional newlines are turned on, and all indentations are
51 turned off. If NIL, never use miser mode.")
52 (defvar *print-pprint-dispatch*
53 (sb!pretty::make-pprint-dispatch-table) ; for type-correctness
54 "The pprint-dispatch-table that controls how to pretty-print objects.")
55 (!defvar *suppress-print-errors* nil
56 "Suppress printer errors when the condition is of the type designated by this
57 variable: an unreadable object representing the error is printed instead.")
59 ;; duplicate defglobal because this file is compiled before "reader"
60 (defglobal *standard-readtable* nil)
62 (defun %with-standard-io-syntax (function)
63 (declare (type function function))
64 (let ((*package* (load-time-value (find-package "COMMON-LISP-USER") t))
65 (*print-array* t)
66 (*print-base* 10)
67 (*print-case* :upcase)
68 (*print-circle* nil)
69 (*print-escape* t)
70 (*print-gensym* t)
71 (*print-length* nil)
72 (*print-level* nil)
73 (*print-lines* nil)
74 (*print-miser-width* nil)
75 (*print-pprint-dispatch* sb!pretty::*standard-pprint-dispatch-table*)
76 (*print-pretty* nil)
77 (*print-radix* nil)
78 (*print-readably* t)
79 (*print-right-margin* nil)
80 (*read-base* 10)
81 (*read-default-float-format* 'single-float)
82 (*read-eval* t)
83 (*read-suppress* nil)
84 (*readtable* *standard-readtable*)
85 (*suppress-print-errors* nil)
86 (*print-vector-length* nil))
87 (funcall function)))
89 ;;;; routines to print objects
91 (macrolet ((def (fn doc &rest forms)
92 `(defun ,fn
93 (object
94 &key
95 ,@(if (eq fn 'write) '(stream))
96 ((:escape *print-escape*) *print-escape*)
97 ((:radix *print-radix*) *print-radix*)
98 ((:base *print-base*) *print-base*)
99 ((:circle *print-circle*) *print-circle*)
100 ((:pretty *print-pretty*) *print-pretty*)
101 ((:level *print-level*) *print-level*)
102 ((:length *print-length*) *print-length*)
103 ((:case *print-case*) *print-case*)
104 ((:array *print-array*) *print-array*)
105 ((:gensym *print-gensym*) *print-gensym*)
106 ((:readably *print-readably*) *print-readably*)
107 ((:right-margin *print-right-margin*)
108 *print-right-margin*)
109 ((:miser-width *print-miser-width*)
110 *print-miser-width*)
111 ((:lines *print-lines*) *print-lines*)
112 ((:pprint-dispatch *print-pprint-dispatch*)
113 *print-pprint-dispatch*)
114 ((:suppress-errors *suppress-print-errors*)
115 *suppress-print-errors*))
116 ,doc
117 (declare (explicit-check))
118 ,@forms)))
119 (def write
120 "Output OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*."
121 (output-object object (out-stream-from-designator stream))
122 object)
123 (def write-to-string
124 "Return the printed representation of OBJECT as a string."
125 (stringify-object object)))
127 ;;; Same as a call to (WRITE OBJECT :STREAM STREAM), but returning OBJECT.
128 (defun %write (object stream)
129 (declare (explicit-check))
130 (output-object object (out-stream-from-designator stream))
131 object)
133 (defun prin1 (object &optional stream)
134 "Output a mostly READable printed representation of OBJECT on the specified
135 STREAM."
136 (declare (explicit-check))
137 (let ((*print-escape* t))
138 (output-object object (out-stream-from-designator stream)))
139 object)
141 (defun princ (object &optional stream)
142 "Output an aesthetic but not necessarily READable printed representation
143 of OBJECT on the specified STREAM."
144 (declare (explicit-check))
145 (let ((*print-escape* nil)
146 (*print-readably* nil))
147 (output-object object (out-stream-from-designator stream)))
148 object)
150 (defun print (object &optional stream)
151 "Output a newline, the mostly READable printed representation of OBJECT, and
152 space to the specified STREAM."
153 (declare (explicit-check))
154 (let ((stream (out-stream-from-designator stream)))
155 (terpri stream)
156 (prin1 object stream)
157 (write-char #\space stream)
158 object))
160 (defun pprint (object &optional stream)
161 "Prettily output OBJECT preceded by a newline."
162 (declare (explicit-check))
163 (let ((*print-pretty* t)
164 (*print-escape* t)
165 (stream (out-stream-from-designator stream)))
166 (terpri stream)
167 (output-object object stream))
168 (values))
170 (defun prin1-to-string (object)
171 "Return the printed representation of OBJECT as a string with
172 slashification on."
173 (let ((*print-escape* t))
174 (stringify-object object)))
176 (defun princ-to-string (object)
177 "Return the printed representation of OBJECT as a string with
178 slashification off."
179 (let ((*print-escape* nil)
180 (*print-readably* nil))
181 (stringify-object object)))
183 ;;; This produces the printed representation of an object as a string.
184 ;;; The few ...-TO-STRING functions above call this.
185 (defun stringify-object (object)
186 (typecase object
187 (integer
188 (multiple-value-bind (fun pretty)
189 (and *print-pretty* (pprint-dispatch object))
190 (if pretty
191 (with-simple-output-to-string (stream)
192 (sb!pretty::with-pretty-stream (stream)
193 (funcall fun stream object)))
194 (let ((buffer-size (approx-chars-in-repr object)))
195 (let* ((string (make-string buffer-size :element-type 'base-char))
196 (stream (%make-finite-base-string-output-stream string)))
197 (declare (inline %make-finite-base-string-output-stream))
198 (declare (truly-dynamic-extent stream))
199 (output-integer object stream *print-base* *print-radix*)
200 (%shrink-vector string
201 (finite-base-string-output-stream-pointer stream)))))))
202 ;; Could do something for other numeric types, symbols, ...
204 (with-simple-output-to-string (stream)
205 (output-object object stream)))))
207 ;;; Estimate the number of chars in the printed representation of OBJECT.
208 ;;; The answer must be an overestimate or exact; never an underestimate.
209 (defun approx-chars-in-repr (object)
210 (declare (integer object))
211 ;; Round *PRINT-BASE* down to the nearest lower power-of-2, call that N,
212 ;; and "guess" that the one character can represent N bits.
213 ;; This is exact for bases which are exactly a power-of-2, or an overestimate
214 ;; otherwise, as mandated by the finite output stream.
215 (let ((bits-per-char
216 (aref #.(!coerce-to-specialized
217 ;; base 2 or base 3 = 1 bit per character
218 ;; base 4 .. base 7 = 2 bits per character
219 ;; base 8 .. base 15 = 3 bits per character, etc
220 #(1 1 2 2 2 2 3 3 3 3 3 3 3 3
221 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5)
222 '(unsigned-byte 8))
223 (- *print-base* 2))))
224 (+ (if (minusp object) 1 0) ; leading sign
225 (if *print-radix* 4 0) ; #rNN or trailing decimal
226 (ceiling (if (fixnump object)
227 sb!vm:n-positive-fixnum-bits
228 (* (%bignum-length object) sb!bignum::digit-size))
229 bits-per-char))))
231 ;;;; support for the PRINT-UNREADABLE-OBJECT macro
233 (defun print-not-readable-error (object stream)
234 (restart-case
235 (error 'print-not-readable :object object)
236 (print-unreadably ()
237 :report "Print unreadably."
238 (let ((*print-readably* nil))
239 (output-object object stream)
240 object))
241 (use-value (o)
242 :report "Supply an object to be printed instead."
243 :interactive
244 (lambda ()
245 (read-evaluated-form "~@<Enter an object (evaluated): ~@:>"))
246 (output-object o stream)
247 o)))
249 ;;; guts of PRINT-UNREADABLE-OBJECT
250 (defun %print-unreadable-object (object stream type identity &optional body)
251 (declare (type (or null function) body))
252 (if *print-readably*
253 (print-not-readable-error object stream)
254 (flet ((print-description ()
255 (when type
256 (write (type-of object) :stream stream :circle nil
257 :level nil :length nil)
258 ;; Do NOT insert a pprint-newline here.
259 ;; See ba34717602d80e5fd74d10e61f4729fb0d019a0c
260 (write-char #\space stream))
261 (when body
262 (funcall body))
263 (when identity
264 (when (or body (not type))
265 (write-char #\space stream))
266 ;; Nor here.
267 (write-char #\{ stream)
268 (write (get-lisp-obj-address object) :stream stream
269 :radix nil :base 16)
270 (write-char #\} stream))))
271 (cond ((print-pretty-on-stream-p stream)
272 ;; Since we're printing prettily on STREAM, format the
273 ;; object within a logical block. PPRINT-LOGICAL-BLOCK does
274 ;; not rebind the stream when it is already a pretty stream,
275 ;; so output from the body will go to the same stream.
276 (pprint-logical-block (stream nil :prefix "#<" :suffix ">")
277 (print-description)))
279 (write-string "#<" stream)
280 (print-description)
281 (write-char #\> stream)))))
282 nil)
284 ;;;; OUTPUT-OBJECT -- the main entry point
286 ;;; Objects whose print representation identifies them EQLly don't
287 ;;; need to be checked for circularity.
288 (defun uniquely-identified-by-print-p (x)
289 (or (numberp x)
290 (characterp x)
291 (and (symbolp x)
292 (symbol-package x))))
294 (defvar *in-print-error* nil)
296 ;;; Output OBJECT to STREAM observing all printer control variables.
297 (defun output-object (object stream)
298 ;; FIXME: this function is declared EXPLICIT-CHECK, so it allows STREAM
299 ;; to be T or NIL (a stream-designator), which is not really right
300 ;; if eventually the call will be to a PRINT-OBJECT method,
301 ;; since the generic function should always receive a stream.
302 (declare (explicit-check))
303 (labels ((print-it (stream)
304 (multiple-value-bind (fun pretty)
305 (and *print-pretty* (pprint-dispatch object))
306 (if pretty
307 (sb!pretty::with-pretty-stream (stream)
308 (funcall fun stream object))
309 (output-ugly-object stream object))))
310 (handle-it (stream)
311 (if *suppress-print-errors*
312 (handler-bind
313 ((condition
314 (lambda (condition)
315 (when (typep condition *suppress-print-errors*)
316 (cond (*in-print-error*
317 (write-string "(error printing " stream)
318 (write-string *in-print-error* stream)
319 (write-string ")" stream))
321 (let ((*print-readably* nil)
322 (*print-escape* t))
323 (write-string
324 "#<error printing a " stream)
325 (let ((*in-print-error* "type"))
326 (output-object (type-of object) stream))
327 (write-string ": " stream)
328 (let ((*in-print-error* "condition"))
329 (output-object condition stream))
330 (write-string ">" stream))))
331 (return-from handle-it object)))))
332 (print-it stream))
333 (print-it stream)))
334 (check-it (stream)
335 (multiple-value-bind (marker initiate)
336 (check-for-circularity object t)
337 (if (eq initiate :initiate)
338 (let ((*circularity-hash-table*
339 (make-hash-table :test 'eq)))
340 (check-it (make-broadcast-stream))
341 (let ((*circularity-counter* 0))
342 (check-it stream)))
343 ;; otherwise
344 (if marker
345 (when (handle-circularity marker stream)
346 (handle-it stream))
347 (handle-it stream))))))
348 (cond (;; Maybe we don't need to bother with circularity detection.
349 (or (not *print-circle*)
350 (uniquely-identified-by-print-p object))
351 (handle-it stream))
352 (;; If we have already started circularity detection, this
353 ;; object might be a shared reference. If we have not, then
354 ;; if it is a compound object it might contain a circular
355 ;; reference to itself or multiple shared references.
356 (or *circularity-hash-table*
357 (compound-object-p object))
358 (check-it stream))
360 (handle-it stream)))))
362 ;;; Output OBJECT to STREAM observing all printer control variables
363 ;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
364 ;;; then the pretty printer will be used for any components of OBJECT,
365 ;;; just not for OBJECT itself.
366 (defun output-ugly-object (stream object)
367 (when (%instancep object)
368 (let* ((layout (layout-of object))
369 (classoid (layout-classoid layout)))
370 ;; If an instance has no layout, it has no PRINT-OBJECT method.
371 ;; Additionally, if the object is an obsolete CONDITION, don't crash.
372 ;; (There is no update-instance protocol for conditions)
373 (when (or (sb!kernel::undefined-classoid-p classoid)
374 (and (layout-invalid layout)
375 (logtest (layout-%flags layout) +condition-layout-flag+)))
376 ;; not only is this unreadable, it's unprintable too.
377 (return-from output-ugly-object
378 (print-unreadable-object (object stream :identity t)
379 (format stream "UNPRINTABLE instance of ~W" classoid))))))
380 (print-object object stream))
382 ;;;; symbols
384 (defmethod print-object ((object symbol) stream)
385 (if (or *print-escape* *print-readably*)
386 ;; Write so that reading back works
387 (output-symbol object (symbol-package object) stream)
388 ;; Write only the characters of the name, never the package
389 (let ((rt *readtable*))
390 (funcall (truly-the function
391 (choose-symbol-out-fun *print-case* (%readtable-case rt)))
392 (symbol-name object) stream rt))))
394 (defun output-symbol (symbol package stream)
395 (let* ((readably *print-readably*)
396 (readtable (if readably *standard-readtable* *readtable*))
397 (out-fun (choose-symbol-out-fun *print-case* (%readtable-case readtable))))
398 (flet ((output-token (name)
399 (declare (type simple-string name))
400 (cond ((or (and (readtable-normalization readtable)
401 (not (sb!unicode:normalized-p name :nfkc)))
402 (symbol-quotep name readtable))
403 ;; Output NAME surrounded with |'s,
404 ;; and with any embedded |'s or \'s escaped.
405 (write-char #\| stream)
406 (dotimes (index (length name))
407 (let ((char (char name index)))
408 ;; Hmm. Should these depend on what characters
409 ;; are actually escapes in the readtable ?
410 ;; (See similar remark at DEFUN QUOTE-STRING)
411 (when (or (char= char #\\) (char= char #\|))
412 (write-char #\\ stream))
413 (write-char char stream)))
414 (write-char #\| stream))
416 (funcall (truly-the function out-fun) name stream readtable)))))
417 (let ((name (symbol-name symbol))
418 (current (sane-package)))
419 (cond
420 ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
421 ;; requires that keywords be printed with preceding colons
422 ;; always, regardless of the value of *PACKAGE*.
423 ((eq package *keyword-package*)
424 (write-char #\: stream))
425 ;; Otherwise, if the symbol's home package is the current
426 ;; one, then a prefix is never necessary.
427 ((eq package current))
428 ;; Uninterned symbols print with a leading #:.
429 ((null package)
430 (when (or *print-gensym* readably)
431 (write-string "#:" stream)))
433 (multiple-value-bind (found accessible) (find-symbol name current)
434 ;; If we can find the symbol by looking it up, it need not
435 ;; be qualified. This can happen if the symbol has been
436 ;; inherited from a package other than its home package.
438 ;; To preserve print-read consistency, use the local nickname if
439 ;; one exists.
440 (unless (and accessible (eq found symbol))
441 (let ((prefix (or (car (rassoc package (package-%local-nicknames current)))
442 (package-name package))))
443 (output-token prefix))
444 (write-char #\: stream)
445 (when (eql (find-external-symbol name package) 0)
446 (write-char #\: stream))))))
447 (output-token name)))))
449 ;;;; escaping symbols
451 ;;; When we print symbols we have to figure out if they need to be
452 ;;; printed with escape characters. This isn't a whole lot easier than
453 ;;; reading symbols in the first place.
455 ;;; For each character, the value of the corresponding element is a
456 ;;; fixnum with bits set corresponding to attributes that the
457 ;;; character has. At characters have at least one bit set, so we can
458 ;;; search for any character with a positive test.
459 (defvar *character-attributes*
460 (make-array 160 ; FIXME
461 :element-type '(unsigned-byte 16)
462 :initial-element 0))
463 (declaim (type (simple-array (unsigned-byte 16) (#.160)) ; FIXME
464 *character-attributes*))
466 ;;; constants which are a bit-mask for each interesting character attribute
467 (defconstant other-attribute (ash 1 0)) ; Anything else legal.
468 (defconstant number-attribute (ash 1 1)) ; A numeric digit.
469 (defconstant uppercase-attribute (ash 1 2)) ; An uppercase letter.
470 (defconstant lowercase-attribute (ash 1 3)) ; A lowercase letter.
471 (defconstant sign-attribute (ash 1 4)) ; +-
472 (defconstant extension-attribute (ash 1 5)) ; ^_
473 (defconstant dot-attribute (ash 1 6)) ; .
474 (defconstant slash-attribute (ash 1 7)) ; /
475 (defconstant funny-attribute (ash 1 8)) ; Anything illegal.
477 (eval-when (:compile-toplevel :load-toplevel :execute)
479 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
480 ;;; that don't need to be escaped (according to READTABLE-CASE.)
481 (defglobal *attribute-names*
482 `((number . number-attribute) (lowercase . lowercase-attribute)
483 (uppercase . uppercase-attribute) (letter . letter-attribute)
484 (sign . sign-attribute) (extension . extension-attribute)
485 (dot . dot-attribute) (slash . slash-attribute)
486 (other . other-attribute) (funny . funny-attribute)))
488 ) ; EVAL-WHEN
490 ;;; For each character, the value of the corresponding element is the
491 ;;; lowest base in which that character is a digit.
492 (declaim (type (simple-array (unsigned-byte 8) (128)) ; FIXME: range?
493 *digit-bases*))
494 (defvar *digit-bases*
495 (make-array 128 ; FIXME
496 :element-type '(unsigned-byte 8)))
498 (defun !printer-cold-init ()
499 ;; The dispatch table will be changed later, so this doesn't really matter
500 ;; except if a full call to WRITE wants to read the current binding.
501 (setq *print-pprint-dispatch* (sb!pretty::make-pprint-dispatch-table))
502 (setq *digit-bases* (make-array 128 ; FIXME
503 :element-type '(unsigned-byte 8)
504 :initial-element 36)
505 *character-attributes* (make-array 160 ; FIXME
506 :element-type '(unsigned-byte 16)
507 :initial-element 0))
508 (dotimes (i 36)
509 (let ((char (digit-char i 36)))
510 (setf (aref *digit-bases* (char-code char)) i)))
512 (flet ((set-bit (char bit)
513 (let ((code (char-code char)))
514 (setf (aref *character-attributes* code)
515 (logior bit (aref *character-attributes* code))))))
517 (dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
518 #\? #\< #\>))
519 (set-bit char other-attribute))
521 (dotimes (i 10)
522 (set-bit (digit-char i) number-attribute))
524 (do ((code (char-code #\A) (1+ code))
525 (end (char-code #\Z)))
526 ((> code end))
527 (declare (fixnum code end))
528 (set-bit (code-char code) uppercase-attribute)
529 (set-bit (char-downcase (code-char code)) lowercase-attribute))
531 (set-bit #\- sign-attribute)
532 (set-bit #\+ sign-attribute)
533 (set-bit #\^ extension-attribute)
534 (set-bit #\_ extension-attribute)
535 (set-bit #\. dot-attribute)
536 (set-bit #\/ slash-attribute)
538 ;; Mark anything not explicitly allowed as funny.
539 (dotimes (i 160) ; FIXME
540 (when (zerop (aref *character-attributes* i))
541 (setf (aref *character-attributes* i) funny-attribute))))
542 ) ; end !COLD-PRINT-INIT
544 ;;; A FSM-like thingie that determines whether a symbol is a potential
545 ;;; number or has evil characters in it.
546 (defun symbol-quotep (name readtable)
547 (declare (simple-string name))
548 (macrolet ((advance (tag &optional (at-end t))
549 `(progn
550 (when (= index len)
551 ,(if at-end '(go TEST-SIGN) '(return nil)))
552 (setq current (schar name index)
553 code (char-code current)
554 bits (cond ; FIXME
555 ((< code 160) (aref attributes code))
556 ((upper-case-p current) uppercase-attribute)
557 ((lower-case-p current) lowercase-attribute)
558 (t other-attribute)))
559 (incf index)
560 (go ,tag)))
561 (test (&rest attributes)
562 `(not (zerop
563 (the fixnum
564 (logand
565 (logior ,@(mapcar
566 (lambda (x)
567 (or (cdr (assoc x
568 *attribute-names*))
569 (error "Blast!")))
570 attributes))
571 bits)))))
572 (digitp ()
573 `(and (< code 128) ; FIXME
574 (< (the fixnum (aref bases code)) base))))
576 (prog ((len (length name))
577 (attributes *character-attributes*)
578 (bases *digit-bases*)
579 (base *print-base*)
580 (letter-attribute
581 (case (%readtable-case readtable)
582 (#.+readtable-upcase+ uppercase-attribute)
583 (#.+readtable-downcase+ lowercase-attribute)
584 (t (logior lowercase-attribute uppercase-attribute))))
585 (index 0)
586 (bits 0)
587 (code 0)
588 current)
589 (declare (fixnum len base index bits code))
590 (advance START t)
592 TEST-SIGN ; At end, see whether it is a sign...
593 (return (not (test sign)))
595 OTHER ; not potential number, see whether funny chars...
596 (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
597 funny-attribute)
598 letter-attribute)))
599 (do ((i (1- index) (1+ i)))
600 ((= i len) (return-from symbol-quotep nil))
601 (unless (zerop (logand (let* ((char (schar name i))
602 (code (char-code char)))
603 (cond
604 ((< code 160) (aref attributes code))
605 ((upper-case-p char) uppercase-attribute)
606 ((lower-case-p char) lowercase-attribute)
607 (t other-attribute)))
608 mask))
609 (return-from symbol-quotep t))))
611 START
612 (when (digitp)
613 (if (test letter)
614 (advance LAST-DIGIT-ALPHA)
615 (advance DIGIT)))
616 (when (test letter number other slash) (advance OTHER nil))
617 (when (char= current #\.) (advance DOT-FOUND))
618 (when (test sign extension) (advance START-STUFF nil))
619 (return t)
621 DOT-FOUND ; leading dots...
622 (when (test letter) (advance START-DOT-MARKER nil))
623 (when (digitp) (advance DOT-DIGIT))
624 (when (test number other) (advance OTHER nil))
625 (when (test extension slash sign) (advance START-DOT-STUFF nil))
626 (when (char= current #\.) (advance DOT-FOUND))
627 (return t)
629 START-STUFF ; leading stuff before any dot or digit
630 (when (digitp)
631 (if (test letter)
632 (advance LAST-DIGIT-ALPHA)
633 (advance DIGIT)))
634 (when (test number other) (advance OTHER nil))
635 (when (test letter) (advance START-MARKER nil))
636 (when (char= current #\.) (advance START-DOT-STUFF nil))
637 (when (test sign extension slash) (advance START-STUFF nil))
638 (return t)
640 START-MARKER ; number marker in leading stuff...
641 (when (test letter) (advance OTHER nil))
642 (go START-STUFF)
644 START-DOT-STUFF ; leading stuff containing dot without digit...
645 (when (test letter) (advance START-DOT-STUFF nil))
646 (when (digitp) (advance DOT-DIGIT))
647 (when (test sign extension dot slash) (advance START-DOT-STUFF nil))
648 (when (test number other) (advance OTHER nil))
649 (return t)
651 START-DOT-MARKER ; number marker in leading stuff with dot..
652 ;; leading stuff containing dot without digit followed by letter...
653 (when (test letter) (advance OTHER nil))
654 (go START-DOT-STUFF)
656 DOT-DIGIT ; in a thing with dots...
657 (when (test letter) (advance DOT-MARKER))
658 (when (digitp) (advance DOT-DIGIT))
659 (when (test number other) (advance OTHER nil))
660 (when (test sign extension dot slash) (advance DOT-DIGIT))
661 (return t)
663 DOT-MARKER ; number marker in number with dot...
664 (when (test letter) (advance OTHER nil))
665 (go DOT-DIGIT)
667 LAST-DIGIT-ALPHA ; previous char is a letter digit...
668 (when (or (digitp) (test sign slash))
669 (advance ALPHA-DIGIT))
670 (when (test letter number other dot) (advance OTHER nil))
671 (return t)
673 ALPHA-DIGIT ; seen a digit which is a letter...
674 (when (or (digitp) (test sign slash))
675 (if (test letter)
676 (advance LAST-DIGIT-ALPHA)
677 (advance ALPHA-DIGIT)))
678 (when (test letter) (advance ALPHA-MARKER))
679 (when (test number other dot) (advance OTHER nil))
680 (return t)
682 ALPHA-MARKER ; number marker in number with alpha digit...
683 (when (test letter) (advance OTHER nil))
684 (go ALPHA-DIGIT)
686 DIGIT ; seen only ordinary (non-alphabetic) numeric digits...
687 (when (digitp)
688 (if (test letter)
689 (advance ALPHA-DIGIT)
690 (advance DIGIT)))
691 (when (test number other) (advance OTHER nil))
692 (when (test letter) (advance MARKER))
693 (when (test extension slash sign) (advance DIGIT))
694 (when (char= current #\.) (advance DOT-DIGIT))
695 (return t)
697 MARKER ; number marker in a numeric number...
698 ;; ("What," you may ask, "is a 'number marker'?" It's something
699 ;; that a conforming implementation might use in number syntax.
700 ;; See ANSI 2.3.1.1 "Potential Numbers as Tokens".)
701 (when (test letter) (advance OTHER nil))
702 (go DIGIT))))
704 ;;;; case hackery: One of these functions is chosen to output symbol
705 ;;;; names according to the values of *PRINT-CASE* and READTABLE-CASE.
707 ;;; called when:
708 ;;; READTABLE-CASE *PRINT-CASE*
709 ;;; :UPCASE :UPCASE
710 ;;; :DOWNCASE :DOWNCASE
711 ;;; :PRESERVE any
712 (defun output-preserve-symbol (pname stream readtable)
713 (declare (ignore readtable))
714 (write-string pname stream))
716 ;;; called when:
717 ;;; READTABLE-CASE *PRINT-CASE*
718 ;;; :UPCASE :DOWNCASE
719 (defun output-lowercase-symbol (pname stream readtable)
720 (declare (simple-string pname) (ignore readtable))
721 (dotimes (index (length pname))
722 (let ((char (schar pname index)))
723 (write-char (char-downcase char) stream))))
725 ;;; called when:
726 ;;; READTABLE-CASE *PRINT-CASE*
727 ;;; :DOWNCASE :UPCASE
728 (defun output-uppercase-symbol (pname stream readtable)
729 (declare (simple-string pname) (ignore readtable))
730 (dotimes (index (length pname))
731 (let ((char (schar pname index)))
732 (write-char (char-upcase char) stream))))
734 ;;; called when:
735 ;;; READTABLE-CASE *PRINT-CASE*
736 ;;; :UPCASE :CAPITALIZE
737 ;;; :DOWNCASE :CAPITALIZE
738 (defun output-capitalize-symbol (pname stream readtable)
739 (declare (simple-string pname))
740 (let ((prev-not-alphanum t)
741 (up (eql (%readtable-case readtable) +readtable-upcase+)))
742 (dotimes (i (length pname))
743 (let ((char (char pname i)))
744 (write-char (if up
745 (if (or prev-not-alphanum (lower-case-p char))
746 char
747 (char-downcase char))
748 (if prev-not-alphanum
749 (char-upcase char)
750 char))
751 stream)
752 (setq prev-not-alphanum (not (alphanumericp char)))))))
754 ;;; called when:
755 ;;; READTABLE-CASE *PRINT-CASE*
756 ;;; :INVERT any
757 (defun output-invert-symbol (pname stream readtable)
758 (declare (simple-string pname) (ignore readtable))
759 (let ((all-upper t)
760 (all-lower t))
761 (dotimes (i (length pname))
762 (let ((ch (schar pname i)))
763 (when (both-case-p ch)
764 (if (upper-case-p ch)
765 (setq all-lower nil)
766 (setq all-upper nil)))))
767 (cond (all-upper (output-lowercase-symbol pname stream nil))
768 (all-lower (output-uppercase-symbol pname stream nil))
770 (write-string pname stream)))))
772 (defun choose-symbol-out-fun (print-case readtable-case)
773 (macrolet
774 ((compute-fun-vector (&aux (vector (make-array 12)))
775 ;; Pack a 2D array of functions into a simple-vector.
776 ;; Major axis is *PRINT-CASE*, minor axis is %READTABLE-CASE.
777 (dotimes (readtable-case-index 4)
778 (dotimes (print-case-index 3)
779 (let ((readtable-case
780 (elt '(:upcase :downcase :preserve :invert) readtable-case-index))
781 (print-case
782 (elt '(:upcase :downcase :capitalize) print-case-index)))
783 (setf (aref vector (logior (ash print-case-index 2)
784 readtable-case-index))
785 (case readtable-case
786 (:upcase
787 (case print-case
788 (:upcase 'output-preserve-symbol)
789 (:downcase 'output-lowercase-symbol)
790 (:capitalize 'output-capitalize-symbol)))
791 (:downcase
792 (case print-case
793 (:upcase 'output-uppercase-symbol)
794 (:downcase 'output-preserve-symbol)
795 (:capitalize 'output-capitalize-symbol)))
796 (:preserve 'output-preserve-symbol)
797 (:invert 'output-invert-symbol))))))
798 `(load-time-value (vector ,@(map 'list (lambda (x) `(function ,x)) vector))
799 t)))
800 (aref (compute-fun-vector)
801 (logior (case print-case (:upcase 0) (:downcase 4) (t 8))
802 (truly-the (mod 4) readtable-case)))))
804 ;;;; recursive objects
806 (defmethod print-object ((list cons) stream)
807 (descend-into (stream)
808 (write-char #\( stream)
809 (let ((length 0)
810 (list list))
811 (loop
812 (punt-print-if-too-long length stream)
813 (output-object (pop list) stream)
814 (unless list
815 (return))
816 (when (or (atom list)
817 (check-for-circularity list))
818 (write-string " . " stream)
819 (output-object list stream)
820 (return))
821 (write-char #\space stream)
822 (incf length)))
823 (write-char #\) stream)))
825 (defmethod print-object ((vector vector) stream)
826 (let ((readably *print-readably*))
827 (flet ((cut-length ()
828 (when (and (not readably)
829 *print-vector-length*
830 (> (length vector) *print-vector-length*))
831 (print-unreadable-object (vector stream :type t :identity t)
832 (format stream "~A..."
833 (make-array *print-vector-length*
834 :element-type (array-element-type vector)
835 :displaced-to vector)))
836 t)))
837 (cond ((stringp vector)
838 (cond ((and readably (not (typep vector '(vector character))))
839 (output-unreadable-array-readably vector stream))
840 ((and *print-escape*
841 (cut-length)))
842 ((or *print-escape* readably)
843 (write-char #\" stream)
844 (quote-string vector stream)
845 (write-char #\" stream))
847 (write-string vector stream))))
848 ((not (or *print-array* readably))
849 (output-terse-array vector stream))
850 ((bit-vector-p vector)
851 (cond ((cut-length))
853 (write-string "#*" stream)
854 (dovector (bit vector)
855 ;; (Don't use OUTPUT-OBJECT here, since this code
856 ;; has to work for all possible *PRINT-BASE* values.)
857 (write-char (if (zerop bit) #\0 #\1) stream)))))
858 ((or (not readably) (array-readably-printable-p vector))
859 (descend-into (stream)
860 (write-string "#(" stream)
861 (dotimes (i (length vector))
862 (unless (zerop i)
863 (write-char #\space stream))
864 (punt-print-if-too-long i stream)
865 (output-object (aref vector i) stream))
866 (write-string ")" stream)))
869 (output-unreadable-array-readably vector stream))))))
871 ;;; This function outputs a string quoting characters sufficiently
872 ;;; so that someone can read it in again. Basically, put a slash in
873 ;;; front of an character satisfying NEEDS-SLASH-P.
874 (defun quote-string (string stream)
875 (macrolet ((needs-slash-p (char)
876 ;; KLUDGE: We probably should look at the readtable, but just do
877 ;; this for now. [noted by anonymous long ago] -- WHN 19991130
878 `(or (char= ,char #\\)
879 (char= ,char #\"))))
880 (with-array-data ((data string) (start) (end)
881 :check-fill-pointer t)
882 (do ((index start (1+ index)))
883 ((>= index end))
884 (let ((char (schar data index)))
885 (when (needs-slash-p char) (write-char #\\ stream))
886 (write-char char stream))))))
888 (defun array-readably-printable-p (array)
889 (and (eq (array-element-type array) t)
890 (let ((zero (position 0 (array-dimensions array)))
891 (number (position 0 (array-dimensions array)
892 :test (complement #'eql)
893 :from-end t)))
894 (or (null zero) (null number) (> zero number)))))
896 ;;; Output the printed representation of any array in either the #< or #A
897 ;;; form.
898 (defmethod print-object ((array array) stream)
899 (if (or *print-array* *print-readably*)
900 (output-array-guts array stream)
901 (output-terse-array array stream)))
903 ;;; Output the abbreviated #< form of an array.
904 (defun output-terse-array (array stream)
905 (let ((*print-level* nil)
906 (*print-length* nil))
907 (print-unreadable-object (array stream :type t :identity t))))
909 ;;; Convert an array into a list that can be used with MAKE-ARRAY's
910 ;;; :INITIAL-CONTENTS keyword argument.
911 (defun listify-array (array)
912 (flet ((compact (seq)
913 (typecase array
914 (string
915 (coerce seq '(simple-array character (*))))
916 ((array bit)
917 (coerce seq 'bit-vector))
919 seq))))
920 (if (typep array '(or string bit-vector))
921 (compact array)
922 (with-array-data ((data array) (start) (end))
923 (declare (ignore end))
924 (labels ((listify (dimensions index)
925 (if (null dimensions)
926 (aref data index)
927 (let* ((dimension (car dimensions))
928 (dimensions (cdr dimensions))
929 (count (reduce #'* dimensions)))
930 (loop for i below dimension
931 for list = (listify dimensions index)
932 collect (if (and dimensions
933 (null (cdr dimensions)))
934 (compact list)
935 list)
936 do (incf index count))))))
937 (listify (array-dimensions array) start))))))
939 ;;; Use nonstandard #A(dimensions element-type contents)
940 ;;; to avoid using #.
941 (defun output-unreadable-array-readably (array stream)
942 (let ((array (list* (array-dimensions array)
943 (array-element-type array)
944 (listify-array array))))
945 (write-string "#A" stream)
946 (write array :stream stream)
947 nil))
949 ;;; Output the readable #A form of an array.
950 (defun output-array-guts (array stream)
951 (cond ((or (not *print-readably*)
952 (array-readably-printable-p array))
953 (write-char #\# stream)
954 (output-integer (array-rank array) stream 10 nil)
955 (write-char #\A stream)
956 (with-array-data ((data array) (start) (end))
957 (declare (ignore end))
958 (sub-output-array-guts data (array-dimensions array) stream start)))
960 (output-unreadable-array-readably array stream))))
962 (defun sub-output-array-guts (array dimensions stream index)
963 (declare (type (simple-array * (*)) array) (fixnum index))
964 (cond ((null dimensions)
965 (output-object (aref array index) stream))
967 (descend-into (stream)
968 (write-char #\( stream)
969 (let* ((dimension (car dimensions))
970 (dimensions (cdr dimensions))
971 (count (reduce #'* dimensions)))
972 (dotimes (i dimension)
973 (unless (zerop i)
974 (write-char #\space stream))
975 (punt-print-if-too-long i stream)
976 (sub-output-array-guts array dimensions stream index)
977 (incf index count)))
978 (write-char #\) stream)))))
981 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
983 (defun %output-radix (base stream)
984 (write-char #\# stream)
985 (write-char (case base
986 (2 #\b)
987 (8 #\o)
988 (16 #\x)
989 (t (%output-reasonable-integer-in-base base 10 stream)
990 #\r))
991 stream))
993 (defun %output-reasonable-integer-in-base (n base stream)
994 (multiple-value-bind (q r)
995 (truncate n base)
996 ;; Recurse until you have all the digits pushed on
997 ;; the stack.
998 (unless (zerop q)
999 (%output-reasonable-integer-in-base q base stream))
1000 ;; Then as each recursive call unwinds, turn the
1001 ;; digit (in remainder) into a character and output
1002 ;; the character.
1003 (write-char
1004 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r)
1005 stream)))
1007 ;;; *POWER-CACHE* is an alist mapping bases to power-vectors. It is
1008 ;;; filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
1009 ;;; always prior a GC to drop overly large bignums from the cache.
1011 ;;; It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
1012 ;;; POWERS-FOR-BASE, see that you don't break the assumptions!
1013 (defglobal *power-cache* (make-array 37 :initial-element nil))
1014 (declaim (type (simple-vector 37) *power-cache*))
1016 (defconstant +power-cache-integer-length-limit+ 2048)
1018 (defun scrub-power-cache (&aux (cache *power-cache*))
1019 (dotimes (i (length cache))
1020 (let ((powers (aref cache i)))
1021 (when powers
1022 (let ((too-big (position-if
1023 (lambda (x)
1024 (>= (integer-length x)
1025 +power-cache-integer-length-limit+))
1026 (the simple-vector powers))))
1027 (when too-big
1028 (setf (aref cache i) (subseq powers 0 too-big))))))))
1030 ;;; Compute (and cache) a power vector for a BASE and LIMIT:
1031 ;;; the vector holds integers for which
1032 ;;; (aref powers k) == (expt base (expt 2 k))
1033 ;;; holds.
1034 (defun powers-for-base (base limit)
1035 (flet ((compute-powers (from)
1036 (let (powers)
1037 (do ((p from (* p p)))
1038 ((> p limit)
1039 ;; We don't actually need this, but we also
1040 ;; prefer not to cons it up a second time...
1041 (push p powers))
1042 (push p powers))
1043 (nreverse powers))))
1044 (let* ((cache *power-cache*)
1045 (powers (aref cache base)))
1046 (setf (aref cache base)
1047 (concatenate 'vector powers
1048 (compute-powers
1049 (if powers
1050 (let* ((len (length powers))
1051 (max (svref powers (1- len))))
1052 (if (> max limit)
1053 (return-from powers-for-base powers)
1054 (* max max)))
1055 base)))))))
1057 ;; Algorithm by Harald Hanche-Olsen, sbcl-devel 2005-02-05
1058 (defun %output-huge-integer-in-base (n base stream)
1059 (declare (type bignum n) (type fixnum base))
1060 ;; POWER is a vector for which the following holds:
1061 ;; (aref power k) == (expt base (expt 2 k))
1062 (let* ((power (powers-for-base base n))
1063 (k-start (or (position-if (lambda (x) (> x n)) power)
1064 (bug "power-vector too short"))))
1065 (labels ((bisect (n k exactp)
1066 (declare (fixnum k))
1067 ;; N is the number to bisect
1068 ;; K on initial entry BASE^(2^K) > N
1069 ;; EXACTP is true if 2^K is the exact number of digits
1070 (cond ((zerop n)
1071 (when exactp
1072 (loop repeat (ash 1 k) do (write-char #\0 stream))))
1073 ((zerop k)
1074 (write-char
1075 (schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n)
1076 stream))
1078 (setf k (1- k))
1079 (multiple-value-bind (q r) (truncate n (aref power k))
1080 ;; EXACTP is NIL only at the head of the
1081 ;; initial number, as we don't know the number
1082 ;; of digits there, but we do know that it
1083 ;; doesn't get any leading zeros.
1084 (bisect q k exactp)
1085 (bisect r k (or exactp (plusp q))))))))
1086 (bisect n k-start nil))))
1088 (defun %output-integer-in-base (integer base stream)
1089 (when (minusp integer)
1090 (write-char #\- stream)
1091 (setf integer (- integer)))
1092 ;; The ideal cutoff point between these two algorithms is almost
1093 ;; certainly quite platform dependent: this gives 87 for 32 bit
1094 ;; SBCL, which is about right at least for x86/Darwin.
1095 (if (or (fixnump integer)
1096 (< (integer-length integer) (* 3 sb!vm:n-positive-fixnum-bits)))
1097 (%output-reasonable-integer-in-base integer base stream)
1098 (%output-huge-integer-in-base integer base stream)))
1100 ;;; This gets both a method and a specifically named function
1101 ;;; since the latter is called from a few places.
1102 (defmethod print-object ((object integer) stream)
1103 (output-integer object stream *print-base* *print-radix*))
1104 (defun output-integer (integer stream base radixp)
1105 (cond (radixp
1106 (unless (= base 10) (%output-radix base stream))
1107 (%output-integer-in-base integer base stream)
1108 (when (= base 10) (write-char #\. stream)))
1110 (%output-integer-in-base integer base stream))))
1112 (defmethod print-object ((ratio ratio) stream)
1113 (let ((base *print-base*))
1114 (when *print-radix*
1115 (%output-radix base stream))
1116 (%output-integer-in-base (numerator ratio) base stream)
1117 (write-char #\/ stream)
1118 (%output-integer-in-base (denominator ratio) base stream)))
1120 (defmethod print-object ((complex complex) stream)
1121 (write-string "#C(" stream)
1122 (output-object (realpart complex) stream)
1123 (write-char #\space stream)
1124 (output-object (imagpart complex) stream)
1125 (write-char #\) stream))
1127 ;;;; float printing
1129 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
1130 ;;; most of the work for all printing of floating point numbers in
1131 ;;; FORMAT. It converts a floating point number to a string in a free
1132 ;;; or fixed format with no exponent. The interpretation of the
1133 ;;; arguments is as follows:
1135 ;;; X - The floating point number to convert, which must not be
1136 ;;; negative.
1137 ;;; WIDTH - The preferred field width, used to determine the number
1138 ;;; of fraction digits to produce if the FDIGITS parameter
1139 ;;; is unspecified or NIL. If the non-fraction digits and the
1140 ;;; decimal point alone exceed this width, no fraction digits
1141 ;;; will be produced unless a non-NIL value of FDIGITS has been
1142 ;;; specified. Field overflow is not considerd an error at this
1143 ;;; level.
1144 ;;; FDIGITS - The number of fractional digits to produce. Insignificant
1145 ;;; trailing zeroes may be introduced as needed. May be
1146 ;;; unspecified or NIL, in which case as many digits as possible
1147 ;;; are generated, subject to the constraint that there are no
1148 ;;; trailing zeroes.
1149 ;;; SCALE - If this parameter is specified or non-NIL, then the number
1150 ;;; printed is (* x (expt 10 scale)). This scaling is exact,
1151 ;;; and cannot lose precision.
1152 ;;; FMIN - This parameter, if specified or non-NIL, is the minimum
1153 ;;; number of fraction digits which will be produced, regardless
1154 ;;; of the value of WIDTH or FDIGITS. This feature is used by
1155 ;;; the ~E format directive to prevent complete loss of
1156 ;;; significance in the printed value due to a bogus choice of
1157 ;;; scale factor.
1159 ;;; Returns:
1160 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1161 ;;; where the results have the following interpretation:
1163 ;;; DIGIT-STRING - The decimal representation of X, with decimal point.
1164 ;;; DIGIT-LENGTH - The length of the string DIGIT-STRING.
1165 ;;; LEADING-POINT - True if the first character of DIGIT-STRING is the
1166 ;;; decimal point.
1167 ;;; TRAILING-POINT - True if the last character of DIGIT-STRING is the
1168 ;;; decimal point.
1169 ;;; POINT-POS - The position of the digit preceding the decimal
1170 ;;; point. Zero indicates point before first digit.
1172 ;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
1173 ;;; accuracy. Specifically, the decimal number printed is the closest
1174 ;;; possible approximation to the true value of the binary number to
1175 ;;; be printed from among all decimal representations with the same
1176 ;;; number of digits. In free-format output, i.e. with the number of
1177 ;;; digits unconstrained, it is guaranteed that all the information is
1178 ;;; preserved, so that a properly- rounding reader can reconstruct the
1179 ;;; original binary number, bit-for-bit, from its printed decimal
1180 ;;; representation. Furthermore, only as many digits as necessary to
1181 ;;; satisfy this condition will be printed.
1183 ;;; FLOAT-DIGITS actually generates the digits for positive numbers;
1184 ;;; see below for comments.
1186 (defun flonum-to-string (x &optional width fdigits scale fmin)
1187 (declare (type float x))
1188 (multiple-value-bind (e string)
1189 (if fdigits
1190 (flonum-to-digits x (min (- (+ fdigits (or scale 0)))
1191 (- (or fmin 0))))
1192 (if (and width (> width 1))
1193 (let ((w (multiple-value-list
1194 (flonum-to-digits x
1195 (max 1
1196 (+ (1- width)
1197 (if (and scale (minusp scale))
1198 scale 0)))
1199 t)))
1200 (f (multiple-value-list
1201 (flonum-to-digits x (- (+ (or fmin 0)
1202 (if scale scale 0)))))))
1203 (cond
1204 ((>= (length (cadr w)) (length (cadr f)))
1205 (values-list w))
1206 (t (values-list f))))
1207 (flonum-to-digits x)))
1208 (let ((e (if (zerop x)
1210 (+ e (or scale 0))))
1211 (stream (make-string-output-stream)))
1212 (if (plusp e)
1213 (progn
1214 (write-string string stream :end (min (length string) e))
1215 (dotimes (i (- e (length string)))
1216 (write-char #\0 stream))
1217 (write-char #\. stream)
1218 (write-string string stream :start (min (length string) e))
1219 (when fdigits
1220 (dotimes (i (- fdigits
1221 (- (length string)
1222 (min (length string) e))))
1223 (write-char #\0 stream))))
1224 (progn
1225 (write-string "." stream)
1226 (dotimes (i (- e))
1227 (write-char #\0 stream))
1228 (write-string string stream :end (when fdigits
1229 (min (length string)
1230 (max (or fmin 0)
1231 (+ fdigits e)))))
1232 (when fdigits
1233 (dotimes (i (+ fdigits e (- (length string))))
1234 (write-char #\0 stream)))))
1235 (let ((string (get-output-stream-string stream)))
1236 (values string (length string)
1237 (char= (char string 0) #\.)
1238 (char= (char string (1- (length string))) #\.)
1239 (position #\. string))))))
1241 ;;; implementation of figure 1 from Burger and Dybvig, 1996. It is
1242 ;;; extended in order to handle rounding.
1244 ;;; As the implementation of the Dragon from Classic CMUCL (and
1245 ;;; previously in SBCL above FLONUM-TO-STRING) says: "DO NOT EVEN
1246 ;;; THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE
1247 ;;; PAPER!", and in this case we have to add that even reading the
1248 ;;; paper might not bring immediate illumination as CSR has attempted
1249 ;;; to turn idiomatic Scheme into idiomatic Lisp.
1251 ;;; FIXME: figure 1 from Burger and Dybvig is the unoptimized
1252 ;;; algorithm, noticeably slow at finding the exponent. Figure 2 has
1253 ;;; an improved algorithm, but CSR ran out of energy.
1255 ;;; possible extension for the enthusiastic: printing floats in bases
1256 ;;; other than base 10.
1257 (defconstant single-float-min-e
1258 (- 2 sb!vm:single-float-bias sb!vm:single-float-digits))
1259 (defconstant double-float-min-e
1260 (- 2 sb!vm:double-float-bias sb!vm:double-float-digits))
1261 #!+long-float
1262 (defconstant long-float-min-e
1263 (nth-value 1 (decode-float least-positive-long-float)))
1265 ;;; Call CHAR-FUN with the digits of FLOAT
1266 ;;; PROLOGUE-FUN and EPILOGUE-FUN are called with the exponent before
1267 ;;; and after printing to set up the state.
1268 (declaim (inline %flonum-to-digits))
1269 (defun %flonum-to-digits (char-fun
1270 prologue-fun
1271 epilogue-fun
1272 float &optional position relativep)
1273 (let ((print-base 10) ; B
1274 (float-radix 2) ; b
1275 (float-digits (float-digits float)) ; p
1276 (min-e
1277 (etypecase float
1278 (single-float single-float-min-e)
1279 (double-float double-float-min-e)
1280 #!+long-float
1281 (long-float long-float-min-e))))
1282 (multiple-value-bind (f e)
1283 (integer-decode-float float)
1284 (let ( ;; FIXME: these even tests assume normal IEEE rounding
1285 ;; mode. I wonder if we should cater for non-normal?
1286 (high-ok (evenp f))
1287 (low-ok (evenp f)))
1288 (labels ((scale (r s m+ m-)
1289 (do ((r+m+ (+ r m+))
1290 (k 0 (1+ k))
1291 (s s (* s print-base)))
1292 ((not (or (> r+m+ s)
1293 (and high-ok (= r+m+ s))))
1294 (do ((k k (1- k))
1295 (r r (* r print-base))
1296 (m+ m+ (* m+ print-base))
1297 (m- m- (* m- print-base)))
1298 ((not (and (> r m-) ; Extension to handle zero
1299 (let ((x (* (+ r m+) print-base)))
1300 (or (< x s)
1301 (and (not high-ok)
1302 (= x s))))))
1303 (funcall prologue-fun k)
1304 (generate r s m+ m-)
1305 (funcall epilogue-fun k))))))
1306 (generate (r s m+ m-)
1307 (let (d tc1 tc2)
1308 (tagbody
1309 loop
1310 (setf (values d r) (truncate (* r print-base) s))
1311 (setf m+ (* m+ print-base))
1312 (setf m- (* m- print-base))
1313 (setf tc1 (or (< r m-) (and low-ok (= r m-))))
1314 (setf tc2 (let ((r+m+ (+ r m+)))
1315 (or (> r+m+ s)
1316 (and high-ok (= r+m+ s)))))
1317 (when (or tc1 tc2)
1318 (go end))
1319 (funcall char-fun d)
1320 (go loop)
1322 (let ((d (cond
1323 ((and (not tc1) tc2) (1+ d))
1324 ((and tc1 (not tc2)) d)
1325 ((< (* r 2) s)
1328 (1+ d)))))
1329 (funcall char-fun d)))))
1330 (initialize ()
1331 (let (r s m+ m-)
1332 (cond ((>= e 0)
1333 (let ((be (expt float-radix e)))
1334 (if (/= f (expt float-radix (1- float-digits)))
1335 ;; multiply F by 2 first, avoding consing two bignums
1336 (setf r (* f 2 be)
1338 m+ be
1339 m- be)
1340 (setf m- be
1341 m+ (* be float-radix)
1342 r (* f 2 m+)
1343 s (* float-radix 2)))))
1344 ((or (= e min-e)
1345 (/= f (expt float-radix (1- float-digits))))
1346 (setf r (* f 2)
1347 s (expt float-radix (- 1 e))
1348 m+ 1
1349 m- 1))
1351 (setf r (* f float-radix 2)
1352 s (expt float-radix (- 2 e))
1353 m+ float-radix
1354 m- 1)))
1355 (when position
1356 (when relativep
1357 (aver (> position 0))
1358 (do ((k 0 (1+ k))
1359 ;; running out of letters here
1360 (l 1 (* l print-base)))
1361 ((>= (* s l) (+ r m+))
1362 ;; k is now \hat{k}
1363 (if (< (+ r (* s (/ (expt print-base (- k position)) 2)))
1364 (* s l))
1365 (setf position (- k position))
1366 (setf position (- k position 1))))))
1367 (let* ((x (/ (* s (expt print-base position)) 2))
1368 (low (max m- x))
1369 (high (max m+ x)))
1370 (when (<= m- low)
1371 (setf m- low)
1372 (setf low-ok t))
1373 (when (<= m+ high)
1374 (setf m+ high)
1375 (setf high-ok t))))
1376 (values r s m+ m-))))
1377 (multiple-value-bind (r s m+ m-) (initialize)
1378 (scale r s m+ m-)))))))
1380 (defun flonum-to-digits (float &optional position relativep)
1381 (let ((digit-characters "0123456789"))
1382 (with-push-char (:element-type base-char)
1383 (%flonum-to-digits
1384 (lambda (d)
1385 (push-char (char digit-characters d)))
1386 (lambda (k) k)
1387 (lambda (k) (values k (get-pushed-string)))
1388 float position relativep))))
1390 (defun print-float (float stream)
1391 (let ((position 0)
1392 (dot-position 0)
1393 (digit-characters "0123456789")
1394 (e-min -3)
1395 (e-max 8))
1396 (%flonum-to-digits
1397 (lambda (d)
1398 (when (= position dot-position)
1399 (write-char #\. stream))
1400 (write-char (char digit-characters d) stream)
1401 (incf position))
1402 (lambda (k)
1403 (cond ((not (< e-min k e-max))
1404 (setf dot-position 1))
1405 ((plusp k)
1406 (setf dot-position k))
1408 (setf dot-position -1)
1409 (write-char #\0 stream)
1410 (write-char #\. stream)
1411 (loop for i below (- k)
1412 do (write-char #\0 stream)))))
1413 (lambda (k)
1414 (when (<= position dot-position)
1415 (loop for i below (- dot-position position)
1416 do (write-char #\0 stream))
1417 (write-char #\. stream)
1418 (write-char #\0 stream))
1419 (if (< e-min k e-max)
1420 (print-float-exponent float 0 stream)
1421 (print-float-exponent float (1- k) stream)))
1422 float)))
1424 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns
1425 ;;; a new floating point number Z in the range (0.1, 1.0] and an
1426 ;;; exponent E such that Z * 10^E is (approximately) equal to the
1427 ;;; original number. There may be some loss of precision due the
1428 ;;; floating point representation. The scaling is always done with
1429 ;;; long float arithmetic, which helps printing of lesser precisions
1430 ;;; as well as avoiding generic arithmetic.
1432 ;;; When computing our initial scale factor using EXPT, we pull out
1433 ;;; part of the computation to avoid over/under flow. When
1434 ;;; denormalized, we must pull out a large factor, since there is more
1435 ;;; negative exponent range than positive range.
1437 (eval-when (:compile-toplevel :execute)
1438 (setf *read-default-float-format*
1439 #!+long-float 'long-float #!-long-float 'double-float))
1440 (defun scale-exponent (original-x)
1441 (let* ((x (coerce original-x 'long-float)))
1442 (multiple-value-bind (sig exponent) (decode-float x)
1443 (declare (ignore sig))
1444 (if (= x 0.0e0)
1445 (values (float 0.0e0 original-x) 1)
1446 (let* ((ex (locally (declare (optimize (safety 0)))
1447 (the fixnum
1448 (round (* exponent
1449 ;; this is the closest double float
1450 ;; to (log 2 10), but expressed so
1451 ;; that we're not vulnerable to the
1452 ;; host lisp's interpretation of
1453 ;; arithmetic. (FIXME: it turns
1454 ;; out that sbcl itself is off by 1
1455 ;; ulp in this value, which is a
1456 ;; little unfortunate.)
1457 (load-time-value
1458 #!-long-float
1459 (make-double-float 1070810131 1352628735)
1460 #!+long-float
1461 (error "(log 2 10) not computed")))))))
1462 (x (if (minusp ex)
1463 (if (float-denormalized-p x)
1464 #!-long-float
1465 (* x 1.0e16 (expt 10.0e0 (- (- ex) 16)))
1466 #!+long-float
1467 (* x 1.0e18 (expt 10.0e0 (- (- ex) 18)))
1468 (* x 10.0e0 (expt 10.0e0 (- (- ex) 1))))
1469 (/ x 10.0e0 (expt 10.0e0 (1- ex))))))
1470 (do ((d 10.0e0 (* d 10.0e0))
1471 (y x (/ x d))
1472 (ex ex (1+ ex)))
1473 ((< y 1.0e0)
1474 (do ((m 10.0e0 (* m 10.0e0))
1475 (z y (* y m))
1476 (ex ex (1- ex)))
1477 ((>= z 0.1e0)
1478 (values (float z original-x) ex))
1479 (declare (long-float m) (integer ex))))
1480 (declare (long-float d))))))))
1481 (eval-when (:compile-toplevel :execute)
1482 (setf *read-default-float-format* 'single-float))
1484 ;;;; entry point for the float printer
1486 ;;; the float printer as called by PRINT, PRIN1, PRINC, etc. The
1487 ;;; argument is printed free-format, in either exponential or
1488 ;;; non-exponential notation, depending on its magnitude.
1490 ;;; NOTE: When a number is to be printed in exponential format, it is
1491 ;;; scaled in floating point. Since precision may be lost in this
1492 ;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
1493 ;;; are lost. The difficulty is that FLONUM-TO-STRING performs
1494 ;;; extensive computations with integers of similar magnitude to that
1495 ;;; of the number being printed. For large exponents, the bignums
1496 ;;; really get out of hand. If bignum arithmetic becomes reasonably
1497 ;;; fast and the exponent range is not too large, then it might become
1498 ;;; attractive to handle exponential notation with the same accuracy
1499 ;;; as non-exponential notation, using the method described in the
1500 ;;; Steele and White paper.
1502 ;;; NOTE II: this has been bypassed slightly by implementing Burger
1503 ;;; and Dybvig, 1996. When someone has time (KLUDGE) they can
1504 ;;; probably (a) implement the optimizations suggested by Burger and
1505 ;;; Dyvbig, and (b) remove all vestiges of Dragon4, including from
1506 ;;; fixed-format printing.
1508 ;;; Print the appropriate exponent marker for X and the specified exponent.
1509 (defun print-float-exponent (x exp stream)
1510 (declare (type float x) (type integer exp) (type stream stream))
1511 (cond ((case *read-default-float-format*
1512 ((short-float single-float)
1513 (typep x 'single-float))
1514 ((double-float #!-long-float long-float)
1515 (typep x 'double-float))
1516 #!+long-float
1517 (long-float
1518 (typep x 'long-float)))
1519 (unless (eql exp 0)
1520 (write-char #\e stream)
1521 (%output-integer-in-base exp 10 stream)))
1523 (write-char
1524 (etypecase x
1525 (single-float #\f)
1526 (double-float #\d)
1527 (short-float #\s)
1528 (long-float #\L))
1529 stream)
1530 (%output-integer-in-base exp 10 stream))))
1532 (defun output-float-infinity (x stream)
1533 (declare (float x) (stream stream))
1534 (cond (*read-eval*
1535 (write-string "#." stream))
1536 (*print-readably*
1537 (return-from output-float-infinity
1538 (print-not-readable-error x stream)))
1540 (write-string "#<" stream)))
1541 (write-string "SB-EXT:" stream)
1542 (write-string (symbol-name (float-format-name x)) stream)
1543 (write-string (if (plusp x) "-POSITIVE-" "-NEGATIVE-")
1544 stream)
1545 (write-string "INFINITY" stream)
1546 (unless *read-eval*
1547 (write-string ">" stream)))
1549 (defun output-float-nan (x stream)
1550 (print-unreadable-object (x stream)
1551 (princ (float-format-name x) stream)
1552 (write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
1553 (write-string " NaN" stream)))
1555 (declaim (inline output-float))
1556 (defun output-float (x stream)
1557 (cond
1558 ((float-infinity-p x)
1559 (output-float-infinity x stream))
1560 ((float-nan-p x)
1561 (output-float-nan x stream))
1563 (let ((x (cond ((minusp (float-sign x))
1564 (write-char #\- stream)
1565 (- x))
1567 x))))
1568 (cond
1569 ((zerop x)
1570 (write-string "0.0" stream)
1571 (print-float-exponent x 0 stream))
1573 (print-float x stream)))))))
1575 ;;; the function called by OUTPUT-OBJECT to handle floats
1576 (defmethod print-object ((x single-float) stream)
1577 (output-float x stream))
1579 (defmethod print-object ((x double-float) stream)
1580 (output-float x stream))
1583 ;;;; other leaf objects
1585 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1586 ;;; the character name or the character in the #\char format.
1587 (defmethod print-object ((char character) stream)
1588 (if (or *print-escape* *print-readably*)
1589 (let ((graphicp (and (graphic-char-p char)
1590 (standard-char-p char)))
1591 (name (char-name char)))
1592 (write-string "#\\" stream)
1593 (if (and name (or (not graphicp) *print-readably*))
1594 (quote-string name stream)
1595 (write-char char stream)))
1596 (write-char char stream)))
1598 (defmethod print-object ((sap system-area-pointer) stream)
1599 (cond (*read-eval*
1600 (format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
1602 (print-unreadable-object (sap stream)
1603 (format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
1605 (defmethod print-object ((weak-pointer weak-pointer) stream)
1606 (print-unreadable-object (weak-pointer stream)
1607 (multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
1608 (cond (validp
1609 (write-string "weak pointer: " stream)
1610 (write value :stream stream))
1612 (write-string "broken weak pointer" stream))))))
1614 (defmethod print-object ((component code-component) stream)
1615 (print-unreadable-object (component stream :identity t)
1616 (let ((dinfo (%code-debug-info component)))
1617 (cond ((eq dinfo :bogus-lra)
1618 (write-string "bogus code object" stream))
1619 ((functionp dinfo)
1620 (format stream "trampoline ~S" dinfo))
1622 (format stream "code object [~D]" (code-n-entries component))
1623 (let ((fun-name (awhen (%code-entry-point component 0)
1624 (%simple-fun-name it))))
1625 (when fun-name
1626 (write-char #\Space stream)
1627 (write fun-name :stream stream))
1628 (cond ((not (typep dinfo 'sb!c::debug-info)))
1629 ((neq (sb!c::debug-info-name dinfo) fun-name)
1630 (write-string ", " stream)
1631 (output-object (sb!c::debug-info-name dinfo) stream)))))))))
1633 #!-(or x86 x86-64)
1634 (defmethod print-object ((lra lra) stream)
1635 (print-unreadable-object (lra stream :identity t)
1636 (write-string "return PC object" stream)))
1638 (defmethod print-object ((fdefn fdefn) stream)
1639 (print-unreadable-object (fdefn stream :type t)
1640 ;; As fdefn names are particularly relevant to those hacking on the compiler
1641 ;; and disassembler, be maximally helpful by neither abbreviating (SETF ...)
1642 ;; due to length cutoff, nor failing to print a package if needed.
1643 ;; Some folks seem to love same-named symbols way too much.
1644 (let ((*print-length* 20)) ; arbitrary
1645 (prin1 (fdefn-name fdefn) stream))))
1647 #!+sb-simd-pack
1648 (defmethod print-object ((pack simd-pack) stream)
1649 (cond ((and *print-readably* *read-eval*)
1650 (multiple-value-bind (format maker extractor)
1651 (etypecase pack
1652 ((simd-pack double-float)
1653 (values "#.(~S ~S ~S)"
1654 '%make-simd-pack-double #'%simd-pack-doubles))
1655 ((simd-pack single-float)
1656 (values "#.(~S ~S ~S ~S ~S)"
1657 '%make-simd-pack-single #'%simd-pack-singles))
1659 (values "#.(~S #X~16,'0X #X~16,'0X)"
1660 '%make-simd-pack-ub64 #'%simd-pack-ub64s)))
1661 (multiple-value-call
1662 #'format stream format maker (funcall extractor pack))))
1663 (*print-readably*
1664 (print-not-readable-error pack stream))
1666 (print-unreadable-object (pack stream)
1667 (flet ((all-ones-p (value start end &aux (mask (- (ash 1 end) (ash 1 start))))
1668 (= (logand value mask) mask))
1669 (split-num (value start)
1670 (loop
1671 for i from 0 to 3
1672 and v = (ash value (- start)) then (ash v -8)
1673 collect (logand v #xFF))))
1674 (multiple-value-bind (low high)
1675 (%simd-pack-ub64s pack)
1676 (etypecase pack
1677 ((simd-pack double-float)
1678 (multiple-value-bind (v0 v1) (%simd-pack-doubles pack)
1679 (format stream "~S~@{ ~:[~,13E~;~*TRUE~]~}"
1680 'simd-pack
1681 (all-ones-p low 0 64) v0
1682 (all-ones-p high 0 64) v1)))
1683 ((simd-pack single-float)
1684 (multiple-value-bind (v0 v1 v2 v3) (%simd-pack-singles pack)
1685 (format stream "~S~@{ ~:[~,7E~;~*TRUE~]~}"
1686 'simd-pack
1687 (all-ones-p low 0 32) v0
1688 (all-ones-p low 32 64) v1
1689 (all-ones-p high 0 32) v2
1690 (all-ones-p high 32 64) v3)))
1692 (format stream "~S~@{ ~{ ~2,'0X~}~}"
1693 'simd-pack
1694 (split-num low 0) (split-num low 32)
1695 (split-num high 0) (split-num high 32))))))))))
1697 ;;;; functions
1699 (defmethod print-object ((object function) stream)
1700 (let* ((name (%fun-name object))
1701 (proper-name-p (and (legal-fun-name-p name) (fboundp name)
1702 (eq (fdefinition name) object))))
1703 ;; ":TYPE T" is no good, since CLOSURE doesn't have full-fledged status.
1704 (print-unreadable-object (object stream :identity (not proper-name-p))
1705 (format stream "~A~@[ ~S~]"
1706 ;; TYPE-OF is so that GFs print as #<STANDARD-GENERIC-FUNCTION>
1707 ;; and not #<FUNCTION> before SRC;PCL;PRINT-OBJECT is loaded.
1708 (if (closurep object) 'closure (type-of object))
1709 name))))
1711 ;;;; catch-all for unknown things
1713 (defmethod print-object ((object t) stream)
1714 (flet ((output-it (stream)
1715 (when (eq object sb!pcl:+slot-unbound+)
1716 (print-unreadable-object (object stream)
1717 ;; If specifically the unbound marker with 0 data,
1718 ;; as opposed to any other unbound marker.
1719 (write-string "unbound" stream))
1720 (return-from output-it))
1721 (print-unreadable-object (object stream :identity t)
1722 (let ((lowtag (lowtag-of object)))
1723 (case lowtag
1724 (#.sb!vm:other-pointer-lowtag
1725 (let ((widetag (widetag-of object)))
1726 (case widetag
1727 (#.sb!vm:value-cell-widetag
1728 (write-string "value cell " stream)
1729 (output-object (value-cell-ref object) stream))
1731 (write-string "unknown pointer object, widetag=" stream)
1732 (output-integer widetag stream 16 t)))))
1733 ((#.sb!vm:fun-pointer-lowtag
1734 #.sb!vm:instance-pointer-lowtag
1735 #.sb!vm:list-pointer-lowtag)
1736 (write-string "unknown pointer object, lowtag=" stream)
1737 (output-integer lowtag stream 16 t))
1739 (case (widetag-of object)
1740 (#.sb!vm:unbound-marker-widetag
1741 (write-string "unbound marker" stream))
1743 (write-string "unknown immediate object, lowtag=" stream)
1744 (output-integer lowtag stream 2 t)
1745 (write-string ", widetag=" stream)
1746 (output-integer (widetag-of object) stream 16 t)))))))))
1747 (if *print-pretty*
1748 ;; This block might not be necessary. Not sure, probably can't hurt.
1749 (pprint-logical-block (stream nil) (output-it stream))
1750 (output-it stream))))