71644524020699e2ae7d9758ee8605c7ffbb9ab4
[sbcl.git] / src / code / print.lisp
1 ;;;; the printer
2
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.
11
12 (in-package "SB!IMPL")
13 \f
14 ;;;; exported printer control variables
15
16 ;;; FIXME: Many of these have nontrivial types, e.g. *PRINT-LEVEL*,
17 ;;; *PRINT-LENGTH*, and *PRINT-LINES* are (OR NULL UNSIGNED-BYTE).
18
19 (defvar *print-readably* nil
20   #!+sb-doc
21   "If true, all objects will printed readably. If readable printing is
22   impossible, an error will be signalled. This overrides the value of
23   *PRINT-ESCAPE*.")
24 (defvar *print-escape* T
25   #!+sb-doc
26   "Flag which indicates that slashification is on. See the manual")
27 (defvar *print-pretty* nil ; (set later when pretty-printer is initialized)
28   #!+sb-doc
29   "Flag which indicates that pretty printing is to be used")
30 (defvar *print-base* 10.
31   #!+sb-doc
32   "The output base for integers and rationals.")
33 (defvar *print-radix* nil
34   #!+sb-doc
35   "This flag requests to verify base when printing rationals.")
36 (defvar *print-level* nil
37   #!+sb-doc
38   "How many levels deep to print. Unlimited if null.")
39 (defvar *print-length* nil
40   #!+sb-doc
41   "How many elements to print on each level. Unlimited if null.")
42 (defvar *print-circle* nil
43   #!+sb-doc
44   "Whether to worry about circular list structures. See the manual.")
45 (defvar *print-case* :upcase
46   #!+sb-doc
47   "What kind of case the printer should use by default")
48 (defvar *print-array* t
49   #!+sb-doc
50   "Whether the array should print its guts out")
51 (defvar *print-gensym* t
52   #!+sb-doc
53   "If true, symbols with no home package are printed with a #: prefix.
54   If false, no prefix is printed.")
55 (defvar *print-lines* nil
56   #!+sb-doc
57   "The maximum number of lines to print. If NIL, unlimited.")
58 (defvar *print-right-margin* nil
59   #!+sb-doc
60   "The position of the right margin in ems. If NIL, try to determine this
61    from the stream in use.")
62 (defvar *print-miser-width* nil
63   #!+sb-doc
64   "If the remaining space between the current column and the right margin
65    is less than this, then print using ``miser-style'' output. Miser
66    style conditional newlines are turned on, and all indentations are
67    turned off. If NIL, never use miser mode.")
68 (defvar *print-pprint-dispatch* nil
69   #!+sb-doc
70   "The pprint-dispatch-table that controls how to pretty print objects. See
71    COPY-PPRINT-DISPATH, PPRINT-DISPATCH, and SET-PPRINT-DISPATCH.")
72
73 (defmacro with-standard-io-syntax (&body body)
74   #!+sb-doc
75   "Bind the reader and printer control variables to values that enable READ
76    to reliably read the results of PRINT. These values are:
77        *PACKAGE*                        the COMMON-LISP-USER package
78        *PRINT-ARRAY*                    T
79        *PRINT-BASE*                     10
80        *PRINT-CASE*                     :UPCASE
81        *PRINT-CIRCLE*                   NIL
82        *PRINT-ESCAPE*                   T
83        *PRINT-GENSYM*                   T
84        *PRINT-LENGTH*                   NIL
85        *PRINT-LEVEL*                    NIL
86        *PRINT-LINES*                    NIL
87        *PRINT-MISER-WIDTH*              NIL
88        *PRINT-PRETTY*                   NIL
89        *PRINT-RADIX*                    NIL
90        *PRINT-READABLY*                 T
91        *PRINT-RIGHT-MARGIN*             NIL
92        *READ-BASE*                      10
93        *READ-DEFAULT-FLOAT-FORMAT*      SINGLE-FLOAT
94        *READ-EVAL*                      T
95        *READ-SUPPRESS*                  NIL
96        *READTABLE*                      the standard readtable."
97   `(%with-standard-io-syntax #'(lambda () ,@body)))
98
99 (defun %with-standard-io-syntax (function)
100   (let ((*package* (find-package "COMMON-LISP-USER"))
101         (*print-array* t)
102         (*print-base* 10)
103         (*print-case* :upcase)
104         (*print-circle* nil)
105         (*print-escape* t)
106         (*print-gensym* t)
107         (*print-length* nil)
108         (*print-level* nil)
109         (*print-lines* nil)
110         (*print-miser-width* nil)
111         (*print-pretty* nil)
112         (*print-radix* nil)
113         (*print-readably* t)
114         (*print-right-margin* nil)
115         (*read-base* 10)
116         (*read-default-float-format* 'single-float)
117         (*read-eval* t)
118         (*read-suppress* nil)
119         ;; FIXME: It doesn't seem like a good idea to expose our
120         ;; disaster-recovery *STANDARD-READTABLE* here. Perhaps we
121         ;; should do a COPY-READTABLE? The consing would be unfortunate,
122         ;; though.
123         (*readtable* *standard-readtable*))
124     (funcall function)))
125 \f
126 ;;;; routines to print objects
127
128 (defun write (object &key
129                      ((:stream stream) *standard-output*)
130                      ((:escape *print-escape*) *print-escape*)
131                      ((:radix *print-radix*) *print-radix*)
132                      ((:base *print-base*) *print-base*)
133                      ((:circle *print-circle*) *print-circle*)
134                      ((:pretty *print-pretty*) *print-pretty*)
135                      ((:level *print-level*) *print-level*)
136                      ((:length *print-length*) *print-length*)
137                      ((:case *print-case*) *print-case*)
138                      ((:array *print-array*) *print-array*)
139                      ((:gensym *print-gensym*) *print-gensym*)
140                      ((:readably *print-readably*) *print-readably*)
141                      ((:right-margin *print-right-margin*)
142                       *print-right-margin*)
143                      ((:miser-width *print-miser-width*)
144                       *print-miser-width*)
145                      ((:lines *print-lines*) *print-lines*)
146                      ((:pprint-dispatch *print-pprint-dispatch*)
147                       *print-pprint-dispatch*))
148   #!+sb-doc
149   "Outputs OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*"
150   (output-object object (out-synonym-of stream))
151   object)
152
153 (defun prin1 (object &optional stream)
154   #!+sb-doc
155   "Outputs a mostly READable printed representation of OBJECT on the specified
156   STREAM."
157   (let ((*print-escape* T))
158     (output-object object (out-synonym-of stream)))
159   object)
160
161 (defun princ (object &optional stream)
162   #!+sb-doc
163   "Outputs an aesthetic but not necessarily READable printed representation
164   of OBJECT on the specified STREAM."
165   (let ((*print-escape* NIL)
166         (*print-readably* NIL))
167     (output-object object (out-synonym-of stream)))
168   object)
169
170 (defun print (object &optional stream)
171   #!+sb-doc
172   "Outputs a terpri, the mostly READable printed represenation of OBJECT, and
173   space to the specified STREAM."
174   (let ((stream (out-synonym-of stream)))
175     (terpri stream)
176     (prin1 object stream)
177     (write-char #\space stream)
178     object))
179
180 (defun pprint (object &optional stream)
181   #!+sb-doc
182   "Prettily outputs OBJECT preceded by a newline."
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))
189
190 (defun write-to-string
191        (object &key
192                ((:escape *print-escape*) *print-escape*)
193                ((:radix *print-radix*) *print-radix*)
194                ((:base *print-base*) *print-base*)
195                ((:circle *print-circle*) *print-circle*)
196                ((:pretty *print-pretty*) *print-pretty*)
197                ((:level *print-level*) *print-level*)
198                ((:length *print-length*) *print-length*)
199                ((:case *print-case*) *print-case*)
200                ((:array *print-array*) *print-array*)
201                ((:gensym *print-gensym*) *print-gensym*)
202                ((:readably *print-readably*) *print-readably*)
203                ((:right-margin *print-right-margin*) *print-right-margin*)
204                ((:miser-width *print-miser-width*) *print-miser-width*)
205                ((:lines *print-lines*) *print-lines*)
206                ((:pprint-dispatch *print-pprint-dispatch*)
207                 *print-pprint-dispatch*))
208   #!+sb-doc
209   "Returns the printed representation of OBJECT as a string."
210   (stringify-object object))
211
212 (defun prin1-to-string (object)
213   #!+sb-doc
214   "Returns the printed representation of OBJECT as a string with
215    slashification on."
216   (stringify-object object t))
217
218 (defun princ-to-string (object)
219   #!+sb-doc
220   "Returns the printed representation of OBJECT as a string with
221   slashification off."
222   (stringify-object object nil))
223
224 ;;; This produces the printed representation of an object as a string. The
225 ;;; few ...-TO-STRING functions above call this.
226 (defvar *string-output-streams* ())
227 (defun stringify-object (object &optional (*print-escape* *print-escape*))
228   (let ((stream (if *string-output-streams*
229                     (pop *string-output-streams*)
230                     (make-string-output-stream))))
231     (setup-printer-state)
232     (output-object object stream)
233     (prog1
234         (get-output-stream-string stream)
235       (push stream *string-output-streams*))))
236 \f
237 ;;;; support for the PRINT-UNREADABLE-OBJECT macro
238
239 ;;; guts of PRINT-UNREADABLE-OBJECT
240 (defun %print-unreadable-object (object stream type identity body)
241   (when *print-readably*
242     (error 'print-not-readable :object object))
243   (flet ((print-description ()
244            (when type
245              (write (type-of object) :stream stream :circle nil
246                     :level nil :length nil)
247              (when (or body identity)
248                (write-char #\space stream)
249                (pprint-newline :fill stream)))
250            (when body
251              (funcall body))
252            (when identity
253              (when body
254                (write-char #\space stream)
255                (pprint-newline :fill stream))
256              (write-char #\{ stream)
257              (write (get-lisp-obj-address object) :stream stream
258                     :radix nil :base 16)
259              (write-char #\} stream))))
260     (cond ((print-pretty-on-stream-p stream)
261            ;; Since we're printing prettily on STREAM, format the
262            ;; object within a logical block. PPRINT-LOGICAL-BLOCK does
263            ;; not rebind the stream when it is already a pretty stream,
264            ;; so output from the body will go to the same stream.
265            (pprint-logical-block (stream nil :prefix "#<" :suffix ">")
266              (print-description)))
267           (t
268             (write-string "#<" stream)
269             (print-description)
270             (write-char #\> stream))))
271   nil)
272 \f
273 ;;;; WHITESPACE-CHAR-P
274
275 ;;; This is used in other files, but is defined in this one for some reason.
276
277 (defun whitespace-char-p (char)
278   #!+sb-doc
279   "Determines whether or not the character is considered whitespace."
280   (or (char= char #\space)
281       (char= char (code-char tab-char-code))
282       (char= char (code-char return-char-code))
283       (char= char #\linefeed)))
284 \f
285 ;;;; circularity detection stuff
286
287 ;;; When *PRINT-CIRCLE* is T, this gets bound to a hash table that (eventually)
288 ;;; ends up with entries for every object printed. When we are initially
289 ;;; looking for circularities, we enter a T when we find an object for the
290 ;;; first time, and a 0 when we encounter an object a second time around.
291 ;;; When we are actually printing, the 0 entries get changed to the actual
292 ;;; marker value when they are first printed.
293 (defvar *circularity-hash-table* nil)
294
295 ;;; When NIL, we are just looking for circularities. After we have found them
296 ;;; all, this gets bound to 0. Then whenever we need a new marker, it is
297 ;;; incremented.
298 (defvar *circularity-counter* nil)
299
300 (defun check-for-circularity (object &optional assign)
301   #!+sb-doc
302   "Check to see whether OBJECT is a circular reference, and return something
303    non-NIL if it is. If ASSIGN is T, then the number to use in the #n= and
304    #n# noise is assigned at this time. Note: CHECK-FOR-CIRCULARITY must
305    be called *EXACTLY* once with ASSIGN T, or the circularity detection noise
306    will get confused about when to use #n= and when to use #n#. If this
307    returns non-NIL when ASSIGN is T, then you must call HANDLE-CIRCULARITY
308    on it. If you are not using this inside a WITH-CIRCULARITY-DETECTION,
309    then you have to be prepared to handle a return value of :INITIATE which
310    means it needs to initiate the circularity detection noise. See the
311    source for info on how to do that."
312   (cond ((null *print-circle*)
313          ;; Don't bother, nobody cares.
314          nil)
315         ((null *circularity-hash-table*)
316          :initiate)
317         ((null *circularity-counter*)
318          (ecase (gethash object *circularity-hash-table*)
319            ((nil)
320             ;; First encounter.
321             (setf (gethash object *circularity-hash-table*) t)
322             ;; We need to keep looking.
323             nil)
324            ((t)
325             ;; Second encounter.
326             (setf (gethash object *circularity-hash-table*) 0)
327             ;; It's a circular reference.
328             t)
329            (0
330             ;; It's a circular reference.
331             t)))
332         (t
333          (let ((value (gethash object *circularity-hash-table*)))
334            (case value
335              ((nil t)
336               ;; If NIL, we found an object that wasn't there the first time
337               ;; around. If T, exactly one occurance of this object appears.
338               ;; Either way, just print the thing without any special
339               ;; processing. Note: you might argue that finding a new object
340               ;; means that something is broken, but this can happen. If
341               ;; someone uses the ~@<...~:> format directive, it conses a
342               ;; new list each time though format (i.e. the &REST list), so
343               ;; we will have different cdrs.
344               nil)
345              (0
346               (if assign
347                   (let ((value (incf *circularity-counter*)))
348                     ;; First occurance of this object. Set the counter.
349                     (setf (gethash object *circularity-hash-table*) value)
350                     value)
351                   t))
352              (t
353               ;; Second or later occurance.
354               (- value)))))))
355
356 (defun handle-circularity (marker stream)
357   #!+sb-doc
358   "Handle the results of CHECK-FOR-CIRCULARITY. If this returns T then
359    you should go ahead and print the object. If it returns NIL, then
360    you should blow it off."
361   (case marker
362     (:initiate
363      ;; Someone forgot to initiate circularity detection.
364      (let ((*print-circle* nil))
365        (error "trying to use CHECK-FOR-CIRCULARITY when ~
366                circularity checking isn't initiated")))
367     ((t)
368      ;; It's a second (or later) reference to the object while we are
369      ;; just looking. So don't bother groveling it again.
370      nil)
371     (t
372      (write-char #\# stream)
373      (let ((*print-base* 10) (*print-radix* nil))
374        (cond ((minusp marker)
375               (output-integer (- marker) stream)
376               (write-char #\# stream)
377               nil)
378              (t
379               (output-integer marker stream)
380               (write-char #\= stream)
381               t))))))
382 \f
383 ;;;; OUTPUT-OBJECT -- the main entry point
384
385 (defvar *pretty-printer* nil
386   #!+sb-doc
387   "The current pretty printer. Should be either a function that takes two
388    arguments (the object and the stream) or NIL to indicate that there is
389    no pretty printer installed.")
390
391 (defun output-object (object stream)
392   #!+sb-doc
393   "Output OBJECT to STREAM observing all printer control variables."
394   (labels ((print-it (stream)
395              (if *print-pretty*
396                  (if *pretty-printer*
397                      (funcall *pretty-printer* object stream)
398                      (let ((*print-pretty* nil))
399                        (output-ugly-object object stream)))
400                  (output-ugly-object object stream)))
401            (check-it (stream)
402              (let ((marker (check-for-circularity object t)))
403                (case marker
404                  (:initiate
405                   (let ((*circularity-hash-table*
406                          (make-hash-table :test 'eq)))
407                     (check-it (make-broadcast-stream))
408                     (let ((*circularity-counter* 0))
409                       (check-it stream))))
410                  ((nil)
411                   (print-it stream))
412                  (t
413                   (when (handle-circularity marker stream)
414                     (print-it stream)))))))
415     (cond ((or (not *print-circle*)
416                (numberp object)
417                (characterp object)
418                (and (symbolp object) (symbol-package object) t))
419            ;; If it a number, character, or interned symbol, we do not want
420            ;; to check for circularity/sharing.
421            (print-it stream))
422           ((or *circularity-hash-table*
423                (consp object)
424                (typep object 'instance)
425                (typep object '(array t *)))
426            ;; If we have already started circularity detection, this object
427            ;; might be a sharded reference. If we have not, then if it is
428            ;; a cons, a instance, or an array of element type t it might
429            ;; contain a circular reference to itself or multiple shared
430            ;; references.
431            (check-it stream))
432           (t
433            (print-it stream)))))
434
435 (defun output-ugly-object (object stream)
436   #!+sb-doc
437   "Output OBJECT to STREAM observing all printer control variables except
438    for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL, then the pretty
439    printer will be used for any components of OBJECT, just not for OBJECT
440    itself."
441   (typecase object
442     ;; KLUDGE: The TYPECASE approach here is non-ANSI; the ANSI definition of
443     ;; PRINT-OBJECT says it provides printing and we're supposed to provide
444     ;; PRINT-OBJECT methods covering all classes. We deviate from this
445     ;; by using PRINT-OBJECT only when we print instance values. However,
446     ;; ANSI makes it hard to tell that we're deviating from this:
447     ;;   (1) ANSI specifies that the user isn't supposed to call PRINT-OBJECT
448     ;;       directly.
449     ;;   (2) ANSI (section 11.1.2.1.2) says it's undefined to define
450     ;;       a method on an external symbol in the CL package which is
451     ;;       applicable to arg lists containing only direct instances of
452     ;;       standardized classes.
453     ;; Thus, in order for the user to detect our sleaziness, he has to do
454     ;; something relatively obscure like
455     ;;   (1) actually use tools like FIND-METHOD to look for PRINT-OBJECT
456     ;;       methods, or
457     ;;   (2) define a PRINT-OBJECT method which is specialized on the stream
458     ;;       value (e.g. a Gray stream object).
459     ;; As long as no one comes up with a non-obscure way of detecting this
460     ;; sleaziness, fixing this nonconformity will probably have a low
461     ;; priority. -- WHN 20000121
462     (fixnum
463      (output-integer object stream))
464     (list
465      (if (null object)
466          (output-symbol object stream)
467          (output-list object stream)))
468     (instance
469      (print-object object stream))
470     (function
471      (unless (and (funcallable-instance-p object)
472                   (printed-as-funcallable-standard-class object stream))
473        (output-function object stream)))
474     (symbol
475      (output-symbol object stream))
476     (number
477      (etypecase object
478        (integer
479         (output-integer object stream))
480        (float
481         (output-float object stream))
482        (ratio
483         (output-ratio object stream))
484        (ratio
485         (output-ratio object stream))
486        (complex
487         (output-complex object stream))))
488     (character
489      (output-character object stream))
490     (vector
491      (output-vector object stream))
492     (array
493      (output-array object stream))
494     (system-area-pointer
495      (output-sap object stream))
496     (weak-pointer
497      (output-weak-pointer object stream))
498     (lra
499      (output-lra object stream))
500     (code-component
501      (output-code-component object stream))
502     (fdefn
503      (output-fdefn object stream))
504     (t
505      (output-random object stream))))
506 \f
507 ;;;; symbols
508
509 ;;; Values of *PRINT-CASE* and (READTABLE-CASE *READTABLE*) the last time the
510 ;;; printer was called.
511 (defvar *previous-case* nil)
512 (defvar *previous-readtable-case* nil)
513
514 ;;; This variable contains the current definition of one of three symbol
515 ;;; printers. SETUP-PRINTER-STATE sets this variable.
516 (defvar *internal-symbol-output-function* nil)
517
518 ;;; This function sets the internal global symbol
519 ;;; *INTERNAL-SYMBOL-OUTPUT-FUNCTION* to the right function depending
520 ;;; on the value of *PRINT-CASE*. See the manual for details. The
521 ;;; print buffer stream is also reset.
522 (defun setup-printer-state ()
523   (unless (and (eq *print-case* *previous-case*)
524                (eq (readtable-case *readtable*) *previous-readtable-case*))
525     (setq *previous-case* *print-case*)
526     (setq *previous-readtable-case* (readtable-case *readtable*))
527     (unless (member *print-case* '(:upcase :downcase :capitalize))
528       (setq *print-case* :upcase)
529       (error "invalid *PRINT-CASE* value: ~S" *previous-case*))
530     (unless (member *previous-readtable-case*
531                     '(:upcase :downcase :invert :preserve))
532       (setf (readtable-case *readtable*) :upcase)
533       (error "invalid READTABLE-CASE value: ~S" *previous-readtable-case*))
534
535     (setq *internal-symbol-output-function*
536           (case *previous-readtable-case*
537             (:upcase
538              (case *print-case*
539                (:upcase #'output-preserve-symbol)
540                (:downcase #'output-lowercase-symbol)
541                (:capitalize #'output-capitalize-symbol)))
542             (:downcase
543              (case *print-case*
544                (:upcase #'output-uppercase-symbol)
545                (:downcase #'output-preserve-symbol)
546                (:capitalize #'output-capitalize-symbol)))
547             (:preserve #'output-preserve-symbol)
548             (:invert #'output-invert-symbol)))))
549
550 ;;; Output PNAME (a symbol-name or package-name) surrounded with |'s,
551 ;;; and with any embedded |'s or \'s escaped.
552 (defun output-quoted-symbol-name (pname stream)
553   (write-char #\| stream)
554   (dotimes (index (length pname))
555     (let ((char (schar pname index)))
556       (when (or (char= char #\\) (char= char #\|))
557         (write-char #\\ stream))
558       (write-char char stream)))
559   (write-char #\| stream))
560
561 (defun output-symbol (object stream)
562   (if (or *print-escape* *print-readably*)
563       (let ((package (symbol-package object))
564             (name (symbol-name object)))
565         (cond
566          ;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
567          ;; requires that keywords be printed with preceding colons
568          ;; always, regardless of the value of *PACKAGE*.
569          ((eq package *keyword-package*)
570           (write-char #\: stream))
571          ;; Otherwise, if the symbol's home package is the current
572          ;; one, then a prefix is never necessary.
573          ((eq package (sane-package)))
574          ;; Uninterned symbols print with a leading #:.
575          ((null package)
576           (when (or *print-gensym* *print-readably*)
577             (write-string "#:" stream)))
578          (t
579           (multiple-value-bind (symbol accessible)
580               (find-symbol name (sane-package))
581             ;; If we can find the symbol by looking it up, it need not
582             ;; be qualified. This can happen if the symbol has been
583             ;; inherited from a package other than its home package.
584             (unless (and accessible (eq symbol object))
585               (output-symbol-name (package-name package) stream)
586               (multiple-value-bind (symbol externalp)
587                   (find-external-symbol name package)
588                 (declare (ignore symbol))
589                 (if externalp
590                     (write-char #\: stream)
591                     (write-string "::" stream)))))))
592         (output-symbol-name name stream))
593       (output-symbol-name (symbol-name object) stream nil)))
594
595 ;;; Output the string NAME as if it were a symbol name. In other words,
596 ;;; diddle its case according to *PRINT-CASE* and READTABLE-CASE.
597 (defun output-symbol-name (name stream &optional (maybe-quote t))
598   (declare (type simple-base-string name))
599   (setup-printer-state)
600   (if (and maybe-quote (symbol-quotep name))
601       (output-quoted-symbol-name name stream)
602       (funcall *internal-symbol-output-function* name stream)))
603 \f
604 ;;;; escaping symbols
605
606 ;;; When we print symbols we have to figure out if they need to be
607 ;;; printed with escape characters. This isn't a whole lot easier than
608 ;;; reading symbols in the first place.
609 ;;;
610 ;;; For each character, the value of the corresponding element is a
611 ;;; fixnum with bits set corresponding to attributes that the
612 ;;; character has. At characters have at least one bit set, so we can
613 ;;; search for any character with a positive test.
614 (defvar *character-attributes*
615   (make-array char-code-limit :element-type '(unsigned-byte 16)
616               :initial-element 0))
617 (declaim (type (simple-array (unsigned-byte 16) (#.char-code-limit))
618                *character-attributes*))
619
620 ;;; Constants which are a bit-mask for each interesting character attribute.
621 (defconstant other-attribute            (ash 1 0)) ; Anything else legal.
622 (defconstant number-attribute           (ash 1 1)) ; A numeric digit.
623 (defconstant uppercase-attribute        (ash 1 2)) ; An uppercase letter.
624 (defconstant lowercase-attribute        (ash 1 3)) ; A lowercase letter.
625 (defconstant sign-attribute             (ash 1 4)) ; +-
626 (defconstant extension-attribute        (ash 1 5)) ; ^_
627 (defconstant dot-attribute              (ash 1 6)) ; .
628 (defconstant slash-attribute            (ash 1 7)) ; /
629 (defconstant funny-attribute            (ash 1 8)) ; Anything illegal.
630
631 (eval-when (:compile-toplevel :load-toplevel :execute)
632
633 ;;; LETTER-ATTRIBUTE is a local of SYMBOL-QUOTEP. It matches letters
634 ;;; that don't need to be escaped (according to READTABLE-CASE.)
635 (defparameter *attribute-names*
636   `((number . number-attribute) (lowercase . lowercase-attribute)
637     (uppercase . uppercase-attribute) (letter . letter-attribute)
638     (sign . sign-attribute) (extension . extension-attribute)
639     (dot . dot-attribute) (slash . slash-attribute)
640     (other . other-attribute) (funny . funny-attribute)))
641
642 ) ; EVAL-WHEN
643
644 (flet ((set-bit (char bit)
645          (let ((code (char-code char)))
646            (setf (aref *character-attributes* code)
647                  (logior bit (aref *character-attributes* code))))))
648
649   (dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
650                   #\? #\< #\>))
651     (set-bit char other-attribute))
652
653   (dotimes (i 10)
654     (set-bit (digit-char i) number-attribute))
655
656   (do ((code (char-code #\A) (1+ code))
657        (end (char-code #\Z)))
658       ((> code end))
659     (declare (fixnum code end))
660     (set-bit (code-char code) uppercase-attribute)
661     (set-bit (char-downcase (code-char code)) lowercase-attribute))
662
663   (set-bit #\- sign-attribute)
664   (set-bit #\+ sign-attribute)
665   (set-bit #\^ extension-attribute)
666   (set-bit #\_ extension-attribute)
667   (set-bit #\. dot-attribute)
668   (set-bit #\/ slash-attribute)
669
670   ;; Mark anything not explicitly allowed as funny.
671   (dotimes (i char-code-limit)
672     (when (zerop (aref *character-attributes* i))
673       (setf (aref *character-attributes* i) funny-attribute))))
674
675 ;;; For each character, the value of the corresponding element is the lowest
676 ;;; base in which that character is a digit.
677 (defvar *digit-bases*
678   (make-array char-code-limit
679               :element-type '(unsigned-byte 8)
680               :initial-element 36))
681 (declaim (type (simple-array (unsigned-byte 8) (#.char-code-limit))
682                *digit-bases*))
683
684 (dotimes (i 36)
685   (let ((char (digit-char i 36)))
686     (setf (aref *digit-bases* (char-code char)) i)))
687
688 ;;; A FSM-like thingie that determines whether a symbol is a potential
689 ;;; number or has evil characters in it.
690 (defun symbol-quotep (name)
691   (declare (simple-string name))
692   (macrolet ((advance (tag &optional (at-end t))
693                `(progn
694                  (when (= index len)
695                    ,(if at-end '(go TEST-SIGN) '(return nil)))
696                  (setq current (schar name index)
697                        code (char-code current)
698                        bits (aref attributes code))
699                  (incf index)
700                  (go ,tag)))
701              (test (&rest attributes)
702                 `(not (zerop
703                        (the fixnum
704                             (logand
705                              (logior ,@(mapcar
706                                         (lambda (x)
707                                           (or (cdr (assoc x
708                                                           *attribute-names*))
709                                               (error "Blast!")))
710                                         attributes))
711                              bits)))))
712              (digitp ()
713                `(< (the fixnum (aref bases code)) base)))
714
715     (prog ((len (length name))
716            (attributes *character-attributes*)
717            (bases *digit-bases*)
718            (base *print-base*)
719            (letter-attribute
720             (case (readtable-case *readtable*)
721               (:upcase uppercase-attribute)
722               (:downcase lowercase-attribute)
723               (t (logior lowercase-attribute uppercase-attribute))))
724            (index 0)
725            (bits 0)
726            (code 0)
727            current)
728       (declare (fixnum len base index bits code))
729       (advance START t)
730
731      TEST-SIGN ; At end, see whether it is a sign...
732       (return (not (test sign)))
733
734      OTHER ; Not potential number, see whether funny chars...
735       (let ((mask (logxor (logior lowercase-attribute uppercase-attribute
736                                   funny-attribute)
737                           letter-attribute)))
738         (do ((i (1- index) (1+ i)))
739             ((= i len) (return-from symbol-quotep nil))
740           (unless (zerop (logand (aref attributes (char-code (schar name i)))
741                                  mask))
742             (return-from symbol-quotep t))))
743
744      START
745       (when (digitp)
746         (if (test letter)
747             (advance LAST-DIGIT-ALPHA)
748             (advance DIGIT)))
749       (when (test letter number other slash) (advance OTHER nil))
750       (when (char= current #\.) (advance DOT-FOUND))
751       (when (test sign extension) (advance START-STUFF nil))
752       (return t)
753
754      DOT-FOUND ; Leading dots...
755       (when (test letter) (advance START-DOT-MARKER nil))
756       (when (digitp) (advance DOT-DIGIT))
757       (when (test number other) (advance OTHER nil))
758       (when (test extension slash sign) (advance START-DOT-STUFF nil))
759       (when (char= current #\.) (advance DOT-FOUND))
760       (return t)
761
762      START-STUFF ; Leading stuff before any dot or digit.
763       (when (digitp)
764         (if (test letter)
765             (advance LAST-DIGIT-ALPHA)
766             (advance DIGIT)))
767       (when (test number other) (advance OTHER nil))
768       (when (test letter) (advance START-MARKER nil))
769       (when (char= current #\.) (advance START-DOT-STUFF nil))
770       (when (test sign extension slash) (advance START-STUFF nil))
771       (return t)
772
773      START-MARKER ; Number marker in leading stuff...
774       (when (test letter) (advance OTHER nil))
775       (go START-STUFF)
776
777      START-DOT-STUFF ; Leading stuff containing dot w/o digit...
778       (when (test letter) (advance START-DOT-STUFF nil))
779       (when (digitp) (advance DOT-DIGIT))
780       (when (test sign extension dot slash) (advance START-DOT-STUFF nil))
781       (when (test number other) (advance OTHER nil))
782       (return t)
783
784      START-DOT-MARKER ; Number marker in leading stuff w/ dot..
785       ;; Leading stuff containing dot w/o digit followed by letter...
786       (when (test letter) (advance OTHER nil))
787       (go START-DOT-STUFF)
788
789      DOT-DIGIT ; In a thing with dots...
790       (when (test letter) (advance DOT-MARKER))
791       (when (digitp) (advance DOT-DIGIT))
792       (when (test number other) (advance OTHER nil))
793       (when (test sign extension dot slash) (advance DOT-DIGIT))
794       (return t)
795
796      DOT-MARKER ; Number maker in number with dot...
797       (when (test letter) (advance OTHER nil))
798       (go DOT-DIGIT)
799
800      LAST-DIGIT-ALPHA ; Previous char is a letter digit...
801       (when (or (digitp) (test sign slash))
802         (advance ALPHA-DIGIT))
803       (when (test letter number other dot) (advance OTHER nil))
804       (return t)
805
806      ALPHA-DIGIT ; Seen a digit which is a letter...
807       (when (or (digitp) (test sign slash))
808         (if (test letter)
809             (advance LAST-DIGIT-ALPHA)
810             (advance ALPHA-DIGIT)))
811       (when (test letter) (advance ALPHA-MARKER))
812       (when (test number other dot) (advance OTHER nil))
813       (return t)
814
815      ALPHA-MARKER ; Number marker in number with alpha digit...
816       (when (test letter) (advance OTHER nil))
817       (go ALPHA-DIGIT)
818
819      DIGIT ; Seen only real numeric digits...
820       (when (digitp)
821         (if (test letter)
822             (advance ALPHA-DIGIT)
823             (advance DIGIT)))
824       (when (test number other) (advance OTHER nil))
825       (when (test letter) (advance MARKER))
826       (when (test extension slash sign) (advance DIGIT))
827       (when (char= current #\.) (advance DOT-DIGIT))
828       (return t)
829
830      MARKER ; Number marker in a numeric number...
831       (when (test letter) (advance OTHER nil))
832       (go DIGIT))))
833 \f
834 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUNCTION*
835 ;;;;
836 ;;;; Case hackery. These functions are stored in
837 ;;;; *INTERNAL-SYMBOL-OUTPUT-FUNCTION* according to the values of *PRINT-CASE*
838 ;;;; and READTABLE-CASE.
839
840 ;; Called when:
841 ;; READTABLE-CASE       *PRINT-CASE*
842 ;; :UPCASE              :UPCASE
843 ;; :DOWNCASE            :DOWNCASE
844 ;; :PRESERVE            any
845 (defun output-preserve-symbol (pname stream)
846   (declare (simple-string pname))
847   (write-string pname stream))
848
849 ;; Called when:
850 ;; READTABLE-CASE       *PRINT-CASE*
851 ;; :UPCASE              :DOWNCASE
852 (defun output-lowercase-symbol (pname stream)
853   (declare (simple-string pname))
854   (dotimes (index (length pname))
855     (let ((char (schar pname index)))
856       (write-char (char-downcase char) stream))))
857
858 ;; Called when:
859 ;; READTABLE-CASE       *PRINT-CASE*
860 ;; :DOWNCASE            :UPCASE
861 (defun output-uppercase-symbol (pname stream)
862   (declare (simple-string pname))
863   (dotimes (index (length pname))
864     (let ((char (schar pname index)))
865       (write-char (char-upcase char) stream))))
866
867 ;; Called when:
868 ;; READTABLE-CASE       *PRINT-CASE*
869 ;; :UPCASE              :CAPITALIZE
870 ;; :DOWNCASE            :CAPITALIZE
871 (defun output-capitalize-symbol (pname stream)
872   (declare (simple-string pname))
873   (let ((prev-not-alpha t)
874         (up (eq (readtable-case *readtable*) :upcase)))
875     (dotimes (i (length pname))
876       (let ((char (char pname i)))
877         (write-char (if up
878                         (if (or prev-not-alpha (lower-case-p char))
879                             char
880                             (char-downcase char))
881                         (if prev-not-alpha
882                             (char-upcase char)
883                             char))
884                     stream)
885         (setq prev-not-alpha (not (alpha-char-p char)))))))
886
887 ;; Called when:
888 ;; READTABLE-CASE       *PRINT-CASE*
889 ;; :INVERT              any
890 (defun output-invert-symbol (pname stream)
891   (declare (simple-string pname))
892   (let ((all-upper t)
893         (all-lower t))
894     (dotimes (i (length pname))
895       (let ((ch (schar pname i)))
896         (when (both-case-p ch)
897           (if (upper-case-p ch)
898               (setq all-lower nil)
899               (setq all-upper nil)))))
900     (cond (all-upper (output-lowercase-symbol pname stream))
901           (all-lower (output-uppercase-symbol pname stream))
902           (t
903            (write-string pname stream)))))
904
905 #|
906 (defun test1 ()
907   (let ((*readtable* (copy-readtable nil)))
908     (format t "READTABLE-CASE  Input   Symbol-name~@
909                ----------------------------------~%")
910     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
911       (setf (readtable-case *readtable*) readtable-case)
912       (dolist (input '("ZEBRA" "Zebra" "zebra"))
913         (format t "~&:~A~16T~A~24T~A"
914                 (string-upcase readtable-case)
915                 input
916                 (symbol-name (read-from-string input)))))))
917
918 (defun test2 ()
919   (let ((*readtable* (copy-readtable nil)))
920     (format t "READTABLE-CASE  *PRINT-CASE*  Symbol-name  Output  Princ~@
921                --------------------------------------------------------~%")
922     (dolist (readtable-case '(:upcase :downcase :preserve :invert))
923       (setf (readtable-case *readtable*) readtable-case)
924       (dolist (*print-case* '(:upcase :downcase :capitalize))
925         (dolist (symbol '(|ZEBRA| |Zebra| |zebra|))
926           (format t "~&:~A~15T:~A~29T~A~42T~A~50T~A"
927                   (string-upcase readtable-case)
928                   (string-upcase *print-case*)
929                   (symbol-name symbol)
930                   (prin1-to-string symbol)
931                   (princ-to-string symbol)))))))
932 |#
933 \f
934 ;;;; recursive objects
935
936 (defun output-list (list stream)
937   (descend-into (stream)
938     (write-char #\( stream)
939     (let ((length 0)
940           (list list))
941       (loop
942         (punt-print-if-too-long length stream)
943         (output-object (pop list) stream)
944         (unless list
945           (return))
946         (when (or (atom list) (check-for-circularity list))
947           (write-string " . " stream)
948           (output-object list stream)
949           (return))
950         (write-char #\space stream)
951         (incf length)))
952     (write-char #\) stream)))
953
954 (defun output-vector (vector stream)
955   (declare (vector vector))
956   (cond ((stringp vector)
957          (cond ((or *print-escape* *print-readably*)
958                 (write-char #\" stream)
959                 (quote-string vector stream)
960                 (write-char #\" stream))
961                (t
962                 (write-string vector stream))))
963         ((not (or *print-array* *print-readably*))
964          (output-terse-array vector stream))
965         ((bit-vector-p vector)
966          (write-string "#*" stream)
967          (dotimes (i (length vector))
968            (output-object (aref vector i) stream)))
969         (t
970          (when (and *print-readably*
971                     (not (eq (array-element-type vector) 't)))
972            (error 'print-not-readable :object vector))
973          (descend-into (stream)
974                        (write-string "#(" stream)
975                        (dotimes (i (length vector))
976                          (unless (zerop i)
977                            (write-char #\space stream))
978                          (punt-print-if-too-long i stream)
979                          (output-object (aref vector i) stream))
980                        (write-string ")" stream)))))
981
982 ;;; This function outputs a string quoting characters sufficiently
983 ;;; that so someone can read it in again. Basically, put a slash in
984 ;;; front of an character satisfying NEEDS-SLASH-P.
985 (defun quote-string (string stream)
986   (macrolet ((needs-slash-p (char)
987                ;; KLUDGE: We probably should look at the readtable, but just do
988                ;; this for now. [noted by anonymous long ago] -- WHN 19991130
989                `(or (char= ,char #\\)
990                  (char= ,char #\"))))
991     (with-array-data ((data string) (start) (end (length string)))
992       (do ((index start (1+ index)))
993           ((>= index end))
994         (let ((char (schar data index)))
995           (when (needs-slash-p char) (write-char #\\ stream))
996           (write-char char stream))))))
997
998 (defun output-array (array stream)
999   #!+sb-doc
1000   "Outputs the printed representation of any array in either the #< or #A
1001    form."
1002   (if (or *print-array* *print-readably*)
1003       (output-array-guts array stream)
1004       (output-terse-array array stream)))
1005
1006 ;;; to output the abbreviated #< form of an array
1007 (defun output-terse-array (array stream)
1008   (let ((*print-level* nil)
1009         (*print-length* nil))
1010     (print-unreadable-object (array stream :type t :identity t))))
1011
1012 ;;; to output the readable #A form of an array
1013 (defun output-array-guts (array stream)
1014   (when (and *print-readably*
1015              (not (eq (array-element-type array) t)))
1016     (error 'print-not-readable :object array))
1017   (write-char #\# stream)
1018   (let ((*print-base* 10))
1019     (output-integer (array-rank array) stream))
1020   (write-char #\A stream)
1021   (with-array-data ((data array) (start) (end))
1022     (declare (ignore end))
1023     (sub-output-array-guts data (array-dimensions array) stream start)))
1024
1025 (defun sub-output-array-guts (array dimensions stream index)
1026   (declare (type (simple-array * (*)) array) (fixnum index))
1027   (cond ((null dimensions)
1028          (output-object (aref array index) stream))
1029         (t
1030          (descend-into (stream)
1031            (write-char #\( stream)
1032            (let* ((dimension (car dimensions))
1033                   (dimensions (cdr dimensions))
1034                   (count (reduce #'* dimensions)))
1035              (dotimes (i dimension)
1036                (unless (zerop i)
1037                  (write-char #\space stream))
1038                (punt-print-if-too-long i stream)
1039                (sub-output-array-guts array dimensions stream index)
1040                (incf index count)))
1041            (write-char #\) stream)))))
1042
1043 ;;; a trivial non-generic-function placeholder for PRINT-OBJECT, for
1044 ;;; use until CLOS is set up (at which time it will be replaced with
1045 ;;; the real generic function implementation)
1046 (defun print-object (instance stream)
1047   (default-structure-print instance stream *current-level*))
1048 \f
1049 ;;;; integer, ratio, and complex printing (i.e. everything but floats)
1050
1051 (defun output-integer (integer stream)
1052   ;; FIXME: This UNLESS form should be pulled out into something like
1053   ;; (SANE-PRINT-BASE), along the lines of (SANE-PACKAGE) for the
1054   ;; *PACKAGE* variable.
1055   (unless (and (fixnump *print-base*)
1056                (< 1 *print-base* 37))
1057     (let ((obase *print-base*))
1058       (setq *print-base* 10.)
1059       (error "~A is not a reasonable value for *PRINT-BASE*." obase)))
1060   (when (and (not (= *print-base* 10.))
1061              *print-radix*)
1062     ;; First print leading base information, if any.
1063     (write-char #\# stream)
1064     (write-char (case *print-base*
1065                   (2. #\b)
1066                   (8. #\o)
1067                   (16. #\x)
1068                   (T (let ((fixbase *print-base*)
1069                            (*print-base* 10.)
1070                            (*print-radix* ()))
1071                        (sub-output-integer fixbase stream))
1072                      #\r))
1073                 stream))
1074   ;; Then output a minus sign if the number is negative, then output
1075   ;; the absolute value of the number.
1076   (cond ((bignump integer) (print-bignum integer stream))
1077         ((< integer 0)
1078          (write-char #\- stream)
1079          (sub-output-integer (- integer) stream))
1080         (t
1081          (sub-output-integer integer stream)))
1082   ;; Print any trailing base information, if any.
1083   (if (and (= *print-base* 10.) *print-radix*)
1084       (write-char #\. stream)))
1085
1086 (defun sub-output-integer (integer stream)
1087   (let ((quotient ())
1088         (remainder ()))
1089     ;; Recurse until you have all the digits pushed on the stack.
1090     (if (not (zerop (multiple-value-setq (quotient remainder)
1091                       (truncate integer *print-base*))))
1092         (sub-output-integer quotient stream))
1093     ;; Then as each recursive call unwinds, turn the digit (in remainder)
1094     ;; into a character and output the character.
1095     (write-char (code-char (if (and (> remainder 9.)
1096                                     (> *print-base* 10.))
1097                                (+ (char-code #\A) (- remainder 10.))
1098                                (+ (char-code #\0) remainder)))
1099                 stream)))
1100 \f
1101 ;;;; bignum printing
1102 ;;;;
1103 ;;;; written by Steven Handerson (based on Skef's idea)
1104 ;;;;
1105 ;;;; rewritten to remove assumptions about the length of fixnums for the
1106 ;;;; MIPS port by William Lott
1107
1108 ;;; *BASE-POWER* holds the number that we keep dividing into the bignum for
1109 ;;; each *print-base*. We want this number as close to *most-positive-fixnum*
1110 ;;; as possible, i.e. (floor (log most-positive-fixnum *print-base*)).
1111 (defparameter *base-power* (make-array 37 :initial-element nil))
1112
1113 ;;; *FIXNUM-POWER--1* holds the number of digits for each *print-base* that
1114 ;;; fit in the corresponding *base-power*.
1115 (defparameter *fixnum-power--1* (make-array 37 :initial-element nil))
1116
1117 ;;; Print the bignum to the stream. We first generate the correct value for
1118 ;;; *base-power* and *fixnum-power--1* if we have not already. Then we call
1119 ;;; bignum-print-aux to do the printing.
1120 (defun print-bignum (big stream)
1121   (unless (aref *base-power* *print-base*)
1122     (do ((power-1 -1 (1+ power-1))
1123          (new-divisor *print-base* (* new-divisor *print-base*))
1124          (divisor 1 new-divisor))
1125         ((not (fixnump new-divisor))
1126          (setf (aref *base-power* *print-base*) divisor)
1127          (setf (aref *fixnum-power--1* *print-base*) power-1))))
1128   (bignum-print-aux (cond ((minusp big)
1129                            (write-char #\- stream)
1130                            (- big))
1131                           (t big))
1132                     (aref *base-power* *print-base*)
1133                     (aref *fixnum-power--1* *print-base*)
1134                     stream)
1135   big)
1136
1137 (defun bignum-print-aux (big divisor power-1 stream)
1138   (multiple-value-bind (newbig fix) (truncate big divisor)
1139     (if (fixnump newbig)
1140         (sub-output-integer newbig stream)
1141         (bignum-print-aux newbig divisor power-1 stream))
1142     (do ((zeros power-1 (1- zeros))
1143          (base-power *print-base* (* base-power *print-base*)))
1144         ((> base-power fix)
1145          (dotimes (i zeros) (write-char #\0 stream))
1146          (sub-output-integer fix stream)))))
1147
1148 (defun output-ratio (ratio stream)
1149   (when *print-radix*
1150     (write-char #\# stream)
1151     (case *print-base*
1152       (2 (write-char #\b stream))
1153       (8 (write-char #\o stream))
1154       (16 (write-char #\x stream))
1155       (t (write *print-base* :stream stream :radix nil :base 10)))
1156     (write-char #\r stream))
1157   (let ((*print-radix* nil))
1158     (output-integer (numerator ratio) stream)
1159     (write-char #\/ stream)
1160     (output-integer (denominator ratio) stream)))
1161
1162 (defun output-complex (complex stream)
1163   (write-string "#C(" stream)
1164   (output-object (realpart complex) stream)
1165   (write-char #\space stream)
1166   (output-object (imagpart complex) stream)
1167   (write-char #\) stream))
1168 \f
1169 ;;;; float printing
1170 ;;;;
1171 ;;;; written by Bill Maddox
1172
1173 ;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does most of
1174 ;;; the work for all printing of floating point numbers in the printer and in
1175 ;;; FORMAT. It converts a floating point number to a string in a free or
1176 ;;; fixed format with no exponent. The interpretation of the arguments is as
1177 ;;; follows:
1178 ;;;
1179 ;;;     X       - The floating point number to convert, which must not be
1180 ;;;             negative.
1181 ;;;     WIDTH    - The preferred field width, used to determine the number
1182 ;;;             of fraction digits to produce if the FDIGITS parameter
1183 ;;;             is unspecified or NIL. If the non-fraction digits and the
1184 ;;;             decimal point alone exceed this width, no fraction digits
1185 ;;;             will be produced unless a non-NIL value of FDIGITS has been
1186 ;;;             specified. Field overflow is not considerd an error at this
1187 ;;;             level.
1188 ;;;     FDIGITS  - The number of fractional digits to produce. Insignificant
1189 ;;;             trailing zeroes may be introduced as needed. May be
1190 ;;;             unspecified or NIL, in which case as many digits as possible
1191 ;;;             are generated, subject to the constraint that there are no
1192 ;;;             trailing zeroes.
1193 ;;;     SCALE    - If this parameter is specified or non-NIL, then the number
1194 ;;;             printed is (* x (expt 10 scale)). This scaling is exact,
1195 ;;;             and cannot lose precision.
1196 ;;;     FMIN     - This parameter, if specified or non-NIL, is the minimum
1197 ;;;             number of fraction digits which will be produced, regardless
1198 ;;;             of the value of WIDTH or FDIGITS. This feature is used by
1199 ;;;             the ~E format directive to prevent complete loss of
1200 ;;;             significance in the printed value due to a bogus choice of
1201 ;;;             scale factor.
1202 ;;;
1203 ;;; Most of the optional arguments are for the benefit for FORMAT and are not
1204 ;;; used by the printer.
1205 ;;;
1206 ;;; Returns:
1207 ;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
1208 ;;; where the results have the following interpretation:
1209 ;;;
1210 ;;;     DIGIT-STRING    - The decimal representation of X, with decimal point.
1211 ;;;     DIGIT-LENGTH    - The length of the string DIGIT-STRING.
1212 ;;;     LEADING-POINT   - True if the first character of DIGIT-STRING is the
1213 ;;;                    decimal point.
1214 ;;;     TRAILING-POINT  - True if the last character of DIGIT-STRING is the
1215 ;;;                    decimal point.
1216 ;;;     POINT-POS       - The position of the digit preceding the decimal
1217 ;;;                    point. Zero indicates point before first digit.
1218 ;;;
1219 ;;; NOTE:  FLONUM-TO-STRING goes to a lot of trouble to guarantee accuracy.
1220 ;;; Specifically, the decimal number printed is the closest possible
1221 ;;; approximation to the true value of the binary number to be printed from
1222 ;;; among all decimal representations  with the same number of digits. In
1223 ;;; free-format output, i.e. with the number of digits unconstrained, it is
1224 ;;; guaranteed that all the information is preserved, so that a properly-
1225 ;;; rounding reader can reconstruct the original binary number, bit-for-bit,
1226 ;;; from its printed decimal representation. Furthermore, only as many digits
1227 ;;; as necessary to satisfy this condition will be printed.
1228 ;;;
1229 ;;; FLOAT-STRING actually generates the digits for positive numbers. The
1230 ;;; algorithm is essentially that of algorithm Dragon4 in "How to Print
1231 ;;; Floating-Point Numbers Accurately" by Steele and White. The current
1232 ;;; (draft) version of this paper may be found in [CMUC]<steele>tradix.press.
1233 ;;; DO NOT EVEN THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING
1234 ;;; THE PAPER!
1235
1236 (defvar *digits* "0123456789")
1237
1238 (defun flonum-to-string (x &optional width fdigits scale fmin)
1239   (cond ((zerop x)
1240          ;; Zero is a special case which FLOAT-STRING cannot handle.
1241          (if fdigits
1242              (let ((s (make-string (1+ fdigits) :initial-element #\0)))
1243                (setf (schar s 0) #\.)
1244                (values s (length s) t (zerop fdigits) 0))
1245              (values "." 1 t t 0)))
1246         (t
1247          (multiple-value-bind (sig exp) (integer-decode-float x)
1248            (let* ((precision (float-precision x))
1249                   (digits (float-digits x))
1250                   (fudge (- digits precision))
1251                   (width (if width (max width 1) nil)))
1252            (float-string (ash sig (- fudge)) (+ exp fudge) precision width
1253                          fdigits scale fmin))))))
1254
1255 (defun float-string (fraction exponent precision width fdigits scale fmin)
1256   (let ((r fraction) (s 1) (m- 1) (m+ 1) (k 0)
1257         (digits 0) (decpnt 0) (cutoff nil) (roundup nil) u low high
1258         (digit-string (make-array 50
1259                                   :element-type 'base-char
1260                                   :fill-pointer 0
1261                                   :adjustable t)))
1262     ;; Represent fraction as r/s, error bounds as m+/s and m-/s.
1263     ;; Rational arithmetic avoids loss of precision in subsequent calculations.
1264     (cond ((> exponent 0)
1265            (setq r (ash fraction exponent))
1266            (setq m- (ash 1 exponent))
1267            (setq m+ m-))
1268           ((< exponent 0)
1269            (setq s (ash 1 (- exponent)))))
1270     ;;adjust the error bounds m+ and m- for unequal gaps
1271     (when (= fraction (ash 1 precision))
1272       (setq m+ (ash m+ 1))
1273       (setq r (ash r 1))
1274       (setq s (ash s 1)))
1275     ;;scale value by requested amount, and update error bounds
1276     (when scale
1277       (if (minusp scale)
1278           (let ((scale-factor (expt 10 (- scale))))
1279             (setq s (* s scale-factor)))
1280           (let ((scale-factor (expt 10 scale)))
1281             (setq r (* r scale-factor))
1282             (setq m+ (* m+ scale-factor))
1283             (setq m- (* m- scale-factor)))))
1284     ;;scale r and s and compute initial k, the base 10 logarithm of r
1285     (do ()
1286         ((>= r (ceiling s 10)))
1287       (decf k)
1288       (setq r (* r 10))
1289       (setq m- (* m- 10))
1290       (setq m+ (* m+ 10)))
1291     (do ()(nil)
1292       (do ()
1293           ((< (+ (ash r 1) m+) (ash s 1)))
1294         (setq s (* s 10))
1295         (incf k))
1296       ;;determine number of fraction digits to generate
1297       (cond (fdigits
1298              ;;use specified number of fraction digits
1299              (setq cutoff (- fdigits))
1300              ;;don't allow less than fmin fraction digits
1301              (if (and fmin (> cutoff (- fmin))) (setq cutoff (- fmin))))
1302             (width
1303              ;;use as many fraction digits as width will permit
1304              ;;but force at least fmin digits even if width will be exceeded
1305              (if (< k 0)
1306                  (setq cutoff (- 1 width))
1307                  (setq cutoff (1+ (- k width))))
1308              (if (and fmin (> cutoff (- fmin))) (setq cutoff (- fmin)))))
1309       ;;If we decided to cut off digit generation before precision has
1310       ;;been exhausted, rounding the last digit may cause a carry propagation.
1311       ;;We can prevent this, preserving left-to-right digit generation, with
1312       ;;a few magical adjustments to m- and m+. Of course, correct rounding
1313       ;;is also preserved.
1314       (when (or fdigits width)
1315         (let ((a (- cutoff k))
1316               (y s))
1317           (if (>= a 0)
1318               (dotimes (i a) (setq y (* y 10)))
1319               (dotimes (i (- a)) (setq y (ceiling y 10))))
1320           (setq m- (max y m-))
1321           (setq m+ (max y m+))
1322           (when (= m+ y) (setq roundup t))))
1323       (when (< (+ (ash r 1) m+) (ash s 1)) (return)))
1324     ;;zero-fill before fraction if no integer part
1325     (when (< k 0)
1326       (setq decpnt digits)
1327       (vector-push-extend #\. digit-string)
1328       (dotimes (i (- k))
1329         (incf digits) (vector-push-extend #\0 digit-string)))
1330     ;;generate the significant digits
1331     (do ()(nil)
1332       (decf k)
1333       (when (= k -1)
1334         (vector-push-extend #\. digit-string)
1335         (setq decpnt digits))
1336       (multiple-value-setq (u r) (truncate (* r 10) s))
1337       (setq m- (* m- 10))
1338       (setq m+ (* m+ 10))
1339       (setq low (< (ash r 1) m-))
1340       (if roundup
1341           (setq high (>= (ash r 1) (- (ash s 1) m+)))
1342           (setq high (> (ash r 1) (- (ash s 1) m+))))
1343       ;;stop when either precision is exhausted or we have printed as many
1344       ;;fraction digits as permitted
1345       (when (or low high (and cutoff (<= k cutoff))) (return))
1346       (vector-push-extend (char *digits* u) digit-string)
1347       (incf digits))
1348     ;; If cutoff occurred before first digit, then no digits are
1349     ;; generated at all.
1350     (when (or (not cutoff) (>= k cutoff))
1351       ;;last digit may need rounding
1352       (vector-push-extend (char *digits*
1353                                 (cond ((and low (not high)) u)
1354                                       ((and high (not low)) (1+ u))
1355                                       (t (if (<= (ash r 1) s) u (1+ u)))))
1356                           digit-string)
1357       (incf digits))
1358     ;;zero-fill after integer part if no fraction
1359     (when (>= k 0)
1360       (dotimes (i k) (incf digits) (vector-push-extend #\0 digit-string))
1361       (vector-push-extend #\. digit-string)
1362       (setq decpnt digits))
1363     ;;add trailing zeroes to pad fraction if fdigits specified
1364     (when fdigits
1365       (dotimes (i (- fdigits (- digits decpnt)))
1366         (incf digits)
1367         (vector-push-extend #\0 digit-string)))
1368     ;;all done
1369     (values digit-string (1+ digits) (= decpnt 0) (= decpnt digits) decpnt)))
1370
1371 ;;; Given a non-negative floating point number, SCALE-EXPONENT returns a new
1372 ;;; floating point number Z in the range (0.1, 1.0] and an exponent E such
1373 ;;; that Z * 10^E is (approximately) equal to the original number. There may
1374 ;;; be some loss of precision due the floating point representation. The
1375 ;;; scaling is always done with long float arithmetic, which helps printing of
1376 ;;; lesser precisions as well as avoiding generic arithmetic.
1377 ;;;
1378 ;;; When computing our initial scale factor using EXPT, we pull out part of
1379 ;;; the computation to avoid over/under flow. When denormalized, we must pull
1380 ;;; out a large factor, since there is more negative exponent range than
1381 ;;; positive range.
1382 (defun scale-exponent (original-x)
1383   (let* ((x (coerce original-x 'long-float)))
1384     (multiple-value-bind (sig exponent) (decode-float x)
1385       (declare (ignore sig))
1386       (if (= x 0.0l0)
1387           (values (float 0.0l0 original-x) 1)
1388           (let* ((ex (round (* exponent (log 2l0 10))))
1389                  (x (if (minusp ex)
1390                         (if (float-denormalized-p x)
1391                             #!-long-float
1392                             (* x 1.0l16 (expt 10.0l0 (- (- ex) 16)))
1393                             #!+long-float
1394                             (* x 1.0l18 (expt 10.0l0 (- (- ex) 18)))
1395                             (* x 10.0l0 (expt 10.0l0 (- (- ex) 1))))
1396                         (/ x 10.0l0 (expt 10.0l0 (1- ex))))))
1397             (do ((d 10.0l0 (* d 10.0l0))
1398                  (y x (/ x d))
1399                  (ex ex (1+ ex)))
1400                 ((< y 1.0l0)
1401                  (do ((m 10.0l0 (* m 10.0l0))
1402                       (z y (* y m))
1403                       (ex ex (1- ex)))
1404                      ((>= z 0.1l0)
1405                       (values (float z original-x) ex))))))))))
1406 \f
1407 ;;;; entry point for the float printer
1408
1409 ;;; Entry point for the float printer as called by PRINT, PRIN1, PRINC,
1410 ;;; etc. The argument is printed free-format, in either exponential or
1411 ;;; non-exponential notation, depending on its magnitude.
1412 ;;;
1413 ;;; NOTE: When a number is to be printed in exponential format, it is scaled in
1414 ;;; floating point. Since precision may be lost in this process, the
1415 ;;; guaranteed accuracy properties of FLONUM-TO-STRING are lost. The
1416 ;;; difficulty is that FLONUM-TO-STRING performs extensive computations with
1417 ;;; integers of similar magnitude to that of the number being printed. For
1418 ;;; large exponents, the bignums really get out of hand. If bignum arithmetic
1419 ;;; becomes reasonably fast and the exponent range is not too large, then it
1420 ;;; might become attractive to handle exponential notation with the same
1421 ;;; accuracy as non-exponential notation, using the method described in the
1422 ;;; Steele and White paper.
1423
1424 ;;; Print the appropriate exponent marker for X and the specified exponent.
1425 (defun print-float-exponent (x exp stream)
1426   (declare (type float x) (type integer exp) (type stream stream))
1427   (let ((*print-radix* nil)
1428         (plusp (plusp exp)))
1429     (if (typep x *read-default-float-format*)
1430         (unless (eql exp 0)
1431           (format stream "e~:[~;+~]~D" plusp exp))
1432         (format stream "~C~:[~;+~]~D"
1433                 (etypecase x
1434                   (single-float #\f)
1435                   (double-float #\d)
1436                   (short-float #\s)
1437                   (long-float #\L))
1438                 plusp exp))))
1439
1440 ;;;    Write out an infinity using #. notation, or flame out if
1441 ;;; *print-readably* is true and *read-eval* is false.
1442 #!+sb-infinities
1443 (defun output-float-infinity (x stream)
1444   (declare (type float x) (type stream stream))
1445   (cond (*read-eval*
1446          (write-string "#." stream))
1447         (*print-readably*
1448          (error 'print-not-readable :object x))
1449         (t
1450          (write-string "#<" stream)))
1451   (write-string "EXT:" stream)
1452   (princ (float-format-name x) stream)
1453   (write-string (if (plusp x) "-POSITIVE-" "-NEGATIVE-")
1454                 stream)
1455   (write-string "INFINITY" stream)
1456   (unless *read-eval*
1457     (write-string ">" stream)))
1458
1459 ;;; Output a #< NaN or die trying.
1460 (defun output-float-nan (x stream)
1461   (print-unreadable-object (x stream)
1462     (princ (float-format-name x) stream)
1463     (write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
1464     (write-string " NaN" stream)))
1465
1466 ;;; the function called by OUTPUT-OBJECT to handle floats
1467 (defun output-float (x stream)
1468   (cond
1469    ((float-infinity-p x)
1470     (output-float-infinity x stream))
1471    ((float-nan-p x)
1472     (output-float-nan x stream))
1473    (t
1474     (let ((x (cond ((minusp (float-sign x))
1475                     (write-char #\- stream)
1476                     (- x))
1477                    (t
1478                     x))))
1479       (cond
1480        ((zerop x)
1481         (write-string "0.0" stream)
1482         (print-float-exponent x 0 stream))
1483        (t
1484         (output-float-aux x stream (float 1/1000 x) (float 10000000 x))))))))
1485 (defun output-float-aux (x stream e-min e-max)
1486   (if (and (>= x e-min) (< x e-max))
1487       ;; free format
1488       (multiple-value-bind (str len lpoint tpoint) (flonum-to-string x)
1489         (declare (ignore len))
1490         (when lpoint (write-char #\0 stream))
1491         (write-string str stream)
1492         (when tpoint (write-char #\0 stream))
1493         (print-float-exponent x 0 stream))
1494       ;; exponential format
1495       (multiple-value-bind (f ex) (scale-exponent x)
1496         (multiple-value-bind (str len lpoint tpoint)
1497             (flonum-to-string f nil nil 1)
1498           (declare (ignore len))
1499           (when lpoint (write-char #\0 stream))
1500           (write-string str stream)
1501           (when tpoint (write-char #\0 stream))
1502           ;; Subtract out scale factor of 1 passed to FLONUM-TO-STRING.
1503           (print-float-exponent x (1- ex) stream)))))
1504 \f
1505 ;;;; other leaf objects
1506
1507 ;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
1508 ;;; the character name or the character in the #\char format.
1509 (defun output-character (char stream)
1510   (if (or *print-escape* *print-readably*)
1511       (let ((name (char-name char)))
1512         (write-string "#\\" stream)
1513         (if name
1514             (quote-string name stream)
1515             (write-char char stream)))
1516       (write-char char stream)))
1517
1518 (defun output-sap (sap stream)
1519   (declare (type system-area-pointer sap))
1520   (cond (*read-eval*
1521          (format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
1522         (t
1523          (print-unreadable-object (sap stream)
1524            (format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
1525
1526 (defun output-weak-pointer (weak-pointer stream)
1527   (declare (type weak-pointer weak-pointer))
1528   (print-unreadable-object (weak-pointer stream)
1529     (multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
1530       (cond (validp
1531              (write-string "weak pointer: " stream)
1532              (write value :stream stream))
1533             (t
1534              (write-string "broken weak pointer" stream))))))
1535
1536 (defun output-code-component (component stream)
1537   (print-unreadable-object (component stream :identity t)
1538     (let ((dinfo (%code-debug-info component)))
1539       (cond ((eq dinfo :bogus-lra)
1540              (write-string "bogus code object" stream))
1541             (t
1542              (write-string "code object" stream)
1543              (when dinfo
1544                (write-char #\space stream)
1545                (output-object (sb!c::debug-info-name dinfo) stream)))))))
1546
1547 (defun output-lra (lra stream)
1548   (print-unreadable-object (lra stream :identity t)
1549     (write-string "return PC object" stream)))
1550
1551 (defun output-fdefn (fdefn stream)
1552   (print-unreadable-object (fdefn stream)
1553     (write-string "FDEFINITION object for " stream)
1554     (output-object (fdefn-name fdefn) stream)))
1555 \f
1556 ;;;; functions
1557
1558 ;;; Output OBJECT as using PRINT-OBJECT if it's a
1559 ;;; FUNCALLABLE-STANDARD-CLASS, or return NIL otherwise.
1560 ;;;
1561 ;;; The definition here is a simple temporary placeholder. It will be
1562 ;;; overwritten by a smarter version (capable of calling generic
1563 ;;; PRINT-OBJECT when appropriate) when CLOS is installed.
1564 (defun printed-as-clos-funcallable-standard-class (object stream)
1565   (declare (ignore object stream))
1566   nil)
1567
1568 (defun output-function (object stream)
1569   (let* ((*print-length* 3) ; in case we have to..
1570          (*print-level* 3)  ; ..print an interpreted function definition
1571          (name (cond ((find (function-subtype object)
1572                             #(#.sb!vm:closure-header-type
1573                               #.sb!vm:byte-code-closure-type))
1574                       "CLOSURE")
1575                      ((sb!eval::interpreted-function-p object)
1576                       (or (sb!eval::interpreted-function-%name object)
1577                           (sb!eval:interpreted-function-lambda-expression
1578                            object)))
1579                      ((find (function-subtype object)
1580                             #(#.sb!vm:function-header-type
1581                               #.sb!vm:closure-function-header-type))
1582                       (%function-name object))
1583                      (t 'no-name-available)))
1584          (identified-by-name-p (and (symbolp name)
1585                                     (fboundp name)
1586                                     (eq (fdefinition name) object))))
1587       (print-unreadable-object (object
1588                                 stream
1589                                 :identity (not identified-by-name-p))
1590         (prin1 'function stream)
1591         (unless (eq name 'no-name-available)
1592           (format stream " ~S" name)))))
1593 \f
1594 ;;;; catch-all for unknown things
1595
1596 (defun output-random (object stream)
1597   (print-unreadable-object (object stream :identity t)
1598     (let ((lowtag (get-lowtag object)))
1599       (case lowtag
1600         (#.sb!vm:other-pointer-type
1601           (let ((type (get-type object)))
1602             (case type
1603               (#.sb!vm:value-cell-header-type
1604                (write-string "value cell " stream)
1605                (output-object (sb!c:value-cell-ref object) stream))
1606               (t
1607                (write-string "unknown pointer object, type=" stream)
1608                (let ((*print-base* 16) (*print-radix* t))
1609                  (output-integer type stream))))))
1610         ((#.sb!vm:function-pointer-type
1611           #.sb!vm:instance-pointer-type
1612           #.sb!vm:list-pointer-type)
1613          (write-string "unknown pointer object, type=" stream))
1614         (t
1615          (case (get-type object)
1616            (#.sb!vm:unbound-marker-type
1617             (write-string "unbound marker" stream))
1618            (t
1619             (write-string "unknown immediate object, lowtag=" stream)
1620             (let ((*print-base* 2) (*print-radix* t))
1621               (output-integer lowtag stream))
1622             (write-string ", type=" stream)
1623             (let ((*print-base* 16) (*print-radix* t))
1624               (output-integer (get-type object) stream)))))))))