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