0.7.1.16:
[sbcl.git] / src / code / stream.lisp
1 ;;;; os-independent stream functions
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
14 (deftype string-stream ()
15   '(or string-input-stream string-output-stream
16        fill-pointer-output-stream))
17
18 ;;;; standard streams
19
20 ;;; The initialization of these streams is performed by
21 ;;; STREAM-COLD-INIT-OR-RESET.
22 (defvar *terminal-io* () #!+sb-doc "terminal I/O stream")
23 (defvar *standard-input* () #!+sb-doc "default input stream")
24 (defvar *standard-output* () #!+sb-doc "default output stream")
25 (defvar *error-output* () #!+sb-doc "error output stream")
26 (defvar *query-io* () #!+sb-doc "query I/O stream")
27 (defvar *trace-output* () #!+sb-doc "trace output stream")
28 (defvar *debug-io* () #!+sb-doc "interactive debugging stream")
29
30 (defun ill-in (stream &rest ignore)
31   (declare (ignore ignore))
32   (error 'simple-type-error
33          :datum stream
34          :expected-type '(satisfies input-stream-p)
35          :format-control "~S is not a character input stream."
36          :format-arguments (list stream)))
37 (defun ill-out (stream &rest ignore)
38   (declare (ignore ignore))
39   (error 'simple-type-error
40          :datum stream
41          :expected-type '(satisfies output-stream-p)
42          :format-control "~S is not a character output stream."
43          :format-arguments (list stream)))
44 (defun ill-bin (stream &rest ignore)
45   (declare (ignore ignore))
46   (error 'simple-type-error
47          :datum stream
48          :expected-type '(satisfies input-stream-p)
49          :format-control "~S is not a binary input stream."
50          :format-arguments (list stream)))
51 (defun ill-bout (stream &rest ignore)
52   (declare (ignore ignore))
53   (error 'simple-type-error
54          :datum stream
55          :expected-type '(satisfies output-stream-p)
56          :format-control "~S is not a binary output stream."
57          :format-arguments (list stream)))
58 (defun closed-flame (stream &rest ignore)
59   (declare (ignore ignore))
60   (error "~S is closed." stream))
61 (defun no-op-placeholder (&rest ignore)
62   (declare (ignore ignore)))
63 \f
64 ;;; stream manipulation functions
65
66 (defun input-stream-p (stream)
67   (declare (type stream stream))
68
69   #!+high-security
70   (when (synonym-stream-p stream)
71     (setf stream
72           (symbol-value (synonym-stream-symbol stream))))
73
74   (and (ansi-stream-p stream)
75        (not (eq (ansi-stream-in stream) #'closed-flame))
76        ;;; KLUDGE: It's probably not good to have EQ tests on function
77        ;;; values like this. What if someone's redefined the function?
78        ;;; Is there a better way? (Perhaps just VALID-FOR-INPUT and
79        ;;; VALID-FOR-OUTPUT flags? -- WHN 19990902
80        (or (not (eq (ansi-stream-in stream) #'ill-in))
81            (not (eq (ansi-stream-bin stream) #'ill-bin)))))
82
83 (defun output-stream-p (stream)
84   (declare (type stream stream))
85
86   #!+high-security
87   (when (synonym-stream-p stream)
88     (setf stream (symbol-value
89                   (synonym-stream-symbol stream))))
90
91   (and (ansi-stream-p stream)
92        (not (eq (ansi-stream-in stream) #'closed-flame))
93        (or (not (eq (ansi-stream-out stream) #'ill-out))
94            (not (eq (ansi-stream-bout stream) #'ill-bout)))))
95
96 (defun open-stream-p (stream)
97   (declare (type stream stream))
98   (not (eq (ansi-stream-in stream) #'closed-flame)))
99
100 (defun stream-element-type (stream)
101   (declare (type stream stream))
102   (funcall (ansi-stream-misc stream) stream :element-type))
103
104 (defun interactive-stream-p (stream)
105   (declare (type stream stream))
106   (funcall (ansi-stream-misc stream) stream :interactive-p))
107
108 (defun close (stream &key abort)
109   (declare (type stream stream))
110   (when (open-stream-p stream)
111     (funcall (ansi-stream-misc stream) stream :close abort))
112   t)
113
114 (defun set-closed-flame (stream)
115   (setf (ansi-stream-in stream) #'closed-flame)
116   (setf (ansi-stream-bin stream) #'closed-flame)
117   (setf (ansi-stream-n-bin stream) #'closed-flame)
118   (setf (ansi-stream-in stream) #'closed-flame)
119   (setf (ansi-stream-out stream) #'closed-flame)
120   (setf (ansi-stream-bout stream) #'closed-flame)
121   (setf (ansi-stream-sout stream) #'closed-flame)
122   (setf (ansi-stream-misc stream) #'closed-flame))
123 \f
124 ;;;; file position and file length
125
126 ;;; Call the MISC method with the :FILE-POSITION operation.
127 (defun file-position (stream &optional position)
128   (declare (type stream stream))
129   (declare (type (or index (member nil :start :end)) position))
130   (cond
131    (position
132     (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
133     (funcall (ansi-stream-misc stream) stream :file-position position))
134    (t
135     (let ((res (funcall (ansi-stream-misc stream) stream :file-position nil)))
136       (when res
137         (- res
138            (- +ansi-stream-in-buffer-length+
139               (ansi-stream-in-index stream))))))))
140
141 ;;; This is a literal translation of the ANSI glossary entry "stream
142 ;;; associated with a file".
143 ;;;
144 ;;; KLUDGE: Note that since Unix famously thinks "everything is a
145 ;;; file", and in particular stdin, stdout, and stderr are files, we
146 ;;; end up with this test being satisfied for weird things like
147 ;;; *STANDARD-OUTPUT* (to a tty). That seems unlikely to be what the
148 ;;; ANSI spec really had in mind, especially since this is used as a
149 ;;; qualification for operations like FILE-LENGTH (so that ANSI was
150 ;;; probably thinking of something like what Unix calls block devices)
151 ;;; but I can't see any better way to do it. -- WHN 2001-04-14
152 (defun stream-associated-with-file-p (x)
153   "Test for the ANSI concept \"stream associated with a file\"."
154   (or (typep x 'file-stream)
155       (and (synonym-stream-p x)
156            (stream-associated-with-file-p (symbol-value
157                                            (synonym-stream-symbol x))))))
158
159 (defun stream-must-be-associated-with-file (stream)
160   (declare (type stream stream))
161   (unless (stream-associated-with-file-p stream)
162     (error 'simple-type-error
163            ;; KLUDGE: The ANSI spec for FILE-LENGTH specifically says
164            ;; this should be TYPE-ERROR. But what then can we use for
165            ;; EXPECTED-TYPE? This SATISFIES type (with a nonstandard
166            ;; private predicate function..) is ugly and confusing, but
167            ;; I can't see any other way. -- WHN 2001-04-14
168            :expected-type '(satisfies stream-associated-with-file-p)
169            :format-string
170            "~@<The stream ~2I~_~S ~I~_isn't associated with a file.~:>"
171            :format-arguments (list stream))))
172
173 ;;; like FILE-POSITION, only using :FILE-LENGTH
174 (defun file-length (stream)
175   (declare (type (or file-stream synonym-stream) stream))
176   (stream-must-be-associated-with-file stream)
177   (funcall (ansi-stream-misc stream) stream :file-length))
178 \f
179 ;;;; input functions
180
181 (defun read-line (&optional (stream *standard-input*) (eof-error-p t) eof-value
182                             recursive-p)
183   (declare (ignore recursive-p))
184   (let ((stream (in-synonym-of stream)))
185     (if (ansi-stream-p stream)
186         (prepare-for-fast-read-char stream
187           (let ((res (make-string 80))
188                 (len 80)
189                 (index 0))
190             (loop
191              (let ((ch (fast-read-char nil nil)))
192                (cond (ch
193                       (when (char= ch #\newline)
194                         (done-with-fast-read-char)
195                         (return (values (shrink-vector res index) nil)))
196                       (when (= index len)
197                         (setq len (* len 2))
198                         (let ((new (make-string len)))
199                           (replace new res)
200                           (setq res new)))
201                       (setf (schar res index) ch)
202                       (incf index))
203                      ((zerop index)
204                       (done-with-fast-read-char)
205                       (return (values (eof-or-lose stream
206                                                    eof-error-p
207                                                    eof-value)
208                                       t)))
209                      ;; Since FAST-READ-CHAR already hit the eof char, we
210                      ;; shouldn't do another READ-CHAR.
211                      (t
212                       (done-with-fast-read-char)
213                       (return (values (shrink-vector res index) t))))))))
214         ;; must be Gray streams FUNDAMENTAL-STREAM
215         (multiple-value-bind (string eof) (stream-read-line stream)
216           (if (and eof (zerop (length string)))
217               (values (eof-or-lose stream eof-error-p eof-value) t)
218               (values string eof))))))
219
220 ;;; We proclaim them INLINE here, then proclaim them MAYBE-INLINE at EOF,
221 ;;; so, except in this file, they are not inline by default, but they can be.
222 #!-sb-fluid (declaim (inline read-char unread-char read-byte listen))
223
224 (defun read-char (&optional (stream *standard-input*)
225                             (eof-error-p t)
226                             eof-value
227                             recursive-p)
228   (declare (ignore recursive-p))
229   (let ((stream (in-synonym-of stream)))
230     (if (ansi-stream-p stream)
231         (prepare-for-fast-read-char stream
232           (prog1
233               (fast-read-char eof-error-p eof-value)
234             (done-with-fast-read-char)))
235         ;; must be Gray streams FUNDAMENTAL-STREAM
236         (let ((char (stream-read-char stream)))
237           (if (eq char :eof)
238               (eof-or-lose stream eof-error-p eof-value)
239               char)))))
240
241 (defun unread-char (character &optional (stream *standard-input*))
242   (let ((stream (in-synonym-of stream)))
243     (if (ansi-stream-p stream)
244         (let ((index (1- (ansi-stream-in-index stream)))
245               (buffer (ansi-stream-in-buffer stream)))
246           (declare (fixnum index))
247           (when (minusp index) (error "nothing to unread"))
248           (cond (buffer
249                  (setf (aref buffer index) (char-code character))
250                  (setf (ansi-stream-in-index stream) index))
251                 (t
252                  (funcall (ansi-stream-misc stream) stream
253                           :unread character))))
254         ;; must be Gray streams FUNDAMENTAL-STREAM
255         (stream-unread-char stream character)))
256   nil)
257
258 (defun peek-char (&optional (peek-type nil)
259                             (stream *standard-input*)
260                             (eof-error-p t)
261                             eof-value
262                             recursive-p)
263   (declare (ignore recursive-p))
264   ;; FIXME: The type of PEEK-TYPE is also declared in a DEFKNOWN, but
265   ;; the compiler doesn't seem to be smart enough to go from there to
266   ;; imposing a type check. Figure out why (because PEEK-TYPE is an
267   ;; &OPTIONAL argument?) and fix it, and then this explicit type
268   ;; check can go away.
269   (unless (typep peek-type '(or character boolean))
270     (error 'simple-type-error
271            :datum peek-type
272            :expected-type '(or character boolean)
273            :format-control "~@<bad PEEK-TYPE=~S, ~_expected ~S~:>"
274            :format-arguments (list peek-type '(or character boolean))))
275   (let ((stream (in-synonym-of stream)))
276     (if (ansi-stream-p stream)
277         (let ((char (read-char stream eof-error-p eof-value)))
278           (cond ((eq char eof-value) char)
279                 ((characterp peek-type)
280                  (do ((char char (read-char stream eof-error-p eof-value)))
281                      ((or (eq char eof-value) (char= char peek-type))
282                       (unless (eq char eof-value)
283                         (unread-char char stream))
284                       char)))
285                 ((eq peek-type t)
286                  (do ((char char (read-char stream eof-error-p eof-value)))
287                      ((or (eq char eof-value) (not (whitespace-char-p char)))
288                       (unless (eq char eof-value)
289                         (unread-char char stream))
290                       char)))
291                 ((null peek-type)
292                  (unread-char char stream)
293                  char)
294                 (t
295                  (bug "impossible case"))))
296         ;; by elimination, must be Gray streams FUNDAMENTAL-STREAM
297         (cond ((characterp peek-type)
298                (do ((char (stream-read-char stream)
299                           (stream-read-char stream)))
300                    ((or (eq char :eof) (char= char peek-type))
301                     (cond ((eq char :eof)
302                            (eof-or-lose stream eof-error-p eof-value))
303                           (t
304                            (stream-unread-char stream char)
305                            char)))))
306               ((eq peek-type t)
307                (do ((char (stream-read-char stream)
308                           (stream-read-char stream)))
309                    ((or (eq char :eof) (not (whitespace-char-p char)))
310                     (cond ((eq char :eof)
311                            (eof-or-lose stream eof-error-p eof-value))
312                           (t
313                            (stream-unread-char stream char)
314                            char)))))
315               ((null peek-type)
316                (let ((char (stream-peek-char stream)))
317                  (if (eq char :eof)
318                      (eof-or-lose stream eof-error-p eof-value)
319                      char)))
320               (t
321                (bug "impossible case"))))))
322
323 (defun listen (&optional (stream *standard-input*))
324   (let ((stream (in-synonym-of stream)))
325     (if (ansi-stream-p stream)
326         (or (/= (the fixnum (ansi-stream-in-index stream))
327                 +ansi-stream-in-buffer-length+)
328             ;; Test for T explicitly since misc methods return :EOF sometimes.
329             (eq (funcall (ansi-stream-misc stream) stream :listen) t))
330         ;; Fall through to Gray streams FUNDAMENTAL-STREAM case.
331         (stream-listen stream))))
332
333 (defun read-char-no-hang (&optional (stream *standard-input*)
334                                     (eof-error-p t)
335                                     eof-value
336                                     recursive-p)
337   (declare (ignore recursive-p))
338   (let ((stream (in-synonym-of stream)))
339     (if (ansi-stream-p stream)
340         (if (funcall (ansi-stream-misc stream) stream :listen)
341             ;; On T or :EOF get READ-CHAR to do the work.
342             (read-char stream eof-error-p eof-value)
343             nil)
344         ;; must be Gray streams FUNDAMENTAL-STREAM
345         (let ((char (stream-read-char-no-hang stream)))
346           (if (eq char :eof)
347               (eof-or-lose stream eof-error-p eof-value)
348               char)))))
349
350 (defun clear-input (&optional (stream *standard-input*))
351   (let ((stream (in-synonym-of stream)))
352     (cond ((ansi-stream-p stream)
353            (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
354            (funcall (ansi-stream-misc stream) stream :clear-input))
355           (t
356            (stream-clear-input stream))))
357   nil)
358 \f
359 (declaim (maybe-inline read-byte))
360 (defun read-byte (stream &optional (eof-error-p t) eof-value)
361   (let ((stream (in-synonym-of stream)))
362     (if (ansi-stream-p stream)
363         (prepare-for-fast-read-byte stream
364           (prog1
365               (fast-read-byte eof-error-p eof-value t)
366             (done-with-fast-read-byte)))
367         ;; must be Gray streams FUNDAMENTAL-STREAM
368         (let ((char (stream-read-byte stream)))
369           (if (eq char :eof)
370               (eof-or-lose stream eof-error-p eof-value)
371               char)))))
372
373 ;;; Read NUMBYTES bytes into BUFFER beginning at START, and return the
374 ;;; number of bytes read.
375 ;;;
376 ;;; Note: CMU CL's version of this had a special interpretation of
377 ;;; EOF-ERROR-P which SBCL does not have. (In the EOF-ERROR-P=NIL
378 ;;; case, CMU CL's version would return as soon as any data became
379 ;;; available.) This could be useful behavior for things like pipes in
380 ;;; some cases, but it wasn't being used in SBCL, so it was dropped.
381 ;;; If we ever need it, it could be added later as a new variant N-BIN
382 ;;; method (perhaps N-BIN-ASAP?) or something.
383 (defun read-n-bytes (stream buffer start numbytes &optional (eof-error-p t))
384   (declare (type ansi-stream stream)
385            (type index numbytes start)
386            (type (or (simple-array * (*)) system-area-pointer) buffer))
387   (let* ((stream (in-synonym-of stream ansi-stream))
388          (in-buffer (ansi-stream-in-buffer stream))
389          (index (ansi-stream-in-index stream))
390          (num-buffered (- +ansi-stream-in-buffer-length+ index)))
391     (declare (fixnum index num-buffered))
392     (cond
393      ((not in-buffer)
394       (funcall (ansi-stream-n-bin stream)
395                stream
396                buffer
397                start
398                numbytes
399                eof-error-p))
400      ((<= numbytes num-buffered)
401       (%byte-blt in-buffer index
402                  buffer start (+ start numbytes))
403       (setf (ansi-stream-in-index stream) (+ index numbytes))
404       numbytes)
405      (t
406       (let ((end (+ start num-buffered)))
407         (%byte-blt in-buffer index buffer start end)
408         (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
409         (+ (funcall (ansi-stream-n-bin stream)
410                     stream
411                     buffer
412                     end
413                     (- numbytes num-buffered)
414                     eof-error-p)
415            num-buffered))))))
416
417 ;;; the amount of space we leave at the start of the in-buffer for
418 ;;; unreading
419 ;;;
420 ;;; (It's 4 instead of 1 to allow word-aligned copies.)
421 (defconstant +ansi-stream-in-buffer-extra+
422   4) ; FIXME: should be symbolic constant
423
424 ;;; This function is called by the FAST-READ-CHAR expansion to refill
425 ;;; the IN-BUFFER for text streams. There is definitely an IN-BUFFER,
426 ;;; and hence must be an N-BIN method.
427 (defun fast-read-char-refill (stream eof-error-p eof-value)
428   (let* ((ibuf (ansi-stream-in-buffer stream))
429          (count (funcall (ansi-stream-n-bin stream)
430                          stream
431                          ibuf
432                          +ansi-stream-in-buffer-extra+
433                          (- +ansi-stream-in-buffer-length+
434                             +ansi-stream-in-buffer-extra+)
435                          nil))
436          (start (- +ansi-stream-in-buffer-length+ count)))
437     (declare (type index start count))
438     (cond ((zerop count)
439            (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
440            (funcall (ansi-stream-in stream) stream eof-error-p eof-value))
441           (t
442            (when (/= start +ansi-stream-in-buffer-extra+)
443              (bit-bash-copy ibuf (+ (* +ansi-stream-in-buffer-extra+
444                                        sb!vm:n-byte-bits)
445                                     (* sb!vm:vector-data-offset
446                                        sb!vm:n-word-bits))
447                             ibuf (+ (the index (* start sb!vm:n-byte-bits))
448                                     (* sb!vm:vector-data-offset
449                                        sb!vm:n-word-bits))
450                             (* count sb!vm:n-byte-bits)))
451            (setf (ansi-stream-in-index stream) (1+ start))
452            (code-char (aref ibuf start))))))
453
454 ;;; This is similar to FAST-READ-CHAR-REFILL, but we don't have to
455 ;;; leave room for unreading.
456 (defun fast-read-byte-refill (stream eof-error-p eof-value)
457   (let* ((ibuf (ansi-stream-in-buffer stream))
458          (count (funcall (ansi-stream-n-bin stream) stream
459                          ibuf 0 +ansi-stream-in-buffer-length+
460                          nil))
461          (start (- +ansi-stream-in-buffer-length+ count)))
462     (declare (type index start count))
463     (cond ((zerop count)
464            (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
465            (funcall (ansi-stream-bin stream) stream eof-error-p eof-value))
466           (t
467            (unless (zerop start)
468              (bit-bash-copy ibuf (* sb!vm:vector-data-offset sb!vm:n-word-bits)
469                             ibuf (+ (the index (* start sb!vm:n-byte-bits))
470                                     (* sb!vm:vector-data-offset
471                                        sb!vm:n-word-bits))
472                             (* count sb!vm:n-byte-bits)))
473            (setf (ansi-stream-in-index stream) (1+ start))
474            (aref ibuf start)))))
475 \f
476 ;;; output functions
477
478 (defun write-char (character &optional (stream *standard-output*))
479   (with-out-stream stream (ansi-stream-out character)
480                    (stream-write-char character))
481   character)
482
483 (defun terpri (&optional (stream *standard-output*))
484   (with-out-stream stream (ansi-stream-out #\newline) (stream-terpri))
485   nil)
486
487 (defun fresh-line (&optional (stream *standard-output*))
488   (let ((stream (out-synonym-of stream)))
489     (if (ansi-stream-p stream)
490         (when (/= (or (charpos stream) 1) 0)
491           (funcall (ansi-stream-out stream) stream #\newline)
492           t)
493         ;; must be Gray streams FUNDAMENTAL-STREAM
494         (stream-fresh-line stream))))
495
496 (defun write-string (string &optional (stream *standard-output*)
497                             &key (start 0) (end nil))
498   (%write-string string stream start (or end (length string)))
499   string)
500
501 (defun %write-string (string stream start end)
502   (declare (type string string))
503   (declare (type streamlike stream))
504   (declare (type index start end))
505
506   ;; Note that even though you might expect, based on the behavior of
507   ;; things like AREF, that the correct upper bound here is
508   ;; (ARRAY-DIMENSION STRING 0), the ANSI glossary definitions for
509   ;; "bounding index" and "length" indicate that in this case (i.e.
510   ;; for the ANSI-specified functions WRITE-STRING and WRITE-LINE
511   ;; which are implemented in terms of this function), (LENGTH STRING)
512   ;; is the required upper bound. A foolish consistency is the
513   ;; hobgoblin of lesser languages..
514   (unless (<= 0 start end (length string))
515     (error "~@<bad bounding indices START=~W END=~W for ~2I~_~S~:>"
516            start
517            end
518            string))
519
520   (let ((stream (out-synonym-of stream)))
521     (cond ((ansi-stream-p stream)
522            (if (array-header-p string)
523                (with-array-data ((data string) (offset-start start)
524                                  (offset-end end))
525                  (funcall (ansi-stream-sout stream)
526                           stream data offset-start offset-end))
527                (funcall (ansi-stream-sout stream) stream string start end))
528            string)
529           (t ; must be Gray streams FUNDAMENTAL-STREAM
530            (stream-write-string stream string start end)))))
531
532 (defun write-line (string &optional (stream *standard-output*)
533                           &key (start 0) (end nil))
534   (let ((defaulted-stream (out-synonym-of stream))
535         (defaulted-end (or end (length string))))
536     (%write-string string defaulted-stream start defaulted-end)
537     (write-char #\newline defaulted-stream))
538   string)
539
540 (defun charpos (&optional (stream *standard-output*))
541   (with-out-stream stream (ansi-stream-misc :charpos) (stream-line-column)))
542
543 (defun line-length (&optional (stream *standard-output*))
544   (with-out-stream stream (ansi-stream-misc :line-length)
545                    (stream-line-length)))
546
547 (defun finish-output (&optional (stream *standard-output*))
548   (with-out-stream stream (ansi-stream-misc :finish-output)
549                    (stream-finish-output))
550   nil)
551
552 (defun force-output (&optional (stream *standard-output*))
553   (with-out-stream stream (ansi-stream-misc :force-output)
554                    (stream-force-output))
555   nil)
556
557 (defun clear-output (&optional (stream *standard-output*))
558   (with-out-stream stream (ansi-stream-misc :clear-output)
559                    (stream-force-output))
560   nil)
561
562 (defun write-byte (integer stream)
563   (with-out-stream stream (ansi-stream-bout integer)
564                    (stream-write-byte integer))
565   integer)
566 \f
567 ;;; This is called from ANSI-STREAM routines that encapsulate CLOS
568 ;;; streams to handle the misc routines and dispatch to the
569 ;;; appropriate Gray stream functions.
570 (defun stream-misc-dispatch (stream operation &optional arg1 arg2)
571   (declare (type fundamental-stream stream)
572            (ignore arg2))
573   (case operation
574     (:listen
575      ;; Return T if input available, :EOF for end-of-file, otherwise NIL.
576      (let ((char (stream-read-char-no-hang stream)))
577        (when (characterp char)
578          (stream-unread-char stream char))
579        char))
580     (:unread
581      (stream-unread-char stream arg1))
582     (:close
583      (close stream))
584     (:clear-input
585      (stream-clear-input stream))
586     (:force-output
587      (stream-force-output stream))
588     (:finish-output
589      (stream-finish-output stream))
590     (:element-type
591      (stream-element-type stream))
592     (:interactive-p
593      (interactive-stream-p stream))
594     (:line-length
595      (stream-line-length stream))
596     (:charpos
597      (stream-line-column stream))
598     (:file-length
599      (file-length stream))
600     (:file-position
601      (file-position stream arg1))))
602 \f
603 ;;;; broadcast streams
604
605 (defstruct (broadcast-stream (:include ansi-stream
606                                        (out #'broadcast-out)
607                                        (bout #'broadcast-bout)
608                                        (sout #'broadcast-sout)
609                                        (misc #'broadcast-misc))
610                              (:constructor #!-high-security-support
611                                            make-broadcast-stream
612                                            #!+high-security-support
613                                            %make-broadcast-stream (&rest
614                                                                    streams))
615                              (:copier nil))
616   ;; a list of all the streams we broadcast to
617   (streams () :type list :read-only t))
618
619 #!+high-security-support
620 (defun make-broadcast-stream (&rest streams)
621   (dolist (stream streams)
622     (unless (or (and (synonym-stream-p stream)
623                      (output-stream-p (symbol-value
624                                        (synonym-stream-symbol stream))))
625                 (output-stream-p stream))
626       (error 'type-error
627              :datum stream
628              :expected-type '(satisfies output-stream-p))))
629   (apply #'%make-broadcast-stream streams))
630
631 (macrolet ((out-fun (fun method stream-method &rest args)
632              `(defun ,fun (stream ,@args)
633                 (dolist (stream (broadcast-stream-streams stream))
634                   (if (ansi-stream-p stream)
635                       (funcall (,method stream) stream ,@args)
636                       (,stream-method stream ,@args))))))
637   (out-fun broadcast-out ansi-stream-out stream-write-char char)
638   (out-fun broadcast-bout ansi-stream-bout stream-write-byte byte)
639   (out-fun broadcast-sout ansi-stream-sout stream-write-string
640            string start end))
641
642 (defun broadcast-misc (stream operation &optional arg1 arg2)
643   (let ((streams (broadcast-stream-streams stream)))
644     (case operation
645       (:charpos
646        (dolist (stream streams)
647          (let ((charpos (charpos stream)))
648            (if charpos (return charpos)))))
649       (:line-length
650        (let ((min nil))
651          (dolist (stream streams min)
652            (let ((res (line-length stream)))
653              (when res (setq min (if min (min res min) res)))))))
654       (:element-type
655        (let (res)
656          (dolist (stream streams (if (> (length res) 1) `(and ,@res) res))
657            (pushnew (stream-element-type stream) res :test #'equal))))
658       (:close)
659       (t
660        (let ((res nil))
661          (dolist (stream streams res)
662            (setq res
663                  (if (ansi-stream-p stream)
664                      (funcall (ansi-stream-misc stream) stream operation
665                               arg1 arg2)
666                      (stream-misc-dispatch stream operation arg1 arg2)))))))))
667 \f
668 ;;;; synonym streams
669
670 (defstruct (synonym-stream (:include ansi-stream
671                                      (in #'synonym-in)
672                                      (bin #'synonym-bin)
673                                      (n-bin #'synonym-n-bin)
674                                      (out #'synonym-out)
675                                      (bout #'synonym-bout)
676                                      (sout #'synonym-sout)
677                                      (misc #'synonym-misc))
678                            (:constructor make-synonym-stream (symbol))
679                            (:copier nil))
680   ;; This is the symbol, the value of which is the stream we are synonym to.
681   (symbol nil :type symbol :read-only t))
682 (def!method print-object ((x synonym-stream) stream)
683   (print-unreadable-object (x stream :type t :identity t)
684     (format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
685
686 ;;; The output simple output methods just call the corresponding method
687 ;;; in the synonymed stream.
688 (macrolet ((out-fun (name slot stream-method &rest args)
689              `(defun ,name (stream ,@args)
690                 (declare (optimize (safety 1)))
691                 (let ((syn (symbol-value (synonym-stream-symbol stream))))
692                   (if (ansi-stream-p syn)
693                       (funcall (,slot syn) syn ,@args)
694                       (,stream-method syn ,@args))))))
695   (out-fun synonym-out ansi-stream-out stream-write-char ch)
696   (out-fun synonym-bout ansi-stream-bout stream-write-byte n)
697   (out-fun synonym-sout ansi-stream-sout stream-write-string string start end))
698
699 ;;; For the input methods, we just call the corresponding function on the
700 ;;; synonymed stream. These functions deal with getting input out of
701 ;;; the In-Buffer if there is any.
702 (macrolet ((in-fun (name fun &rest args)
703              `(defun ,name (stream ,@args)
704                 (declare (optimize (safety 1)))
705                 (,fun (symbol-value (synonym-stream-symbol stream))
706                       ,@args))))
707   (in-fun synonym-in read-char eof-error-p eof-value)
708   (in-fun synonym-bin read-byte eof-error-p eof-value)
709   (in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
710
711 (defun synonym-misc (stream operation &optional arg1 arg2)
712   (declare (optimize (safety 1)))
713   (let ((syn (symbol-value (synonym-stream-symbol stream))))
714     (if (ansi-stream-p syn)
715         ;; We have to special-case some operations which interact with
716         ;; the in-buffer of the wrapped stream, since just calling
717         ;; ANSI-STREAM-MISC on them
718         (case operation
719           (:listen (or (/= (the fixnum (ansi-stream-in-index syn))
720                            +ansi-stream-in-buffer-length+)
721                        (funcall (ansi-stream-misc syn) syn :listen)))
722           (:clear-input (clear-input syn))
723           (:unread (unread-char arg1 syn))
724           (t
725            (funcall (ansi-stream-misc syn) syn operation arg1 arg2)))
726         (stream-misc-dispatch syn operation arg1 arg2))))
727 \f
728 ;;;; two-way streams
729
730 (defstruct (two-way-stream
731             (:include ansi-stream
732                       (in #'two-way-in)
733                       (bin #'two-way-bin)
734                       (n-bin #'two-way-n-bin)
735                       (out #'two-way-out)
736                       (bout #'two-way-bout)
737                       (sout #'two-way-sout)
738                       (misc #'two-way-misc))
739             (:constructor #!-high-security-support
740                           make-two-way-stream
741                           #!+high-security-support
742                           %make-two-way-stream (input-stream output-stream))
743             (:copier nil))
744   (input-stream (missing-arg) :type stream :read-only t)
745   (output-stream (missing-arg) :type stream :read-only t))
746 (defprinter (two-way-stream) input-stream output-stream)
747
748 #!-high-security-support
749 (setf (fdocumentation 'make-two-way-stream 'function)
750   "Return a bidirectional stream which gets its input from Input-Stream and
751    sends its output to Output-Stream.")
752 #!+high-security-support
753 (defun make-two-way-stream (input-stream output-stream)
754   #!+sb-doc
755   "Return a bidirectional stream which gets its input from Input-Stream and
756    sends its output to Output-Stream."
757   ;; FIXME: This idiom of the-real-stream-of-a-possibly-synonym-stream
758   ;; should be encapsulated in a function, and used here and most of
759   ;; the other places that SYNONYM-STREAM-P appears.
760   (unless (or (and (synonym-stream-p output-stream)
761                    (output-stream-p (symbol-value
762                                      (synonym-stream-symbol output-stream))))
763               (output-stream-p output-stream))
764     (error 'type-error
765            :datum output-stream
766            :expected-type '(satisfies output-stream-p)))
767   (unless (or (and (synonym-stream-p input-stream)
768                    (input-stream-p (symbol-value
769                                     (synonym-stream-symbol input-stream))))
770               (input-stream-p input-stream))
771     (error 'type-error
772            :datum input-stream
773            :expected-type '(satisfies input-stream-p)))
774   (funcall #'%make-two-way-stream input-stream output-stream))
775
776 (macrolet ((out-fun (name slot stream-method &rest args)
777              `(defun ,name (stream ,@args)
778                 (let ((syn (two-way-stream-output-stream stream)))
779                   (if (ansi-stream-p syn)
780                       (funcall (,slot syn) syn ,@args)
781                       (,stream-method syn ,@args))))))
782   (out-fun two-way-out ansi-stream-out stream-write-char ch)
783   (out-fun two-way-bout ansi-stream-bout stream-write-byte n)
784   (out-fun two-way-sout ansi-stream-sout stream-write-string string start end))
785
786 (macrolet ((in-fun (name fun &rest args)
787              `(defun ,name (stream ,@args)
788                 (force-output (two-way-stream-output-stream stream))
789                 (,fun (two-way-stream-input-stream stream) ,@args))))
790   (in-fun two-way-in read-char eof-error-p eof-value)
791   (in-fun two-way-bin read-byte eof-error-p eof-value)
792   (in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
793
794 (defun two-way-misc (stream operation &optional arg1 arg2)
795   (let* ((in (two-way-stream-input-stream stream))
796          (out (two-way-stream-output-stream stream))
797          (in-ansi-stream-p (ansi-stream-p in))
798          (out-ansi-stream-p (ansi-stream-p out)))
799     (case operation
800       (:listen
801        (if in-ansi-stream-p
802            (or (/= (the fixnum (ansi-stream-in-index in))
803                    +ansi-stream-in-buffer-length+)
804                (funcall (ansi-stream-misc in) in :listen))
805            (stream-listen in)))
806       ((:finish-output :force-output :clear-output)
807        (if out-ansi-stream-p
808            (funcall (ansi-stream-misc out) out operation arg1 arg2)
809            (stream-misc-dispatch out operation arg1 arg2)))
810       (:clear-input (clear-input in))
811       (:unread (unread-char arg1 in))
812       (:element-type
813        (let ((in-type (stream-element-type in))
814              (out-type (stream-element-type out)))
815          (if (equal in-type out-type)
816              in-type `(and ,in-type ,out-type))))
817       (:close
818        (set-closed-flame stream))
819       (t
820        (or (if in-ansi-stream-p
821                (funcall (ansi-stream-misc in) in operation arg1 arg2)
822                (stream-misc-dispatch in operation arg1 arg2))
823            (if out-ansi-stream-p
824                (funcall (ansi-stream-misc out) out operation arg1 arg2)
825                (stream-misc-dispatch out operation arg1 arg2)))))))
826 \f
827 ;;;; concatenated streams
828
829 (defstruct (concatenated-stream
830             (:include ansi-stream
831                       (in #'concatenated-in)
832                       (bin #'concatenated-bin)
833                       (n-bin #'concatenated-n-bin)
834                       (misc #'concatenated-misc))
835             (:constructor
836              #!-high-security-support make-concatenated-stream
837              #!+high-security-support %make-concatenated-stream
838                  (&rest streams &aux (current streams)))
839             (:copier nil))
840   ;; The car of this is the substream we are reading from now.
841   current
842   ;; This is a list of all the substreams there ever were. We need to
843   ;; remember them so that we can close them.
844   ;;
845   ;; FIXME: ANSI says this is supposed to be the list of streams that
846   ;; we still have to read from. So either this needs to become a
847   ;; private member %STREAM (with CONCATENATED-STREAM-STREAMS a wrapper
848   ;; around it which discards closed files from the head of the list)
849   ;; or we need to update it as we run out of files.
850   (streams nil :type list :read-only t))
851 (def!method print-object ((x concatenated-stream) stream)
852   (print-unreadable-object (x stream :type t :identity t)
853     (format stream
854             ":STREAMS ~S"
855             (concatenated-stream-streams x))))
856
857 #!-high-security-support
858 (setf (fdocumentation 'make-concatenated-stream 'function)
859   "Return a stream which takes its input from each of the Streams in turn,
860    going on to the next at EOF.")
861
862 #!+high-security-support
863 (defun make-concatenated-stream (&rest streams)
864   #!+sb-doc
865   "Return a stream which takes its input from each of the Streams in turn,
866    going on to the next at EOF."
867   (dolist (stream streams)
868     (unless (or (and (synonym-stream-p stream)
869                      (input-stream-p (symbol-value
870                                       (synonym-stream-symbol stream))))
871                 (input-stream-p stream))
872       (error 'type-error
873              :datum stream
874              :expected-type '(satisfies input-stream-p))))
875   (apply #'%make-concatenated-stream streams))
876
877 (macrolet ((in-fun (name fun)
878              `(defun ,name (stream eof-error-p eof-value)
879                 (do ((current (concatenated-stream-current stream)
880                               (cdr current)))
881                     ((null current)
882                      (eof-or-lose stream eof-error-p eof-value))
883                   (let* ((stream (car current))
884                          (result (,fun stream nil nil)))
885                     (when result (return result)))
886                   (setf (concatenated-stream-current stream) current)))))
887   (in-fun concatenated-in read-char)
888   (in-fun concatenated-bin read-byte))
889
890 (defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
891   (do ((current (concatenated-stream-current stream) (cdr current))
892        (current-start start)
893        (remaining-bytes numbytes))
894       ((null current)
895        (if eof-errorp
896            (error 'end-of-file :stream stream)
897            (- numbytes remaining-bytes)))
898     (let* ((stream (car current))
899            (bytes-read (read-n-bytes stream buffer current-start
900                                      remaining-bytes nil)))
901       (incf current-start bytes-read)
902       (decf remaining-bytes bytes-read)
903       (when (zerop remaining-bytes) (return numbytes)))
904     (setf (concatenated-stream-current stream) (cdr current))))
905
906 (defun concatenated-misc (stream operation &optional arg1 arg2)
907   (let ((left (concatenated-stream-current stream)))
908     (when left
909       (let* ((current (car left)))
910         (case operation
911           (:listen
912            (loop
913              (let ((stuff (if (ansi-stream-p current)
914                               (funcall (ansi-stream-misc current) current
915                                        :listen)
916                               (stream-misc-dispatch current :listen))))
917                (cond ((eq stuff :eof)
918                       ;; Advance CURRENT, and try again.
919                       (pop (concatenated-stream-current stream))
920                       (setf current
921                             (car (concatenated-stream-current stream)))
922                       (unless current
923                         ;; No further streams. EOF.
924                         (return :eof)))
925                      (stuff
926                       ;; Stuff's available.
927                       (return t))
928                      (t
929                       ;; Nothing is available yet.
930                       (return nil))))))
931           (:clear-input (clear-input current))
932           (:unread (unread-char arg1 current))
933           (:close
934            (set-closed-flame stream))
935           (t
936            (if (ansi-stream-p current)
937                (funcall (ansi-stream-misc current) current operation arg1 arg2)
938                (stream-misc-dispatch current operation arg1 arg2))))))))
939 \f
940 ;;;; echo streams
941
942 (defstruct (echo-stream
943             (:include two-way-stream
944                       (in #'echo-in)
945                       (bin #'echo-bin)
946                       (misc #'echo-misc)
947                       (n-bin #'ill-bin))
948             (:constructor make-echo-stream (input-stream output-stream))
949             (:copier nil))
950   unread-stuff)
951 (def!method print-object ((x echo-stream) stream)
952   (print-unreadable-object (x stream :type t :identity t)
953     (format stream
954             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
955             (two-way-stream-input-stream x)
956             (two-way-stream-output-stream x))))
957
958 (macrolet ((in-fun (name fun out-slot stream-method &rest args)
959              `(defun ,name (stream ,@args)
960                 (or (pop (echo-stream-unread-stuff stream))
961                     (let* ((in (echo-stream-input-stream stream))
962                            (out (echo-stream-output-stream stream))
963                            (result (,fun in ,@args)))
964                       (if (ansi-stream-p out)
965                           (funcall (,out-slot out) out result)
966                           (,stream-method out result))
967                       result)))))
968   (in-fun echo-in read-char ansi-stream-out stream-write-char
969           eof-error-p eof-value)
970   (in-fun echo-bin read-byte ansi-stream-bout stream-write-byte
971           eof-error-p eof-value))
972
973 (defun echo-misc (stream operation &optional arg1 arg2)
974   (let* ((in (two-way-stream-input-stream stream))
975          (out (two-way-stream-output-stream stream)))
976     (case operation
977       (:listen
978        (or (not (null (echo-stream-unread-stuff stream)))
979            (if (ansi-stream-p in)
980                (or (/= (the fixnum (ansi-stream-in-index in))
981                        +ansi-stream-in-buffer-length+)
982                    (funcall (ansi-stream-misc in) in :listen))
983                (stream-misc-dispatch in :listen))))
984       (:unread (push arg1 (echo-stream-unread-stuff stream)))
985       (:element-type
986        (let ((in-type (stream-element-type in))
987              (out-type (stream-element-type out)))
988          (if (equal in-type out-type)
989              in-type `(and ,in-type ,out-type))))
990       (:close
991        (set-closed-flame stream))
992       (t
993        (or (if (ansi-stream-p in)
994                (funcall (ansi-stream-misc in) in operation arg1 arg2)
995                (stream-misc-dispatch in operation arg1 arg2))
996            (if (ansi-stream-p out)
997                (funcall (ansi-stream-misc out) out operation arg1 arg2)
998                (stream-misc-dispatch out operation arg1 arg2)))))))
999
1000 #!+sb-doc
1001 (setf (fdocumentation 'make-echo-stream 'function)
1002   "Return a bidirectional stream which gets its input from INPUT-STREAM and
1003    sends its output to OUTPUT-STREAM. In addition, all input is echoed to
1004    the output stream")
1005 \f
1006 ;;;; string input streams
1007
1008 (defstruct (string-input-stream
1009              (:include ansi-stream
1010                        (in #'string-inch)
1011                        (bin #'string-binch)
1012                        (n-bin #'string-stream-read-n-bytes)
1013                        (misc #'string-in-misc))
1014              (:constructor internal-make-string-input-stream
1015                            (string current end))
1016              (:copier nil))
1017   (string nil :type simple-string)
1018   (current nil :type index)
1019   (end nil :type index))
1020
1021 (defun string-inch (stream eof-error-p eof-value)
1022   (let ((string (string-input-stream-string stream))
1023         (index (string-input-stream-current stream)))
1024     (declare (simple-string string) (fixnum index))
1025     (cond ((= index (the index (string-input-stream-end stream)))
1026            (eof-or-lose stream eof-error-p eof-value))
1027           (t
1028            (setf (string-input-stream-current stream) (1+ index))
1029            (aref string index)))))
1030
1031 (defun string-binch (stream eof-error-p eof-value)
1032   (let ((string (string-input-stream-string stream))
1033         (index (string-input-stream-current stream)))
1034     (declare (simple-string string)
1035              (type index index))
1036     (cond ((= index (the index (string-input-stream-end stream)))
1037            (eof-or-lose stream eof-error-p eof-value))
1038           (t
1039            (setf (string-input-stream-current stream) (1+ index))
1040            (char-code (aref string index))))))
1041
1042 (defun string-stream-read-n-bytes (stream buffer start requested eof-error-p)
1043   (declare (type string-input-stream stream)
1044            (type index start requested))
1045   (let* ((string (string-input-stream-string stream))
1046          (index (string-input-stream-current stream))
1047          (available (- (string-input-stream-end stream) index))
1048          (copy (min available requested)))
1049     (declare (simple-string string)
1050              (type index index available copy))
1051     (when (plusp copy)
1052       (setf (string-input-stream-current stream)
1053             (truly-the index (+ index copy)))
1054       (sb!sys:without-gcing
1055        (system-area-copy (vector-sap string)
1056                          (* index sb!vm:n-byte-bits)
1057                          (if (typep buffer 'system-area-pointer)
1058                              buffer
1059                              (vector-sap buffer))
1060                          (* start sb!vm:n-byte-bits)
1061                          (* copy sb!vm:n-byte-bits))))
1062     (if (and (> requested copy) eof-error-p)
1063         (error 'end-of-file :stream stream)
1064         copy)))
1065
1066 (defun string-in-misc (stream operation &optional arg1 arg2)
1067   (declare (ignore arg2))
1068   (case operation
1069     (:file-position
1070      (if arg1
1071          (setf (string-input-stream-current stream) arg1)
1072          (string-input-stream-current stream)))
1073     (:file-length (length (string-input-stream-string stream)))
1074     (:unread (decf (string-input-stream-current stream)))
1075     (:listen (or (/= (the fixnum (string-input-stream-current stream))
1076                      (the fixnum (string-input-stream-end stream)))
1077                  :eof))
1078     (:element-type 'base-char)))
1079
1080 (defun make-string-input-stream (string &optional
1081                                         (start 0) (end (length string)))
1082   #!+sb-doc
1083   "Return an input stream which will supply the characters of STRING between
1084   START and END in order."
1085   (declare (type string string)
1086            (type index start)
1087            (type (or index null) end))
1088
1089   #!+high-security
1090   (when (> end (length string))
1091     (cerror "Continue with end changed from ~S to ~S"
1092             "Write-string: end (~S) is larger then the length of the string (~S)"
1093             end (1- (length string))))
1094
1095   (internal-make-string-input-stream (coerce string 'simple-string)
1096                                      start end))
1097 \f
1098 ;;;; string output streams
1099
1100 (defstruct (string-output-stream
1101             (:include ansi-stream
1102                       (out #'string-ouch)
1103                       (sout #'string-sout)
1104                       (misc #'string-out-misc))
1105             (:constructor make-string-output-stream ())
1106             (:copier nil))
1107   ;; The string we throw stuff in.
1108   (string (make-string 40) :type simple-string)
1109   ;; Index of the next location to use.
1110   (index 0 :type fixnum))
1111
1112 #!+sb-doc
1113 (setf (fdocumentation 'make-string-output-stream 'function)
1114   "Return an output stream which will accumulate all output given it for
1115    the benefit of the function GET-OUTPUT-STREAM-STRING.")
1116
1117 (defun string-ouch (stream character)
1118   (let ((current (string-output-stream-index stream))
1119         (workspace (string-output-stream-string stream)))
1120     (declare (simple-string workspace) (fixnum current))
1121     (if (= current (the fixnum (length workspace)))
1122         (let ((new-workspace (make-string (* current 2))))
1123           (replace new-workspace workspace)
1124           (setf (aref new-workspace current) character)
1125           (setf (string-output-stream-string stream) new-workspace))
1126         (setf (aref workspace current) character))
1127     (setf (string-output-stream-index stream) (1+ current))))
1128
1129 (defun string-sout (stream string start end)
1130   (declare (simple-string string) (fixnum start end))
1131   (let* ((current (string-output-stream-index stream))
1132          (length (- end start))
1133          (dst-end (+ length current))
1134          (workspace (string-output-stream-string stream)))
1135     (declare (simple-string workspace)
1136              (fixnum current length dst-end))
1137     (if (> dst-end (the fixnum (length workspace)))
1138         (let ((new-workspace (make-string (+ (* current 2) length))))
1139           (replace new-workspace workspace :end2 current)
1140           (replace new-workspace string
1141                    :start1 current :end1 dst-end
1142                    :start2 start :end2 end)
1143           (setf (string-output-stream-string stream) new-workspace))
1144         (replace workspace string
1145                  :start1 current :end1 dst-end
1146                  :start2 start :end2 end))
1147     (setf (string-output-stream-index stream) dst-end)))
1148
1149 (defun string-out-misc (stream operation &optional arg1 arg2)
1150   (declare (ignore arg2))
1151   (case operation
1152     (:file-position
1153      (if (null arg1)
1154          (string-output-stream-index stream)))
1155     (:charpos
1156      (do ((index (1- (the fixnum (string-output-stream-index stream)))
1157                  (1- index))
1158           (count 0 (1+ count))
1159           (string (string-output-stream-string stream)))
1160          ((< index 0) count)
1161        (declare (simple-string string)
1162                 (fixnum index count))
1163        (if (char= (schar string index) #\newline)
1164            (return count))))
1165     (:element-type 'base-char)))
1166
1167 ;;; Return a string of all the characters sent to a stream made by
1168 ;;; MAKE-STRING-OUTPUT-STREAM since the last call to this function.
1169 (defun get-output-stream-string (stream)
1170   (declare (type string-output-stream stream))
1171   (let* ((length (string-output-stream-index stream))
1172          (result (make-string length)))
1173     (replace result (string-output-stream-string stream))
1174     (setf (string-output-stream-index stream) 0)
1175     result))
1176
1177 ;;; Dump the characters buffer up in IN-STREAM to OUT-STREAM as
1178 ;;; GET-OUTPUT-STREAM-STRING would return them.
1179 (defun dump-output-stream-string (in-stream out-stream)
1180   (%write-string (string-output-stream-string in-stream)
1181                  out-stream
1182                  0
1183                  (string-output-stream-index in-stream))
1184   (setf (string-output-stream-index in-stream) 0))
1185 \f
1186 ;;;; fill-pointer streams
1187
1188 ;;; Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
1189 ;;; the CLM, but they are required for the implementation of
1190 ;;; WITH-OUTPUT-TO-STRING.
1191
1192 (defstruct (fill-pointer-output-stream
1193             (:include ansi-stream
1194                       (out #'fill-pointer-ouch)
1195                       (sout #'fill-pointer-sout)
1196                       (misc #'fill-pointer-misc))
1197             (:constructor make-fill-pointer-output-stream (string))
1198             (:copier nil))
1199   ;; the string we throw stuff in
1200   string)
1201
1202 (defun fill-pointer-ouch (stream character)
1203   (let* ((buffer (fill-pointer-output-stream-string stream))
1204          (current (fill-pointer buffer))
1205          (current+1 (1+ current)))
1206     (declare (fixnum current))
1207     (with-array-data ((workspace buffer) (start) (end))
1208       (declare (simple-string workspace))
1209       (let ((offset-current (+ start current)))
1210         (declare (fixnum offset-current))
1211         (if (= offset-current end)
1212             (let* ((new-length (1+ (* current 2)))
1213                    (new-workspace (make-string new-length)))
1214               (declare (simple-string new-workspace))
1215               (%byte-blt workspace start
1216                          new-workspace 0 current)
1217               (setf workspace new-workspace)
1218               (setf offset-current current)
1219               (set-array-header buffer workspace new-length
1220                                 current+1 0 new-length nil))
1221             (setf (fill-pointer buffer) current+1))
1222         (setf (schar workspace offset-current) character)))
1223     current+1))
1224
1225 (defun fill-pointer-sout (stream string start end)
1226   (declare (simple-string string) (fixnum start end))
1227   (let* ((buffer (fill-pointer-output-stream-string stream))
1228          (current (fill-pointer buffer))
1229          (string-len (- end start))
1230          (dst-end (+ string-len current)))
1231     (declare (fixnum current dst-end string-len))
1232     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1233       (declare (simple-string workspace))
1234       (let ((offset-dst-end (+ dst-start dst-end))
1235             (offset-current (+ dst-start current)))
1236         (declare (fixnum offset-dst-end offset-current))
1237         (if (> offset-dst-end dst-length)
1238             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1239                    (new-workspace (make-string new-length)))
1240               (declare (simple-string new-workspace))
1241               (%byte-blt workspace dst-start
1242                          new-workspace 0 current)
1243               (setf workspace new-workspace)
1244               (setf offset-current current)
1245               (setf offset-dst-end dst-end)
1246               (set-array-header buffer
1247                                 workspace
1248                                 new-length
1249                                 dst-end
1250                                 0
1251                                 new-length
1252                                 nil))
1253             (setf (fill-pointer buffer) dst-end))
1254         (%byte-blt string start
1255                    workspace offset-current offset-dst-end)))
1256     dst-end))
1257
1258 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1259   (declare (ignore arg1 arg2))
1260   (case operation
1261     (:charpos
1262      (let* ((buffer (fill-pointer-output-stream-string stream))
1263             (current (fill-pointer buffer)))
1264        (with-array-data ((string buffer) (start) (end current))
1265          (declare (simple-string string) (ignore start))
1266          (let ((found (position #\newline string :test #'char=
1267                                 :end end :from-end t)))
1268            (if found
1269                (- end (the fixnum found))
1270                current)))))
1271      (:element-type 'base-char)))
1272 \f
1273 ;;;; indenting streams
1274
1275 (defstruct (indenting-stream (:include ansi-stream
1276                                        (out #'indenting-out)
1277                                        (sout #'indenting-sout)
1278                                        (misc #'indenting-misc))
1279                              (:constructor make-indenting-stream (stream))
1280                              (:copier nil))
1281   ;; the stream we're based on
1282   stream
1283   ;; how much we indent on each line
1284   (indentation 0))
1285
1286 #!+sb-doc
1287 (setf (fdocumentation 'make-indenting-stream 'function)
1288  "Return an output stream which indents its output by some amount.")
1289
1290 ;;; INDENTING-INDENT writes the correct number of spaces needed to indent
1291 ;;; output on the given STREAM based on the specified SUB-STREAM.
1292 (defmacro indenting-indent (stream sub-stream)
1293   ;; KLUDGE: bare magic number 60
1294   `(do ((i 0 (+ i 60))
1295         (indentation (indenting-stream-indentation ,stream)))
1296        ((>= i indentation))
1297      (%write-string
1298       "                                                     "
1299       ,sub-stream
1300       0
1301       (min 60 (- indentation i)))))
1302
1303 ;;; INDENTING-OUT writes a character to an indenting stream.
1304 (defun indenting-out (stream char)
1305   (let ((sub-stream (indenting-stream-stream stream)))
1306     (write-char char sub-stream)
1307     (if (char= char #\newline)
1308         (indenting-indent stream sub-stream))))
1309
1310 ;;; INDENTING-SOUT writes a string to an indenting stream.
1311 (defun indenting-sout (stream string start end)
1312   (declare (simple-string string) (fixnum start end))
1313   (do ((i start)
1314        (sub-stream (indenting-stream-stream stream)))
1315       ((= i end))
1316     (let ((newline (position #\newline string :start i :end end)))
1317       (cond (newline
1318              (%write-string string sub-stream i (1+ newline))
1319              (indenting-indent stream sub-stream)
1320              (setq i (+ newline 1)))
1321             (t
1322              (%write-string string sub-stream i end)
1323              (setq i end))))))
1324
1325 ;;; INDENTING-MISC just treats just the :LINE-LENGTH message
1326 ;;; differently. INDENTING-CHARPOS says the charpos is the charpos of
1327 ;;; the base stream minus the stream's indentation.
1328 (defun indenting-misc (stream operation &optional arg1 arg2)
1329   (let ((sub-stream (indenting-stream-stream stream)))
1330     (if (ansi-stream-p sub-stream)
1331         (let ((method (ansi-stream-misc sub-stream)))
1332           (case operation
1333             (:line-length
1334              (let ((line-length (funcall method sub-stream operation)))
1335                (if line-length
1336                    (- line-length (indenting-stream-indentation stream)))))
1337             (:charpos
1338              (let ((charpos (funcall method sub-stream operation)))
1339                (if charpos
1340                    (- charpos (indenting-stream-indentation stream)))))
1341             (t
1342              (funcall method sub-stream operation arg1 arg2))))
1343         ;; must be Gray streams FUNDAMENTAL-STREAM
1344         (case operation
1345           (:line-length
1346            (let ((line-length (stream-line-length sub-stream)))
1347              (if line-length
1348                  (- line-length (indenting-stream-indentation stream)))))
1349           (:charpos
1350            (let ((charpos (stream-line-column sub-stream)))
1351              (if charpos
1352                  (- charpos (indenting-stream-indentation stream)))))
1353           (t
1354            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1355
1356 (declaim (maybe-inline read-char unread-char read-byte listen))
1357 \f
1358 ;;;; case frobbing streams, used by FORMAT ~(...~)
1359
1360 (defstruct (case-frob-stream
1361             (:include ansi-stream
1362                       (misc #'case-frob-misc))
1363             (:constructor %make-case-frob-stream (target out sout))
1364             (:copier nil))
1365   (target (missing-arg) :type stream))
1366
1367 (defun make-case-frob-stream (target kind)
1368   #!+sb-doc
1369   "Return a stream that sends all output to the stream TARGET, but modifies
1370    the case of letters, depending on KIND, which should be one of:
1371      :upcase - convert to upper case.
1372      :downcase - convert to lower case.
1373      :capitalize - convert the first letter of words to upper case and the
1374         rest of the word to lower case.
1375      :capitalize-first - convert the first letter of the first word to upper
1376         case and everything else to lower case."
1377   (declare (type stream target)
1378            (type (member :upcase :downcase :capitalize :capitalize-first)
1379                  kind)
1380            (values stream))
1381   (if (case-frob-stream-p target)
1382       ;; If we are going to be writing to a stream that already does
1383       ;; case frobbing, why bother frobbing the case just so it can
1384       ;; frob it again?
1385       target
1386       (multiple-value-bind (out sout)
1387           (ecase kind
1388             (:upcase
1389              (values #'case-frob-upcase-out
1390                      #'case-frob-upcase-sout))
1391             (:downcase
1392              (values #'case-frob-downcase-out
1393                      #'case-frob-downcase-sout))
1394             (:capitalize
1395              (values #'case-frob-capitalize-out
1396                      #'case-frob-capitalize-sout))
1397             (:capitalize-first
1398              (values #'case-frob-capitalize-first-out
1399                      #'case-frob-capitalize-first-sout)))
1400         (%make-case-frob-stream target out sout))))
1401
1402 (defun case-frob-misc (stream op &optional arg1 arg2)
1403   (declare (type case-frob-stream stream))
1404   (case op
1405     (:close)
1406     (t
1407      (let ((target (case-frob-stream-target stream)))
1408        (if (ansi-stream-p target)
1409            (funcall (ansi-stream-misc target) target op arg1 arg2)
1410            (stream-misc-dispatch target op arg1 arg2))))))
1411
1412 (defun case-frob-upcase-out (stream char)
1413   (declare (type case-frob-stream stream)
1414            (type base-char char))
1415   (let ((target (case-frob-stream-target stream))
1416         (char (char-upcase char)))
1417     (if (ansi-stream-p target)
1418         (funcall (ansi-stream-out target) target char)
1419         (stream-write-char target char))))
1420
1421 (defun case-frob-upcase-sout (stream str start end)
1422   (declare (type case-frob-stream stream)
1423            (type simple-base-string str)
1424            (type index start)
1425            (type (or index null) end))
1426   (let* ((target (case-frob-stream-target stream))
1427          (len (length str))
1428          (end (or end len))
1429          (string (if (and (zerop start) (= len end))
1430                      (string-upcase str)
1431                      (nstring-upcase (subseq str start end))))
1432          (string-len (- end start)))
1433     (if (ansi-stream-p target)
1434         (funcall (ansi-stream-sout target) target string 0 string-len)
1435         (stream-write-string target string 0 string-len))))
1436
1437 (defun case-frob-downcase-out (stream char)
1438   (declare (type case-frob-stream stream)
1439            (type base-char char))
1440   (let ((target (case-frob-stream-target stream))
1441         (char (char-downcase char)))
1442     (if (ansi-stream-p target)
1443         (funcall (ansi-stream-out target) target char)
1444         (stream-write-char target char))))
1445
1446 (defun case-frob-downcase-sout (stream str start end)
1447   (declare (type case-frob-stream stream)
1448            (type simple-base-string str)
1449            (type index start)
1450            (type (or index null) end))
1451   (let* ((target (case-frob-stream-target stream))
1452          (len (length str))
1453          (end (or end len))
1454          (string (if (and (zerop start) (= len end))
1455                      (string-downcase str)
1456                      (nstring-downcase (subseq str start end))))
1457          (string-len (- end start)))
1458     (if (ansi-stream-p target)
1459         (funcall (ansi-stream-sout target) target string 0 string-len)
1460         (stream-write-string target string 0 string-len))))
1461
1462 (defun case-frob-capitalize-out (stream char)
1463   (declare (type case-frob-stream stream)
1464            (type base-char char))
1465   (let ((target (case-frob-stream-target stream)))
1466     (cond ((alphanumericp char)
1467            (let ((char (char-upcase char)))
1468              (if (ansi-stream-p target)
1469                  (funcall (ansi-stream-out target) target char)
1470                  (stream-write-char target char)))
1471            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1472            (setf (case-frob-stream-sout stream)
1473                  #'case-frob-capitalize-aux-sout))
1474           (t
1475            (if (ansi-stream-p target)
1476                (funcall (ansi-stream-out target) target char)
1477                (stream-write-char target char))))))
1478
1479 (defun case-frob-capitalize-sout (stream str start end)
1480   (declare (type case-frob-stream stream)
1481            (type simple-base-string str)
1482            (type index start)
1483            (type (or index null) end))
1484   (let* ((target (case-frob-stream-target stream))
1485          (str (subseq str start end))
1486          (len (length str))
1487          (inside-word nil))
1488     (dotimes (i len)
1489       (let ((char (schar str i)))
1490         (cond ((not (alphanumericp char))
1491                (setf inside-word nil))
1492               (inside-word
1493                (setf (schar str i) (char-downcase char)))
1494               (t
1495                (setf inside-word t)
1496                (setf (schar str i) (char-upcase char))))))
1497     (when inside-word
1498       (setf (case-frob-stream-out stream)
1499             #'case-frob-capitalize-aux-out)
1500       (setf (case-frob-stream-sout stream)
1501             #'case-frob-capitalize-aux-sout))
1502     (if (ansi-stream-p target)
1503         (funcall (ansi-stream-sout target) target str 0 len)
1504         (stream-write-string target str 0 len))))
1505
1506 (defun case-frob-capitalize-aux-out (stream char)
1507   (declare (type case-frob-stream stream)
1508            (type base-char char))
1509   (let ((target (case-frob-stream-target stream)))
1510     (cond ((alphanumericp char)
1511            (let ((char (char-downcase char)))
1512              (if (ansi-stream-p target)
1513                  (funcall (ansi-stream-out target) target char)
1514                  (stream-write-char target char))))
1515           (t
1516            (if (ansi-stream-p target)
1517                (funcall (ansi-stream-out target) target char)
1518                (stream-write-char target char))
1519            (setf (case-frob-stream-out stream)
1520                  #'case-frob-capitalize-out)
1521            (setf (case-frob-stream-sout stream)
1522                  #'case-frob-capitalize-sout)))))
1523
1524 (defun case-frob-capitalize-aux-sout (stream str start end)
1525   (declare (type case-frob-stream stream)
1526            (type simple-base-string str)
1527            (type index start)
1528            (type (or index null) end))
1529   (let* ((target (case-frob-stream-target stream))
1530          (str (subseq str start end))
1531          (len (length str))
1532          (inside-word t))
1533     (dotimes (i len)
1534       (let ((char (schar str i)))
1535         (cond ((not (alphanumericp char))
1536                (setf inside-word nil))
1537               (inside-word
1538                (setf (schar str i) (char-downcase char)))
1539               (t
1540                (setf inside-word t)
1541                (setf (schar str i) (char-upcase char))))))
1542     (unless inside-word
1543       (setf (case-frob-stream-out stream)
1544             #'case-frob-capitalize-out)
1545       (setf (case-frob-stream-sout stream)
1546             #'case-frob-capitalize-sout))
1547     (if (ansi-stream-p target)
1548         (funcall (ansi-stream-sout target) target str 0 len)
1549         (stream-write-string target str 0 len))))
1550
1551 (defun case-frob-capitalize-first-out (stream char)
1552   (declare (type case-frob-stream stream)
1553            (type base-char char))
1554   (let ((target (case-frob-stream-target stream)))
1555     (cond ((alphanumericp char)
1556            (let ((char (char-upcase char)))
1557              (if (ansi-stream-p target)
1558                  (funcall (ansi-stream-out target) target char)
1559                  (stream-write-char target char)))
1560            (setf (case-frob-stream-out stream)
1561                  #'case-frob-downcase-out)
1562            (setf (case-frob-stream-sout stream)
1563                  #'case-frob-downcase-sout))
1564           (t
1565            (if (ansi-stream-p target)
1566                (funcall (ansi-stream-out target) target char)
1567                (stream-write-char target char))))))
1568
1569 (defun case-frob-capitalize-first-sout (stream str start end)
1570   (declare (type case-frob-stream stream)
1571            (type simple-base-string str)
1572            (type index start)
1573            (type (or index null) end))
1574   (let* ((target (case-frob-stream-target stream))
1575          (str (subseq str start end))
1576          (len (length str)))
1577     (dotimes (i len)
1578       (let ((char (schar str i)))
1579         (when (alphanumericp char)
1580           (setf (schar str i) (char-upcase char))
1581           (do ((i (1+ i) (1+ i)))
1582               ((= i len))
1583             (setf (schar str i) (char-downcase (schar str i))))
1584           (setf (case-frob-stream-out stream)
1585                 #'case-frob-downcase-out)
1586           (setf (case-frob-stream-sout stream)
1587                 #'case-frob-downcase-sout)
1588           (return))))
1589     (if (ansi-stream-p target)
1590         (funcall (ansi-stream-sout target) target str 0 len)
1591         (stream-write-string target str 0 len))))
1592 \f
1593 ;;;; stream commands
1594
1595 (defstruct (stream-command (:constructor make-stream-command
1596                                          (name &optional args))
1597                            (:copier nil))
1598   (name nil :type symbol)
1599   (args nil :type list))
1600 (def!method print-object ((obj stream-command) str)
1601   (print-unreadable-object (obj str :type t :identity t)
1602     (prin1 (stream-command-name obj) str)))
1603
1604 ;;; Take a stream and wait for text or a command to appear on it. If
1605 ;;; text appears before a command, return NIL, otherwise return a
1606 ;;; command.
1607 ;;;
1608 ;;; We can't simply call the stream's misc method because NIL is an
1609 ;;; ambiguous return value: does it mean text arrived, or does it mean
1610 ;;; the stream's misc method had no :GET-COMMAND implementation? We
1611 ;;; can't return NIL until there is text input. We don't need to loop
1612 ;;; because any stream implementing :GET-COMMAND would wait until it
1613 ;;; had some input. If the LISTEN fails, then we have some stream we
1614 ;;; must wait on.
1615 (defun get-stream-command (stream)
1616   (let ((cmdp (funcall (ansi-stream-misc stream) stream :get-command)))
1617     (cond (cmdp)
1618           ((listen stream)
1619            nil)
1620           (t
1621            ;; This waits for input and returns NIL when it arrives.
1622            (unread-char (read-char stream) stream)))))
1623 \f
1624 ;;;; READ-SEQUENCE
1625
1626 (defun read-sequence (seq stream &key (start 0) (end nil))
1627   #!+sb-doc
1628   "Destructively modify SEQ by reading elements from STREAM.
1629   That part of SEQ bounded by START and END is destructively modified by
1630   copying successive elements into it from STREAM. If the end of file
1631   for STREAM is reached before copying all elements of the subsequence,
1632   then the extra elements near the end of sequence are not updated, and
1633   the index of the next element is returned."
1634   (declare (type sequence seq)
1635            (type stream stream)
1636            (type index start)
1637            (type sequence-end end)
1638            (values index))
1639   (if (ansi-stream-p stream)
1640       (ansi-stream-read-sequence seq stream start end)
1641       ;; must be Gray streams FUNDAMENTAL-STREAM
1642       (stream-read-sequence stream seq start end)))
1643
1644 (defun ansi-stream-read-sequence (seq stream start %end)
1645   (declare (type sequence seq)
1646            (type ansi-stream stream)
1647            (type index start)
1648            (type sequence-end %end)
1649            (values index))
1650   (let ((end (or %end (length seq))))
1651     (declare (type index end))
1652     (etypecase seq
1653       (list
1654        (let ((read-function
1655               (if (subtypep (stream-element-type stream) 'character)
1656                   #'read-char
1657                   #'read-byte)))
1658          (do ((rem (nthcdr start seq) (rest rem))
1659               (i start (1+ i)))
1660              ((or (endp rem) (>= i end)) i)
1661            (declare (type list rem)
1662                     (type index i))
1663            (let ((el (funcall read-function stream nil :eof)))
1664              (when (eq el :eof)
1665                (return i))
1666              (setf (first rem) el)))))
1667       (vector
1668        (with-array-data ((data seq) (offset-start start) (offset-end end))
1669          (typecase data
1670            ((or (simple-array (unsigned-byte 8) (*))
1671                 (simple-array (signed-byte 8) (*))
1672                 simple-string)
1673             (let* ((numbytes (- end start))
1674                    (bytes-read (sb!sys:read-n-bytes stream
1675                                                     data
1676                                                     offset-start
1677                                                     numbytes
1678                                                     nil)))
1679               (if (< bytes-read numbytes)
1680                   (+ start bytes-read)
1681                   end)))
1682            (t
1683             (let ((read-function
1684                    (if (subtypep (stream-element-type stream) 'character)
1685                        #'read-char
1686                        #'read-byte)))
1687               (do ((i offset-start (1+ i)))
1688                   ((>= i offset-end) end)
1689                 (declare (type index i))
1690                 (let ((el (funcall read-function stream nil :eof)))
1691                   (when (eq el :eof)
1692                     (return (+ start (- i offset-start))))
1693                   (setf (aref data i) el)))))))))))
1694 \f
1695 ;;;; WRITE-SEQUENCE
1696
1697 (defun write-sequence (seq stream &key (start 0) (end nil))
1698   #!+sb-doc
1699   "Write the elements of SEQ bounded by START and END to STREAM."
1700   (declare (type sequence seq)
1701            (type stream stream)
1702            (type index start)
1703            (type sequence-end end)
1704            (values sequence))
1705   (if (ansi-stream-p stream)
1706       (ansi-stream-write-sequence seq stream start end)
1707       ;; must be Gray-streams FUNDAMENTAL-STREAM
1708       (stream-write-sequence stream seq start end)))
1709
1710 (defun ansi-stream-write-sequence (seq stream start %end)
1711   (declare (type sequence seq)
1712            (type ansi-stream stream)
1713            (type index start)
1714            (type sequence-end %end)
1715            (values sequence))
1716   (let ((end (or %end (length seq))))
1717     (declare (type index end))
1718     (etypecase seq
1719       (list
1720        (let ((write-function
1721               (if (subtypep (stream-element-type stream) 'character)
1722                   #'write-char
1723                   #'write-byte)))
1724          (do ((rem (nthcdr start seq) (rest rem))
1725               (i start (1+ i)))
1726              ((or (endp rem) (>= i end)) seq)
1727            (declare (type list rem)
1728                     (type index i))
1729            (funcall write-function (first rem) stream))))
1730       (string
1731        (%write-string seq stream start end))
1732       (vector
1733        (let ((write-function
1734               (if (subtypep (stream-element-type stream) 'character)
1735                   #'write-char
1736                   #'write-byte)))
1737          (do ((i start (1+ i)))
1738              ((>= i end) seq)
1739            (declare (type index i))
1740            (funcall write-function (aref seq i) stream)))))))
1741 \f
1742 ;;;; etc.
1743
1744 ;;; (These were inline throughout this file, but that's not appropriate
1745 ;;; globally.)
1746 (declaim (maybe-inline read-char unread-char read-byte listen))