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