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