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