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