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