1553dbf1c2c2abdf40ef0b692cb3e4ca0a446cdb
[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 (lisp-stream-bout integer)
617                    (stream-write-byte integer))
618   integer)
619 \f
620 ;;; This is called from lisp-steam routines that encapsulate CLOS
621 ;;; streams to handle the misc routines and dispatch to the
622 ;;; appropriate Gray stream functions.
623 (defun stream-misc-dispatch (stream operation &optional arg1 arg2)
624   (declare (type fundamental-stream stream)
625            (ignore arg2))
626   (case operation
627     (:listen
628      ;; Return true if input available, :EOF for end-of-file, otherwise NIL.
629      (let ((char (stream-read-char-no-hang stream)))
630        (when (characterp char)
631          (stream-unread-char stream char))
632        char))
633     (:unread
634      (stream-unread-char stream arg1))
635     (:close
636      (close stream))
637     (:clear-input
638      (stream-clear-input stream))
639     (:force-output
640      (stream-force-output stream))
641     (:finish-output
642      (stream-finish-output stream))
643     (:element-type
644      (stream-element-type stream))
645     (:interactive-p
646      (interactive-stream-p stream))
647     (:line-length
648      (stream-line-length stream))
649     (:charpos
650      (stream-line-column stream))
651     (:file-length
652      (file-length stream))
653     (:file-position
654      (file-position stream arg1))))
655 \f
656 ;;;; broadcast streams
657
658 (defstruct (broadcast-stream (:include lisp-stream
659                                        (out #'broadcast-out)
660                                        (bout #'broadcast-bout)
661                                        (sout #'broadcast-sout)
662                                        (misc #'broadcast-misc))
663                              (:constructor #!-high-security-support
664                                            make-broadcast-stream
665                                            #!+high-security-support
666                                            %make-broadcast-stream (&rest streams)))
667   ;; a list of all the streams we broadcast to
668   (streams () :type list :read-only t))
669
670 #!+high-security-support
671 (defun make-broadcast-stream (&rest streams)
672   (dolist (stream streams)
673     (unless (or (and (synonym-stream-p stream)
674                      (output-stream-p (symbol-value
675                                        (synonym-stream-symbol stream))))
676                 (output-stream-p stream))
677       (error 'type-error
678              :datum stream
679              :expected-type '(satisfies output-stream-p))))
680   (apply #'%make-broadcast-stream streams))
681
682 (macrolet ((out-fun (fun method stream-method &rest args)
683              `(defun ,fun (stream ,@args)
684                 (dolist (stream (broadcast-stream-streams stream))
685                   (if (lisp-stream-p stream)
686                       (funcall (,method stream) stream ,@args)
687                       (,stream-method stream ,@args))))))
688   (out-fun broadcast-out lisp-stream-out stream-write-char char)
689   (out-fun broadcast-bout lisp-stream-bout stream-write-byte byte)
690   (out-fun broadcast-sout lisp-stream-sout stream-write-string
691            string start end))
692
693 (defun broadcast-misc (stream operation &optional arg1 arg2)
694   (let ((streams (broadcast-stream-streams stream)))
695     (case operation
696       (:charpos
697        (dolist (stream streams)
698          (let ((charpos (charpos stream)))
699            (if charpos (return charpos)))))
700       (:line-length
701        (let ((min nil))
702          (dolist (stream streams min)
703            (let ((res (line-length stream)))
704              (when res (setq min (if min (min res min) res)))))))
705       (:element-type
706        (let (res)
707          (dolist (stream streams (if (> (length res) 1) `(and ,@res) res))
708            (pushnew (stream-element-type stream) res :test #'equal))))
709       (:close)
710       (t
711        (let ((res nil))
712          (dolist (stream streams res)
713            (setq res
714                  (if (lisp-stream-p stream)
715                      (funcall (lisp-stream-misc stream) stream operation
716                               arg1 arg2)
717                      (stream-misc-dispatch stream operation arg1 arg2)))))))))
718 \f
719 ;;;; synonym streams
720
721 (defstruct (synonym-stream (:include lisp-stream
722                                      (in #'synonym-in)
723                                      (bin #'synonym-bin)
724                                      (n-bin #'synonym-n-bin)
725                                      (out #'synonym-out)
726                                      (bout #'synonym-bout)
727                                      (sout #'synonym-sout)
728                                      (misc #'synonym-misc))
729                            (:constructor make-synonym-stream (symbol)))
730   ;; This is the symbol, the value of which is the stream we are synonym to.
731   (symbol nil :type symbol :read-only t))
732 (def!method print-object ((x synonym-stream) stream)
733   (print-unreadable-object (x stream :type t :identity t)
734     (format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
735
736 ;;; The output simple output methods just call the corresponding method
737 ;;; in the synonymed stream.
738 (macrolet ((out-fun (name slot stream-method &rest args)
739              `(defun ,name (stream ,@args)
740                 (declare (optimize (safety 1)))
741                 (let ((syn (symbol-value (synonym-stream-symbol stream))))
742                   (if (lisp-stream-p syn)
743                       (funcall (,slot syn) syn ,@args)
744                       (,stream-method syn ,@args))))))
745   (out-fun synonym-out lisp-stream-out stream-write-char ch)
746   (out-fun synonym-bout lisp-stream-bout stream-write-byte n)
747   (out-fun synonym-sout lisp-stream-sout stream-write-string string start end))
748
749 ;;; For the input methods, we just call the corresponding function on the
750 ;;; synonymed stream. These functions deal with getting input out of
751 ;;; the In-Buffer if there is any.
752 (macrolet ((in-fun (name fun &rest args)
753              `(defun ,name (stream ,@args)
754                 (declare (optimize (safety 1)))
755                 (,fun (symbol-value (synonym-stream-symbol stream))
756                       ,@args))))
757   (in-fun synonym-in read-char eof-error-p eof-value)
758   (in-fun synonym-bin read-byte eof-error-p eof-value)
759   (in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
760
761 ;;; We have to special-case the operations which could look at stuff in
762 ;;; the in-buffer.
763 (defun synonym-misc (stream operation &optional arg1 arg2)
764   (declare (optimize (safety 1)))
765   (let ((syn (symbol-value (synonym-stream-symbol stream))))
766     (if (lisp-stream-p syn)
767         (case operation
768           (:listen (or (/= (the fixnum (lisp-stream-in-index syn))
769                            in-buffer-length)
770                        (funcall (lisp-stream-misc syn) syn :listen)))
771           (t
772            (funcall (lisp-stream-misc syn) syn operation arg1 arg2)))
773         (stream-misc-dispatch syn operation arg1 arg2))))
774 \f
775 ;;;; two-way streams
776
777 (defstruct (two-way-stream
778             (:include lisp-stream
779                       (in #'two-way-in)
780                       (bin #'two-way-bin)
781                       (n-bin #'two-way-n-bin)
782                       (out #'two-way-out)
783                       (bout #'two-way-bout)
784                       (sout #'two-way-sout)
785                       (misc #'two-way-misc))
786             (:constructor #!-high-security-support
787                           make-two-way-stream
788                           #!+high-security-support
789                           %make-two-way-stream (input-stream output-stream)))
790   (input-stream (required-argument) :type stream :read-only t)
791   (output-stream (required-argument) :type stream :read-only t))
792 (def!method print-object ((x two-way-stream) stream)
793   (print-unreadable-object (x stream :type t :identity t)
794     (format stream
795             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
796             (two-way-stream-input-stream x)
797             (two-way-stream-output-stream x))))
798
799 #!-high-security-support
800 (setf (fdocumentation 'make-two-way-stream 'function)
801   "Returns a bidirectional stream which gets its input from Input-Stream and
802    sends its output to Output-Stream.")
803 #!+high-security-support
804 (defun make-two-way-stream (input-stream output-stream)
805   #!+sb-doc
806   "Returns a bidirectional stream which gets its input from Input-Stream and
807    sends its output to Output-Stream."
808   ;; FIXME: This idiom of the-real-stream-of-a-possibly-synonym-stream
809   ;; should be encapsulated in a function, and used here and most of
810   ;; the other places that SYNONYM-STREAM-P appears.
811   (unless (or (and (synonym-stream-p output-stream)
812                    (output-stream-p (symbol-value
813                                      (synonym-stream-symbol output-stream))))
814               (output-stream-p output-stream))
815     (error 'type-error
816            :datum output-stream
817            :expected-type '(satisfies output-stream-p)))
818   (unless (or (and (synonym-stream-p input-stream)
819                    (input-stream-p (symbol-value
820                                     (synonym-stream-symbol input-stream))))
821               (input-stream-p input-stream))
822     (error 'type-error
823            :datum input-stream
824            :expected-type '(satisfies input-stream-p)))
825   (funcall #'%make-two-way-stream input-stream output-stream))
826
827 (macrolet ((out-fun (name slot stream-method &rest args)
828              `(defun ,name (stream ,@args)
829                 (let ((syn (two-way-stream-output-stream stream)))
830                   (if (lisp-stream-p syn)
831                       (funcall (,slot syn) syn ,@args)
832                       (,stream-method syn ,@args))))))
833   (out-fun two-way-out lisp-stream-out stream-write-char ch)
834   (out-fun two-way-bout lisp-stream-bout stream-write-byte n)
835   (out-fun two-way-sout lisp-stream-sout stream-write-string string start end))
836
837 (macrolet ((in-fun (name fun &rest args)
838              `(defun ,name (stream ,@args)
839                 (force-output (two-way-stream-output-stream stream))
840                 (,fun (two-way-stream-input-stream stream) ,@args))))
841   (in-fun two-way-in read-char eof-error-p eof-value)
842   (in-fun two-way-bin read-byte eof-error-p eof-value)
843   (in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
844
845 (defun two-way-misc (stream operation &optional arg1 arg2)
846   (let* ((in (two-way-stream-input-stream stream))
847          (out (two-way-stream-output-stream stream))
848          (in-lisp-stream-p (lisp-stream-p in))
849          (out-lisp-stream-p (lisp-stream-p out)))
850     (case operation
851       (:listen
852        (if in-lisp-stream-p
853            (or (/= (the fixnum (lisp-stream-in-index in)) in-buffer-length)
854                (funcall (lisp-stream-misc in) in :listen))
855            (stream-listen in)))
856       ((:finish-output :force-output :clear-output)
857        (if out-lisp-stream-p
858            (funcall (lisp-stream-misc out) out operation arg1 arg2)
859            (stream-misc-dispatch out operation arg1 arg2)))
860       ((:clear-input :unread)
861        (if in-lisp-stream-p
862            (funcall (lisp-stream-misc in) in operation arg1 arg2)
863            (stream-misc-dispatch in operation arg1 arg2)))
864       (:element-type
865        (let ((in-type (stream-element-type in))
866              (out-type (stream-element-type out)))
867          (if (equal in-type out-type)
868              in-type `(and ,in-type ,out-type))))
869       (:close
870        (set-closed-flame stream))
871       (t
872        (or (if in-lisp-stream-p
873                (funcall (lisp-stream-misc in) in operation arg1 arg2)
874                (stream-misc-dispatch in operation arg1 arg2))
875            (if out-lisp-stream-p
876                (funcall (lisp-stream-misc out) out operation arg1 arg2)
877                (stream-misc-dispatch out operation arg1 arg2)))))))
878 \f
879 ;;;; concatenated streams
880
881 (defstruct (concatenated-stream
882             (:include lisp-stream
883                       (in #'concatenated-in)
884                       (bin #'concatenated-bin)
885                       (misc #'concatenated-misc))
886             (:constructor
887              #!-high-security-support make-concatenated-stream
888              #!+high-security-support %make-concatenated-stream
889                  (&rest streams &aux (current streams))))
890   ;; The car of this is the stream we are reading from now.
891   current
892   ;; This is a list of all the streams. We need to remember them so that
893   ;; we can close them.
894   ;;
895   ;; FIXME: ANSI says this is supposed to be the list of streams that
896   ;; we still have to read from. So either this needs to become a
897   ;; private member %STREAM (with CONCATENATED-STREAM-STREAMS a wrapper
898   ;; around it which discards closed files from the head of the list)
899   ;; or we need to update it as we run out of files.
900   (streams nil :type list :read-only t))
901 (def!method print-object ((x concatenated-stream) stream)
902   (print-unreadable-object (x stream :type t :identity t)
903     (format stream
904             ":STREAMS ~S"
905             (concatenated-stream-streams x))))
906
907 #!-high-security-support
908 (setf (fdocumentation 'make-concatenated-stream 'function)
909   "Returns a stream which takes its input from each of the Streams in turn,
910    going on to the next at EOF.")
911
912 #!+high-security-support
913 (defun make-concatenated-stream (&rest streams)
914   #!+sb-doc
915   "Returns a stream which takes its input from each of the Streams in turn,
916    going on to the next at EOF."
917   (dolist (stream streams)
918     (unless (or (and (synonym-stream-p stream)
919                      (input-stream-p (symbol-value
920                                       (synonym-stream-symbol stream))))
921                 (input-stream-p stream))
922       (error 'type-error
923              :datum stream
924              :expected-type '(satisfies input-stream-p))))
925   (apply #'%make-concatenated-stream streams))
926
927 (macrolet ((in-fun (name fun)
928              `(defun ,name (stream eof-error-p eof-value)
929                 (do ((current (concatenated-stream-current stream) (cdr current)))
930                     ((null current)
931                      (eof-or-lose stream eof-error-p eof-value))
932                   (let* ((stream (car current))
933                          (result (,fun stream nil nil)))
934                     (when result (return result)))
935                   (setf (concatenated-stream-current stream) current)))))
936   (in-fun concatenated-in read-char)
937   (in-fun concatenated-bin read-byte))
938
939 (defun concatenated-misc (stream operation &optional arg1 arg2)
940   (let ((left (concatenated-stream-current stream)))
941     (when left
942       (let* ((current (car left)))
943         (case operation
944           (:listen
945            (loop
946              (let ((stuff (if (lisp-stream-p current)
947                               (funcall (lisp-stream-misc current) current
948                                        :listen)
949                               (stream-misc-dispatch current :listen))))
950                (cond ((eq stuff :eof)
951                       ;; Advance CURRENT, and try again.
952                       (pop (concatenated-stream-current stream))
953                       (setf current
954                             (car (concatenated-stream-current stream)))
955                       (unless current
956                         ;; No further streams. EOF.
957                         (return :eof)))
958                      (stuff
959                       ;; Stuff's available.
960                       (return t))
961                      (t
962                       ;; Nothing is available yet.
963                       (return nil))))))
964           (:close
965            (set-closed-flame stream))
966           (t
967            (if (lisp-stream-p current)
968                (funcall (lisp-stream-misc current) current operation arg1 arg2)
969                (stream-misc-dispatch current operation arg1 arg2))))))))
970 \f
971 ;;;; echo streams
972
973 (defstruct (echo-stream
974             (:include two-way-stream
975                       (in #'echo-in)
976                       (bin #'echo-bin)
977                       (misc #'echo-misc)
978                       (n-bin #'ill-bin))
979             (:constructor make-echo-stream (input-stream output-stream)))
980   unread-stuff)
981 (def!method print-object ((x echo-stream) stream)
982   (print-unreadable-object (x stream :type t :identity t)
983     (format stream
984             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
985             (two-way-stream-input-stream x)
986             (two-way-stream-output-stream x))))
987
988 (macrolet ((in-fun (name fun out-slot stream-method &rest args)
989              `(defun ,name (stream ,@args)
990                 (or (pop (echo-stream-unread-stuff stream))
991                     (let* ((in (echo-stream-input-stream stream))
992                            (out (echo-stream-output-stream stream))
993                            (result (,fun in ,@args)))
994                       (if (lisp-stream-p out)
995                           (funcall (,out-slot out) out result)
996                           (,stream-method out result))
997                       result)))))
998   (in-fun echo-in read-char lisp-stream-out stream-write-char
999           eof-error-p eof-value)
1000   (in-fun echo-bin read-byte lisp-stream-bout stream-write-byte
1001           eof-error-p eof-value))
1002
1003 (defun echo-misc (stream operation &optional arg1 arg2)
1004   (let* ((in (two-way-stream-input-stream stream))
1005          (out (two-way-stream-output-stream stream)))
1006     (case operation
1007       (:listen
1008        (or (not (null (echo-stream-unread-stuff stream)))
1009            (if (lisp-stream-p in)
1010                (or (/= (the fixnum (lisp-stream-in-index in)) in-buffer-length)
1011                    (funcall (lisp-stream-misc in) in :listen))
1012                (stream-misc-dispatch in :listen))))
1013       (:unread (push arg1 (echo-stream-unread-stuff stream)))
1014       (:element-type
1015        (let ((in-type (stream-element-type in))
1016              (out-type (stream-element-type out)))
1017          (if (equal in-type out-type)
1018              in-type `(and ,in-type ,out-type))))
1019       (:close
1020        (set-closed-flame stream))
1021       (t
1022        (or (if (lisp-stream-p in)
1023                (funcall (lisp-stream-misc in) in operation arg1 arg2)
1024                (stream-misc-dispatch in operation arg1 arg2))
1025            (if (lisp-stream-p out)
1026                (funcall (lisp-stream-misc out) out operation arg1 arg2)
1027                (stream-misc-dispatch out operation arg1 arg2)))))))
1028
1029 #!+sb-doc
1030 (setf (fdocumentation 'make-echo-stream 'function)
1031   "Returns a bidirectional stream which gets its input from Input-Stream and
1032    sends its output to Output-Stream. In addition, all input is echoed to
1033    the output stream")
1034 \f
1035 ;;;; string input streams
1036
1037 (defstruct (string-input-stream
1038              (:include lisp-stream
1039                        (in #'string-inch)
1040                        (bin #'string-binch)
1041                        (n-bin #'string-stream-read-n-bytes)
1042                        (misc #'string-in-misc))
1043              (:constructor internal-make-string-input-stream
1044                            (string current end)))
1045   (string nil :type simple-string)
1046   (current nil :type index)
1047   (end nil :type index))
1048
1049 (defun string-inch (stream eof-error-p eof-value)
1050   (let ((string (string-input-stream-string stream))
1051         (index (string-input-stream-current stream)))
1052     (declare (simple-string string) (fixnum index))
1053     (cond ((= index (the index (string-input-stream-end stream)))
1054            (eof-or-lose stream eof-error-p eof-value))
1055           (t
1056            (setf (string-input-stream-current stream) (1+ index))
1057            (aref string index)))))
1058
1059 (defun string-binch (stream eof-error-p eof-value)
1060   (let ((string (string-input-stream-string stream))
1061         (index (string-input-stream-current stream)))
1062     (declare (simple-string string)
1063              (type index index))
1064     (cond ((= index (the index (string-input-stream-end stream)))
1065            (eof-or-lose stream eof-error-p eof-value))
1066           (t
1067            (setf (string-input-stream-current stream) (1+ index))
1068            (char-code (aref string index))))))
1069
1070 (defun string-stream-read-n-bytes (stream buffer start requested eof-error-p)
1071   (declare (type string-input-stream stream)
1072            (type index start requested))
1073   (let* ((string (string-input-stream-string stream))
1074          (index (string-input-stream-current stream))
1075          (available (- (string-input-stream-end stream) index))
1076          (copy (min available requested)))
1077     (declare (simple-string string)
1078              (type index index available copy))
1079     (when (plusp copy)
1080       (setf (string-input-stream-current stream)
1081             (truly-the index (+ index copy)))
1082       (sb!sys:without-gcing
1083        (system-area-copy (vector-sap string)
1084                          (* index sb!vm:byte-bits)
1085                          (if (typep buffer 'system-area-pointer)
1086                              buffer
1087                              (vector-sap buffer))
1088                          (* start sb!vm:byte-bits)
1089                          (* copy sb!vm:byte-bits))))
1090     (if (and (> requested copy) eof-error-p)
1091         (error 'end-of-file :stream stream)
1092         copy)))
1093
1094 (defun string-in-misc (stream operation &optional arg1 arg2)
1095   (declare (ignore arg2))
1096   (case operation
1097     (:file-position
1098      (if arg1
1099          (setf (string-input-stream-current stream) arg1)
1100          (string-input-stream-current stream)))
1101     (:file-length (length (string-input-stream-string stream)))
1102     (:unread (decf (string-input-stream-current stream)))
1103     (:listen (or (/= (the fixnum (string-input-stream-current stream))
1104                      (the fixnum (string-input-stream-end stream)))
1105                  :eof))
1106     (:element-type 'base-char)))
1107
1108 (defun make-string-input-stream (string &optional
1109                                         (start 0) (end (length string)))
1110   #!+sb-doc
1111   "Returns an input stream which will supply the characters of String between
1112   Start and End in order."
1113   (declare (type string string)
1114            (type index start)
1115            (type (or index null) end))
1116
1117   #!+high-security
1118   (when (> end (length string))
1119     (cerror "Continue with end changed from ~S to ~S"
1120             "Write-string: end (~S) is larger then the length of the string (~S)"
1121             end (1- (length string))))
1122
1123   (internal-make-string-input-stream (coerce string 'simple-string)
1124                                      start end))
1125 \f
1126 ;;;; string output streams
1127
1128 (defstruct (string-output-stream
1129             (:include lisp-stream
1130                       (out #'string-ouch)
1131                       (sout #'string-sout)
1132                       (misc #'string-out-misc))
1133             (:constructor make-string-output-stream ()))
1134   ;; The string we throw stuff in.
1135   (string (make-string 40) :type simple-string)
1136   ;; Index of the next location to use.
1137   (index 0 :type fixnum))
1138
1139 #!+sb-doc
1140 (setf (fdocumentation 'make-string-output-stream 'function)
1141   "Returns an Output stream which will accumulate all output given it for
1142    the benefit of the function Get-Output-Stream-String.")
1143
1144 (defun string-ouch (stream character)
1145   (let ((current (string-output-stream-index stream))
1146         (workspace (string-output-stream-string stream)))
1147     (declare (simple-string workspace) (fixnum current))
1148     (if (= current (the fixnum (length workspace)))
1149         (let ((new-workspace (make-string (* current 2))))
1150           (replace new-workspace workspace)
1151           (setf (aref new-workspace current) character)
1152           (setf (string-output-stream-string stream) new-workspace))
1153         (setf (aref workspace current) character))
1154     (setf (string-output-stream-index stream) (1+ current))))
1155
1156 (defun string-sout (stream string start end)
1157   (declare (simple-string string) (fixnum start end))
1158   (let* ((current (string-output-stream-index stream))
1159          (length (- end start))
1160          (dst-end (+ length current))
1161          (workspace (string-output-stream-string stream)))
1162     (declare (simple-string workspace)
1163              (fixnum current length dst-end))
1164     (if (> dst-end (the fixnum (length workspace)))
1165         (let ((new-workspace (make-string (+ (* current 2) length))))
1166           (replace new-workspace workspace :end2 current)
1167           (replace new-workspace string
1168                    :start1 current :end1 dst-end
1169                    :start2 start :end2 end)
1170           (setf (string-output-stream-string stream) new-workspace))
1171         (replace workspace string
1172                  :start1 current :end1 dst-end
1173                  :start2 start :end2 end))
1174     (setf (string-output-stream-index stream) dst-end)))
1175
1176 (defun string-out-misc (stream operation &optional arg1 arg2)
1177   (declare (ignore arg2))
1178   (case operation
1179     (:file-position
1180      (if (null arg1)
1181          (string-output-stream-index stream)))
1182     (:charpos
1183      (do ((index (1- (the fixnum (string-output-stream-index stream)))
1184                  (1- index))
1185           (count 0 (1+ count))
1186           (string (string-output-stream-string stream)))
1187          ((< index 0) count)
1188        (declare (simple-string string)
1189                 (fixnum index count))
1190        (if (char= (schar string index) #\newline)
1191            (return count))))
1192     (:element-type 'base-char)))
1193
1194 (defun get-output-stream-string (stream)
1195   #!+sb-doc
1196   "Returns a string of all the characters sent to a stream made by
1197    Make-String-Output-Stream since the last call to this function."
1198   (declare (type string-output-stream stream))
1199   (let* ((length (string-output-stream-index stream))
1200          (result (make-string length)))
1201     (replace result (string-output-stream-string stream))
1202     (setf (string-output-stream-index stream) 0)
1203     result))
1204
1205 (defun dump-output-stream-string (in-stream out-stream)
1206   #!+sb-doc
1207   "Dumps the characters buffer up in the In-Stream to the Out-Stream as
1208   Get-Output-Stream-String would return them."
1209   (write-string* (string-output-stream-string in-stream) out-stream
1210                  0 (string-output-stream-index in-stream))
1211   (setf (string-output-stream-index in-stream) 0))
1212 \f
1213 ;;;; fill-pointer streams
1214
1215 ;;; Fill pointer string output streams are not explicitly mentioned in the CLM,
1216 ;;; but they are required for the implementation of With-Output-To-String.
1217
1218 (defstruct (fill-pointer-output-stream
1219             (:include lisp-stream
1220                       (out #'fill-pointer-ouch)
1221                       (sout #'fill-pointer-sout)
1222                       (misc #'fill-pointer-misc))
1223             (:constructor make-fill-pointer-output-stream (string)))
1224   ;; The string we throw stuff in.
1225   string)
1226
1227 (defun fill-pointer-ouch (stream character)
1228   (let* ((buffer (fill-pointer-output-stream-string stream))
1229          (current (fill-pointer buffer))
1230          (current+1 (1+ current)))
1231     (declare (fixnum current))
1232     (with-array-data ((workspace buffer) (start) (end))
1233       (declare (simple-string workspace))
1234       (let ((offset-current (+ start current)))
1235         (declare (fixnum offset-current))
1236         (if (= offset-current end)
1237             (let* ((new-length (* current 2))
1238                    (new-workspace (make-string new-length)))
1239               (declare (simple-string new-workspace))
1240               (%primitive sb!c:byte-blt
1241                           workspace
1242                           start
1243                           new-workspace
1244                           0
1245                           current)
1246               (setf workspace new-workspace)
1247               (setf offset-current current)
1248               (set-array-header buffer workspace new-length
1249                                 current+1 0 new-length nil))
1250             (setf (fill-pointer buffer) current+1))
1251         (setf (schar workspace offset-current) character)))
1252     current+1))
1253
1254 (defun fill-pointer-sout (stream string start end)
1255   (declare (simple-string string) (fixnum start end))
1256   (let* ((buffer (fill-pointer-output-stream-string stream))
1257          (current (fill-pointer buffer))
1258          (string-len (- end start))
1259          (dst-end (+ string-len current)))
1260     (declare (fixnum current dst-end string-len))
1261     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1262       (declare (simple-string workspace))
1263       (let ((offset-dst-end (+ dst-start dst-end))
1264             (offset-current (+ dst-start current)))
1265         (declare (fixnum offset-dst-end offset-current))
1266         (if (> offset-dst-end dst-length)
1267             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1268                    (new-workspace (make-string new-length)))
1269               (declare (simple-string new-workspace))
1270               (%primitive sb!c:byte-blt
1271                           workspace
1272                           dst-start
1273                           new-workspace
1274                           0
1275                           current)
1276               (setf workspace new-workspace)
1277               (setf offset-current current)
1278               (setf offset-dst-end dst-end)
1279               (set-array-header buffer
1280                                 workspace
1281                                 new-length
1282                                 dst-end
1283                                 0
1284                                 new-length
1285                                 nil))
1286             (setf (fill-pointer buffer) dst-end))
1287         (%primitive sb!c:byte-blt
1288                     string
1289                     start
1290                     workspace
1291                     offset-current
1292                     offset-dst-end)))
1293     dst-end))
1294
1295 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1296   (declare (ignore arg1 arg2))
1297   (case operation
1298     (:charpos
1299      (let* ((buffer (fill-pointer-output-stream-string stream))
1300             (current (fill-pointer buffer)))
1301        (with-array-data ((string buffer) (start) (end current))
1302          (declare (simple-string string) (ignore start))
1303          (let ((found (position #\newline string :test #'char=
1304                                 :end end :from-end t)))
1305            (if found
1306                (- end (the fixnum found))
1307                current)))))
1308      (:element-type 'base-char)))
1309 \f
1310 ;;;; indenting streams
1311
1312 (defstruct (indenting-stream (:include lisp-stream
1313                                        (out #'indenting-out)
1314                                        (sout #'indenting-sout)
1315                                        (misc #'indenting-misc))
1316                              (:constructor make-indenting-stream (stream)))
1317   ;; the stream we're based on
1318   stream
1319   ;; how much we indent on each line
1320   (indentation 0))
1321
1322 #!+sb-doc
1323 (setf (fdocumentation 'make-indenting-stream 'function)
1324  "Returns an output stream which indents its output by some amount.")
1325
1326 ;;; Indenting-Indent writes the correct number of spaces needed to indent
1327 ;;; output on the given Stream based on the specified Sub-Stream.
1328 (defmacro indenting-indent (stream sub-stream)
1329   ;; KLUDGE: bare magic number 60
1330   `(do ((i 0 (+ i 60))
1331         (indentation (indenting-stream-indentation ,stream)))
1332        ((>= i indentation))
1333      (write-string*
1334       "                                                     "
1335       ,sub-stream 0 (min 60 (- indentation i)))))
1336
1337 ;;; Indenting-Out writes a character to an indenting stream.
1338 (defun indenting-out (stream char)
1339   (let ((sub-stream (indenting-stream-stream stream)))
1340     (write-char char sub-stream)
1341     (if (char= char #\newline)
1342         (indenting-indent stream sub-stream))))
1343
1344 ;;; Indenting-Sout writes a string to an indenting stream.
1345
1346 (defun indenting-sout (stream string start end)
1347   (declare (simple-string string) (fixnum start end))
1348   (do ((i start)
1349        (sub-stream (indenting-stream-stream stream)))
1350       ((= i end))
1351     (let ((newline (position #\newline string :start i :end end)))
1352       (cond (newline
1353              (write-string* string sub-stream i (1+ newline))
1354              (indenting-indent stream sub-stream)
1355              (setq i (+ newline 1)))
1356             (t
1357              (write-string* string sub-stream i end)
1358              (setq i end))))))
1359
1360 ;;; Indenting-Misc just treats just the :Line-Length message differently.
1361 ;;; Indenting-Charpos says the charpos is the charpos of the base stream minus
1362 ;;; the stream's indentation.
1363
1364 (defun indenting-misc (stream operation &optional arg1 arg2)
1365   (let ((sub-stream (indenting-stream-stream stream)))
1366     (if (lisp-stream-p sub-stream)
1367         (let ((method (lisp-stream-misc sub-stream)))
1368           (case operation
1369             (:line-length
1370              (let ((line-length (funcall method sub-stream operation)))
1371                (if line-length
1372                    (- line-length (indenting-stream-indentation stream)))))
1373             (:charpos
1374              (let ((charpos (funcall method sub-stream operation)))
1375                (if charpos
1376                    (- charpos (indenting-stream-indentation stream)))))
1377             (t
1378              (funcall method sub-stream operation arg1 arg2))))
1379         ;; Fundamental-stream.
1380         (case operation
1381           (:line-length
1382            (let ((line-length (stream-line-length sub-stream)))
1383              (if line-length
1384                  (- line-length (indenting-stream-indentation stream)))))
1385           (:charpos
1386            (let ((charpos (stream-line-column sub-stream)))
1387              (if charpos
1388                  (- charpos (indenting-stream-indentation stream)))))
1389           (t
1390            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1391
1392 (declaim (maybe-inline read-char unread-char read-byte listen))
1393 \f
1394 ;;;; case frobbing streams, used by format ~(...~)
1395
1396 (defstruct (case-frob-stream
1397             (:include lisp-stream
1398                       (:misc #'case-frob-misc))
1399             (:constructor %make-case-frob-stream (target out sout)))
1400   (target (required-argument) :type stream))
1401
1402 (defun make-case-frob-stream (target kind)
1403   #!+sb-doc
1404   "Returns a stream that sends all output to the stream TARGET, but modifies
1405    the case of letters, depending on KIND, which should be one of:
1406      :upcase - convert to upper case.
1407      :downcase - convert to lower case.
1408      :capitalize - convert the first letter of words to upper case and the
1409         rest of the word to lower case.
1410      :capitalize-first - convert the first letter of the first word to upper
1411         case and everything else to lower case."
1412   (declare (type stream target)
1413            (type (member :upcase :downcase :capitalize :capitalize-first)
1414                  kind)
1415            (values stream))
1416   (if (case-frob-stream-p target)
1417       ;; If we are going to be writing to a stream that already does case
1418       ;; frobbing, why bother frobbing the case just so it can frob it
1419       ;; again?
1420       target
1421       (multiple-value-bind (out sout)
1422           (ecase kind
1423             (:upcase
1424              (values #'case-frob-upcase-out
1425                      #'case-frob-upcase-sout))
1426             (:downcase
1427              (values #'case-frob-downcase-out
1428                      #'case-frob-downcase-sout))
1429             (:capitalize
1430              (values #'case-frob-capitalize-out
1431                      #'case-frob-capitalize-sout))
1432             (:capitalize-first
1433              (values #'case-frob-capitalize-first-out
1434                      #'case-frob-capitalize-first-sout)))
1435         (%make-case-frob-stream target out sout))))
1436
1437 (defun case-frob-misc (stream op &optional arg1 arg2)
1438   (declare (type case-frob-stream stream))
1439   (case op
1440     (:close)
1441     (t
1442      (let ((target (case-frob-stream-target stream)))
1443        (if (lisp-stream-p target)
1444            (funcall (lisp-stream-misc target) target op arg1 arg2)
1445            (stream-misc-dispatch target op arg1 arg2))))))
1446
1447 (defun case-frob-upcase-out (stream char)
1448   (declare (type case-frob-stream stream)
1449            (type base-char char))
1450   (let ((target (case-frob-stream-target stream))
1451         (char (char-upcase char)))
1452     (if (lisp-stream-p target)
1453         (funcall (lisp-stream-out target) target char)
1454         (stream-write-char target char))))
1455
1456 (defun case-frob-upcase-sout (stream str start end)
1457   (declare (type case-frob-stream stream)
1458            (type simple-base-string str)
1459            (type index start)
1460            (type (or index null) end))
1461   (let* ((target (case-frob-stream-target stream))
1462          (len (length str))
1463          (end (or end len))
1464          (string (if (and (zerop start) (= len end))
1465                      (string-upcase str)
1466                      (nstring-upcase (subseq str start end))))
1467          (string-len (- end start)))
1468     (if (lisp-stream-p target)
1469         (funcall (lisp-stream-sout target) target string 0 string-len)
1470         (stream-write-string target string 0 string-len))))
1471
1472 (defun case-frob-downcase-out (stream char)
1473   (declare (type case-frob-stream stream)
1474            (type base-char char))
1475   (let ((target (case-frob-stream-target stream))
1476         (char (char-downcase char)))
1477     (if (lisp-stream-p target)
1478         (funcall (lisp-stream-out target) target char)
1479         (stream-write-char target char))))
1480
1481 (defun case-frob-downcase-sout (stream str start end)
1482   (declare (type case-frob-stream stream)
1483            (type simple-base-string str)
1484            (type index start)
1485            (type (or index null) end))
1486   (let* ((target (case-frob-stream-target stream))
1487          (len (length str))
1488          (end (or end len))
1489          (string (if (and (zerop start) (= len end))
1490                      (string-downcase str)
1491                      (nstring-downcase (subseq str start end))))
1492          (string-len (- end start)))
1493     (if (lisp-stream-p target)
1494         (funcall (lisp-stream-sout target) target string 0 string-len)
1495         (stream-write-string target string 0 string-len))))
1496
1497 (defun case-frob-capitalize-out (stream char)
1498   (declare (type case-frob-stream stream)
1499            (type base-char char))
1500   (let ((target (case-frob-stream-target stream)))
1501     (cond ((alphanumericp char)
1502            (let ((char (char-upcase char)))
1503              (if (lisp-stream-p target)
1504                  (funcall (lisp-stream-out target) target char)
1505                  (stream-write-char target char)))
1506            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1507            (setf (case-frob-stream-sout stream)
1508                  #'case-frob-capitalize-aux-sout))
1509           (t
1510            (if (lisp-stream-p target)
1511                (funcall (lisp-stream-out target) target char)
1512                (stream-write-char target char))))))
1513
1514 (defun case-frob-capitalize-sout (stream str start end)
1515   (declare (type case-frob-stream stream)
1516            (type simple-base-string str)
1517            (type index start)
1518            (type (or index null) end))
1519   (let* ((target (case-frob-stream-target stream))
1520          (str (subseq str start end))
1521          (len (length str))
1522          (inside-word nil))
1523     (dotimes (i len)
1524       (let ((char (schar str i)))
1525         (cond ((not (alphanumericp char))
1526                (setf inside-word nil))
1527               (inside-word
1528                (setf (schar str i) (char-downcase char)))
1529               (t
1530                (setf inside-word t)
1531                (setf (schar str i) (char-upcase char))))))
1532     (when inside-word
1533       (setf (case-frob-stream-out stream)
1534             #'case-frob-capitalize-aux-out)
1535       (setf (case-frob-stream-sout stream)
1536             #'case-frob-capitalize-aux-sout))
1537     (if (lisp-stream-p target)
1538         (funcall (lisp-stream-sout target) target str 0 len)
1539         (stream-write-string target str 0 len))))
1540
1541 (defun case-frob-capitalize-aux-out (stream char)
1542   (declare (type case-frob-stream stream)
1543            (type base-char char))
1544   (let ((target (case-frob-stream-target stream)))
1545     (cond ((alphanumericp char)
1546            (let ((char (char-downcase char)))
1547              (if (lisp-stream-p target)
1548                  (funcall (lisp-stream-out target) target char)
1549                  (stream-write-char target char))))
1550           (t
1551            (if (lisp-stream-p target)
1552                (funcall (lisp-stream-out target) target char)
1553                (stream-write-char target char))
1554            (setf (case-frob-stream-out stream)
1555                  #'case-frob-capitalize-out)
1556            (setf (case-frob-stream-sout stream)
1557                  #'case-frob-capitalize-sout)))))
1558
1559 (defun case-frob-capitalize-aux-sout (stream str start end)
1560   (declare (type case-frob-stream stream)
1561            (type simple-base-string str)
1562            (type index start)
1563            (type (or index null) end))
1564   (let* ((target (case-frob-stream-target stream))
1565          (str (subseq str start end))
1566          (len (length str))
1567          (inside-word t))
1568     (dotimes (i len)
1569       (let ((char (schar str i)))
1570         (cond ((not (alphanumericp char))
1571                (setf inside-word nil))
1572               (inside-word
1573                (setf (schar str i) (char-downcase char)))
1574               (t
1575                (setf inside-word t)
1576                (setf (schar str i) (char-upcase char))))))
1577     (unless inside-word
1578       (setf (case-frob-stream-out stream)
1579             #'case-frob-capitalize-out)
1580       (setf (case-frob-stream-sout stream)
1581             #'case-frob-capitalize-sout))
1582     (if (lisp-stream-p target)
1583         (funcall (lisp-stream-sout target) target str 0 len)
1584         (stream-write-string target str 0 len))))
1585
1586 (defun case-frob-capitalize-first-out (stream char)
1587   (declare (type case-frob-stream stream)
1588            (type base-char char))
1589   (let ((target (case-frob-stream-target stream)))
1590     (cond ((alphanumericp char)
1591            (let ((char (char-upcase char)))
1592              (if (lisp-stream-p target)
1593                  (funcall (lisp-stream-out target) target char)
1594                  (stream-write-char target char)))
1595            (setf (case-frob-stream-out stream)
1596                  #'case-frob-downcase-out)
1597            (setf (case-frob-stream-sout stream)
1598                  #'case-frob-downcase-sout))
1599           (t
1600            (if (lisp-stream-p target)
1601                (funcall (lisp-stream-out target) target char)
1602                (stream-write-char target char))))))
1603
1604 (defun case-frob-capitalize-first-sout (stream str start end)
1605   (declare (type case-frob-stream stream)
1606            (type simple-base-string str)
1607            (type index start)
1608            (type (or index null) end))
1609   (let* ((target (case-frob-stream-target stream))
1610          (str (subseq str start end))
1611          (len (length str)))
1612     (dotimes (i len)
1613       (let ((char (schar str i)))
1614         (when (alphanumericp char)
1615           (setf (schar str i) (char-upcase char))
1616           (do ((i (1+ i) (1+ i)))
1617               ((= i len))
1618             (setf (schar str i) (char-downcase (schar str i))))
1619           (setf (case-frob-stream-out stream)
1620                 #'case-frob-downcase-out)
1621           (setf (case-frob-stream-sout stream)
1622                 #'case-frob-downcase-sout)
1623           (return))))
1624     (if (lisp-stream-p target)
1625         (funcall (lisp-stream-sout target) target str 0 len)
1626         (stream-write-string target str 0 len))))
1627 \f
1628 ;;;; public interface from "EXTENSIONS" package
1629
1630 (defstruct (stream-command (:constructor make-stream-command
1631                                          (name &optional args)))
1632   (name nil :type symbol)
1633   (args nil :type list))
1634 (def!method print-object ((obj stream-command) str)
1635   (print-unreadable-object (obj str :type t :identity t)
1636     (prin1 (stream-command-name obj) str)))
1637
1638 ;;; We can't simply call the stream's misc method because NIL is an
1639 ;;; ambiguous return value: does it mean text arrived, or does it mean the
1640 ;;; stream's misc method had no :GET-COMMAND implementation. We can't return
1641 ;;; NIL until there is text input. We don't need to loop because any stream
1642 ;;; implementing :get-command would wait until it had some input. If the
1643 ;;; LISTEN fails, then we have some stream we must wait on.
1644 (defun get-stream-command (stream)
1645   #!+sb-doc
1646   "This takes a stream and waits for text or a command to appear on it. If
1647    text appears before a command, this returns nil, and otherwise it returns
1648    a command."
1649   (let ((cmdp (funcall (lisp-stream-misc stream) stream :get-command)))
1650     (cond (cmdp)
1651           ((listen stream)
1652            nil)
1653           (t
1654            ;; This waits for input and returns nil when it arrives.
1655            (unread-char (read-char stream) stream)))))
1656 \f
1657 (defun read-sequence (seq stream &key (start 0) (end nil))
1658   #!+sb-doc
1659   "Destructively modify SEQ by reading elements from STREAM.
1660   That part of SEQ bounded by START and END is destructively modified by
1661   copying successive elements into it from STREAM. If the end of file
1662   for STREAM is reached before copying all elements of the subsequence,
1663   then the extra elements near the end of sequence are not updated, and
1664   the index of the next element is returned."
1665   (declare (type sequence seq)
1666            (type stream stream)
1667            (type index start)
1668            (type sequence-end end)
1669            (values index))
1670   (let ((end (or end (length seq))))
1671     (declare (type index end))
1672     (etypecase seq
1673       (list
1674        (let ((read-function
1675               (if (subtypep (stream-element-type stream) 'character)
1676                   #'read-char
1677                   #'read-byte)))
1678          (do ((rem (nthcdr start seq) (rest rem))
1679               (i start (1+ i)))
1680              ((or (endp rem) (>= i end)) i)
1681            (declare (type list rem)
1682                     (type index i))
1683            (let ((el (funcall read-function stream nil :eof)))
1684              (when (eq el :eof)
1685                (return i))
1686              (setf (first rem) el)))))
1687       (vector
1688        (with-array-data ((data seq) (offset-start start) (offset-end end))
1689          (typecase data
1690            ((or (simple-array (unsigned-byte 8) (*))
1691                 (simple-array (signed-byte 8) (*))
1692                 simple-string)
1693             (let* ((numbytes (- end start))
1694                    (bytes-read (sb!sys:read-n-bytes stream
1695                                                     data
1696                                                     offset-start
1697                                                     numbytes
1698                                                     nil)))
1699               (if (< bytes-read numbytes)
1700                   (+ start bytes-read)
1701                   end)))
1702            (t
1703             (let ((read-function
1704                    (if (subtypep (stream-element-type stream) 'character)
1705                        #'read-char
1706                        #'read-byte)))
1707               (do ((i offset-start (1+ i)))
1708                   ((>= i offset-end) end)
1709                 (declare (type index i))
1710                 (let ((el (funcall read-function stream nil :eof)))
1711                   (when (eq el :eof)
1712                     (return (+ start (- i offset-start))))
1713                   (setf (aref data i) el)))))))))))
1714
1715 (defun write-sequence (seq stream &key (start 0) (end nil))
1716   #!+sb-doc
1717   "Write the elements of SEQ bounded by START and END to STREAM."
1718   (declare (type sequence seq)
1719            (type stream stream)
1720            (type index start)
1721            (type sequence-end end)
1722            (values sequence))
1723   (let ((end (or end (length seq))))
1724     (declare (type index start end))
1725     (etypecase seq
1726       (list
1727        (let ((write-function
1728               (if (subtypep (stream-element-type stream) 'character)
1729                   #'write-char
1730                   #'write-byte)))
1731          (do ((rem (nthcdr start seq) (rest rem))
1732               (i start (1+ i)))
1733              ((or (endp rem) (>= i end)) seq)
1734            (declare (type list rem)
1735                     (type index i))
1736            (funcall write-function (first rem) stream))))
1737       (string
1738        (write-string* seq stream start end))
1739       (vector
1740        (let ((write-function
1741               (if (subtypep (stream-element-type stream) 'character)
1742                   #'write-char
1743                   #'write-byte)))
1744          (do ((i start (1+ i)))
1745              ((>= i end) seq)
1746            (declare (type index i))
1747            (funcall write-function (aref seq i) stream)))))))
1748
1749 ;;; (These were inline throughout this file, but that's not appropriate
1750 ;;; globally.)
1751 (declaim (maybe-inline read-char unread-char read-byte listen))