Debian Codegraph @

src/libio.scm

raw
1 ;;;
2 ;;; libio.scm - builtin port and I/O procedures
3 ;;;
4 ;;; Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 (select-module gauche.internal)
35
36 (inline-stub
37 (.include "gauche/priv/configP.h"
38 "gauche/vminsn.h"
39 "gauche/exception.h"
40 "gauche/priv/portP.h"
41 "gauche/priv/writerP.h"
42 <stdlib.h>
43 <fcntl.h>))
44
45 ;;;
46 ;;; Ports
47 ;;;
48
49 ;;
50 ;; Predicates
51 ;;
52
53 (select-module scheme)
54 (define-cproc input-port? (obj) ::<boolean> SCM_IPORTP)
55 (define-cproc output-port? (obj) ::<boolean> SCM_OPORTP)
56 (define-cproc port? (obj) ::<boolean> SCM_PORTP)
57
58 (select-module gauche)
59 (define-cproc port-closed? (obj::<port>) ::<boolean> SCM_PORT_CLOSED_P)
60
61 ;;
62 ;; Default coding
63 ;;
64
65 (inline-stub
66 (define-cvar default-file-encoding::ScmPrimitiveParameter* :static)
67 (initcode
68 (set! default-file-encoding
69 (Scm_BindPrimitiveParameter (Scm_GaucheModule)
70 "default-file-encoding"
71 (Scm_CharEncodingName) 0)))
72 )
73
74 ;;
75 ;; Preexisting ports
76 ;;
77
78 (select-module gauche)
79
80 (define-cproc standard-input-port (:optional (p::<input-port>? #f))
81 (return (?: p (Scm_SetStdin p) (Scm_Stdin))))
82 (define-cproc standard-output-port (:optional (p::<output-port>? #f))
83 (return (?: p (Scm_SetStdout p) (Scm_Stdout))))
84 (define-cproc standard-error-port (:optional (p::<output-port>? #f))
85 (return (?: p (Scm_SetStderr p) (Scm_Stderr))))
86
87 (inline-stub
88 (initcode
89 (Scm_BindPrimitiveParameter (Scm_GaucheModule)
90 "current-trace-port"
91 (Scm_Stderr) 0)))
92
93 ;;
94 ;; Query and low-level properties
95 ;;
96
97 (select-module gauche)
98
99 (define-cproc port-name (port::<port>) Scm_PortName)
100 (define-cproc port-current-line (port::<port>) ::<fixnum> Scm_PortLine)
101
102 (define-cproc port-file-number (port::<port> :optional (dup?::<boolean> #f))
103 (let* ([i::int (Scm_PortFileNo port)])
104 (when (< i 0) (return SCM_FALSE))
105 (when dup?
106 (let* ([r::int 0])
107 (SCM_SYSCALL r (dup i))
108 (when (< r 0) (Scm_SysError "dup(2) failed"))
109 (set! i r)))
110 (return (Scm_MakeInteger i))))
111 (define-cproc port-fd-dup! (dst::<port> src::<port>) ::<void> Scm_PortFdDup)
112
113 (define-cproc port-attribute-set! (port::<port> key val)
114 Scm_PortAttrSet)
115 (define-cproc port-attribute-ref (port::<port> key :optional fallback)
116 (setter port-attribute-set!)
117 Scm_PortAttrGet)
118 (define-cproc port-attribute-delete! (port::<port> key)
119 Scm_PortAttrDelete)
120 (define-cproc port-attributes (port::<port>)
121 Scm_PortAttrs)
122
123
124 (define-cproc port-type (port::<port>)
125 (case (SCM_PORT_TYPE port)
126 [(SCM_PORT_FILE) (return 'file)]
127 [(SCM_PORT_PROC) (return 'proc)]
128 [(SCM_PORT_OSTR SCM_PORT_ISTR) (return 'string)]
129 [else (return '#f)]))
130
131 (define-cproc port-buffering (port::<port>)
132 (setter (port::<port> mode) ::<void>
133 (unless (== (SCM_PORT_TYPE port) SCM_PORT_FILE)
134 (Scm_Error "can't set buffering mode to non-buffered port: %S"port))
135 (Scm_SetPortBufferingMode
136 port (Scm_BufferingMode mode (-> port direction) -1)))
137 (return (Scm_GetPortBufferingModeAsKeyword port)))
138
139 (define-cproc port-link! (iport::<input-port> oport::<output-port>) ::<void>
140 Scm_LinkPorts)
141
142 (define-cproc port-unlink! (port::<port>) ::<void> Scm_UnlinkPorts)
143
144 (select-module gauche.internal)
145 (define-cproc port-case-fold (port::<port>) ::<boolean>
146 (setter (port::<port> flag::<boolean>) ::<void>
147 (if flag
148 (logior= (SCM_PORT_FLAGS port) SCM_PORT_CASE_FOLD)
149 (logand= (SCM_PORT_FLAGS port) (lognot SCM_PORT_CASE_FOLD))))
150 (return (logand (SCM_PORT_FLAGS port) SCM_PORT_CASE_FOLD)))
151
152
153 ;;
154 ;; Open and close
155 ;;
156
157 (select-module scheme)
158 (define-cproc close-input-port (port::<input-port>) ::<void> Scm_ClosePort)
159 (define-cproc close-output-port (port::<output-port>) ::<void> Scm_ClosePort)
160 (select-module gauche)
161 (define-cproc close-port (port::<port>) ::<void> Scm_ClosePort) ;R6RS
162
163 (select-module gauche.internal)
164 (inline-stub
165 ;; NB: On MinGW, if we try to create a file and a directory with the
166 ;; same name exists, open(2) throws EACCES. Weird, eh? We don't want
167 ;; to catch EACCES on other platforms, hence this dirty trick.
168 (.if (defined GAUCHE_WINDOWS)
169 (.define DIRECTORY_GETS_IN_WAY (x) (== x EACCES))
170 (.define DIRECTORY_GETS_IN_WAY (x) FALSE))
171
172 ;; Some cise macros for common idioms
173 (define-cise-expr %open/allow-noexist?
174 [(_ if-does-not-exist-is-false)
175 `(and ,if-does-not-exist-is-false
176 (or (== errno ENOENT)
177 (== errno ENODEV)
178 (== errno ENXIO)
179 (== errno ENOTDIR)))])
180
181 (define-cise-expr %open/allow-exist?
182 [(_ if-exists-is-false)
183 `(and ,if-exists-is-false
184 (or (== errno EEXIST)
185 (== errno ENOTDIR)
186 (DIRECTORY_GETS_IN_WAY errno)))])
187 )
188
189 ;; Primitive open routine. The Scheme wrapper handles other keyword args.
190 (define-cproc %open-input-file (path::<string>
191 :key (if-does-not-exist :error)
192 (buffering #f)
193 (element-type :binary))
194 (let* ([ignerr::int FALSE]
195 [flags::int O_RDONLY])
196 (cond [(SCM_FALSEP if-does-not-exist) (set! ignerr TRUE)]
197 [(not (SCM_EQ if-does-not-exist ':error))
198 (Scm_TypeError ":if-does-not-exist" ":error or #f"
199 if-does-not-exist)])
200 (unless (or (SCM_EQ element-type ':character)
201 (SCM_EQ element-type ':binary))
202 (Scm_Error "bad element-type argument: either :character or :binary \
203 expected, but got %S" element-type))
204 (.if (and (defined O_BINARY) (defined O_TEXT))
205 (if (SCM_EQ element-type ':character)
206 (logior= flags O_TEXT)
207 (logior= flags O_BINARY)))
208 (let* ([bufmode::int (Scm_BufferingMode buffering SCM_PORT_INPUT
209 SCM_PORT_BUFFER_FULL)]
210 [o (Scm_OpenFilePort (Scm_GetStringConst path)
211 flags bufmode 0)])
212 (when (and (SCM_FALSEP o) (not (%open/allow-noexist? ignerr)))
213 (Scm_SysError "couldn't open input file: %S" path))
214 (return o))))
215
216 ;; Primitive open routine. The Scheme wrapper handles other keyword args
217 (define-cproc %open-output-file (path::<string>
218 :key (if-exists :supersede)
219 (if-does-not-exist :create)
220 (mode::<fixnum> #o666)
221 (buffering #f)
222 (element-type :binary))
223 (let* ([ignerr-noexist::int FALSE]
224 [ignerr-exist::int FALSE]
225 [flags::int O_WRONLY])
226 (unless (or (SCM_EQ element-type ':character)
227 (SCM_EQ element-type ':binary))
228 (Scm_Error "bad element-type argument: either :character or :binary \
229 expected, but got %S" element-type))
230 (.if (and (defined O_BINARY) (defined O_TEXT))
231 (if (SCM_EQ element-type ':character)
232 (logior= flags O_TEXT)
233 (logior= flags O_BINARY)))
234 ;; check if-exists flag
235 (cond
236 [(SCM_EQ if-exists ':append) (logior= flags O_APPEND)]
237 [(SCM_EQ if-exists ':error)
238 (logior= flags O_EXCL)
239 (when (SCM_EQ if-does-not-exist ':error)
240 (Scm_Error "bad flag combination: :if-exists and :if-does-not-exist can't be :error the same time."))]
241 [(SCM_EQ if-exists ':supersede) (logior= flags O_TRUNC)]
242 [(SCM_EQ if-exists ':overwrite)] ; no need to add flags
243 [(SCM_FALSEP if-exists) (logior= flags O_EXCL) (set! ignerr-exist TRUE)]
244 [else
245 (Scm_TypeError ":if-exists" ":supersede, :overwrite, :append, :error or #f" if-exists)])
246 ;; check if-does-not-exist flag
247 (cond
248 [(SCM_EQ if-does-not-exist ':create) (logior= flags O_CREAT)]
249 [(SCM_FALSEP if-does-not-exist) (set! ignerr-noexist TRUE)]
250 [(SCM_EQ if-does-not-exist ':error)] ; no need to add flags
251 [else (Scm_TypeError ":if-does-not-exist" ":error, :create or #f"
252 if-does-not-exist)])
253 (let* ([bufmode::int
254 (Scm_BufferingMode buffering SCM_PORT_OUTPUT SCM_PORT_BUFFER_FULL)]
255 [o (Scm_OpenFilePort (Scm_GetStringConst path)
256 flags bufmode mode)])
257 (when (and (SCM_FALSEP o)
258 (not (%open/allow-noexist? ignerr-noexist))
259 (not (%open/allow-exist? ignerr-exist)))
260 (Scm_Error "couldn't open output file: %S" path))
261 (return o))))
262
263 ;; Open port from fd
264 (select-module gauche)
265
266 (define-cproc open-input-fd-port (fd::<fixnum>
267 :key (buffering #f)
268 (owner? #f)
269 (name #f))
270 (let* ([bufmode::int (Scm_BufferingMode buffering SCM_PORT_INPUT
271 SCM_PORT_BUFFER_FULL)])
272 (when (< fd 0) (Scm_Error "bad file descriptor: %ld" fd))
273 (cond
274 [(SCM_EQ owner? 'dup)
275 (let* ([r::int 0])
276 (SCM_SYSCALL r (dup fd))
277 (when (< r 0) (Scm_SysError "dup(2) failed"))
278 (set! fd r))]
279 [(not (SCM_BOOLP owner?))
280 (Scm_Error "owner? argument must be either #f, #t or a symbol dup, \n\
281 but go t%S" owner?)])
282 (return (Scm_MakePortWithFd name SCM_PORT_INPUT fd bufmode
283 (not (SCM_FALSEP owner?))))))
284
285 (define-cproc open-output-fd-port (fd::<fixnum>
286 :key (buffering #f)
287 (owner? #f)
288 (name #f))
289 (let* ([bufmode::int (Scm_BufferingMode buffering SCM_PORT_OUTPUT
290 SCM_PORT_BUFFER_FULL)])
291 (when (< fd 0) (Scm_Error "bad file descriptor: %d" fd))
292 (cond
293 [(SCM_EQ owner? 'dup)
294 (let* ([r::int 0])
295 (SCM_SYSCALL r (dup fd))
296 (when (< r 0) (Scm_SysError "dup(2) failed"))
297 (set! fd r))]
298 [(not (SCM_BOOLP owner?))
299 (Scm_Error "owner? argument must be either #f, #t or a symbol dup, \n\
300 but go t%S" owner?)])
301 (return (Scm_MakePortWithFd name SCM_PORT_OUTPUT fd bufmode
302 (not (SCM_FALSEP owner?))))))
303
304 ;; Buffered port
305 (select-module gauche)
306 (inline-stub
307 ;; Buffered port
308 ;; NB: the interface may be changed soon!!
309 (define-cfn bufport-closer (p::ScmPort*) ::void :static
310 (when (== (SCM_PORT_DIR p) SCM_PORT_OUTPUT)
311 (let* ((scmflusher (SCM_OBJ (-> (PORT_BUF p) data)))
312 (siz::int (cast int (- (-> (PORT_BUF p) current)
313 (-> (PORT_BUF p) buffer)))))
314 (when (> siz 0)
315 (Scm_ApplyRec1 scmflusher
316 (Scm_MakeString (-> (PORT_BUF p) buffer) siz siz
317 (logior SCM_STRING_INCOMPLETE
318 SCM_STRING_COPYING))))
319 (Scm_ApplyRec1 scmflusher SCM_FALSE))))
320
321 (define-cfn bufport-filler (p::ScmPort* cnt::ScmSize) ::ScmSize :static
322 (let* ([scmfiller (SCM_OBJ (-> (PORT_BUF p) data))]
323 [r (Scm_ApplyRec1 scmfiller (Scm_MakeInteger cnt))])
324 (cond [(or (SCM_EOFP r) (SCM_FALSEP r)) (return 0)]
325 [(not (SCM_STRINGP r))
326 (Scm_Error "buffered port callback procedure returned non-string: %S" r)])
327 (let* ([b::(const ScmStringBody*) (SCM_STRING_BODY r)]
328 [siz::ScmSize (SCM_STRING_BODY_SIZE b)])
329 (when (> siz cnt) (set! siz cnt)) ; for safety
330 (memcpy (-> (PORT_BUF p) end) (SCM_STRING_BODY_START b) siz)
331 (return (SCM_STRING_BODY_SIZE b)))))
332 )
333
334 (define-cproc open-input-buffered-port
335 (filler::<procedure> buffer-size::<fixnum>)
336 (let* ([bufrec::ScmPortBuffer])
337 (set! (ref bufrec size) buffer-size
338 (ref bufrec buffer) NULL
339 (ref bufrec mode) SCM_PORT_BUFFER_FULL
340 (ref bufrec filler) bufport-filler
341 (ref bufrec flusher) NULL
342 (ref bufrec closer) bufport-closer
343 (ref bufrec ready) NULL
344 (ref bufrec filenum) NULL
345 (ref bufrec data) (cast void* filler))
346 (return (Scm_MakeBufferedPort SCM_CLASS_PORT SCM_FALSE SCM_PORT_INPUT TRUE (& bufrec)))))
347
348 (inline-stub
349 (define-cfn bufport-flusher (p::ScmPort* cnt::ScmSize _::int)
350 ::ScmSize :static
351 (let* ([scmflusher (SCM_OBJ (-> (PORT_BUF p) data))]
352 [s (Scm_MakeString (-> (PORT_BUF p) buffer) cnt cnt
353 (logior SCM_STRING_INCOMPLETE SCM_STRING_COPYING))])
354 (Scm_ApplyRec1 scmflusher s)
355 (return cnt)))
356 )
357
358 (define-cproc open-output-buffered-port
359 (flusher::<procedure> buffer-size::<fixnum>)
360 (let* ([bufrec::ScmPortBuffer])
361 (set! (ref bufrec size) buffer-size
362 (ref bufrec buffer) NULL
363 (ref bufrec mode) SCM_PORT_BUFFER_FULL
364 (ref bufrec filler) NULL
365 (ref bufrec flusher) bufport-flusher
366 (ref bufrec closer) bufport-closer
367 (ref bufrec ready) NULL
368 (ref bufrec filenum) NULL
369 (ref bufrec data) (cast void* flusher))
370 (return (Scm_MakeBufferedPort SCM_CLASS_PORT SCM_FALSE SCM_PORT_OUTPUT
371 TRUE (& bufrec)))))
372
373 ;; String ports (SRFI-6)
374 ;; By default, string ports are named as "(input string port)" and
375 ;; "(output string port)", which aren't very informative. The caller
376 ;; can specify alternative name with :name keyword argument. NB: Currently,
377 ;; port name is assumed to be a pathname if it doesn't match #/^\(.*\)$/.
378 ;; This convention may be replaced by more reliable mechanism to determine
379 ;; port source path. Until then, be careful to name the ports.
380 (select-module gauche)
381
382 (define-cproc open-input-string (string::<string>
383 :key (private?::<boolean> #f)
384 (name "(input string port)"))
385 (let* ([flags::u_long (?: private? SCM_PORT_STRING_PRIVATE 0)])
386 (return (Scm_MakeInputStringPortFull string name flags))))
387
388 (define-cproc open-output-string (:key (private?::<boolean> #f)
389 (name "(output string port)"))
390 (let* ([flags::u_long (?: private? SCM_PORT_STRING_PRIVATE 0)])
391 (return (Scm_MakeOutputStringPortFull name flags))))
392
393 (define-cproc get-output-string (oport::<output-port>) ;SRFI-6
394 (return (Scm_GetOutputString oport 0)))
395
396 (define-cproc get-output-byte-string (oport::<output-port>)
397 (return (Scm_GetOutputString oport SCM_STRING_INCOMPLETE)))
398
399 (define-cproc get-remaining-input-string (iport::<input-port>)
400 (return (Scm_GetRemainingInputString iport 0)))
401
402 ;; Coding aware port
403 (select-module gauche)
404
405 (define-cproc open-coding-aware-port (iport::<input-port>)
406 Scm_MakeCodingAwarePort)
407
408 ;;
409 ;; Miscellaneous
410 ;;
411
412 ;; SRFI-191
413 (define-cproc port-has-port-position? (port::<port>) ::<boolean>
414 (return (Scm_PortPositionable port FALSE)))
415 (define-cproc port-has-set-port-position!? (port::<port>) ::<boolean>
416 (return (Scm_PortPositionable port TRUE)))
417
418 (define-cproc port-position (port::<port>)
419 (return (Scm_GetPortPosition port)))
420 (define-cproc set-port-position! (port::<port> pos)
421 (return (Scm_SetPortPosition port pos)))
422
423 (select-module gauche)
424 (inline-stub
425 (define-enum SEEK_SET)
426 (define-enum SEEK_CUR)
427 (define-enum SEEK_END)
428 )
429
430 (define-cproc port-seek
431 (port::<port> offset::<integer>
432 :optional (whence::<fixnum> (c "SCM_MAKE_INT(SEEK_SET)")))
433 Scm_PortSeek)
434
435 ;; useful alias
436 (define (port-tell p) (port-seek p 0 SEEK_CUR))
437
438 ;; useful for error messages
439 (define (port-position-prefix port)
440 (if (port? port)
441 (if-let1 n (port-name port)
442 (let1 l (port-current-line port)
443 (if (positive? l)
444 (format #f "~s:line ~a: " n l)
445 (format #f "~s: " n))
446 ""))
447 "???"))
448
449 (select-module gauche.internal)
450
451 ;; Transient flags during circular/shared-aware writing
452 (define-cproc %port-walking? (port::<port>) ::<boolean>
453 (setter (port::<port> flag::<boolean>) ::<void>
454 (if flag
455 (logior= (-> port flags) SCM_PORT_WALKING)
456 (logand= (-> port flags) (lognot SCM_PORT_WALKING))))
457 PORT_WALKER_P)
458 (define-cproc %port-writing-shared? (port::<port>) ::<boolean>
459 (setter (port::<port> flag::<boolean>) ::<void>
460 (if flag
461 (logior= (-> port flags) SCM_PORT_WRITESS)
462 (logand= (-> port flags) (lognot SCM_PORT_WRITESS))))
463 PORT_WRITESS_P)
464
465 (inline-stub
466 (define-cfn write_state_allocate (_::ScmClass* _) :static
467 (return (SCM_OBJ (Scm_MakeWriteState NULL))))
468
469 (define-cfn write_state_print (obj port::ScmPort* _::ScmWriteContext*)
470 ::void :static
471 (Scm_Printf port "#<write-state %p>" obj))
472
473 (define-cclass <write-state>
474 "ScmWriteState*" "Scm_WriteStateClass"
475 ("Scm_TopClass")
476 ((shared-table :type <hash-table>? :c-name "sharedTable")
477 (shared-counter :type <int> :c-name "sharedCounter"))
478 (allocator (c "write_state_allocate"))
479 (printer (c "write_state_print")))
480 )
481
482 (define-cproc %port-write-state (port::<port>)
483 (setter (port::<port> obj) ::<void>
484 (if (SCM_WRITE_STATE_P obj)
485 (Scm_PortWriteStateSet port (SCM_WRITE_STATE obj))
486 (Scm_PortWriteStateSet port NULL)))
487 (let* ([r::ScmWriteState* (Scm_PortWriteState port)])
488 (return (?: r (SCM_OBJ r) SCM_FALSE))))
489
490 (define-cproc %port-lock! (port::<port>) ::<void>
491 (let* ([vm::ScmVM* (Scm_VM)])
492 (PORT_LOCK port vm)))
493 (define-cproc %port-unlock! (port::<port>) ::<void>
494 (PORT_UNLOCK port))
495
496 ;; Passing extra args is unusual for with-* style, but it can allow avoiding
497 ;; closure allocation and may be useful for performance-sensitive parts.
498 (define-in-module gauche (with-port-locking port proc . args)
499 (unwind-protect
500 (begin (%port-lock! port)
501 (apply proc args))
502 (%port-unlock! port)))
503
504 (define-in-module gauche.internal ; used by two-pass output
505 (%with-2pass-setup port walker emitter . args)
506 ;; The caller guarantees to call this when port isn't in two-pass
507 ;; mode. We lock the port, and call WALKER with setting the port
508 ;; to 'walking' mode, then call EMITTER with setting the port to
509 ;; 'write-ss' mode.
510 (unwind-protect
511 (begin
512 (%port-lock! port)
513 (when (%port-write-state port)
514 (error "[internal] %with-2pass-setup called recursively on port:"
515 port))
516 (set! (%port-write-state port)
517 (make <write-state> :shared-table (make-hash-table 'eq?)))
518 (set! (%port-walking? port) #t)
519 (apply walker args)
520 (set! (%port-walking? port) #f)
521 (apply emitter args))
522 (set! (%port-walking? port) #f)
523 (set! (%port-write-state port) #f)
524 (%port-unlock! port)))
525
526 ;; For the time being, we keep this in gauche.internal, for we don't know
527 ;; how complete column count feature can be.
528 (define-cproc port-column (port::<port>) ::<fixnum>
529 (return (Scm_PortColumn port)))
530
531
532 ;;;
533 ;;; Input
534 ;;;
535
536 (select-module scheme)
537
538 (define-cproc read (:optional (port::<input-port> (current-input-port)))
539 (return (Scm_Read (SCM_OBJ port))))
540
541 (define-cproc read-char (:optional (port::<input-port> (current-input-port)))
542 (inliner READ-CHAR)
543 (let* ([ch::int])
544 (SCM_GETC ch port)
545 (return (?: (== ch EOF) SCM_EOF (SCM_MAKE_CHAR ch)))))
546
547 (define-cproc peek-char (:optional (port::<input-port> (current-input-port)))
548 (inliner PEEK-CHAR)
549 (let* ([ch::ScmChar (Scm_Peekc port)])
550 (return (?: (== ch EOF) SCM_EOF (SCM_MAKE_CHAR ch)))))
551
552 (define-cproc eof-object? (obj) ::<boolean> :fast-flonum
553 (inliner EOFP) SCM_EOFP)
554
555 (define-cproc char-ready? (:optional (port::<input-port> (current-input-port)))
556 ::<boolean> Scm_CharReady)
557
558
559 (select-module gauche)
560
561 (define-cproc eof-object () :constant (return SCM_EOF)) ;R6RS
562
563 (define-cproc byte-ready? (:optional (port::<input-port> (current-input-port)))
564 ::<boolean> Scm_ByteReady)
565
566 (define u8-ready? byte-ready?) ;R7RS
567
568 (define-cproc read-byte (:optional (port::<input-port> (current-input-port)))
569 (let* ([b::int])
570 (SCM_GETB b port)
571 (return (?: (< b 0) SCM_EOF (SCM_MAKE_INT b)))))
572
573 (define read-u8 read-byte) ;R7RS
574
575 (define-cproc peek-byte (:optional (port::<input-port> (current-input-port)))
576 (let* ([b::int (Scm_Peekb port)])
577 (return (?: (< b 0) SCM_EOF (SCM_MAKE_INT b)))))
578
579 (define peek-u8 peek-byte) ;R7RS
580
581 (define-cproc read-line (:optional (port::<input-port> (current-input-port))
582 (allowbytestr #f))
583 (let* ([r (Scm_ReadLine port)])
584 (when (and (SCM_FALSEP allowbytestr)
585 (SCM_STRINGP r)
586 (SCM_STRING_INCOMPLETE_P r))
587 (Scm_ReadError port "read-line: encountered illegal byte sequence: %S" r))
588 (return r)))
589
590 (define (read-string n :optional (port (current-input-port)))
591 (define o (open-output-string :private? #t))
592 (let loop ([i 0])
593 (if (>= i n)
594 (get-output-string o)
595 (let1 c (read-char port)
596 (if (eof-object? c)
597 (if (= i 0)
598 (eof-object)
599 (get-output-string o))
600 (begin (write-char c o) (loop (+ i 1))))))))
601
602 (define (write-string string :optional (port (current-output-port))
603 (start 0)
604 (end -1))
605 (display (opt-substring string start end) port))
606
607 ;; Consume trailing whiespaces up to (including) first EOL.
608 ;; This is mainly intended for interactive REPL,
609 ;; where the input is buffered by line. We want to ignore the
610 ;; trailing newline, so that when the user type (read-line) RET,
611 ;; we consume that RET and start reading from the fresh line.
612 ;
613 ;; We need to be careful not to block; that's why we use binary
614 ;; input here, since character input may block if the input stop
615 ;; between a multibyte character.
616 ;; Note that the 'whitespaces' here only inlucdes #\tab, #\space,
617 ;; #\return and #\newline.
618 (define (consume-trailing-whitespaces :optional (port (current-input-port)))
619 (let loop ()
620 (when (byte-ready? port)
621 (let1 b (peek-byte port)
622 (cond [(memv b '(9 32)) (read-byte port) (loop)] ;tab, space
623 [(eqv? b 13) ;cr or crlf
624 (read-byte port)
625 (when (and (byte-ready? port)
626 (eqv? (peek-byte port) 10))
627 (read-byte port))]
628 [(eqv? b 10) (read-byte port)]))))) ;lf
629
630 (define-cproc char-word-constituent? (ch::<char>) ::<boolean>
631 (return (Scm_CharWordConstituent ch 0)))
632
633 ;; DEPRECATED - read-uvector should be used
634 (define-cproc read-block (bytes::<fixnum>
635 :optional (port::<input-port> (current-input-port)))
636 (when (< bytes 0)
637 (Scm_Error "bytes must be non-negative integer: %ld" bytes))
638 (if (== bytes 0)
639 (return (Scm_MakeString "" 0 0 0))
640 (let* ([buf::char* (SCM_NEW_ATOMIC2 (C: char*) (+ bytes 1))]
641 [nread::int (Scm_Getz buf bytes port)])
642 (cond [(<= nread 0) (return SCM_EOF)]
643 [else
644 (SCM_ASSERT (<= nread bytes))
645 (set! (aref buf nread) #\x00)
646 (return (Scm_MakeString buf nread nread SCM_STRING_INCOMPLETE))]
647 ))))
648
649 (define-cproc read-list (closer::<char>
650 :optional (port (current-input-port)))
651 (return (Scm_ReadList port closer)))
652
653 (define-cproc port->byte-string (port::<input-port>)
654 (let* ([ds::ScmDString] [buf::(.array char (1024))])
655 (Scm_DStringInit (& ds))
656 (loop (let* ([nbytes::int (Scm_Getz buf 1024 port)])
657 (when (<= nbytes 0) (break))
658 (Scm_DStringPutz (& ds) buf nbytes)))
659 (return (Scm_DStringGet (& ds) SCM_STRING_INCOMPLETE))))
660
661 (define (port->string port)
662 (let1 out (open-output-string :private? #t)
663 (copy-port port out :unit 'byte)
664 (get-output-string out)))
665
666 (define (port->list reader port)
667 (with-port-locking port
668 (^[]
669 (let loop ([obj (reader port)]
670 [result '()])
671 (if (eof-object? obj)
672 (reverse! result)
673 (loop (reader port) (cons obj result)))))))
674
675 (define (port->string-list port) (port->list (cut read-line <> #t) port))
676 (define (port->sexp-list port) (port->list read port))
677
678 ;; Reader parameters
679 (define-cproc reader-lexical-mode (:optional k)
680 (if (SCM_UNBOUNDP k)
681 (return (Scm_ReaderLexicalMode))
682 (return (Scm_SetReaderLexicalMode k))))
683
684 (select-module gauche.internal)
685 (define-cproc %port-ungotten-chars (port::<input-port>)
686 Scm_UngottenChars)
687 (define-cproc %port-ungotten-bytes (port::<input-port>)
688 Scm_UngottenBytes)
689
690 ;; Read time constructor (SRFI-10)
691 (select-module gauche)
692
693 (define-cproc define-reader-ctor (symbol proc :optional (finisher #f))
694 (return (Scm_DefineReaderCtor symbol proc finisher SCM_FALSE)))
695
696 (define-cproc %get-reader-ctor (symbol)
697 (return (Scm_GetReaderCtor symbol SCM_FALSE)))
698
699 (define-cproc define-reader-directive (symbol proc)
700 Scm_DefineReaderDirective)
701
702 (inline-stub
703 (declare-stub-type <read-context> "ScmReadContext*" "read context"
704 "SCM_READ_CONTEXT_P" "SCM_READ_CONTEXT" "")
705
706 (declare-stub-type <read-reference> "ScmReadReference*" "read reference"
707 "SCM_READ_REFERENCE_P" "SCM_READ_REFERENCE" "")
708 )
709
710 (define-cproc current-read-context (:optional ctx)
711 (if (SCM_UNBOUNDP ctx)
712 (return (SCM_OBJ (Scm_CurrentReadContext)))
713 (if (SCM_READ_CONTEXT_P ctx)
714 (return (SCM_OBJ (Scm_SetCurrentReadContext (SCM_READ_CONTEXT ctx))))
715 (begin (Scm_Error "<read-context> required, but got:" ctx)
716 (return SCM_UNDEFINED))))) ;dummy
717
718 (define-cproc read-reference? (obj) ::<boolean> SCM_READ_REFERENCE_P)
719
720 (define-cproc read-reference-has-value? (ref::<read-reference>)
721 ::<boolean> (return (not (SCM_UNBOUNDP (-> ref value)))))
722
723 (define-cproc read-reference-value (ref::<read-reference>)
724 (when (SCM_UNBOUNDP (-> ref value))
725 (Scm_Error "read reference hasn't been resolved"))
726 (return (-> ref value)))
727
728 ;; SRFI-38
729 (define-in-module gauche read-with-shared-structure read)
730 (define-in-module gauche read/ss read)
731
732 ;;;
733 ;;; Output
734 ;;;
735
736 (inline-stub
737 (declare-stub-type <write-controls> "ScmWriteControls*" "write controls"
738 "SCM_WRITE_CONTROLS_P" "SCM_WRITE_CONTROLS" "")
739
740 (define-cfn parse-write-optionals (opt1 opt2
741 pp::ScmPort**
742 pc::(const ScmWriteControls**))
743 ::void :static
744 (let* ([p::ScmPort* SCM_CUROUT]
745 [c::(const ScmWriteControls*) (Scm_DefaultWriteControls)])
746 (unless (SCM_UNBOUNDP opt1)
747 (cond [(SCM_PORTP opt1)
748 (set! p (SCM_PORT opt1))
749 (unless (SCM_UNBOUNDP opt2)
750 (if (SCM_WRITE_CONTROLS_P opt2)
751 (set! c (SCM_WRITE_CONTROLS opt2))
752 (Scm_Error "Expected write-controls, but got: %S" opt2)))]
753 [(SCM_WRITE_CONTROLS_P opt1)
754 (set! c (SCM_WRITE_CONTROLS opt1))
755 (unless (SCM_UNBOUNDP opt2)
756 (if (SCM_PORTP opt2)
757 (set! p (SCM_PORT opt2))
758 (Scm_Error "Expected port, but got: %S" opt2)))]
759 [else
760 (Scm_Error "Expected port or write-controls, but got: %S" opt1)]))
761 (set! (* pp) p)
762 (set! (* pc) c)))
763 )
764 (select-module scheme)
765
766 (define-cproc write (obj :optional port-or-control-1 port-or-control-2)
767 ::<void>
768 (let* ([p::ScmPort*] [c::(const ScmWriteControls*)])
769 (parse-write-optionals port-or-control-1 port-or-control-2 (& p) (& c))
770 (Scm_WriteWithControls obj (SCM_OBJ p) SCM_WRITE_WRITE c)))
771
772 (define-cproc write-simple (obj :optional (port::<output-port>
773 (current-output-port)))
774 ::<void>
775 (Scm_Write obj (SCM_OBJ port) SCM_WRITE_SIMPLE))
776
777 (define-cproc write-shared (obj :optional port-or-control-1 port-or-control-2)
778 ::<void>
779 (let* ([p::ScmPort*] [c::(const ScmWriteControls*)])
780 (parse-write-optionals port-or-control-1 port-or-control-2 (& p) (& c))
781 (Scm_WriteWithControls obj (SCM_OBJ p) SCM_WRITE_SHARED c)))
782
783 (define-cproc display (obj :optional port-or-control-1 port-or-control-2)
784 ::<void>
785 (let* ([p::ScmPort*] [c::(const ScmWriteControls*)])
786 (parse-write-optionals port-or-control-1 port-or-control-2 (& p) (& c))
787 (Scm_WriteWithControls obj (SCM_OBJ p) SCM_WRITE_DISPLAY c)))
788
789 (define-cproc newline (:optional (port::<output-port> (current-output-port)))
790 ::<void> (SCM_PUTC #\newline port))
791
792 (define-cproc fresh-line (:optional (port::<output-port> (current-output-port)))
793 ::<boolean>
794 (if (== (Scm_PortColumn port) 0)
795 (return FALSE)
796 (begin (SCM_PUTC #\newline port) (return TRUE))))
797
798 (define-cproc write-char
799 (ch::<char> :optional (port::<output-port> (current-output-port)))
800 ::<void> (inliner WRITE-CHAR) (SCM_PUTC ch port))
801
802
803 (select-module gauche)
804
805 (define-cproc write-byte (byte::<fixnum>
806 :optional (port::<output-port> (current-output-port)))
807 ::<int>
808 (when (or (< byte 0) (> byte 255))
809 (Scm_Error "argument out of range: %ld" byte))
810 (SCM_PUTB byte port)
811 (return 1))
812
813 (define write-u8 write-byte) ;R7RS
814
815 (define-cproc write-limited (obj limit::<fixnum>
816 :optional (port (current-output-port)))
817 ::<int> (return (Scm_WriteLimited obj port SCM_WRITE_WRITE limit)))
818
819 (define write* write-shared)
820
821 (define-cproc flush (:optional (oport::<output-port> (current-output-port)))
822 ::<void> Scm_Flush)
823
824 (define-cproc flush-all-ports () ::<void> (Scm_FlushAllPorts FALSE))
825
826 ;;
827 ;; Internal recusive writer
828 ;;
829 (select-module gauche.internal)
830
831 (define-cproc write-need-recurse? (obj) ::<boolean>
832 (return (not (or (not (SCM_PTRP obj))
833 (SCM_NUMBERP obj)
834 (SCM_KEYWORDP obj)
835 (and (SCM_SYMBOLP obj) (SCM_SYMBOL_INTERNED obj))
836 (and (SCM_STRINGP obj) (== (SCM_STRING_SIZE obj) 0))
837 (and (SCM_VECTORP obj) (== (SCM_VECTOR_SIZE obj) 0))))))
838
839 (define (write-walk obj port)
840 (if-let1 s (%port-write-state port)
841 (%write-walk-rec obj port (~ s shared-table))))
842
843 (define (%write-walk-rec obj port tab)
844 (when (write-need-recurse? obj)
845 (if (hash-table-exists? tab obj)
846 (hash-table-update! tab obj (cut + <> 1)) ; seen more than once
847 (begin
848 (hash-table-put! tab obj 1) ; seen once
849 (cond
850 [(symbol? obj)] ; uninterned symbols
851 [(string? obj)]
852 [(uvector? obj)]
853 [(pair? obj)
854 (%write-walk-rec (car obj) port tab)
855 (%write-walk-rec (cdr obj) port tab)]
856 [(vector? obj)
857 (dotimes [i (vector-length obj)]
858 (%write-walk-rec (vector-ref obj i) port tab))]
859 [(box? obj)
860 (dotimes [i (box-arity obj)]
861 (%write-walk-rec (unbox-value obj i) port tab))]
862 [(is-a? obj <dictionary>)
863 (%dict-walk! obj
864 (^[k v]
865 (%write-walk-rec k port tab)
866 (%write-walk-rec v port tab)))]
867 [else ; generic objects. we go walk pass via write-object
868 (write-object obj port)])
869 ;; If circular-only, we don't count non-circular objects.
870 (unless (%port-writing-shared? port)
871 (when (eqv? (hash-table-get tab obj #f) 1)
872 (hash-table-delete! tab obj)))
873 ))))
874
875 ;; Kludge - gauche.libdict is initialized after libio, so we can't use
876 ;; with-module. We hope we can fix this later.
877 (define %dict-walk!
878 (let ([walker #f]
879 [transparent? #f])
880 (^[dict proc]
881 (unless walker
882 (set! walker
883 (module-binding-ref 'gauche.libdict 'dict-for-each)))
884 (unless transparent?
885 (set! transparent?
886 (module-binding-ref 'gauche.libdict 'dict-transparent?)))
887 (when (transparent? dict)
888 (walker dict proc)))))
889
890 (select-module gauche.internal)
891
892 ;; SRFI-38
893 (define-in-module gauche (write-with-shared-structure obj :optional (port (current-output-port)))
894 (write* obj port))
895 (define-in-module gauche write/ss write-with-shared-structure)
896
897 (define-in-module gauche (print . args) (for-each display args) (newline))
898
899 ;;
900 ;; Write controls
901 ;; For performance reasons, we don't make them a SRFI-39 parameters.
902 ;;
903
904 (select-module gauche)
905 (inline-stub
906 (define-cfn write_controls_allocate (_::ScmClass* _) :static
907 (return (SCM_OBJ (Scm_MakeWriteControls NULL))))
908
909 ;; TODO: We want to treat <write-controls> as immutable structure, but
910 ;; define-cclass doesn't yet handle a slot that's immutable but allowing
911 ;; initialized by init-keywords.
912 (define-cclass <write-controls>
913 "ScmWriteControls*" "Scm_WriteControlsClass"
914 ("Scm_TopClass")
915 ((length :type <int> :c-name "printLength"
916 :getter "if (obj->printLength < 0) return SCM_FALSE; \
917 else return SCM_MAKE_INT(obj->printLength);"
918 :setter "if (SCM_INTP(value) && SCM_INT_VALUE(value) >= 0) \
919 obj->printLength = SCM_INT_VALUE(value); \
920 else obj->printLength = -1;")
921 (level :type <int> :c-name "printLevel"
922 :getter "if (obj->printLevel < 0) return SCM_FALSE; \
923 else return SCM_MAKE_INT(obj->printLevel);"
924 :setter "if (SCM_INTP(value) && SCM_INT_VALUE(value) >= 0) \
925 obj->printLevel = SCM_INT_VALUE(value); \
926 else obj->printLevel = -1;")
927 (width :type <int> :c-name "printWidth"
928 :getter "if (obj->printWidth < 0) return SCM_FALSE; \
929 else return SCM_MAKE_INT(obj->printWidth);"
930 :setter "if (SCM_INTP(value) && SCM_INT_VALUE(value) >= 0) \
931 obj->printWidth = SCM_INT_VALUE(value); \
932 else obj->printWidth = -1;")
933 (base :type <int> :c-name "printBase"
934 :setter "if (SCM_INTP(value) \
935 && SCM_INT_VALUE(value) >= SCM_RADIX_MIN \
936 && SCM_INT_VALUE(value) <= SCM_RADIX_MAX) \
937 obj->printBase = SCM_INT_VALUE(value); \
938 else Scm_Error(\"print-base must be an integer \
939 between %d and %d, but got: %S\", \
940 SCM_RADIX_MIN, SCM_RADIX_MAX, value);")
941 (radix :type <boolean> :c-name "printRadix"
942 :setter "obj->printRadix = !SCM_FALSEP(value);")
943 (pretty :type <boolean> :c-name "printPretty"
944 :setter "obj->printPretty = !SCM_FALSEP(value);")
945 (indent :type <int> :c-name "printIndent"
946 :setter "if (SCM_INTP(value) && SCM_INT_VALUE(value) >= 0) \
947 obj->printIndent = SCM_INT_VALUE(value); \
948 else obj->printIndent = 0;")
949 (string-length :type <int> :c-name "stringLength"
950 :getter "if (obj->stringLength < 0) return SCM_FALSE; \
951 else return SCM_MAKE_INT(obj->stringLength);"
952 :setter "if (SCM_INTP(value) && SCM_INT_VALUE(value) >= 0) \
953 obj->stringLength = SCM_INT_VALUE(value); \
954 else obj->stringLength = -1;")
955 (exact-decimal :type <boolean> :c-name "exactDecimal"
956 :setter "obj->exactDecimal = !SCM_FALSEP(value);")
957 )
958 (allocator (c "write_controls_allocate")))
959 ;; NB: Printer is defined in libobj.scm via write-object method
960 )
961
962 ;; TRANSIENT: The print-* keyword arguments for the backward compatibility
963 (define (make-write-controls :key length level width base radix pretty indent
964 string-length exact-decimal
965 print-length print-level print-width
966 print-base print-radix print-pretty)
967 (define (arg k k-alt) (if (undefined? k-alt) k k-alt))
968 (make <write-controls>
969 :length (arg length print-length)
970 :level (arg level print-level)
971 :width (arg width print-width)
972 :base (arg base print-base)
973 :radix (arg radix print-radix)
974 :pretty (arg pretty print-pretty)
975 :string-length string-length
976 :indent indent
977 :exact-decimal exact-decimal))
978
979 ;; Returns fresh write-controls where the specified slot value is replaced
980 ;; from the original WC.
981 ;; NB: If the specified values doesn't change the original value at all,
982 ;; we don't bother to create a copy. This assumes we treat WC immutable.
983 ;; (Maybe we should write this in C to avoid overhead.)
984 ;; TRANSIENT: The print-* keyword arguments for the backward compatibility
985 (define (write-controls-copy wc :key length level width base radix pretty indent
986 string-length exact-decimal
987 print-length print-level print-width
988 print-base print-radix print-pretty)
989 (let-syntax [(select
990 (syntax-rules ()
991 [(_ k k-alt)
992 (if (undefined? k)
993 (if (undefined? k-alt)
994 (slot-ref wc 'k)
995 k-alt)
996 k)]
997 [(_ k)
998 (if (undefined? k)
999 (slot-ref wc 'k)
1000 k)]))]
1001 (let ([length (select length print-length)]
1002 [level (select level print-level)]
1003 [width (select width print-width)]
1004 [base (select base print-base)]
1005 [radix (select radix print-radix)]
1006 [pretty (select pretty print-pretty)]
1007 [indent (select indent)]
1008 [string-length (select string-length)]
1009 [exact-decimal (select exact-decimal)])
1010 (if (and (eqv? length (slot-ref wc 'length))
1011 (eqv? level (slot-ref wc 'level))
1012 (eqv? width (slot-ref wc 'width))
1013 (eqv? base (slot-ref wc 'base))
1014 (eqv? radix (slot-ref wc 'radix))
1015 (eqv? pretty (slot-ref wc 'pretty))
1016 (eqv? indent (slot-ref wc 'indent))
1017 (eqv? string-length (slot-ref wc 'string-length))
1018 (eqv? exact-decimal (slot-ref wc 'exact-decimal)))
1019 wc
1020 (make <write-controls>
1021 :length length
1022 :level level
1023 :width width
1024 :base base
1025 :radix radix
1026 :pretty pretty
1027 :indent indent
1028 :string-length string-length
1029 :exact-decimal exact-decimal)))))
1030
1031 ;;;
1032 ;;; With-something
1033 ;;;
1034
1035 (select-module gauche.internal)
1036
1037 ;; R5RS open-{input|output}-file can be hooked by conversion port.
1038 ;; %open-{input|output}-file/conv are autoloaded.
1039
1040 (define-in-module scheme (open-input-file filename . args)
1041 (let1 e (get-keyword :encoding args (default-file-encoding))
1042 (cond [(eq? e (gauche-character-encoding))
1043 (apply %open-input-file filename (delete-keyword :encoding args))]
1044 [(eq? e #t) ;using coding-aware port
1045 (and-let* ([p (apply %open-input-file filename
1046 (delete-keyword :encoding args))])
1047 (open-coding-aware-port p))]
1048 [else (apply %open-input-file/conv filename args)])))
1049
1050 (define-in-module scheme (open-output-file filename . args)
1051 (let1 e (get-keyword :encoding args #f)
1052 (if (and (not e)
1053 (eq? (default-file-encoding) (gauche-character-encoding)))
1054 (apply %open-output-file filename args)
1055 (apply %open-output-file/conv filename args))))
1056
1057 ;; R6RS call-with-port
1058 ;; Make sure to close PORT when proc returns or throws an error
1059 (define-in-module gauche (call-with-port port proc)
1060 (unwind-protect (proc port)
1061 (close-port port)))
1062
1063 ;; File ports.
1064
1065 (define-in-module scheme (call-with-input-file filename proc . flags)
1066 (let1 port (apply open-input-file filename flags)
1067 (unwind-protect (proc port)
1068 (when port (close-input-port port)))))
1069
1070 (define-in-module scheme (call-with-output-file filename proc . flags)
1071 (let1 port (apply open-output-file filename flags)
1072 (unwind-protect (proc port)
1073 (when port (close-output-port port)))))
1074
1075 (define-in-module scheme (with-input-from-file filename thunk . flags)
1076 (let1 port (apply open-input-file filename flags)
1077 (and port
1078 (unwind-protect (with-input-from-port port thunk)
1079 (close-input-port port)))))
1080
1081 (define-in-module scheme (with-output-to-file filename thunk . flags)
1082 (let1 port (apply open-output-file filename flags)
1083 (and port
1084 (unwind-protect (with-output-to-port port thunk)
1085 (close-output-port port)))))
1086
1087 ;; String ports
1088 (define-in-module gauche (with-output-to-string thunk)
1089 (let1 out (open-output-string)
1090 (with-output-to-port out thunk)
1091 (get-output-string out)))
1092
1093 (define-in-module gauche (with-input-from-string str thunk)
1094 (with-input-from-port (open-input-string str) thunk))
1095
1096 (define-in-module gauche (call-with-output-string proc)
1097 (let1 out (open-output-string)
1098 (proc out)
1099 (get-output-string out)))
1100
1101 (define-in-module gauche (call-with-input-string str proc)
1102 (proc (open-input-string str)))
1103
1104 (define-in-module gauche (call-with-string-io str proc)
1105 (let ([out (open-output-string)]
1106 [in (open-input-string str)])
1107 (proc in out)
1108 (get-output-string out)))
1109
1110 (define-in-module gauche (with-string-io str thunk)
1111 (with-output-to-string (cut with-input-from-string str thunk)))
1112
1113 (define-in-module gauche (write-to-string obj :optional (writer write))
1114 (with-output-to-string (cut writer obj)))
1115
1116 (define-in-module gauche (read-from-string string . args)
1117 (with-input-from-string
1118 (if (null? args) string (apply opt-substring string args))
1119 read))
1120
1121 ;; with-port
1122
1123 (define-syntax %with-ports
1124 (syntax-rules ()
1125 [(_ "tmp" (tmp ...) () (port ...) (param ...) thunk)
1126 (let ((tmp #f) ...)
1127 (dynamic-wind
1128 (^[] (when port (set! tmp (param port))) ...)
1129 thunk
1130 (^[] (when tmp (param tmp)) ...)))]
1131 [(_ "tmp" tmps (port . more) ports params thunk)
1132 (%with-ports "tmp" (tmp . tmps) more ports params thunk)]
1133 [(_ ((param port) ...) thunk)
1134 (%with-ports "tmp" () (port ...) (port ...) (param ...) thunk)]))
1135
1136 (define-in-module gauche (with-input-from-port port thunk)
1137 (%with-ports ((current-input-port port)) thunk))
1138
1139 (define-in-module gauche (with-output-to-port port thunk)
1140 (%with-ports ((current-output-port port)) thunk))
1141
1142 (define-in-module gauche (with-error-to-port port thunk)
1143 (%with-ports ((current-error-port port)) thunk))
1144
1145 (define-in-module gauche (with-ports iport oport eport thunk)
1146 (%with-ports ((current-input-port iport)
1147 (current-output-port oport)
1148 (current-error-port eport))
1149 thunk))
1150
1151 ;;;
1152 ;;; #! directives
1153 ;;;
1154
1155 (define-reader-directive 'r6rs
1156 (^[sym port ctx]
1157 (warn "Reading R6RS source file. Note that Gauche is not R6RS compliant.")
1158 ;; TODO: we could do some adjustments, such as switching the semantics of
1159 ;; '#,' from SRFI-10 to r6rs 'unsyntax'.
1160 (values)))
1161
1162 (define-reader-directive 'fold-case
1163 (^[sym port ctx]
1164 (set! ((with-module gauche.internal port-case-fold) port) #t)
1165 (values)))
1166
1167 (define-reader-directive 'no-fold-case
1168 (^[sym port ctx]
1169 (set! ((with-module gauche.internal port-case-fold) port) #f)
1170 (values)))
1171
1172 (define-reader-directive 'gauche-legacy
1173 (^[sym port ctx]
1174 (port-attribute-set! port 'reader-lexical-mode 'legacy)
1175 (values)))
1176
1177 (define-reader-directive 'r7rs
1178 (^[sym port ctx]
1179 (port-attribute-set! port 'reader-lexical-mode 'strict-r7)
1180 (values)))