0.8.8.22:
[sbcl.git] / src / code / pprint.lisp
1 ;;;; Common Lisp pretty 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!PRETTY")
13 \f
14 ;;;; pretty streams
15
16 ;;; There are three different units for measuring character positions:
17 ;;;  COLUMN - offset (if characters) from the start of the current line
18 ;;;  INDEX  - index into the output buffer
19 ;;;  POSN   - some position in the stream of characters cycling through
20 ;;;           the output buffer
21 (deftype column ()
22   '(and fixnum unsigned-byte))
23 ;;; The INDEX type is picked up from the kernel package.
24 (deftype posn ()
25   'fixnum)
26
27 (defconstant initial-buffer-size 128)
28
29 (defconstant default-line-length 80)
30
31 (defstruct (pretty-stream (:include sb!kernel:ansi-stream
32                                     (out #'pretty-out)
33                                     (sout #'pretty-sout)
34                                     (misc #'pretty-misc))
35                           (:constructor make-pretty-stream (target))
36                           (:copier nil))
37   ;; Where the output is going to finally go.
38   (target (missing-arg) :type stream)
39   ;; Line length we should format to. Cached here so we don't have to keep
40   ;; extracting it from the target stream.
41   (line-length (or *print-right-margin*
42                    (sb!impl::line-length target)
43                    default-line-length)
44                :type column)
45   ;; A simple string holding all the text that has been output but not yet
46   ;; printed.
47   (buffer (make-string initial-buffer-size) :type (simple-array character (*)))
48   ;; The index into BUFFER where more text should be put.
49   (buffer-fill-pointer 0 :type index)
50   ;; Whenever we output stuff from the buffer, we shift the remaining noise
51   ;; over. This makes it difficult to keep references to locations in
52   ;; the buffer. Therefore, we have to keep track of the total amount of
53   ;; stuff that has been shifted out of the buffer.
54   (buffer-offset 0 :type posn)
55   ;; The column the first character in the buffer will appear in. Normally
56   ;; zero, but if we end up with a very long line with no breaks in it we
57   ;; might have to output part of it. Then this will no longer be zero.
58   (buffer-start-column (or (sb!impl::charpos target) 0) :type column)
59   ;; The line number we are currently on. Used for *PRINT-LINES*
60   ;; abbreviations and to tell when sections have been split across
61   ;; multiple lines.
62   (line-number 0 :type index)
63   ;; the value of *PRINT-LINES* captured at object creation time. We
64   ;; use this, instead of the dynamic *PRINT-LINES*, to avoid
65   ;; weirdness like
66   ;;   (let ((*print-lines* 50))
67   ;;     (pprint-logical-block ..
68   ;;       (dotimes (i 10)
69   ;;         (let ((*print-lines* 8))
70   ;;           (print (aref possiblybigthings i) prettystream)))))
71   ;; terminating the output of the entire logical blockafter 8 lines.
72   (print-lines *print-lines* :type (or index null) :read-only t)
73   ;; Stack of logical blocks in effect at the buffer start.
74   (blocks (list (make-logical-block)) :type list)
75   ;; Buffer holding the per-line prefix active at the buffer start.
76   ;; Indentation is included in this. The length of this is stored
77   ;; in the logical block stack.
78   (prefix (make-string initial-buffer-size) :type (simple-array character (*)))
79   ;; Buffer holding the total remaining suffix active at the buffer start.
80   ;; The characters are right-justified in the buffer to make it easier
81   ;; to output the buffer. The length is stored in the logical block
82   ;; stack.
83   (suffix (make-string initial-buffer-size) :type (simple-array character (*)))
84   ;; Queue of pending operations. When empty, HEAD=TAIL=NIL. Otherwise,
85   ;; TAIL holds the first (oldest) cons and HEAD holds the last (newest)
86   ;; cons. Adding things to the queue is basically (setf (cdr head) (list
87   ;; new)) and removing them is basically (pop tail) [except that care must
88   ;; be taken to handle the empty queue case correctly.]
89   (queue-tail nil :type list)
90   (queue-head nil :type list)
91   ;; Block-start queue entries in effect at the queue head.
92   (pending-blocks nil :type list))
93 (def!method print-object ((pstream pretty-stream) stream)
94   ;; FIXME: CMU CL had #+NIL'ed out this code and done a hand-written
95   ;; FORMAT hack instead. Make sure that this code actually works instead
96   ;; of falling into infinite regress or something.
97   (print-unreadable-object (pstream stream :type t :identity t)))
98
99 #!-sb-fluid (declaim (inline index-posn posn-index posn-column))
100 (defun index-posn (index stream)
101   (declare (type index index) (type pretty-stream stream)
102            (values posn))
103   (+ index (pretty-stream-buffer-offset stream)))
104 (defun posn-index (posn stream)
105   (declare (type posn posn) (type pretty-stream stream)
106            (values index))
107   (- posn (pretty-stream-buffer-offset stream)))
108 (defun posn-column (posn stream)
109   (declare (type posn posn) (type pretty-stream stream)
110            (values posn))
111   (index-column (posn-index posn stream) stream))
112
113 ;;; Is it OK to do pretty printing on this stream at this time?
114 (defun print-pretty-on-stream-p (stream)
115   (and (pretty-stream-p stream)
116        *print-pretty*))
117 \f
118 ;;;; stream interface routines
119
120 (defun pretty-out (stream char)
121   (declare (type pretty-stream stream)
122            (type base-char char))
123   (cond ((char= char #\newline)
124          (enqueue-newline stream :literal))
125         (t
126          (ensure-space-in-buffer stream 1)
127          (let ((fill-pointer (pretty-stream-buffer-fill-pointer stream)))
128            (setf (schar (pretty-stream-buffer stream) fill-pointer) char)
129            (setf (pretty-stream-buffer-fill-pointer stream)
130                  (1+ fill-pointer))))))
131
132 (defun pretty-sout (stream string start end)
133   (declare (type pretty-stream stream)
134            (type simple-string string)
135            (type index start)
136            (type (or index null) end))
137   (let* ((string (if (typep string '(simple-array character (*)))
138                      string
139                      (coerce string '(simple-array character (*)))))
140          (end (or end (length string))))
141     (unless (= start end)
142       (let ((newline (position #\newline string :start start :end end)))
143         (cond
144          (newline
145           (pretty-sout stream string start newline)
146           (enqueue-newline stream :literal)
147           (pretty-sout stream string (1+ newline) end))
148          (t
149           (let ((chars (- end start)))
150             (loop
151               (let* ((available (ensure-space-in-buffer stream chars))
152                      (count (min available chars))
153                      (fill-pointer (pretty-stream-buffer-fill-pointer stream))
154                      (new-fill-ptr (+ fill-pointer count)))
155                 (replace (pretty-stream-buffer stream)
156                          string
157                          :start1 fill-pointer :end1 new-fill-ptr
158                          :start2 start)
159                 (setf (pretty-stream-buffer-fill-pointer stream) new-fill-ptr)
160                 (decf chars count)
161                 (when (zerop count)
162                   (return))
163                 (incf start count))))))))))
164
165 (defun pretty-misc (stream op &optional arg1 arg2)
166   (declare (ignore stream op arg1 arg2)))
167 \f
168 ;;;; logical blocks
169
170 (defstruct (logical-block (:copier nil))
171   ;; The column this logical block started in.
172   (start-column 0 :type column)
173   ;; The column the current section started in.
174   (section-column 0 :type column)
175   ;; The length of the per-line prefix. We can't move the indentation
176   ;; left of this.
177   (per-line-prefix-end 0 :type index)
178   ;; The overall length of the prefix, including any indentation.
179   (prefix-length 0 :type index)
180   ;; The overall length of the suffix.
181   (suffix-length 0 :type index)
182   ;; The line number
183   (section-start-line 0 :type index))
184
185 (defun really-start-logical-block (stream column prefix suffix)
186   (let* ((blocks (pretty-stream-blocks stream))
187          (prev-block (car blocks))
188          (per-line-end (logical-block-per-line-prefix-end prev-block))
189          (prefix-length (logical-block-prefix-length prev-block))
190          (suffix-length (logical-block-suffix-length prev-block))
191          (block (make-logical-block
192                  :start-column column
193                  :section-column column
194                  :per-line-prefix-end per-line-end
195                  :prefix-length prefix-length
196                  :suffix-length suffix-length
197                  :section-start-line (pretty-stream-line-number stream))))
198     (setf (pretty-stream-blocks stream) (cons block blocks))
199     (set-indentation stream column)
200     (when prefix
201       (setf (logical-block-per-line-prefix-end block) column)
202       (replace (pretty-stream-prefix stream) prefix
203                :start1 (- column (length prefix)) :end1 column))
204     (when suffix
205       (let* ((total-suffix (pretty-stream-suffix stream))
206              (total-suffix-len (length total-suffix))
207              (additional (length suffix))
208              (new-suffix-len (+ suffix-length additional)))
209         (when (> new-suffix-len total-suffix-len)
210           (let ((new-total-suffix-len
211                  (max (* total-suffix-len 2)
212                       (+ suffix-length
213                          (floor (* additional 5) 4)))))
214             (setf total-suffix
215                   (replace (make-string new-total-suffix-len) total-suffix
216                            :start1 (- new-total-suffix-len suffix-length)
217                            :start2 (- total-suffix-len suffix-length)))
218             (setf total-suffix-len new-total-suffix-len)
219             (setf (pretty-stream-suffix stream) total-suffix)))
220         (replace total-suffix suffix
221                  :start1 (- total-suffix-len new-suffix-len)
222                  :end1 (- total-suffix-len suffix-length))
223         (setf (logical-block-suffix-length block) new-suffix-len))))
224   nil)
225
226 (defun set-indentation (stream column)
227   (let* ((prefix (pretty-stream-prefix stream))
228          (prefix-len (length prefix))
229          (block (car (pretty-stream-blocks stream)))
230          (current (logical-block-prefix-length block))
231          (minimum (logical-block-per-line-prefix-end block))
232          (column (max minimum column)))
233     (when (> column prefix-len)
234       (setf prefix
235             (replace (make-string (max (* prefix-len 2)
236                                        (+ prefix-len
237                                           (floor (* (- column prefix-len) 5)
238                                                  4))))
239                      prefix
240                      :end1 current))
241       (setf (pretty-stream-prefix stream) prefix))
242     (when (> column current)
243       (fill prefix #\space :start current :end column))
244     (setf (logical-block-prefix-length block) column)))
245
246 (defun really-end-logical-block (stream)
247   (let* ((old (pop (pretty-stream-blocks stream)))
248          (old-indent (logical-block-prefix-length old))
249          (new (car (pretty-stream-blocks stream)))
250          (new-indent (logical-block-prefix-length new)))
251     (when (> new-indent old-indent)
252       (fill (pretty-stream-prefix stream) #\space
253             :start old-indent :end new-indent)))
254   nil)
255 \f
256 ;;;; the pending operation queue
257
258 (defstruct (queued-op (:constructor nil)
259                       (:copier nil))
260   (posn 0 :type posn))
261
262 (defmacro enqueue (stream type &rest args)
263   (let ((constructor (symbolicate "MAKE-" type)))
264     (once-only ((stream stream)
265                 (entry `(,constructor :posn
266                                       (index-posn
267                                        (pretty-stream-buffer-fill-pointer
268                                         ,stream)
269                                        ,stream)
270                                       ,@args))
271                 (op `(list ,entry))
272                 (head `(pretty-stream-queue-head ,stream)))
273       `(progn
274          (if ,head
275              (setf (cdr ,head) ,op)
276              (setf (pretty-stream-queue-tail ,stream) ,op))
277          (setf (pretty-stream-queue-head ,stream) ,op)
278          ,entry))))
279
280 (defstruct (section-start (:include queued-op)
281                           (:constructor nil)
282                           (:copier nil))
283   (depth 0 :type index)
284   (section-end nil :type (or null newline block-end)))
285
286 (defstruct (newline (:include section-start)
287                     (:copier nil))
288   (kind (missing-arg)
289         :type (member :linear :fill :miser :literal :mandatory)))
290
291 (defun enqueue-newline (stream kind)
292   (let* ((depth (length (pretty-stream-pending-blocks stream)))
293          (newline (enqueue stream newline :kind kind :depth depth)))
294     (dolist (entry (pretty-stream-queue-tail stream))
295       (when (and (not (eq newline entry))
296                  (section-start-p entry)
297                  (null (section-start-section-end entry))
298                  (<= depth (section-start-depth entry)))
299         (setf (section-start-section-end entry) newline))))
300   (maybe-output stream (or (eq kind :literal) (eq kind :mandatory))))
301
302 (defstruct (indentation (:include queued-op)
303                         (:copier nil))
304   (kind (missing-arg) :type (member :block :current))
305   (amount 0 :type fixnum))
306
307 (defun enqueue-indent (stream kind amount)
308   (enqueue stream indentation :kind kind :amount amount))
309
310 (defstruct (block-start (:include section-start)
311                         (:copier nil))
312   (block-end nil :type (or null block-end))
313   (prefix nil :type (or null (simple-array character (*))))
314   (suffix nil :type (or null (simple-array character (*)))))
315
316 (defun start-logical-block (stream prefix per-line-p suffix)
317   ;; (In the PPRINT-LOGICAL-BLOCK form which calls us,
318   ;; :PREFIX and :PER-LINE-PREFIX have hairy defaulting behavior,
319   ;; and might end up being NIL.)
320   (declare (type (or null string) prefix))
321   ;; (But the defaulting behavior of PPRINT-LOGICAL-BLOCK :SUFFIX is
322   ;; trivial, so it should always be a string.)
323   (declare (type string suffix))
324   (when prefix
325     (setq prefix (coerce prefix '(simple-array character (*))))
326     (pretty-sout stream prefix 0 (length prefix)))
327   (let* ((pending-blocks (pretty-stream-pending-blocks stream))
328          (start (enqueue stream block-start
329                          :prefix (and per-line-p prefix)
330                          :suffix (coerce suffix '(simple-array character (*)))
331                          :depth (length pending-blocks))))
332     (setf (pretty-stream-pending-blocks stream)
333           (cons start pending-blocks))))
334
335 (defstruct (block-end (:include queued-op)
336                       (:copier nil))
337   (suffix nil :type (or null (simple-array character (*)))))
338
339 (defun end-logical-block (stream)
340   (let* ((start (pop (pretty-stream-pending-blocks stream)))
341          (suffix (block-start-suffix start))
342          (end (enqueue stream block-end :suffix suffix)))
343     (when suffix
344       (pretty-sout stream suffix 0 (length suffix)))
345     (setf (block-start-block-end start) end)))
346
347 (defstruct (tab (:include queued-op)
348                 (:copier nil))
349   (sectionp nil :type (member t nil))
350   (relativep nil :type (member t nil))
351   (colnum 0 :type column)
352   (colinc 0 :type column))
353
354 (defun enqueue-tab (stream kind colnum colinc)
355   (multiple-value-bind (sectionp relativep)
356       (ecase kind
357         (:line (values nil nil))
358         (:line-relative (values nil t))
359         (:section (values t nil))
360         (:section-relative (values t t)))
361     (enqueue stream tab :sectionp sectionp :relativep relativep
362              :colnum colnum :colinc colinc)))
363 \f
364 ;;;; tab support
365
366 (defun compute-tab-size (tab section-start column)
367   (let ((origin (if (tab-sectionp tab) section-start 0))
368         (colnum (tab-colnum tab))
369         (colinc (tab-colinc tab)))
370     (cond ((tab-relativep tab)
371            (unless (<= colinc 1)
372              (let ((newposn (+ column colnum)))
373                (let ((rem (rem newposn colinc)))
374                  (unless (zerop rem)
375                    (incf colnum (- colinc rem))))))
376            colnum)
377           ((<= column (+ colnum origin))
378            (- (+ colnum origin) column))
379           (t
380            (- colinc
381               (rem (- column origin) colinc))))))
382
383 (defun index-column (index stream)
384   (let ((column (pretty-stream-buffer-start-column stream))
385         (section-start (logical-block-section-column
386                         (first (pretty-stream-blocks stream))))
387         (end-posn (index-posn index stream)))
388     (dolist (op (pretty-stream-queue-tail stream))
389       (when (>= (queued-op-posn op) end-posn)
390         (return))
391       (typecase op
392         (tab
393          (incf column
394                (compute-tab-size op
395                                  section-start
396                                  (+ column
397                                     (posn-index (tab-posn op)
398                                                     stream)))))
399         ((or newline block-start)
400          (setf section-start
401                (+ column (posn-index (queued-op-posn op)
402                                          stream))))))
403     (+ column index)))
404
405 (defun expand-tabs (stream through)
406   (let ((insertions nil)
407         (additional 0)
408         (column (pretty-stream-buffer-start-column stream))
409         (section-start (logical-block-section-column
410                         (first (pretty-stream-blocks stream)))))
411     (dolist (op (pretty-stream-queue-tail stream))
412       (typecase op
413         (tab
414          (let* ((index (posn-index (tab-posn op) stream))
415                 (tabsize (compute-tab-size op
416                                            section-start
417                                            (+ column index))))
418            (unless (zerop tabsize)
419              (push (cons index tabsize) insertions)
420              (incf additional tabsize)
421              (incf column tabsize))))
422         ((or newline block-start)
423          (setf section-start
424                (+ column (posn-index (queued-op-posn op) stream)))))
425       (when (eq op through)
426         (return)))
427     (when insertions
428       (let* ((fill-ptr (pretty-stream-buffer-fill-pointer stream))
429              (new-fill-ptr (+ fill-ptr additional))
430              (buffer (pretty-stream-buffer stream))
431              (new-buffer buffer)
432              (length (length buffer))
433              (end fill-ptr))
434         (when (> new-fill-ptr length)
435           (let ((new-length (max (* length 2)
436                                  (+ fill-ptr
437                                     (floor (* additional 5) 4)))))
438             (setf new-buffer (make-string new-length))
439             (setf (pretty-stream-buffer stream) new-buffer)))
440         (setf (pretty-stream-buffer-fill-pointer stream) new-fill-ptr)
441         (decf (pretty-stream-buffer-offset stream) additional)
442         (dolist (insertion insertions)
443           (let* ((srcpos (car insertion))
444                  (amount (cdr insertion))
445                  (dstpos (+ srcpos additional)))
446             (replace new-buffer buffer :start1 dstpos :start2 srcpos :end2 end)
447             (fill new-buffer #\space :start (- dstpos amount) :end dstpos)
448             (decf additional amount)
449             (setf end srcpos)))
450         (unless (eq new-buffer buffer)
451           (replace new-buffer buffer :end1 end :end2 end))))))
452 \f
453 ;;;; stuff to do the actual outputting
454
455 (defun ensure-space-in-buffer (stream want)
456   (declare (type pretty-stream stream)
457            (type index want))
458   (let* ((buffer (pretty-stream-buffer stream))
459          (length (length buffer))
460          (fill-ptr (pretty-stream-buffer-fill-pointer stream))
461          (available (- length fill-ptr)))
462     (cond ((plusp available)
463            available)
464           ((> fill-ptr (pretty-stream-line-length stream))
465            (unless (maybe-output stream nil)
466              (output-partial-line stream))
467            (ensure-space-in-buffer stream want))
468           (t
469            (let* ((new-length (max (* length 2)
470                                    (+ length
471                                       (floor (* want 5) 4))))
472                   (new-buffer (make-string new-length)))
473              (setf (pretty-stream-buffer stream) new-buffer)
474              (replace new-buffer buffer :end1 fill-ptr)
475              (- new-length fill-ptr))))))
476
477 (defun maybe-output (stream force-newlines-p)
478   (declare (type pretty-stream stream))
479   (let ((tail (pretty-stream-queue-tail stream))
480         (output-anything nil))
481     (loop
482       (unless tail
483         (setf (pretty-stream-queue-head stream) nil)
484         (return))
485       (let ((next (pop tail)))
486         (etypecase next
487           (newline
488            (when (ecase (newline-kind next)
489                    ((:literal :mandatory :linear) t)
490                    (:miser (misering-p stream))
491                    (:fill
492                     (or (misering-p stream)
493                         (> (pretty-stream-line-number stream)
494                            (logical-block-section-start-line
495                             (first (pretty-stream-blocks stream))))
496                         (ecase (fits-on-line-p stream
497                                                (newline-section-end next)
498                                                force-newlines-p)
499                           ((t) nil)
500                           ((nil) t)
501                           (:dont-know
502                            (return))))))
503              (setf output-anything t)
504              (output-line stream next)))
505           (indentation
506            (unless (misering-p stream)
507              (set-indentation stream
508                               (+ (ecase (indentation-kind next)
509                                    (:block
510                                     (logical-block-start-column
511                                      (car (pretty-stream-blocks stream))))
512                                    (:current
513                                     (posn-column
514                                      (indentation-posn next)
515                                      stream)))
516                                  (indentation-amount next)))))
517           (block-start
518            (ecase (fits-on-line-p stream (block-start-section-end next)
519                                   force-newlines-p)
520              ((t)
521               ;; Just nuke the whole logical block and make it look
522               ;; like one nice long literal.
523               (let ((end (block-start-block-end next)))
524                 (expand-tabs stream end)
525                 (setf tail (cdr (member end tail)))))
526              ((nil)
527               (really-start-logical-block
528                stream
529                (posn-column (block-start-posn next) stream)
530                (block-start-prefix next)
531                (block-start-suffix next)))
532              (:dont-know
533               (return))))
534           (block-end
535            (really-end-logical-block stream))
536           (tab
537            (expand-tabs stream next))))
538       (setf (pretty-stream-queue-tail stream) tail))
539     output-anything))
540
541 (defun misering-p (stream)
542   (declare (type pretty-stream stream))
543   (and *print-miser-width*
544        (<= (- (pretty-stream-line-length stream)
545               (logical-block-start-column (car (pretty-stream-blocks stream))))
546            *print-miser-width*)))
547
548 (defun fits-on-line-p (stream until force-newlines-p)
549   (let ((available (pretty-stream-line-length stream)))
550     (when (and (not *print-readably*)
551                (pretty-stream-print-lines stream)
552                (= (pretty-stream-print-lines stream)
553                   (pretty-stream-line-number stream)))
554       (decf available 3) ; for the `` ..''
555       (decf available (logical-block-suffix-length
556                        (car (pretty-stream-blocks stream)))))
557     (cond (until
558            (<= (posn-column (queued-op-posn until) stream) available))
559           (force-newlines-p nil)
560           ((> (index-column (pretty-stream-buffer-fill-pointer stream) stream)
561               available)
562            nil)
563           (t
564            :dont-know))))
565
566 (defun output-line (stream until)
567   (declare (type pretty-stream stream)
568            (type newline until))
569   (let* ((target (pretty-stream-target stream))
570          (buffer (pretty-stream-buffer stream))
571          (kind (newline-kind until))
572          (literal-p (eq kind :literal))
573          (amount-to-consume (posn-index (newline-posn until) stream))
574          (amount-to-print
575           (if literal-p
576               amount-to-consume
577               (let ((last-non-blank
578                      (position #\space buffer :end amount-to-consume
579                                :from-end t :test #'char/=)))
580                 (if last-non-blank
581                     (1+ last-non-blank)
582                     0)))))
583     (write-string buffer target :end amount-to-print)
584     (let ((line-number (pretty-stream-line-number stream)))
585       (incf line-number)
586       (when (and (not *print-readably*)
587                  (pretty-stream-print-lines stream)
588                  (>= line-number (pretty-stream-print-lines stream)))
589         (write-string " .." target)
590         (let ((suffix-length (logical-block-suffix-length
591                               (car (pretty-stream-blocks stream)))))
592           (unless (zerop suffix-length)
593             (let* ((suffix (pretty-stream-suffix stream))
594                    (len (length suffix)))
595               (write-string suffix target
596                             :start (- len suffix-length)
597                             :end len))))
598         (throw 'line-limit-abbreviation-happened t))
599       (setf (pretty-stream-line-number stream) line-number)
600       (write-char #\newline target)
601       (setf (pretty-stream-buffer-start-column stream) 0)
602       (let* ((fill-ptr (pretty-stream-buffer-fill-pointer stream))
603              (block (first (pretty-stream-blocks stream)))
604              (prefix-len
605               (if literal-p
606                   (logical-block-per-line-prefix-end block)
607                   (logical-block-prefix-length block)))
608              (shift (- amount-to-consume prefix-len))
609              (new-fill-ptr (- fill-ptr shift))
610              (new-buffer buffer)
611              (buffer-length (length buffer)))
612         (when (> new-fill-ptr buffer-length)
613           (setf new-buffer
614                 (make-string (max (* buffer-length 2)
615                                   (+ buffer-length
616                                      (floor (* (- new-fill-ptr buffer-length)
617                                                5)
618                                             4)))))
619           (setf (pretty-stream-buffer stream) new-buffer))
620         (replace new-buffer buffer
621                  :start1 prefix-len :start2 amount-to-consume :end2 fill-ptr)
622         (replace new-buffer (pretty-stream-prefix stream)
623                  :end1 prefix-len)
624         (setf (pretty-stream-buffer-fill-pointer stream) new-fill-ptr)
625         (incf (pretty-stream-buffer-offset stream) shift)
626         (unless literal-p
627           (setf (logical-block-section-column block) prefix-len)
628           (setf (logical-block-section-start-line block) line-number))))))
629
630 (defun output-partial-line (stream)
631   (let* ((fill-ptr (pretty-stream-buffer-fill-pointer stream))
632          (tail (pretty-stream-queue-tail stream))
633          (count
634           (if tail
635               (posn-index (queued-op-posn (car tail)) stream)
636               fill-ptr))
637          (new-fill-ptr (- fill-ptr count))
638          (buffer (pretty-stream-buffer stream)))
639     (when (zerop count)
640       (error "Output-partial-line called when nothing can be output."))
641     (write-string buffer (pretty-stream-target stream)
642                   :start 0 :end count)
643     (incf (pretty-stream-buffer-start-column stream) count)
644     (replace buffer buffer :end1 new-fill-ptr :start2 count :end2 fill-ptr)
645     (setf (pretty-stream-buffer-fill-pointer stream) new-fill-ptr)
646     (incf (pretty-stream-buffer-offset stream) count)))
647
648 (defun force-pretty-output (stream)
649   (maybe-output stream nil)
650   (expand-tabs stream nil)
651   (write-string (pretty-stream-buffer stream)
652                 (pretty-stream-target stream)
653                 :end (pretty-stream-buffer-fill-pointer stream)))
654 \f
655 ;;;; user interface to the pretty printer
656
657 (defun pprint-newline (kind &optional stream)
658   #!+sb-doc
659   "Output a conditional newline to STREAM (which defaults to
660    *STANDARD-OUTPUT*) if it is a pretty-printing stream, and do
661    nothing if not. KIND can be one of:
662      :LINEAR - A line break is inserted if and only if the immediatly
663         containing section cannot be printed on one line.
664      :MISER - Same as LINEAR, but only if ``miser-style'' is in effect.
665         (See *PRINT-MISER-WIDTH*.)
666      :FILL - A line break is inserted if and only if either:
667        (a) the following section cannot be printed on the end of the
668            current line,
669        (b) the preceding section was not printed on a single line, or
670        (c) the immediately containing section cannot be printed on one
671            line and miser-style is in effect.
672      :MANDATORY - A line break is always inserted.
673    When a line break is inserted by any type of conditional newline, any
674    blanks that immediately precede the conditional newline are ommitted
675    from the output and indentation is introduced at the beginning of the
676    next line. (See PPRINT-INDENT.)"
677   (declare (type (member :linear :miser :fill :mandatory) kind)
678            (type (or stream (member t nil)) stream)
679            (values null))
680   (let ((stream (case stream
681                   ((t) *terminal-io*)
682                   ((nil) *standard-output*)
683                   (t stream))))
684     (when (print-pretty-on-stream-p stream)
685       (enqueue-newline stream kind)))
686   nil)
687
688 (defun pprint-indent (relative-to n &optional stream)
689   #!+sb-doc
690   "Specify the indentation to use in the current logical block if STREAM
691    (which defaults to *STANDARD-OUTPUT*) is it is a pretty-printing stream
692    and do nothing if not. (See PPRINT-LOGICAL-BLOCK.)  N is the indention
693    to use (in ems, the width of an ``m'') and RELATIVE-TO can be either:
694      :BLOCK - Indent relative to the column the current logical block
695         started on.
696      :CURRENT - Indent relative to the current column.
697    The new indention value does not take effect until the following line
698    break."
699   (declare (type (member :block :current) relative-to)
700            (type integer n)
701            (type (or stream (member t nil)) stream)
702            (values null))
703   (let ((stream (case stream
704                   ((t) *terminal-io*)
705                   ((nil) *standard-output*)
706                   (t stream))))
707     (when (print-pretty-on-stream-p stream)
708       (enqueue-indent stream relative-to n)))
709   nil)
710
711 (defun pprint-tab (kind colnum colinc &optional stream)
712   #!+sb-doc
713   "If STREAM (which defaults to *STANDARD-OUTPUT*) is a pretty-printing
714    stream, perform tabbing based on KIND, otherwise do nothing. KIND can
715    be one of:
716      :LINE - Tab to column COLNUM. If already past COLNUM tab to the next
717        multiple of COLINC.
718      :SECTION - Same as :LINE, but count from the start of the current
719        section, not the start of the line.
720      :LINE-RELATIVE - Output COLNUM spaces, then tab to the next multiple of
721        COLINC.
722      :SECTION-RELATIVE - Same as :LINE-RELATIVE, but count from the start
723        of the current section, not the start of the line."
724   (declare (type (member :line :section :line-relative :section-relative) kind)
725            (type unsigned-byte colnum colinc)
726            (type (or stream (member t nil)) stream)
727            (values null))
728   (let ((stream (case stream
729                   ((t) *terminal-io*)
730                   ((nil) *standard-output*)
731                   (t stream))))
732     (when (print-pretty-on-stream-p stream)
733       (enqueue-tab stream kind colnum colinc)))
734   nil)
735
736 (defun pprint-fill (stream list &optional (colon? t) atsign?)
737   #!+sb-doc
738   "Output LIST to STREAM putting :FILL conditional newlines between each
739    element. If COLON? is NIL (defaults to T), then no parens are printed
740    around the output. ATSIGN? is ignored (but allowed so that PPRINT-FILL
741    can be used with the ~/.../ format directive."
742   (declare (ignore atsign?))
743   (pprint-logical-block (stream list
744                                 :prefix (if colon? "(" "")
745                                 :suffix (if colon? ")" ""))
746     (pprint-exit-if-list-exhausted)
747     (loop
748       (output-object (pprint-pop) stream)
749       (pprint-exit-if-list-exhausted)
750       (write-char #\space stream)
751       (pprint-newline :fill stream))))
752
753 (defun pprint-linear (stream list &optional (colon? t) atsign?)
754   #!+sb-doc
755   "Output LIST to STREAM putting :LINEAR conditional newlines between each
756    element. If COLON? is NIL (defaults to T), then no parens are printed
757    around the output. ATSIGN? is ignored (but allowed so that PPRINT-LINEAR
758    can be used with the ~/.../ format directive."
759   (declare (ignore atsign?))
760   (pprint-logical-block (stream list
761                                 :prefix (if colon? "(" "")
762                                 :suffix (if colon? ")" ""))
763     (pprint-exit-if-list-exhausted)
764     (loop
765       (output-object (pprint-pop) stream)
766       (pprint-exit-if-list-exhausted)
767       (write-char #\space stream)
768       (pprint-newline :linear stream))))
769
770 (defun pprint-tabular (stream list &optional (colon? t) atsign? tabsize)
771   #!+sb-doc
772   "Output LIST to STREAM tabbing to the next column that is an even multiple
773    of TABSIZE (which defaults to 16) between each element. :FILL style
774    conditional newlines are also output between each element. If COLON? is
775    NIL (defaults to T), then no parens are printed around the output.
776    ATSIGN? is ignored (but allowed so that PPRINT-TABULAR can be used with
777    the ~/.../ format directive."
778   (declare (ignore atsign?))
779   (pprint-logical-block (stream list
780                                 :prefix (if colon? "(" "")
781                                 :suffix (if colon? ")" ""))
782     (pprint-exit-if-list-exhausted)
783     (loop
784       (output-object (pprint-pop) stream)
785       (pprint-exit-if-list-exhausted)
786       (write-char #\space stream)
787       (pprint-tab :section-relative 0 (or tabsize 16) stream)
788       (pprint-newline :fill stream))))
789 \f
790 ;;;; pprint-dispatch tables
791
792 (defvar *initial-pprint-dispatch*)
793 (defvar *building-initial-table* nil)
794
795 (defstruct (pprint-dispatch-entry (:copier nil))
796   ;; the type specifier for this entry
797   (type (missing-arg) :type t)
798   ;; a function to test to see whether an object is of this time.
799   ;; Pretty must just (LAMBDA (OBJ) (TYPEP OBJECT TYPE)) except that
800   ;; we handle the CONS type specially so that (CONS (MEMBER FOO))
801   ;; works. We don't bother computing this for entries in the CONS
802   ;; hash table, because we don't need it.
803   (test-fn nil :type (or function null))
804   ;; the priority for this guy
805   (priority 0 :type real)
806   ;; T iff one of the original entries.
807   (initial-p *building-initial-table* :type (member t nil))
808   ;; and the associated function
809   (fun (missing-arg) :type function))
810 (def!method print-object ((entry pprint-dispatch-entry) stream)
811   (print-unreadable-object (entry stream :type t)
812     (format stream "type=~S, priority=~S~@[ [initial]~]"
813             (pprint-dispatch-entry-type entry)
814             (pprint-dispatch-entry-priority entry)
815             (pprint-dispatch-entry-initial-p entry))))
816
817 (defun cons-type-specifier-p (spec)
818   (and (consp spec)
819        (eq (car spec) 'cons)
820        (cdr spec)
821        (null (cddr spec))
822        (let ((car (cadr spec)))
823          (and (consp car)
824               (let ((carcar (car car)))
825                 (or (eq carcar 'member)
826                     (eq carcar 'eql)))
827               (cdr car)
828               (null (cddr car))))))
829
830 (defun entry< (e1 e2)
831   (declare (type pprint-dispatch-entry e1 e2))
832   (if (pprint-dispatch-entry-initial-p e1)
833       (if (pprint-dispatch-entry-initial-p e2)
834           (< (pprint-dispatch-entry-priority e1)
835              (pprint-dispatch-entry-priority e2))
836           t)
837       (if (pprint-dispatch-entry-initial-p e2)
838           nil
839           (< (pprint-dispatch-entry-priority e1)
840              (pprint-dispatch-entry-priority e2)))))
841
842 (macrolet ((frob (x)
843              `(cons ',x (lambda (object) ,x))))
844   (defvar *precompiled-pprint-dispatch-funs*
845     (list (frob (typep object 'array))
846           (frob (and (consp object)
847                      (symbolp (car object))
848                      (fboundp (car object))))
849           (frob (typep object 'cons)))))
850
851 (defun compute-test-fn (type)
852   (let ((was-cons nil))
853     (labels ((compute-test-expr (type object)
854                (if (listp type)
855                    (case (car type)
856                      (cons
857                       (setq was-cons t)
858                       (destructuring-bind
859                           (&optional (car nil car-p) (cdr nil cdr-p))
860                           (cdr type)
861                         `(and (consp ,object)
862                               ,@(when car-p
863                                   `(,(compute-test-expr
864                                       car `(car ,object))))
865                               ,@(when cdr-p
866                                   `(,(compute-test-expr
867                                       cdr `(cdr ,object)))))))
868                      (not
869                       (destructuring-bind (type) (cdr type)
870                         `(not ,(compute-test-expr type object))))
871                      (and
872                       `(and ,@(mapcar (lambda (type)
873                                         (compute-test-expr type object))
874                                       (cdr type))))
875                      (or
876                       `(or ,@(mapcar (lambda (type)
877                                        (compute-test-expr type object))
878                                      (cdr type))))
879                      (t
880                       `(typep ,object ',type)))
881                    `(typep ,object ',type))))
882       (let ((expr (compute-test-expr type 'object)))
883         (cond ((cdr (assoc expr *precompiled-pprint-dispatch-funs*
884                            :test #'equal)))
885               (t
886                (compile nil `(lambda (object) ,expr))))))))
887
888 (defun copy-pprint-dispatch (&optional (table *print-pprint-dispatch*))
889   (declare (type (or pprint-dispatch-table null) table))
890   (let* ((orig (or table *initial-pprint-dispatch*))
891          (new (make-pprint-dispatch-table
892                :entries (copy-list (pprint-dispatch-table-entries orig))))
893          (new-cons-entries (pprint-dispatch-table-cons-entries new)))
894     (maphash (lambda (key value)
895                (setf (gethash key new-cons-entries) value))
896              (pprint-dispatch-table-cons-entries orig))
897     new))
898
899 (defun pprint-dispatch (object &optional (table *print-pprint-dispatch*))
900   (declare (type (or pprint-dispatch-table null) table))
901   (let* ((table (or table *initial-pprint-dispatch*))
902          (cons-entry
903           (and (consp object)
904                (gethash (car object)
905                         (pprint-dispatch-table-cons-entries table))))
906          (entry
907           (dolist (entry (pprint-dispatch-table-entries table) cons-entry)
908             (when (and cons-entry
909                        (entry< entry cons-entry))
910               (return cons-entry))
911             (when (funcall (pprint-dispatch-entry-test-fn entry) object)
912               (return entry)))))
913     (if entry
914         (values (pprint-dispatch-entry-fun entry) t)
915         (values (lambda (stream object)
916                   (output-ugly-object object stream))
917                 nil))))
918
919 (defun set-pprint-dispatch (type function &optional
920                             (priority 0) (table *print-pprint-dispatch*))
921   (declare (type (or null callable) function)
922            (type real priority)
923            (type pprint-dispatch-table table))
924   (/show0 "entering SET-PPRINT-DISPATCH, TYPE=...")
925   (/hexstr type)
926   (if function
927       ;; KLUDGE: this impairs debuggability, and probably isn't even
928       ;; conforming -- maybe we should not coerce to function, but
929       ;; cater downstream (in PPRINT-DISPATCH-ENTRY) for having
930       ;; callables here.
931       (let ((function (%coerce-callable-to-fun function)))
932         (if (cons-type-specifier-p type)
933             (setf (gethash (second (second type))
934                            (pprint-dispatch-table-cons-entries table))
935                   (make-pprint-dispatch-entry :type type
936                                               :priority priority
937                                               :fun function))
938             (let ((list (delete type (pprint-dispatch-table-entries table)
939                                 :key #'pprint-dispatch-entry-type
940                                 :test #'equal))
941                   (entry (make-pprint-dispatch-entry
942                           :type type
943                           :test-fn (compute-test-fn type)
944                           :priority priority
945                           :fun function)))
946               (do ((prev nil next)
947                    (next list (cdr next)))
948                   ((null next)
949                    (if prev
950                        (setf (cdr prev) (list entry))
951                        (setf list (list entry))))
952                 (when (entry< (car next) entry)
953                   (if prev
954                       (setf (cdr prev) (cons entry next))
955                       (setf list (cons entry next)))
956                   (return)))
957               (setf (pprint-dispatch-table-entries table) list))))
958       (if (cons-type-specifier-p type)
959           (remhash (second (second type))
960                    (pprint-dispatch-table-cons-entries table))
961           (setf (pprint-dispatch-table-entries table)
962                 (delete type (pprint-dispatch-table-entries table)
963                         :key #'pprint-dispatch-entry-type
964                         :test #'equal))))
965   (/show0 "about to return NIL from SET-PPRINT-DISPATCH")
966   nil)
967 \f
968 ;;;; standard pretty-printing routines
969
970 (defun pprint-array (stream array)
971   (cond ((or (and (null *print-array*) (null *print-readably*))
972              (stringp array)
973              (bit-vector-p array))
974          (output-ugly-object array stream))
975         ((and *print-readably*
976               (not (array-readably-printable-p array)))
977          (let ((*print-readably* nil))
978            (error 'print-not-readable :object array)))
979         ((vectorp array)
980          (pprint-vector stream array))
981         (t
982          (pprint-multi-dim-array stream array))))
983
984 (defun pprint-vector (stream vector)
985   (pprint-logical-block (stream nil :prefix "#(" :suffix ")")
986     (dotimes (i (length vector))
987       (unless (zerop i)
988         (format stream " ~:_"))
989       (pprint-pop)
990       (output-object (aref vector i) stream))))
991
992 (defun pprint-multi-dim-array (stream array)
993   (funcall (formatter "#~DA") stream (array-rank array))
994   (with-array-data ((data array) (start) (end))
995     (declare (ignore end))
996     (labels ((output-guts (stream index dimensions)
997                (if (null dimensions)
998                    (output-object (aref data index) stream)
999                    (pprint-logical-block
1000                        (stream nil :prefix "(" :suffix ")")
1001                      (let ((dim (car dimensions)))
1002                        (unless (zerop dim)
1003                          (let* ((dims (cdr dimensions))
1004                                 (index index)
1005                                 (step (reduce #'* dims))
1006                                 (count 0))
1007                            (loop
1008                              (pprint-pop)
1009                              (output-guts stream index dims)
1010                              (when (= (incf count) dim)
1011                                (return))
1012                              (write-char #\space stream)
1013                              (pprint-newline (if dims :linear :fill)
1014                                              stream)
1015                              (incf index step)))))))))
1016       (output-guts stream start (array-dimensions array)))))
1017
1018 (defun pprint-lambda-list (stream lambda-list &rest noise)
1019   (declare (ignore noise))
1020   (when (and (consp lambda-list)
1021              (member (car lambda-list) *backq-tokens*))
1022     ;; if this thing looks like a backquoty thing, then we don't want
1023     ;; to destructure it, we want to output it straight away.  [ this
1024     ;; is the exception to the normal processing: if we did this
1025     ;; generally we would find lambda lists such as (FUNCTION FOO)
1026     ;; being printed as #'FOO ]  -- CSR, 2003-12-07
1027     (output-object lambda-list stream)
1028     (return-from pprint-lambda-list nil))
1029   (pprint-logical-block (stream lambda-list :prefix "(" :suffix ")")
1030     (let ((state :required)
1031           (first t))
1032       (loop
1033         (pprint-exit-if-list-exhausted)
1034         (unless first
1035           (write-char #\space stream))
1036         (let ((arg (pprint-pop)))
1037           (unless first
1038             (case arg
1039               (&optional
1040                (setf state :optional)
1041                (pprint-newline :linear stream))
1042               ((&rest &body)
1043                (setf state :required)
1044                (pprint-newline :linear stream))
1045               (&key
1046                (setf state :key)
1047                (pprint-newline :linear stream))
1048               (&aux
1049                (setf state :optional)
1050                (pprint-newline :linear stream))
1051               (t
1052                (pprint-newline :fill stream))))
1053           (ecase state
1054             (:required
1055              (pprint-lambda-list stream arg))
1056             ((:optional :key)
1057              (pprint-logical-block
1058                  (stream arg :prefix "(" :suffix ")")
1059                (pprint-exit-if-list-exhausted)
1060                (if (eq state :key)
1061                    (pprint-logical-block
1062                        (stream (pprint-pop) :prefix "(" :suffix ")")
1063                      (pprint-exit-if-list-exhausted)
1064                      (output-object (pprint-pop) stream)
1065                      (pprint-exit-if-list-exhausted)
1066                      (write-char #\space stream)
1067                      (pprint-newline :fill stream)
1068                      (pprint-lambda-list stream (pprint-pop))
1069                      (loop
1070                        (pprint-exit-if-list-exhausted)
1071                        (write-char #\space stream)
1072                        (pprint-newline :fill stream)
1073                        (output-object (pprint-pop) stream)))
1074                    (pprint-lambda-list stream (pprint-pop)))
1075                (loop
1076                  (pprint-exit-if-list-exhausted)
1077                  (write-char #\space stream)
1078                  (pprint-newline :linear stream)
1079                  (output-object (pprint-pop) stream))))))
1080         (setf first nil)))))
1081
1082 (defun pprint-lambda (stream list &rest noise)
1083   (declare (ignore noise))
1084   (funcall (formatter
1085             ;; KLUDGE: This format string, and other format strings which also
1086             ;; refer to SB!PRETTY, rely on the current SBCL not-quite-ANSI
1087             ;; behavior of FORMATTER in order to make code which survives the
1088             ;; transition when SB!PRETTY is renamed to SB-PRETTY after cold
1089             ;; init. (ANSI says that the FORMATTER functions should be
1090             ;; equivalent to the format string, but the SBCL FORMATTER
1091             ;; functions contain references to package objects, not package
1092             ;; names, so they keep right on going if the packages are renamed.)
1093             ;; If our FORMATTER behavior is ever made more compliant, the code
1094             ;; here will have to change. -- WHN 19991207
1095             "~:<~^~W~^~3I ~:_~/SB!PRETTY:PPRINT-LAMBDA-LIST/~1I~@{ ~_~W~}~:>")
1096            stream
1097            list))
1098
1099 (defun pprint-block (stream list &rest noise)
1100   (declare (ignore noise))
1101   (funcall (formatter "~:<~^~W~^~3I ~:_~W~1I~@{ ~_~W~}~:>") stream list))
1102
1103 (defun pprint-flet (stream list &rest noise)
1104   (declare (ignore noise))
1105   (funcall (formatter
1106             "~:<~^~W~^ ~@_~:<~@{~:<~^~W~^~3I ~:_~/SB!PRETTY:PPRINT-LAMBDA-LIST/~1I~:@_~@{~W~^ ~_~}~:>~^ ~_~}~:>~1I~@:_~@{~W~^ ~_~}~:>")
1107            stream
1108            list))
1109
1110 (defun pprint-let (stream list &rest noise)
1111   (declare (ignore noise))
1112   (funcall (formatter "~:<~^~W~^ ~@_~:<~@{~:<~^~W~@{ ~_~W~}~:>~^ ~_~}~:>~1I~:@_~@{~W~^ ~_~}~:>")
1113            stream
1114            list))
1115
1116 (defun pprint-progn (stream list &rest noise)
1117   (declare (ignore noise))
1118   (funcall (formatter "~:<~^~W~@{ ~_~W~}~:>") stream list))
1119
1120 (defun pprint-progv (stream list &rest noise)
1121   (declare (ignore noise))
1122   (funcall (formatter "~:<~^~W~^~3I ~_~W~^ ~_~W~^~1I~@{ ~_~W~}~:>")
1123            stream list))
1124
1125 (defun pprint-quote (stream list &rest noise)
1126   (declare (ignore noise))
1127   (if (and (consp list)
1128            (consp (cdr list))
1129            (null (cddr list)))
1130       (case (car list)
1131         (function
1132          (write-string "#'" stream)
1133          (output-object (cadr list) stream))
1134         (quote
1135          (write-char #\' stream)
1136          (output-object (cadr list) stream))
1137         (t
1138          (pprint-fill stream list)))
1139       (pprint-fill stream list)))
1140
1141 (defun pprint-setq (stream list &rest noise)
1142   (declare (ignore noise))
1143   (pprint-logical-block (stream list :prefix "(" :suffix ")")
1144     (pprint-exit-if-list-exhausted)
1145     (output-object (pprint-pop) stream)
1146     (pprint-exit-if-list-exhausted)
1147     (write-char #\space stream)
1148     (pprint-newline :miser stream)
1149     (if (and (consp (cdr list)) (consp (cddr list)))
1150         (loop
1151           (pprint-indent :current 2 stream)
1152           (output-object (pprint-pop) stream)
1153           (pprint-exit-if-list-exhausted)
1154           (write-char #\space stream)
1155           (pprint-newline :linear stream)
1156           (pprint-indent :current -2 stream)
1157           (output-object (pprint-pop) stream)
1158           (pprint-exit-if-list-exhausted)
1159           (write-char #\space stream)
1160           (pprint-newline :linear stream))
1161         (progn
1162           (pprint-indent :current 0 stream)
1163           (output-object (pprint-pop) stream)
1164           (pprint-exit-if-list-exhausted)
1165           (write-char #\space stream)
1166           (pprint-newline :linear stream)
1167           (output-object (pprint-pop) stream)))))
1168
1169 ;;; FIXME: could become SB!XC:DEFMACRO wrapped in EVAL-WHEN (COMPILE EVAL)
1170 (defmacro pprint-tagbody-guts (stream)
1171   `(loop
1172      (pprint-exit-if-list-exhausted)
1173      (write-char #\space ,stream)
1174      (let ((form-or-tag (pprint-pop)))
1175        (pprint-indent :block
1176                       (if (atom form-or-tag) 0 1)
1177                       ,stream)
1178        (pprint-newline :linear ,stream)
1179        (output-object form-or-tag ,stream))))
1180
1181 (defun pprint-tagbody (stream list &rest noise)
1182   (declare (ignore noise))
1183   (pprint-logical-block (stream list :prefix "(" :suffix ")")
1184     (pprint-exit-if-list-exhausted)
1185     (output-object (pprint-pop) stream)
1186     (pprint-tagbody-guts stream)))
1187
1188 (defun pprint-case (stream list &rest noise)
1189   (declare (ignore noise))
1190   (funcall (formatter
1191             "~:<~^~W~^ ~3I~:_~W~1I~@{ ~_~:<~^~:/SB!PRETTY:PPRINT-FILL/~^~@{ ~_~W~}~:>~}~:>")
1192            stream
1193            list))
1194
1195 (defun pprint-defun (stream list &rest noise)
1196   (declare (ignore noise))
1197   (funcall (formatter
1198             "~:<~^~W~^ ~@_~:I~W~^ ~:_~/SB!PRETTY:PPRINT-LAMBDA-LIST/~1I~@{ ~_~W~}~:>")
1199            stream
1200            list))
1201
1202 (defun pprint-destructuring-bind (stream list &rest noise)
1203   (declare (ignore noise))
1204   (funcall (formatter
1205             "~:<~^~W~^~3I ~_~:/SB!PRETTY:PPRINT-LAMBDA-LIST/~^ ~_~W~^~1I~@{ ~_~W~}~:>")
1206            stream list))
1207
1208 (defun pprint-do (stream list &rest noise)
1209   (declare (ignore noise))
1210   (pprint-logical-block (stream list :prefix "(" :suffix ")")
1211     (pprint-exit-if-list-exhausted)
1212     (output-object (pprint-pop) stream)
1213     (pprint-exit-if-list-exhausted)
1214     (write-char #\space stream)
1215     (pprint-indent :current 0 stream)
1216     (funcall (formatter "~:<~@{~:<~^~W~^ ~@_~:I~W~@{ ~_~W~}~:>~^~:@_~}~:>")
1217              stream
1218              (pprint-pop))
1219     (pprint-exit-if-list-exhausted)
1220     (write-char #\space stream)
1221     (pprint-newline :linear stream)
1222     (pprint-linear stream (pprint-pop))
1223     (pprint-tagbody-guts stream)))
1224
1225 (defun pprint-dolist (stream list &rest noise)
1226   (declare (ignore noise))
1227   (pprint-logical-block (stream list :prefix "(" :suffix ")")
1228     (pprint-exit-if-list-exhausted)
1229     (output-object (pprint-pop) stream)
1230     (pprint-exit-if-list-exhausted)
1231     (pprint-indent :block 3 stream)
1232     (write-char #\space stream)
1233     (pprint-newline :fill stream)
1234     (funcall (formatter "~:<~^~W~^ ~:_~:I~W~@{ ~_~W~}~:>")
1235              stream
1236              (pprint-pop))
1237     (pprint-tagbody-guts stream)))
1238
1239 (defun pprint-typecase (stream list &rest noise)
1240   (declare (ignore noise))
1241   (funcall (formatter
1242             "~:<~^~W~^ ~3I~:_~W~1I~@{ ~_~:<~^~W~^~@{ ~_~W~}~:>~}~:>")
1243            stream
1244            list))
1245
1246 (defun pprint-prog (stream list &rest noise)
1247   (declare (ignore noise))
1248   (pprint-logical-block (stream list :prefix "(" :suffix ")")
1249     (pprint-exit-if-list-exhausted)
1250     (output-object (pprint-pop) stream)
1251     (pprint-exit-if-list-exhausted)
1252     (write-char #\space stream)
1253     (pprint-newline :miser stream)
1254     (pprint-fill stream (pprint-pop))
1255     (pprint-tagbody-guts stream)))
1256
1257 (defun pprint-fun-call (stream list &rest noise)
1258   (declare (ignore noise))
1259   (funcall (formatter "~:<~^~W~^ ~:_~:I~@{~W~^ ~_~}~:>")
1260            stream
1261            list))
1262 \f
1263 ;;;; the interface seen by regular (ugly) printer and initialization routines
1264
1265 ;;; OUTPUT-PRETTY-OBJECT is called by OUTPUT-OBJECT when
1266 ;;; *PRINT-PRETTY* is true.
1267 (defun output-pretty-object (object stream)
1268   (with-pretty-stream (stream)
1269     (funcall (pprint-dispatch object) stream object)))
1270
1271 (defun !pprint-cold-init ()
1272   (/show0 "entering !PPRINT-COLD-INIT")
1273   (setf *initial-pprint-dispatch* (make-pprint-dispatch-table))
1274   (let ((*print-pprint-dispatch* *initial-pprint-dispatch*)
1275         (*building-initial-table* t))
1276     ;; printers for regular types
1277     (/show0 "doing SET-PPRINT-DISPATCH for regular types")
1278     (set-pprint-dispatch 'array #'pprint-array)
1279     (set-pprint-dispatch '(cons symbol)
1280                          #'pprint-fun-call -1)
1281     (set-pprint-dispatch 'cons #'pprint-fill -2)
1282     ;; cons cells with interesting things for the car
1283     (/show0 "doing SET-PPRINT-DISPATCH for CONS with interesting CAR")
1284
1285     (dolist (magic-form '((lambda pprint-lambda)
1286
1287                           ;; special forms
1288                           (block pprint-block)
1289                           (catch pprint-block)
1290                           (eval-when pprint-block)
1291                           (flet pprint-flet)
1292                           (function pprint-quote)
1293                           (labels pprint-flet)
1294                           (let pprint-let)
1295                           (let* pprint-let)
1296                           (locally pprint-progn)
1297                           (macrolet pprint-flet)
1298                           (multiple-value-call pprint-block)
1299                           (multiple-value-prog1 pprint-block)
1300                           (progn pprint-progn)
1301                           (progv pprint-progv)
1302                           (quote pprint-quote)
1303                           (return-from pprint-block)
1304                           (setq pprint-setq)
1305                           (symbol-macrolet pprint-let)
1306                           (tagbody pprint-tagbody)
1307                           (throw pprint-block)
1308                           (unwind-protect pprint-block)
1309
1310                           ;; macros
1311                           (case pprint-case)
1312                           (ccase pprint-case)
1313                           (ctypecase pprint-typecase)
1314                           (defconstant pprint-block)
1315                           (define-modify-macro pprint-defun)
1316                           (define-setf-expander pprint-defun)
1317                           (defmacro pprint-defun)
1318                           (defparameter pprint-block)
1319                           (defsetf pprint-defun)
1320                           (defstruct pprint-block)
1321                           (deftype pprint-defun)
1322                           (defun pprint-defun)
1323                           (defvar pprint-block)
1324                           (destructuring-bind pprint-destructuring-bind)
1325                           (do pprint-do)
1326                           (do* pprint-do)
1327                           (do-all-symbols pprint-dolist)
1328                           (do-external-symbols pprint-dolist)
1329                           (do-symbols pprint-dolist)
1330                           (dolist pprint-dolist)
1331                           (dotimes pprint-dolist)
1332                           (ecase pprint-case)
1333                           (etypecase pprint-typecase)
1334                           #+nil (handler-bind ...)
1335                           #+nil (handler-case ...)
1336                           #+nil (loop ...)
1337                           (multiple-value-bind pprint-progv)
1338                           (multiple-value-setq pprint-block)
1339                           (pprint-logical-block pprint-block)
1340                           (print-unreadable-object pprint-block)
1341                           (prog pprint-prog)
1342                           (prog* pprint-prog)
1343                           (prog1 pprint-block)
1344                           (prog2 pprint-progv)
1345                           (psetf pprint-setq)
1346                           (psetq pprint-setq)
1347                           #+nil (restart-bind ...)
1348                           #+nil (restart-case ...)
1349                           (setf pprint-setq)
1350                           (step pprint-progn)
1351                           (time pprint-progn)
1352                           (typecase pprint-typecase)
1353                           (unless pprint-block)
1354                           (when pprint-block)
1355                           (with-compilation-unit pprint-block)
1356                           #+nil (with-condition-restarts ...)
1357                           (with-hash-table-iterator pprint-block)
1358                           (with-input-from-string pprint-block)
1359                           (with-open-file pprint-block)
1360                           (with-open-stream pprint-block)
1361                           (with-output-to-string pprint-block)
1362                           (with-package-iterator pprint-block)
1363                           (with-simple-restart pprint-block)
1364                           (with-standard-io-syntax pprint-progn)))
1365
1366       (set-pprint-dispatch `(cons (eql ,(first magic-form)))
1367                            (symbol-function (second magic-form))))
1368
1369     ;; other pretty-print init forms
1370     (/show0 "about to call !BACKQ-PP-COLD-INIT")
1371     (sb!impl::!backq-pp-cold-init)
1372     (/show0 "leaving !PPRINT-COLD-INIT"))
1373
1374   (setf *print-pprint-dispatch* (copy-pprint-dispatch nil))
1375   (setf *print-pretty* t))