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