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