Print the faulty object upon invalid-keyword errors.
[bpt/guile.git] / libguile / ports.c
1 /* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2006,
2 * 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public License
6 * as published by the Free Software Foundation; either version 3 of
7 * the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301 USA
18 */
19
20
21 \f
22 /* Headers. */
23
24 #define _LARGEFILE64_SOURCE /* ask for stat64 etc */
25
26 #ifdef HAVE_CONFIG_H
27 # include <config.h>
28 #endif
29
30 #include <stdio.h>
31 #include <errno.h>
32 #include <fcntl.h> /* for chsize on mingw */
33 #include <assert.h>
34 #include <iconv.h>
35 #include <uniconv.h>
36 #include <unistr.h>
37 #include <striconveh.h>
38 #include <c-strcase.h>
39
40 #include <assert.h>
41
42 #include "libguile/_scm.h"
43 #include "libguile/async.h"
44 #include "libguile/deprecation.h"
45 #include "libguile/eval.h"
46 #include "libguile/fports.h" /* direct access for seek and truncate */
47 #include "libguile/goops.h"
48 #include "libguile/smob.h"
49 #include "libguile/chars.h"
50 #include "libguile/dynwind.h"
51
52 #include "libguile/keywords.h"
53 #include "libguile/hashtab.h"
54 #include "libguile/root.h"
55 #include "libguile/strings.h"
56 #include "libguile/mallocs.h"
57 #include "libguile/validate.h"
58 #include "libguile/ports.h"
59 #include "libguile/ports-internal.h"
60 #include "libguile/vectors.h"
61 #include "libguile/weaks.h"
62 #include "libguile/fluids.h"
63 #include "libguile/eq.h"
64
65 #ifdef HAVE_STRING_H
66 #include <string.h>
67 #endif
68
69 #ifdef HAVE_IO_H
70 #include <io.h>
71 #endif
72
73 #ifdef HAVE_UNISTD_H
74 #include <unistd.h>
75 #endif
76
77 #ifdef HAVE_SYS_IOCTL_H
78 #include <sys/ioctl.h>
79 #endif
80
81 /* Mingw (version 3.4.5, circa 2006) has ftruncate as an alias for chsize
82 already, but have this code here in case that wasn't so in past versions,
83 or perhaps to help other minimal DOS environments.
84
85 gnulib ftruncate.c has code using fcntl F_CHSIZE and F_FREESP, which
86 might be possibilities if we've got other systems without ftruncate. */
87
88 #if defined HAVE_CHSIZE && ! defined HAVE_FTRUNCATE
89 #define ftruncate(fd, size) chsize (fd, size)
90 #undef HAVE_FTRUNCATE
91 #define HAVE_FTRUNCATE 1
92 #endif
93
94 \f
95 /* The port kind table --- a dynamically resized array of port types. */
96
97
98 /* scm_ptobs scm_numptob
99 * implement a dynamically resized array of ptob records.
100 * Indexes into this table are used when generating type
101 * tags for smobjects (if you know a tag you can get an index and conversely).
102 */
103 scm_t_ptob_descriptor *scm_ptobs = NULL;
104 long scm_numptob = 0;
105
106 /* GC marker for a port with stream of SCM type. */
107 SCM
108 scm_markstream (SCM ptr)
109 {
110 int openp;
111 openp = SCM_CELL_WORD_0 (ptr) & SCM_OPN;
112 if (openp)
113 return SCM_PACK (SCM_STREAM (ptr));
114 else
115 return SCM_BOOL_F;
116 }
117
118 /*
119 * We choose to use an interface similar to the smob interface with
120 * fill_input and write as standard fields, passed to the port
121 * type constructor, and optional fields set by setters.
122 */
123
124 static void
125 flush_port_default (SCM port SCM_UNUSED)
126 {
127 }
128
129 static void
130 end_input_default (SCM port SCM_UNUSED, int offset SCM_UNUSED)
131 {
132 }
133
134 scm_t_bits
135 scm_make_port_type (char *name,
136 int (*fill_input) (SCM port),
137 void (*write) (SCM port, const void *data, size_t size))
138 {
139 char *tmp;
140 if (SCM_I_MAX_PORT_TYPE_COUNT - 1 <= scm_numptob)
141 goto ptoberr;
142 SCM_CRITICAL_SECTION_START;
143 tmp = (char *) scm_gc_realloc ((char *) scm_ptobs,
144 scm_numptob * sizeof (scm_t_ptob_descriptor),
145 (1 + scm_numptob)
146 * sizeof (scm_t_ptob_descriptor),
147 "port-type");
148 if (tmp)
149 {
150 scm_ptobs = (scm_t_ptob_descriptor *) tmp;
151
152 scm_ptobs[scm_numptob].name = name;
153 scm_ptobs[scm_numptob].mark = 0;
154 scm_ptobs[scm_numptob].free = NULL;
155 scm_ptobs[scm_numptob].print = scm_port_print;
156 scm_ptobs[scm_numptob].equalp = 0;
157 scm_ptobs[scm_numptob].close = 0;
158
159 scm_ptobs[scm_numptob].write = write;
160 scm_ptobs[scm_numptob].flush = flush_port_default;
161
162 scm_ptobs[scm_numptob].end_input = end_input_default;
163 scm_ptobs[scm_numptob].fill_input = fill_input;
164 scm_ptobs[scm_numptob].input_waiting = 0;
165
166 scm_ptobs[scm_numptob].seek = 0;
167 scm_ptobs[scm_numptob].truncate = 0;
168
169 scm_numptob++;
170 }
171 SCM_CRITICAL_SECTION_END;
172 if (!tmp)
173 {
174 ptoberr:
175 scm_memory_error ("scm_make_port_type");
176 }
177 /* Make a class object if Goops is present */
178 if (SCM_UNPACK (scm_port_class[0]) != 0)
179 scm_make_port_classes (scm_numptob - 1, SCM_PTOBNAME (scm_numptob - 1));
180 return scm_tc7_port + (scm_numptob - 1) * 256;
181 }
182
183 void
184 scm_set_port_mark (scm_t_bits tc, SCM (*mark) (SCM))
185 {
186 scm_ptobs[SCM_TC2PTOBNUM (tc)].mark = mark;
187 }
188
189 void
190 scm_set_port_free (scm_t_bits tc, size_t (*free) (SCM))
191 {
192 scm_ptobs[SCM_TC2PTOBNUM (tc)].free = free;
193 }
194
195 void
196 scm_set_port_print (scm_t_bits tc, int (*print) (SCM exp, SCM port,
197 scm_print_state *pstate))
198 {
199 scm_ptobs[SCM_TC2PTOBNUM (tc)].print = print;
200 }
201
202 void
203 scm_set_port_equalp (scm_t_bits tc, SCM (*equalp) (SCM, SCM))
204 {
205 scm_ptobs[SCM_TC2PTOBNUM (tc)].equalp = equalp;
206 }
207
208 void
209 scm_set_port_flush (scm_t_bits tc, void (*flush) (SCM port))
210 {
211 scm_ptobs[SCM_TC2PTOBNUM (tc)].flush = flush;
212 }
213
214 void
215 scm_set_port_end_input (scm_t_bits tc, void (*end_input) (SCM port, int offset))
216 {
217 scm_ptobs[SCM_TC2PTOBNUM (tc)].end_input = end_input;
218 }
219
220 void
221 scm_set_port_close (scm_t_bits tc, int (*close) (SCM))
222 {
223 scm_ptobs[SCM_TC2PTOBNUM (tc)].close = close;
224 }
225
226 void
227 scm_set_port_seek (scm_t_bits tc,
228 scm_t_off (*seek) (SCM, scm_t_off, int))
229 {
230 scm_ptobs[SCM_TC2PTOBNUM (tc)].seek = seek;
231 }
232
233 void
234 scm_set_port_truncate (scm_t_bits tc, void (*truncate) (SCM, scm_t_off))
235 {
236 scm_ptobs[SCM_TC2PTOBNUM (tc)].truncate = truncate;
237 }
238
239 void
240 scm_set_port_input_waiting (scm_t_bits tc, int (*input_waiting) (SCM))
241 {
242 scm_ptobs[SCM_TC2PTOBNUM (tc)].input_waiting = input_waiting;
243 }
244
245 static void
246 scm_i_set_pending_eof (SCM port)
247 {
248 SCM_PORT_GET_INTERNAL (port)->pending_eof = 1;
249 }
250
251 static void
252 scm_i_clear_pending_eof (SCM port)
253 {
254 SCM_PORT_GET_INTERNAL (port)->pending_eof = 0;
255 }
256
257 SCM
258 scm_i_port_alist (SCM port)
259 {
260 return SCM_PORT_GET_INTERNAL (port)->alist;
261 }
262
263 void
264 scm_i_set_port_alist_x (SCM port, SCM alist)
265 {
266 SCM_PORT_GET_INTERNAL (port)->alist = alist;
267 }
268
269 \f
270
271 SCM_DEFINE (scm_char_ready_p, "char-ready?", 0, 1, 0,
272 (SCM port),
273 "Return @code{#t} if a character is ready on input @var{port}\n"
274 "and return @code{#f} otherwise. If @code{char-ready?} returns\n"
275 "@code{#t} then the next @code{read-char} operation on\n"
276 "@var{port} is guaranteed not to hang. If @var{port} is a file\n"
277 "port at end of file then @code{char-ready?} returns @code{#t}.\n"
278 "\n"
279 "@code{char-ready?} exists to make it possible for a\n"
280 "program to accept characters from interactive ports without\n"
281 "getting stuck waiting for input. Any input editors associated\n"
282 "with such ports must make sure that characters whose existence\n"
283 "has been asserted by @code{char-ready?} cannot be rubbed out.\n"
284 "If @code{char-ready?} were to return @code{#f} at end of file,\n"
285 "a port at end of file would be indistinguishable from an\n"
286 "interactive port that has no ready characters.")
287 #define FUNC_NAME s_scm_char_ready_p
288 {
289 scm_t_port *pt;
290
291 if (SCM_UNBNDP (port))
292 port = scm_current_input_port ();
293 /* It's possible to close the current input port, so validate even in
294 this case. */
295 SCM_VALIDATE_OPINPORT (1, port);
296
297 pt = SCM_PTAB_ENTRY (port);
298
299 /* if the current read buffer is filled, or the
300 last pushed-back char has been read and the saved buffer is
301 filled, result is true. */
302 if (pt->read_pos < pt->read_end
303 || (pt->read_buf == pt->putback_buf
304 && pt->saved_read_pos < pt->saved_read_end))
305 return SCM_BOOL_T;
306 else
307 {
308 scm_t_ptob_descriptor *ptob = &scm_ptobs[SCM_PTOBNUM (port)];
309
310 if (ptob->input_waiting)
311 return scm_from_bool(ptob->input_waiting (port));
312 else
313 return SCM_BOOL_T;
314 }
315 }
316 #undef FUNC_NAME
317
318 /* Move up to READ_LEN bytes from PORT's putback and/or read buffers
319 into memory starting at DEST. Return the number of bytes moved.
320 PORT's line/column numbers are left unchanged. */
321 size_t
322 scm_take_from_input_buffers (SCM port, char *dest, size_t read_len)
323 {
324 scm_t_port *pt = SCM_PTAB_ENTRY (port);
325 size_t bytes_read = 0;
326 size_t from_buf = min (pt->read_end - pt->read_pos, read_len);
327
328 if (from_buf > 0)
329 {
330 memcpy (dest, pt->read_pos, from_buf);
331 pt->read_pos += from_buf;
332 bytes_read += from_buf;
333 read_len -= from_buf;
334 dest += from_buf;
335 }
336
337 /* if putback was active, try the real input buffer too. */
338 if (pt->read_buf == pt->putback_buf)
339 {
340 from_buf = min (pt->saved_read_end - pt->saved_read_pos, read_len);
341 if (from_buf > 0)
342 {
343 memcpy (dest, pt->saved_read_pos, from_buf);
344 pt->saved_read_pos += from_buf;
345 bytes_read += from_buf;
346 }
347 }
348
349 return bytes_read;
350 }
351
352 /* Clear a port's read buffers, returning the contents. */
353 SCM_DEFINE (scm_drain_input, "drain-input", 1, 0, 0,
354 (SCM port),
355 "This procedure clears a port's input buffers, similar\n"
356 "to the way that force-output clears the output buffer. The\n"
357 "contents of the buffers are returned as a single string, e.g.,\n"
358 "\n"
359 "@lisp\n"
360 "(define p (open-input-file ...))\n"
361 "(drain-input p) => empty string, nothing buffered yet.\n"
362 "(unread-char (read-char p) p)\n"
363 "(drain-input p) => initial chars from p, up to the buffer size.\n"
364 "@end lisp\n\n"
365 "Draining the buffers may be useful for cleanly finishing\n"
366 "buffered I/O so that the file descriptor can be used directly\n"
367 "for further input.")
368 #define FUNC_NAME s_scm_drain_input
369 {
370 SCM result;
371 char *data;
372 scm_t_port *pt;
373 long count;
374
375 SCM_VALIDATE_OPINPORT (1, port);
376 pt = SCM_PTAB_ENTRY (port);
377
378 count = pt->read_end - pt->read_pos;
379 if (pt->read_buf == pt->putback_buf)
380 count += pt->saved_read_end - pt->saved_read_pos;
381
382 if (count)
383 {
384 result = scm_i_make_string (count, &data, 0);
385 scm_take_from_input_buffers (port, data, count);
386 }
387 else
388 result = scm_nullstr;
389
390 return result;
391 }
392 #undef FUNC_NAME
393
394 \f
395 /* Standard ports --- current input, output, error, and more(!). */
396
397 static SCM cur_inport_fluid = SCM_BOOL_F;
398 static SCM cur_outport_fluid = SCM_BOOL_F;
399 static SCM cur_errport_fluid = SCM_BOOL_F;
400 static SCM cur_loadport_fluid = SCM_BOOL_F;
401
402 SCM_DEFINE (scm_current_input_port, "current-input-port", 0, 0, 0,
403 (),
404 "Return the current input port. This is the default port used\n"
405 "by many input procedures. Initially, @code{current-input-port}\n"
406 "returns the @dfn{standard input} in Unix and C terminology.")
407 #define FUNC_NAME s_scm_current_input_port
408 {
409 if (scm_is_true (cur_inport_fluid))
410 return scm_fluid_ref (cur_inport_fluid);
411 else
412 return SCM_BOOL_F;
413 }
414 #undef FUNC_NAME
415
416 SCM_DEFINE (scm_current_output_port, "current-output-port", 0, 0, 0,
417 (),
418 "Return the current output port. This is the default port used\n"
419 "by many output procedures. Initially,\n"
420 "@code{current-output-port} returns the @dfn{standard output} in\n"
421 "Unix and C terminology.")
422 #define FUNC_NAME s_scm_current_output_port
423 {
424 if (scm_is_true (cur_outport_fluid))
425 return scm_fluid_ref (cur_outport_fluid);
426 else
427 return SCM_BOOL_F;
428 }
429 #undef FUNC_NAME
430
431 SCM_DEFINE (scm_current_error_port, "current-error-port", 0, 0, 0,
432 (),
433 "Return the port to which errors and warnings should be sent (the\n"
434 "@dfn{standard error} in Unix and C terminology).")
435 #define FUNC_NAME s_scm_current_error_port
436 {
437 if (scm_is_true (cur_errport_fluid))
438 return scm_fluid_ref (cur_errport_fluid);
439 else
440 return SCM_BOOL_F;
441 }
442 #undef FUNC_NAME
443
444 SCM
445 scm_current_warning_port (void)
446 {
447 static SCM cwp_var = SCM_UNDEFINED;
448 static scm_i_pthread_mutex_t cwp_var_mutex
449 = SCM_I_PTHREAD_MUTEX_INITIALIZER;
450
451 scm_i_scm_pthread_mutex_lock (&cwp_var_mutex);
452 if (SCM_UNBNDP (cwp_var))
453 cwp_var = scm_c_private_variable ("guile", "current-warning-port");
454 scm_i_pthread_mutex_unlock (&cwp_var_mutex);
455
456 return scm_call_0 (scm_variable_ref (cwp_var));
457 }
458
459 SCM_DEFINE (scm_current_load_port, "current-load-port", 0, 0, 0,
460 (),
461 "Return the current-load-port.\n"
462 "The load port is used internally by @code{primitive-load}.")
463 #define FUNC_NAME s_scm_current_load_port
464 {
465 return scm_fluid_ref (cur_loadport_fluid);
466 }
467 #undef FUNC_NAME
468
469 SCM_DEFINE (scm_set_current_input_port, "set-current-input-port", 1, 0, 0,
470 (SCM port),
471 "@deffnx {Scheme Procedure} set-current-output-port port\n"
472 "@deffnx {Scheme Procedure} set-current-error-port port\n"
473 "Change the ports returned by @code{current-input-port},\n"
474 "@code{current-output-port} and @code{current-error-port}, respectively,\n"
475 "so that they use the supplied @var{port} for input or output.")
476 #define FUNC_NAME s_scm_set_current_input_port
477 {
478 SCM oinp = scm_fluid_ref (cur_inport_fluid);
479 SCM_VALIDATE_OPINPORT (1, port);
480 scm_fluid_set_x (cur_inport_fluid, port);
481 return oinp;
482 }
483 #undef FUNC_NAME
484
485
486 SCM_DEFINE (scm_set_current_output_port, "set-current-output-port", 1, 0, 0,
487 (SCM port),
488 "Set the current default output port to @var{port}.")
489 #define FUNC_NAME s_scm_set_current_output_port
490 {
491 SCM ooutp = scm_fluid_ref (cur_outport_fluid);
492 port = SCM_COERCE_OUTPORT (port);
493 SCM_VALIDATE_OPOUTPORT (1, port);
494 scm_fluid_set_x (cur_outport_fluid, port);
495 return ooutp;
496 }
497 #undef FUNC_NAME
498
499
500 SCM_DEFINE (scm_set_current_error_port, "set-current-error-port", 1, 0, 0,
501 (SCM port),
502 "Set the current default error port to @var{port}.")
503 #define FUNC_NAME s_scm_set_current_error_port
504 {
505 SCM oerrp = scm_fluid_ref (cur_errport_fluid);
506 port = SCM_COERCE_OUTPORT (port);
507 SCM_VALIDATE_OPOUTPORT (1, port);
508 scm_fluid_set_x (cur_errport_fluid, port);
509 return oerrp;
510 }
511 #undef FUNC_NAME
512
513
514 SCM
515 scm_set_current_warning_port (SCM port)
516 {
517 static SCM cwp_var = SCM_BOOL_F;
518
519 if (scm_is_false (cwp_var))
520 cwp_var = scm_c_private_lookup ("guile", "current-warning-port");
521
522 return scm_call_1 (scm_variable_ref (cwp_var), port);
523 }
524
525
526 void
527 scm_dynwind_current_input_port (SCM port)
528 #define FUNC_NAME NULL
529 {
530 SCM_VALIDATE_OPINPORT (1, port);
531 scm_dynwind_fluid (cur_inport_fluid, port);
532 }
533 #undef FUNC_NAME
534
535 void
536 scm_dynwind_current_output_port (SCM port)
537 #define FUNC_NAME NULL
538 {
539 port = SCM_COERCE_OUTPORT (port);
540 SCM_VALIDATE_OPOUTPORT (1, port);
541 scm_dynwind_fluid (cur_outport_fluid, port);
542 }
543 #undef FUNC_NAME
544
545 void
546 scm_dynwind_current_error_port (SCM port)
547 #define FUNC_NAME NULL
548 {
549 port = SCM_COERCE_OUTPORT (port);
550 SCM_VALIDATE_OPOUTPORT (1, port);
551 scm_dynwind_fluid (cur_errport_fluid, port);
552 }
553 #undef FUNC_NAME
554
555 void
556 scm_i_dynwind_current_load_port (SCM port)
557 {
558 scm_dynwind_fluid (cur_loadport_fluid, port);
559 }
560
561 \f
562 /* The port table --- an array of pointers to ports. */
563
564 /*
565 We need a global registry of ports to flush them all at exit, and to
566 get all the ports matching a file descriptor.
567 */
568 SCM scm_i_port_weak_hash;
569
570 scm_i_pthread_mutex_t scm_i_port_table_mutex = SCM_I_PTHREAD_MUTEX_INITIALIZER;
571
572 \f
573 /* Port finalization. */
574
575
576 static void finalize_port (void *, void *);
577
578 /* Register a finalizer for PORT. */
579 static SCM_C_INLINE_KEYWORD void
580 register_finalizer_for_port (SCM port)
581 {
582 /* Register a finalizer for PORT so that its
583 type's `free' function gets called. */
584 scm_i_set_finalizer (SCM2PTR (port), finalize_port, NULL);
585 }
586
587 /* Finalize the object (a port) pointed to by PTR. */
588 static void
589 finalize_port (void *ptr, void *data)
590 {
591 long port_type;
592 SCM port = PTR2SCM (ptr);
593
594 if (!SCM_PORTP (port))
595 abort ();
596
597 if (SCM_OPENP (port))
598 {
599 if (SCM_REVEALED (port) > 0)
600 /* Keep "revealed" ports alive and re-register a finalizer. */
601 register_finalizer_for_port (port);
602 else
603 {
604 port_type = SCM_TC2PTOBNUM (SCM_CELL_TYPE (port));
605 if (port_type >= scm_numptob)
606 abort ();
607
608 if (scm_ptobs[port_type].free)
609 /* Yes, I really do mean `.free' rather than `.close'. `.close'
610 is for explicit `close-port' by user. */
611 scm_ptobs[port_type].free (port);
612
613 SCM_SETSTREAM (port, 0);
614 SCM_CLR_PORT_OPEN_FLAG (port);
615
616 scm_gc_ports_collected++;
617 }
618 }
619 }
620
621
622
623 \f
624
625 /* This function is not and should not be thread safe. */
626 SCM
627 scm_new_port_table_entry (scm_t_bits tag)
628 #define FUNC_NAME "scm_new_port_table_entry"
629 {
630 /*
631 We initialize the cell to empty, this is in case scm_gc_calloc
632 triggers GC ; we don't want the GC to scan a half-finished Z.
633 */
634
635 SCM z = scm_cons (SCM_EOL, SCM_EOL);
636 scm_t_port *entry = scm_gc_typed_calloc (scm_t_port);
637 scm_t_port_internal *pti = scm_gc_typed_calloc (scm_t_port_internal);
638 const char *encoding;
639
640 entry->file_name = SCM_BOOL_F;
641 entry->rw_active = SCM_PORT_NEITHER;
642 entry->port = z;
643
644 /* Initialize this port with the thread's current default
645 encoding. */
646 encoding = scm_i_default_port_encoding ();
647 entry->ilseq_handler = scm_i_default_port_conversion_handler ();
648 entry->encoding = encoding ? scm_gc_strdup (encoding, "port") : NULL;
649 if (encoding && c_strcasecmp (encoding, "UTF-8") == 0)
650 pti->encoding_mode = SCM_PORT_ENCODING_MODE_UTF8;
651 else
652 pti->encoding_mode = SCM_PORT_ENCODING_MODE_ICONV;
653 pti->iconv_descriptors = NULL;
654
655 pti->at_stream_start_for_bom_read = 1;
656 pti->at_stream_start_for_bom_write = 1;
657
658 /* XXX These fields are not what they seem. They have been
659 repurposed, but cannot safely be renamed in 2.0 without breaking
660 ABI compatibility. This will be cleaned up in 2.2. */
661 entry->input_cd = pti; /* XXX pointer to the internal port structure */
662 entry->output_cd = NULL; /* XXX unused */
663
664 pti->pending_eof = 0;
665 pti->alist = SCM_EOL;
666
667 SCM_SET_CELL_TYPE (z, tag);
668 SCM_SETPTAB_ENTRY (z, entry);
669
670 scm_hashq_set_x (scm_i_port_weak_hash, z, SCM_BOOL_F);
671
672 /* For each new port, register a finalizer so that it port type's free
673 function can be invoked eventually. */
674 register_finalizer_for_port (z);
675
676 return z;
677 }
678 #undef FUNC_NAME
679
680 #if SCM_ENABLE_DEPRECATED==1
681 scm_t_port *
682 scm_add_to_port_table (SCM port)
683 {
684 SCM z;
685 scm_t_port * pt;
686
687 scm_c_issue_deprecation_warning ("scm_add_to_port_table is deprecated.");
688
689 scm_i_pthread_mutex_lock (&scm_i_port_table_mutex);
690 z = scm_new_port_table_entry (scm_tc7_port);
691 pt = SCM_PTAB_ENTRY(z);
692 pt->port = port;
693 SCM_SETCAR (z, SCM_EOL);
694 SCM_SETCDR (z, SCM_EOL);
695 SCM_SETPTAB_ENTRY (port, pt);
696 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
697
698 return pt;
699 }
700 #endif
701
702
703 /* Remove a port from the table and destroy it. */
704
705 static void close_iconv_descriptors (scm_t_iconv_descriptors *id);
706
707 static void
708 scm_i_remove_port (SCM port)
709 #define FUNC_NAME "scm_remove_port"
710 {
711 scm_t_port *p;
712 scm_t_port_internal *pti;
713
714 scm_i_scm_pthread_mutex_lock (&scm_i_port_table_mutex);
715
716 p = SCM_PTAB_ENTRY (port);
717 pti = SCM_PORT_GET_INTERNAL (port);
718 scm_port_non_buffer (p);
719 p->putback_buf = NULL;
720 p->putback_buf_size = 0;
721
722 if (pti->iconv_descriptors)
723 {
724 close_iconv_descriptors (pti->iconv_descriptors);
725 pti->iconv_descriptors = NULL;
726 }
727
728 SCM_SETPTAB_ENTRY (port, 0);
729
730 scm_hashq_remove_x (scm_i_port_weak_hash, port);
731
732 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
733 }
734 #undef FUNC_NAME
735
736
737 /* Functions for debugging. */
738 #ifdef GUILE_DEBUG
739 SCM_DEFINE (scm_pt_size, "pt-size", 0, 0, 0,
740 (),
741 "Return the number of ports in the port table. @code{pt-size}\n"
742 "is only included in @code{--enable-guile-debug} builds.")
743 #define FUNC_NAME s_scm_pt_size
744 {
745 return scm_from_int (SCM_HASHTABLE_N_ITEMS (scm_i_port_weak_hash));
746 }
747 #undef FUNC_NAME
748 #endif
749
750 void
751 scm_port_non_buffer (scm_t_port *pt)
752 {
753 pt->read_pos = pt->read_buf = pt->read_end = &pt->shortbuf;
754 pt->write_buf = pt->write_pos = &pt->shortbuf;
755 pt->read_buf_size = pt->write_buf_size = 1;
756 pt->write_end = pt->write_buf + pt->write_buf_size;
757 }
758
759 \f
760 /* Revealed counts --- an oddity inherited from SCSH. */
761
762 /* Find a port in the table and return its revealed count.
763 Also used by the garbage collector.
764 */
765
766 int
767 scm_revealed_count (SCM port)
768 {
769 return SCM_REVEALED(port);
770 }
771
772
773
774 /* Return the revealed count for a port. */
775
776 SCM_DEFINE (scm_port_revealed, "port-revealed", 1, 0, 0,
777 (SCM port),
778 "Return the revealed count for @var{port}.")
779 #define FUNC_NAME s_scm_port_revealed
780 {
781 port = SCM_COERCE_OUTPORT (port);
782 SCM_VALIDATE_OPENPORT (1, port);
783 return scm_from_int (scm_revealed_count (port));
784 }
785 #undef FUNC_NAME
786
787 /* Set the revealed count for a port. */
788 SCM_DEFINE (scm_set_port_revealed_x, "set-port-revealed!", 2, 0, 0,
789 (SCM port, SCM rcount),
790 "Sets the revealed count for a port to a given value.\n"
791 "The return value is unspecified.")
792 #define FUNC_NAME s_scm_set_port_revealed_x
793 {
794 port = SCM_COERCE_OUTPORT (port);
795 SCM_VALIDATE_OPENPORT (1, port);
796 SCM_REVEALED (port) = scm_to_int (rcount);
797 return SCM_UNSPECIFIED;
798 }
799 #undef FUNC_NAME
800
801
802 \f
803 /* Retrieving a port's mode. */
804
805 /* Return the flags that characterize a port based on the mode
806 * string used to open a file for that port.
807 *
808 * See PORT FLAGS in scm.h
809 */
810
811 static long
812 scm_i_mode_bits_n (SCM modes)
813 {
814 return (SCM_OPN
815 | (scm_i_string_contains_char (modes, 'r')
816 || scm_i_string_contains_char (modes, '+') ? SCM_RDNG : 0)
817 | (scm_i_string_contains_char (modes, 'w')
818 || scm_i_string_contains_char (modes, 'a')
819 || scm_i_string_contains_char (modes, '+') ? SCM_WRTNG : 0)
820 | (scm_i_string_contains_char (modes, '0') ? SCM_BUF0 : 0)
821 | (scm_i_string_contains_char (modes, 'l') ? SCM_BUFLINE : 0));
822 }
823
824 long
825 scm_mode_bits (char *modes)
826 {
827 return scm_i_mode_bits (scm_from_locale_string (modes));
828 }
829
830 long
831 scm_i_mode_bits (SCM modes)
832 {
833 long bits;
834
835 if (!scm_is_string (modes))
836 scm_wrong_type_arg_msg (NULL, 0, modes, "string");
837
838 bits = scm_i_mode_bits_n (modes);
839 scm_remember_upto_here_1 (modes);
840 return bits;
841 }
842
843 /* Return the mode flags from an open port.
844 * Some modes such as "append" are only used when opening
845 * a file and are not returned here. */
846
847 SCM_DEFINE (scm_port_mode, "port-mode", 1, 0, 0,
848 (SCM port),
849 "Return the port modes associated with the open port @var{port}.\n"
850 "These will not necessarily be identical to the modes used when\n"
851 "the port was opened, since modes such as \"append\" which are\n"
852 "used only during port creation are not retained.")
853 #define FUNC_NAME s_scm_port_mode
854 {
855 char modes[4];
856 modes[0] = '\0';
857
858 port = SCM_COERCE_OUTPORT (port);
859 SCM_VALIDATE_OPPORT (1, port);
860 if (SCM_CELL_WORD_0 (port) & SCM_RDNG) {
861 if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
862 strcpy (modes, "r+");
863 else
864 strcpy (modes, "r");
865 }
866 else if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
867 strcpy (modes, "w");
868 if (SCM_CELL_WORD_0 (port) & SCM_BUF0)
869 strcat (modes, "0");
870 return scm_from_locale_string (modes);
871 }
872 #undef FUNC_NAME
873
874
875 \f
876 /* Closing ports. */
877
878 /* scm_close_port
879 * Call the close operation on a port object.
880 * see also scm_close.
881 */
882 SCM_DEFINE (scm_close_port, "close-port", 1, 0, 0,
883 (SCM port),
884 "Close the specified port object. Return @code{#t} if it\n"
885 "successfully closes a port or @code{#f} if it was already\n"
886 "closed. An exception may be raised if an error occurs, for\n"
887 "example when flushing buffered output. See also @ref{Ports and\n"
888 "File Descriptors, close}, for a procedure which can close file\n"
889 "descriptors.")
890 #define FUNC_NAME s_scm_close_port
891 {
892 size_t i;
893 int rv;
894
895 port = SCM_COERCE_OUTPORT (port);
896
897 SCM_VALIDATE_PORT (1, port);
898 if (SCM_CLOSEDP (port))
899 return SCM_BOOL_F;
900 i = SCM_PTOBNUM (port);
901 if (scm_ptobs[i].close)
902 rv = (scm_ptobs[i].close) (port);
903 else
904 rv = 0;
905 scm_i_remove_port (port);
906 SCM_CLR_PORT_OPEN_FLAG (port);
907 return scm_from_bool (rv >= 0);
908 }
909 #undef FUNC_NAME
910
911 SCM_DEFINE (scm_close_input_port, "close-input-port", 1, 0, 0,
912 (SCM port),
913 "Close the specified input port object. The routine has no effect if\n"
914 "the file has already been closed. An exception may be raised if an\n"
915 "error occurs. The value returned is unspecified.\n\n"
916 "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
917 "which can close file descriptors.")
918 #define FUNC_NAME s_scm_close_input_port
919 {
920 SCM_VALIDATE_INPUT_PORT (1, port);
921 scm_close_port (port);
922 return SCM_UNSPECIFIED;
923 }
924 #undef FUNC_NAME
925
926 SCM_DEFINE (scm_close_output_port, "close-output-port", 1, 0, 0,
927 (SCM port),
928 "Close the specified output port object. The routine has no effect if\n"
929 "the file has already been closed. An exception may be raised if an\n"
930 "error occurs. The value returned is unspecified.\n\n"
931 "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
932 "which can close file descriptors.")
933 #define FUNC_NAME s_scm_close_output_port
934 {
935 port = SCM_COERCE_OUTPORT (port);
936 SCM_VALIDATE_OUTPUT_PORT (1, port);
937 scm_close_port (port);
938 return SCM_UNSPECIFIED;
939 }
940 #undef FUNC_NAME
941
942 static SCM
943 collect_keys (void *unused, SCM key, SCM value, SCM result)
944 {
945 return scm_cons (key, result);
946 }
947
948 void
949 scm_c_port_for_each (void (*proc)(void *data, SCM p), void *data)
950 {
951 SCM ports;
952
953 /* Copy out the port table as a list so that we get strong references
954 to all the values. */
955 scm_i_pthread_mutex_lock (&scm_i_port_table_mutex);
956 ports = scm_internal_hash_fold (collect_keys, NULL,
957 SCM_EOL, scm_i_port_weak_hash);
958 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
959
960 for (; scm_is_pair (ports); ports = scm_cdr (ports))
961 {
962 SCM p = scm_car (ports);
963 if (SCM_PORTP (p))
964 proc (data, p);
965 }
966 }
967
968 SCM_DEFINE (scm_port_for_each, "port-for-each", 1, 0, 0,
969 (SCM proc),
970 "Apply @var{proc} to each port in the Guile port table\n"
971 "in turn. The return value is unspecified. More specifically,\n"
972 "@var{proc} is applied exactly once to every port that exists\n"
973 "in the system at the time @code{port-for-each} is invoked.\n"
974 "Changes to the port table while @code{port-for-each} is running\n"
975 "have no effect as far as @code{port-for-each} is concerned.")
976 #define FUNC_NAME s_scm_port_for_each
977 {
978 SCM ports;
979
980 SCM_VALIDATE_PROC (1, proc);
981
982 /* Copy out the port table as a list so that we get strong references
983 to all the values. */
984 scm_i_pthread_mutex_lock (&scm_i_port_table_mutex);
985 ports = scm_internal_hash_fold (collect_keys, NULL,
986 SCM_EOL, scm_i_port_weak_hash);
987 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
988
989 for (; scm_is_pair (ports); ports = scm_cdr (ports))
990 if (SCM_PORTP (SCM_CAR (ports)))
991 scm_call_1 (proc, SCM_CAR (ports));
992
993 return SCM_UNSPECIFIED;
994 }
995 #undef FUNC_NAME
996
997
998 \f
999 /* Utter miscellany. Gosh, we should clean this up some time. */
1000
1001 SCM_DEFINE (scm_input_port_p, "input-port?", 1, 0, 0,
1002 (SCM x),
1003 "Return @code{#t} if @var{x} is an input port, otherwise return\n"
1004 "@code{#f}. Any object satisfying this predicate also satisfies\n"
1005 "@code{port?}.")
1006 #define FUNC_NAME s_scm_input_port_p
1007 {
1008 return scm_from_bool (SCM_INPUT_PORT_P (x));
1009 }
1010 #undef FUNC_NAME
1011
1012 SCM_DEFINE (scm_output_port_p, "output-port?", 1, 0, 0,
1013 (SCM x),
1014 "Return @code{#t} if @var{x} is an output port, otherwise return\n"
1015 "@code{#f}. Any object satisfying this predicate also satisfies\n"
1016 "@code{port?}.")
1017 #define FUNC_NAME s_scm_output_port_p
1018 {
1019 x = SCM_COERCE_OUTPORT (x);
1020 return scm_from_bool (SCM_OUTPUT_PORT_P (x));
1021 }
1022 #undef FUNC_NAME
1023
1024 SCM_DEFINE (scm_port_p, "port?", 1, 0, 0,
1025 (SCM x),
1026 "Return a boolean indicating whether @var{x} is a port.\n"
1027 "Equivalent to @code{(or (input-port? @var{x}) (output-port?\n"
1028 "@var{x}))}.")
1029 #define FUNC_NAME s_scm_port_p
1030 {
1031 return scm_from_bool (SCM_PORTP (x));
1032 }
1033 #undef FUNC_NAME
1034
1035 SCM_DEFINE (scm_port_closed_p, "port-closed?", 1, 0, 0,
1036 (SCM port),
1037 "Return @code{#t} if @var{port} is closed or @code{#f} if it is\n"
1038 "open.")
1039 #define FUNC_NAME s_scm_port_closed_p
1040 {
1041 SCM_VALIDATE_PORT (1, port);
1042 return scm_from_bool (!SCM_OPPORTP (port));
1043 }
1044 #undef FUNC_NAME
1045
1046 SCM_DEFINE (scm_eof_object_p, "eof-object?", 1, 0, 0,
1047 (SCM x),
1048 "Return @code{#t} if @var{x} is an end-of-file object; otherwise\n"
1049 "return @code{#f}.")
1050 #define FUNC_NAME s_scm_eof_object_p
1051 {
1052 return scm_from_bool(SCM_EOF_OBJECT_P (x));
1053 }
1054 #undef FUNC_NAME
1055
1056 SCM_DEFINE (scm_force_output, "force-output", 0, 1, 0,
1057 (SCM port),
1058 "Flush the specified output port, or the current output port if @var{port}\n"
1059 "is omitted. The current output buffer contents are passed to the\n"
1060 "underlying port implementation (e.g., in the case of fports, the\n"
1061 "data will be written to the file and the output buffer will be cleared.)\n"
1062 "It has no effect on an unbuffered port.\n\n"
1063 "The return value is unspecified.")
1064 #define FUNC_NAME s_scm_force_output
1065 {
1066 if (SCM_UNBNDP (port))
1067 port = scm_current_output_port ();
1068 else
1069 {
1070 port = SCM_COERCE_OUTPORT (port);
1071 SCM_VALIDATE_OPOUTPORT (1, port);
1072 }
1073 scm_flush (port);
1074 return SCM_UNSPECIFIED;
1075 }
1076 #undef FUNC_NAME
1077
1078
1079 static void
1080 flush_output_port (void *closure, SCM port)
1081 {
1082 if (SCM_OPOUTPORTP (port))
1083 scm_flush (port);
1084 }
1085
1086 SCM_DEFINE (scm_flush_all_ports, "flush-all-ports", 0, 0, 0,
1087 (),
1088 "Equivalent to calling @code{force-output} on\n"
1089 "all open output ports. The return value is unspecified.")
1090 #define FUNC_NAME s_scm_flush_all_ports
1091 {
1092 scm_c_port_for_each (&flush_output_port, NULL);
1093 return SCM_UNSPECIFIED;
1094 }
1095 #undef FUNC_NAME
1096
1097 SCM_DEFINE (scm_read_char, "read-char", 0, 1, 0,
1098 (SCM port),
1099 "Return the next character available from @var{port}, updating\n"
1100 "@var{port} to point to the following character. If no more\n"
1101 "characters are available, the end-of-file object is returned.\n"
1102 "\n"
1103 "When @var{port}'s data cannot be decoded according to its\n"
1104 "character encoding, a @code{decoding-error} is raised and\n"
1105 "@var{port} points past the erroneous byte sequence.\n")
1106 #define FUNC_NAME s_scm_read_char
1107 {
1108 scm_t_wchar c;
1109 if (SCM_UNBNDP (port))
1110 port = scm_current_input_port ();
1111 SCM_VALIDATE_OPINPORT (1, port);
1112 c = scm_getc (port);
1113 if (EOF == c)
1114 return SCM_EOF_VAL;
1115 return SCM_MAKE_CHAR (c);
1116 }
1117 #undef FUNC_NAME
1118
1119 /* Update the line and column number of PORT after consumption of C. */
1120 static inline void
1121 update_port_lf (scm_t_wchar c, SCM port)
1122 {
1123 switch (c)
1124 {
1125 case '\a':
1126 case EOF:
1127 break;
1128 case '\b':
1129 SCM_DECCOL (port);
1130 break;
1131 case '\n':
1132 SCM_INCLINE (port);
1133 break;
1134 case '\r':
1135 SCM_ZEROCOL (port);
1136 break;
1137 case '\t':
1138 SCM_TABCOL (port);
1139 break;
1140 default:
1141 SCM_INCCOL (port);
1142 break;
1143 }
1144 }
1145
1146 #define SCM_MBCHAR_BUF_SIZE (4)
1147
1148 /* Convert the SIZE-byte UTF-8 sequence in UTF8_BUF to a codepoint.
1149 UTF8_BUF is assumed to contain a valid UTF-8 sequence. */
1150 static scm_t_wchar
1151 utf8_to_codepoint (const scm_t_uint8 *utf8_buf, size_t size)
1152 {
1153 scm_t_wchar codepoint;
1154
1155 if (utf8_buf[0] <= 0x7f)
1156 {
1157 assert (size == 1);
1158 codepoint = utf8_buf[0];
1159 }
1160 else if ((utf8_buf[0] & 0xe0) == 0xc0)
1161 {
1162 assert (size == 2);
1163 codepoint = ((scm_t_wchar) utf8_buf[0] & 0x1f) << 6UL
1164 | (utf8_buf[1] & 0x3f);
1165 }
1166 else if ((utf8_buf[0] & 0xf0) == 0xe0)
1167 {
1168 assert (size == 3);
1169 codepoint = ((scm_t_wchar) utf8_buf[0] & 0x0f) << 12UL
1170 | ((scm_t_wchar) utf8_buf[1] & 0x3f) << 6UL
1171 | (utf8_buf[2] & 0x3f);
1172 }
1173 else
1174 {
1175 assert (size == 4);
1176 codepoint = ((scm_t_wchar) utf8_buf[0] & 0x07) << 18UL
1177 | ((scm_t_wchar) utf8_buf[1] & 0x3f) << 12UL
1178 | ((scm_t_wchar) utf8_buf[2] & 0x3f) << 6UL
1179 | (utf8_buf[3] & 0x3f);
1180 }
1181
1182 return codepoint;
1183 }
1184
1185 /* Read a UTF-8 sequence from PORT. On success, return 0 and set
1186 *CODEPOINT to the codepoint that was read, fill BUF with its UTF-8
1187 representation, and set *LEN to the length in bytes. Return
1188 `EILSEQ' on error. */
1189 static int
1190 get_utf8_codepoint (SCM port, scm_t_wchar *codepoint,
1191 scm_t_uint8 buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
1192 {
1193 #define ASSERT_NOT_EOF(b) \
1194 if (SCM_UNLIKELY ((b) == EOF)) \
1195 goto invalid_seq
1196 #define CONSUME_PEEKED_BYTE() \
1197 pt->read_pos++
1198
1199 int byte;
1200 scm_t_port *pt;
1201
1202 *len = 0;
1203 pt = SCM_PTAB_ENTRY (port);
1204
1205 byte = scm_get_byte_or_eof (port);
1206 if (byte == EOF)
1207 {
1208 *codepoint = EOF;
1209 return 0;
1210 }
1211
1212 buf[0] = (scm_t_uint8) byte;
1213 *len = 1;
1214
1215 if (buf[0] <= 0x7f)
1216 /* 1-byte form. */
1217 *codepoint = buf[0];
1218 else if (buf[0] >= 0xc2 && buf[0] <= 0xdf)
1219 {
1220 /* 2-byte form. */
1221 byte = scm_peek_byte_or_eof (port);
1222 ASSERT_NOT_EOF (byte);
1223
1224 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1225 goto invalid_seq;
1226
1227 CONSUME_PEEKED_BYTE ();
1228 buf[1] = (scm_t_uint8) byte;
1229 *len = 2;
1230
1231 *codepoint = ((scm_t_wchar) buf[0] & 0x1f) << 6UL
1232 | (buf[1] & 0x3f);
1233 }
1234 else if ((buf[0] & 0xf0) == 0xe0)
1235 {
1236 /* 3-byte form. */
1237 byte = scm_peek_byte_or_eof (port);
1238 ASSERT_NOT_EOF (byte);
1239
1240 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80
1241 || (buf[0] == 0xe0 && byte < 0xa0)
1242 || (buf[0] == 0xed && byte > 0x9f)))
1243 goto invalid_seq;
1244
1245 CONSUME_PEEKED_BYTE ();
1246 buf[1] = (scm_t_uint8) byte;
1247 *len = 2;
1248
1249 byte = scm_peek_byte_or_eof (port);
1250 ASSERT_NOT_EOF (byte);
1251
1252 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1253 goto invalid_seq;
1254
1255 CONSUME_PEEKED_BYTE ();
1256 buf[2] = (scm_t_uint8) byte;
1257 *len = 3;
1258
1259 *codepoint = ((scm_t_wchar) buf[0] & 0x0f) << 12UL
1260 | ((scm_t_wchar) buf[1] & 0x3f) << 6UL
1261 | (buf[2] & 0x3f);
1262 }
1263 else if (buf[0] >= 0xf0 && buf[0] <= 0xf4)
1264 {
1265 /* 4-byte form. */
1266 byte = scm_peek_byte_or_eof (port);
1267 ASSERT_NOT_EOF (byte);
1268
1269 if (SCM_UNLIKELY (((byte & 0xc0) != 0x80)
1270 || (buf[0] == 0xf0 && byte < 0x90)
1271 || (buf[0] == 0xf4 && byte > 0x8f)))
1272 goto invalid_seq;
1273
1274 CONSUME_PEEKED_BYTE ();
1275 buf[1] = (scm_t_uint8) byte;
1276 *len = 2;
1277
1278 byte = scm_peek_byte_or_eof (port);
1279 ASSERT_NOT_EOF (byte);
1280
1281 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1282 goto invalid_seq;
1283
1284 CONSUME_PEEKED_BYTE ();
1285 buf[2] = (scm_t_uint8) byte;
1286 *len = 3;
1287
1288 byte = scm_peek_byte_or_eof (port);
1289 ASSERT_NOT_EOF (byte);
1290
1291 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1292 goto invalid_seq;
1293
1294 CONSUME_PEEKED_BYTE ();
1295 buf[3] = (scm_t_uint8) byte;
1296 *len = 4;
1297
1298 *codepoint = ((scm_t_wchar) buf[0] & 0x07) << 18UL
1299 | ((scm_t_wchar) buf[1] & 0x3f) << 12UL
1300 | ((scm_t_wchar) buf[2] & 0x3f) << 6UL
1301 | (buf[3] & 0x3f);
1302 }
1303 else
1304 goto invalid_seq;
1305
1306 return 0;
1307
1308 invalid_seq:
1309 /* Here we could choose the consume the faulty byte when it's not a
1310 valid starting byte, but it's not a requirement. What Section 3.9
1311 of Unicode 6.0.0 mandates, though, is to not consume a byte that
1312 would otherwise be a valid starting byte. */
1313
1314 return EILSEQ;
1315
1316 #undef CONSUME_PEEKED_BYTE
1317 #undef ASSERT_NOT_EOF
1318 }
1319
1320 /* Likewise, read a byte sequence from PORT, passing it through its
1321 input conversion descriptor. */
1322 static int
1323 get_iconv_codepoint (SCM port, scm_t_wchar *codepoint,
1324 char buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
1325 {
1326 scm_t_iconv_descriptors *id;
1327 scm_t_uint8 utf8_buf[SCM_MBCHAR_BUF_SIZE];
1328 size_t input_size = 0;
1329
1330 id = scm_i_port_iconv_descriptors (port, SCM_PORT_READ);
1331
1332 for (;;)
1333 {
1334 int byte_read;
1335 char *input, *output;
1336 size_t input_left, output_left, done;
1337
1338 byte_read = scm_get_byte_or_eof (port);
1339 if (SCM_UNLIKELY (byte_read == EOF))
1340 {
1341 if (SCM_LIKELY (input_size == 0))
1342 {
1343 *codepoint = (scm_t_wchar) EOF;
1344 *len = input_size;
1345 return 0;
1346 }
1347 else
1348 {
1349 /* EOF found in the middle of a multibyte character. */
1350 scm_i_set_pending_eof (port);
1351 return EILSEQ;
1352 }
1353 }
1354
1355 buf[input_size++] = byte_read;
1356
1357 input = buf;
1358 input_left = input_size;
1359 output = (char *) utf8_buf;
1360 output_left = sizeof (utf8_buf);
1361
1362 done = iconv (id->input_cd, &input, &input_left, &output, &output_left);
1363
1364 if (done == (size_t) -1)
1365 {
1366 int err = errno;
1367 if (SCM_LIKELY (err == EINVAL))
1368 /* The input byte sequence did not form a complete
1369 character. Read another byte and try again. */
1370 continue;
1371 else
1372 return err;
1373 }
1374 else
1375 {
1376 size_t output_size = sizeof (utf8_buf) - output_left;
1377 if (SCM_LIKELY (output_size > 0))
1378 {
1379 /* iconv generated output. Convert the UTF8_BUF sequence
1380 to a Unicode code point. */
1381 *codepoint = utf8_to_codepoint (utf8_buf, output_size);
1382 *len = input_size;
1383 return 0;
1384 }
1385 else
1386 {
1387 /* iconv consumed some bytes without producing any output.
1388 Most likely this means that a Unicode byte-order mark
1389 (BOM) was consumed, which should not be included in the
1390 returned buf. Shift any remaining bytes to the beginning
1391 of buf, and continue the loop. */
1392 memmove (buf, input, input_left);
1393 input_size = input_left;
1394 continue;
1395 }
1396 }
1397 }
1398 }
1399
1400 /* Read a codepoint from PORT and return it in *CODEPOINT. Fill BUF
1401 with the byte representation of the codepoint in PORT's encoding, and
1402 set *LEN to the length in bytes of that representation. Return 0 on
1403 success and an errno value on error. */
1404 static int
1405 get_codepoint (SCM port, scm_t_wchar *codepoint,
1406 char buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
1407 {
1408 int err;
1409 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1410 scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
1411
1412 if (pti->encoding_mode == SCM_PORT_ENCODING_MODE_UTF8)
1413 err = get_utf8_codepoint (port, codepoint, (scm_t_uint8 *) buf, len);
1414 else
1415 err = get_iconv_codepoint (port, codepoint, buf, len);
1416
1417 if (SCM_LIKELY (err == 0))
1418 {
1419 if (SCM_UNLIKELY (pti->at_stream_start_for_bom_read))
1420 {
1421 /* Record that we're no longer at stream start. */
1422 pti->at_stream_start_for_bom_read = 0;
1423 if (pt->rw_random)
1424 pti->at_stream_start_for_bom_write = 0;
1425
1426 /* If we just read a BOM in an encoding that recognizes them,
1427 then silently consume it and read another code point. */
1428 if (SCM_UNLIKELY
1429 (*codepoint == SCM_UNICODE_BOM
1430 && (pti->encoding_mode == SCM_PORT_ENCODING_MODE_UTF8
1431 || c_strcasecmp (pt->encoding, "UTF-16") == 0
1432 || c_strcasecmp (pt->encoding, "UTF-32") == 0)))
1433 return get_codepoint (port, codepoint, buf, len);
1434 }
1435 update_port_lf (*codepoint, port);
1436 }
1437 else if (pt->ilseq_handler == SCM_ICONVEH_QUESTION_MARK)
1438 {
1439 *codepoint = '?';
1440 err = 0;
1441 update_port_lf (*codepoint, port);
1442 }
1443
1444 return err;
1445 }
1446
1447 /* Read a codepoint from PORT and return it. */
1448 scm_t_wchar
1449 scm_getc (SCM port)
1450 #define FUNC_NAME "scm_getc"
1451 {
1452 int err;
1453 size_t len;
1454 scm_t_wchar codepoint;
1455 char buf[SCM_MBCHAR_BUF_SIZE];
1456
1457 err = get_codepoint (port, &codepoint, buf, &len);
1458 if (SCM_UNLIKELY (err != 0))
1459 /* At this point PORT should point past the invalid encoding, as per
1460 R6RS-lib Section 8.2.4. */
1461 scm_decoding_error (FUNC_NAME, err, "input decoding error", port);
1462
1463 return codepoint;
1464 }
1465 #undef FUNC_NAME
1466
1467 /* this should only be called when the read buffer is empty. it
1468 tries to refill the read buffer. it returns the first char from
1469 the port, which is either EOF or *(pt->read_pos). */
1470 static int
1471 scm_i_fill_input (SCM port)
1472 {
1473 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1474 scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
1475
1476 assert (pt->read_pos == pt->read_end);
1477
1478 if (pti->pending_eof)
1479 {
1480 pti->pending_eof = 0;
1481 return EOF;
1482 }
1483
1484 if (pt->read_buf == pt->putback_buf)
1485 {
1486 /* finished reading put-back chars. */
1487 pt->read_buf = pt->saved_read_buf;
1488 pt->read_pos = pt->saved_read_pos;
1489 pt->read_end = pt->saved_read_end;
1490 pt->read_buf_size = pt->saved_read_buf_size;
1491 if (pt->read_pos < pt->read_end)
1492 return *(pt->read_pos);
1493 }
1494 return scm_ptobs[SCM_PTOBNUM (port)].fill_input (port);
1495 }
1496
1497 int
1498 scm_fill_input (SCM port)
1499 {
1500 return scm_i_fill_input (port);
1501 }
1502
1503 /* Slow-path fallback for 'scm_get_byte_or_eof' in inline.h */
1504 int
1505 scm_slow_get_byte_or_eof (SCM port)
1506 {
1507 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1508
1509 if (pt->rw_active == SCM_PORT_WRITE)
1510 scm_flush (port);
1511
1512 if (pt->rw_random)
1513 pt->rw_active = SCM_PORT_READ;
1514
1515 if (pt->read_pos >= pt->read_end)
1516 {
1517 if (SCM_UNLIKELY (scm_i_fill_input (port) == EOF))
1518 return EOF;
1519 }
1520
1521 return *pt->read_pos++;
1522 }
1523
1524 /* Slow-path fallback for 'scm_peek_byte_or_eof' in inline.h */
1525 int
1526 scm_slow_peek_byte_or_eof (SCM port)
1527 {
1528 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1529
1530 if (pt->rw_active == SCM_PORT_WRITE)
1531 scm_flush (port);
1532
1533 if (pt->rw_random)
1534 pt->rw_active = SCM_PORT_READ;
1535
1536 if (pt->read_pos >= pt->read_end)
1537 {
1538 if (SCM_UNLIKELY (scm_i_fill_input (port) == EOF))
1539 {
1540 scm_i_set_pending_eof (port);
1541 return EOF;
1542 }
1543 }
1544
1545 return *pt->read_pos;
1546 }
1547
1548
1549 /* scm_lfwrite
1550 *
1551 * This function differs from scm_c_write; it updates port line and
1552 * column. */
1553
1554 void
1555 scm_lfwrite (const char *ptr, size_t size, SCM port)
1556 {
1557 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1558 scm_t_ptob_descriptor *ptob = &scm_ptobs[SCM_PTOBNUM (port)];
1559
1560 if (pt->rw_active == SCM_PORT_READ)
1561 scm_end_input (port);
1562
1563 ptob->write (port, ptr, size);
1564
1565 for (; size; ptr++, size--)
1566 update_port_lf ((scm_t_wchar) (unsigned char) *ptr, port);
1567
1568 if (pt->rw_random)
1569 pt->rw_active = SCM_PORT_WRITE;
1570 }
1571
1572 /* Write STR to PORT from START inclusive to END exclusive. */
1573 void
1574 scm_lfwrite_substr (SCM str, size_t start, size_t end, SCM port)
1575 {
1576 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1577
1578 if (pt->rw_active == SCM_PORT_READ)
1579 scm_end_input (port);
1580
1581 if (end == (size_t) -1)
1582 end = scm_i_string_length (str);
1583
1584 scm_i_display_substring (str, start, end, port);
1585
1586 if (pt->rw_random)
1587 pt->rw_active = SCM_PORT_WRITE;
1588 }
1589
1590 /* scm_c_read
1591 *
1592 * Used by an application to read arbitrary number of bytes from an
1593 * SCM port. Same semantics as libc read, except that scm_c_read only
1594 * returns less than SIZE bytes if at end-of-file.
1595 *
1596 * Warning: Doesn't update port line and column counts! */
1597
1598 /* This structure, and the following swap_buffer function, are used
1599 for temporarily swapping a port's own read buffer, and the buffer
1600 that the caller of scm_c_read provides. */
1601 struct port_and_swap_buffer
1602 {
1603 scm_t_port *pt;
1604 unsigned char *buffer;
1605 size_t size;
1606 };
1607
1608 static void
1609 swap_buffer (void *data)
1610 {
1611 struct port_and_swap_buffer *psb = (struct port_and_swap_buffer *) data;
1612 unsigned char *old_buf = psb->pt->read_buf;
1613 size_t old_size = psb->pt->read_buf_size;
1614
1615 /* Make the port use (buffer, size) from the struct. */
1616 psb->pt->read_pos = psb->pt->read_buf = psb->pt->read_end = psb->buffer;
1617 psb->pt->read_buf_size = psb->size;
1618
1619 /* Save the port's old (buffer, size) in the struct. */
1620 psb->buffer = old_buf;
1621 psb->size = old_size;
1622 }
1623
1624 size_t
1625 scm_c_read (SCM port, void *buffer, size_t size)
1626 #define FUNC_NAME "scm_c_read"
1627 {
1628 scm_t_port *pt;
1629 size_t n_read = 0, n_available;
1630 struct port_and_swap_buffer psb;
1631
1632 SCM_VALIDATE_OPINPORT (1, port);
1633
1634 pt = SCM_PTAB_ENTRY (port);
1635 if (pt->rw_active == SCM_PORT_WRITE)
1636 scm_ptobs[SCM_PTOBNUM (port)].flush (port);
1637
1638 if (pt->rw_random)
1639 pt->rw_active = SCM_PORT_READ;
1640
1641 /* Take bytes first from the port's read buffer. */
1642 if (pt->read_pos < pt->read_end)
1643 {
1644 n_available = min (size, pt->read_end - pt->read_pos);
1645 memcpy (buffer, pt->read_pos, n_available);
1646 buffer = (char *) buffer + n_available;
1647 pt->read_pos += n_available;
1648 n_read += n_available;
1649 size -= n_available;
1650 }
1651
1652 /* Avoid the scm_dynwind_* costs if we now have enough data. */
1653 if (size == 0)
1654 return n_read;
1655
1656 /* Now we will call scm_i_fill_input repeatedly until we have read the
1657 requested number of bytes. (Note that a single scm_i_fill_input
1658 call does not guarantee to fill the whole of the port's read
1659 buffer.) */
1660 if (pt->read_buf_size <= 1 && pt->encoding == NULL)
1661 {
1662 /* The port that we are reading from is unbuffered - i.e. does
1663 not have its own persistent buffer - but we have a buffer,
1664 provided by our caller, that is the right size for the data
1665 that is wanted. For the following scm_i_fill_input calls,
1666 therefore, we use the buffer in hand as the port's read
1667 buffer.
1668
1669 We need to make sure that the port's normal (1 byte) buffer
1670 is reinstated in case one of the scm_i_fill_input () calls
1671 throws an exception; we use the scm_dynwind_* API to achieve
1672 that.
1673
1674 A consequence of this optimization is that the fill_input
1675 functions can't unget characters. That'll push data to the
1676 pushback buffer instead of this psb buffer. */
1677 #if SCM_DEBUG == 1
1678 unsigned char *pback = pt->putback_buf;
1679 #endif
1680 psb.pt = pt;
1681 psb.buffer = buffer;
1682 psb.size = size;
1683 scm_dynwind_begin (SCM_F_DYNWIND_REWINDABLE);
1684 scm_dynwind_rewind_handler (swap_buffer, &psb, SCM_F_WIND_EXPLICITLY);
1685 scm_dynwind_unwind_handler (swap_buffer, &psb, SCM_F_WIND_EXPLICITLY);
1686
1687 /* Call scm_i_fill_input until we have all the bytes that we need,
1688 or we hit EOF. */
1689 while (pt->read_buf_size && (scm_i_fill_input (port) != EOF))
1690 {
1691 pt->read_buf_size -= (pt->read_end - pt->read_pos);
1692 pt->read_pos = pt->read_buf = pt->read_end;
1693 }
1694 #if SCM_DEBUG == 1
1695 if (pback != pt->putback_buf
1696 || pt->read_buf - (unsigned char *) buffer < 0)
1697 scm_misc_error (FUNC_NAME,
1698 "scm_c_read must not call a fill function that pushes "
1699 "back characters onto an unbuffered port", SCM_EOL);
1700 #endif
1701 n_read += pt->read_buf - (unsigned char *) buffer;
1702
1703 /* Reinstate the port's normal buffer. */
1704 scm_dynwind_end ();
1705 }
1706 else
1707 {
1708 /* The port has its own buffer. It is important that we use it,
1709 even if it happens to be smaller than our caller's buffer, so
1710 that a custom port implementation's entry points (in
1711 particular, fill_input) can rely on the buffer always being
1712 the same as they first set up. */
1713 while (size && (scm_i_fill_input (port) != EOF))
1714 {
1715 n_available = min (size, pt->read_end - pt->read_pos);
1716 memcpy (buffer, pt->read_pos, n_available);
1717 buffer = (char *) buffer + n_available;
1718 pt->read_pos += n_available;
1719 n_read += n_available;
1720 size -= n_available;
1721 }
1722 }
1723
1724 return n_read;
1725 }
1726 #undef FUNC_NAME
1727
1728 /* scm_c_write
1729 *
1730 * Used by an application to write arbitrary number of bytes to an SCM
1731 * port. Similar semantics as libc write. However, unlike libc
1732 * write, scm_c_write writes the requested number of bytes and has no
1733 * return value.
1734 *
1735 * Warning: Doesn't update port line and column counts!
1736 */
1737
1738 void
1739 scm_c_write (SCM port, const void *ptr, size_t size)
1740 #define FUNC_NAME "scm_c_write"
1741 {
1742 scm_t_port *pt;
1743 scm_t_ptob_descriptor *ptob;
1744
1745 SCM_VALIDATE_OPOUTPORT (1, port);
1746
1747 pt = SCM_PTAB_ENTRY (port);
1748 ptob = &scm_ptobs[SCM_PTOBNUM (port)];
1749
1750 if (pt->rw_active == SCM_PORT_READ)
1751 scm_end_input (port);
1752
1753 ptob->write (port, ptr, size);
1754
1755 if (pt->rw_random)
1756 pt->rw_active = SCM_PORT_WRITE;
1757 }
1758 #undef FUNC_NAME
1759
1760 void
1761 scm_flush (SCM port)
1762 {
1763 long i = SCM_PTOBNUM (port);
1764 assert (i >= 0);
1765 (scm_ptobs[i].flush) (port);
1766 }
1767
1768 void
1769 scm_end_input (SCM port)
1770 {
1771 long offset;
1772 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1773
1774 scm_i_clear_pending_eof (port);
1775 if (pt->read_buf == pt->putback_buf)
1776 {
1777 offset = pt->read_end - pt->read_pos;
1778 pt->read_buf = pt->saved_read_buf;
1779 pt->read_pos = pt->saved_read_pos;
1780 pt->read_end = pt->saved_read_end;
1781 pt->read_buf_size = pt->saved_read_buf_size;
1782 }
1783 else
1784 offset = 0;
1785
1786 scm_ptobs[SCM_PTOBNUM (port)].end_input (port, offset);
1787 }
1788
1789 \f
1790
1791
1792 static void
1793 scm_i_unget_bytes (const unsigned char *buf, size_t len, SCM port)
1794 #define FUNC_NAME "scm_unget_bytes"
1795 {
1796 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1797 size_t old_len, new_len;
1798
1799 scm_i_clear_pending_eof (port);
1800
1801 if (pt->read_buf != pt->putback_buf)
1802 /* switch to the put-back buffer. */
1803 {
1804 if (pt->putback_buf == NULL)
1805 {
1806 pt->putback_buf_size = (len > SCM_INITIAL_PUTBACK_BUF_SIZE
1807 ? len : SCM_INITIAL_PUTBACK_BUF_SIZE);
1808 pt->putback_buf
1809 = (unsigned char *) scm_gc_malloc_pointerless
1810 (pt->putback_buf_size, "putback buffer");
1811 }
1812
1813 pt->saved_read_buf = pt->read_buf;
1814 pt->saved_read_pos = pt->read_pos;
1815 pt->saved_read_end = pt->read_end;
1816 pt->saved_read_buf_size = pt->read_buf_size;
1817
1818 /* Put read_pos at the end of the buffer, so that ungets will not
1819 have to shift the buffer contents each time. */
1820 pt->read_buf = pt->putback_buf;
1821 pt->read_pos = pt->read_end = pt->putback_buf + pt->putback_buf_size;
1822 pt->read_buf_size = pt->putback_buf_size;
1823 }
1824
1825 old_len = pt->read_end - pt->read_pos;
1826 new_len = old_len + len;
1827
1828 if (new_len > pt->read_buf_size)
1829 /* The putback buffer needs to be enlarged. */
1830 {
1831 size_t new_buf_size;
1832 unsigned char *new_buf, *new_end, *new_pos;
1833
1834 new_buf_size = pt->read_buf_size * 2;
1835 if (new_buf_size < new_len)
1836 new_buf_size = new_len;
1837
1838 new_buf = (unsigned char *)
1839 scm_gc_malloc_pointerless (new_buf_size, "putback buffer");
1840
1841 /* Put the bytes at the end of the buffer, so that future
1842 ungets won't need to shift the buffer. */
1843 new_end = new_buf + new_buf_size;
1844 new_pos = new_end - old_len;
1845 memcpy (new_pos, pt->read_pos, old_len);
1846
1847 pt->read_buf = pt->putback_buf = new_buf;
1848 pt->read_pos = new_pos;
1849 pt->read_end = new_end;
1850 pt->read_buf_size = pt->putback_buf_size = new_buf_size;
1851 }
1852 else if (pt->read_buf + len < pt->read_pos)
1853 /* If needed, shift the existing buffer contents up.
1854 This should not happen unless some external code
1855 manipulates the putback buffer pointers. */
1856 {
1857 unsigned char *new_end = pt->read_buf + pt->read_buf_size;
1858 unsigned char *new_pos = new_end - old_len;
1859
1860 memmove (new_pos, pt->read_pos, old_len);
1861 pt->read_pos = new_pos;
1862 pt->read_end = new_end;
1863 }
1864
1865 /* Move read_pos back and copy the bytes there. */
1866 pt->read_pos -= len;
1867 memcpy (pt->read_buf + (pt->read_pos - pt->read_buf), buf, len);
1868
1869 if (pt->rw_active == SCM_PORT_WRITE)
1870 scm_flush (port);
1871
1872 if (pt->rw_random)
1873 pt->rw_active = SCM_PORT_READ;
1874 }
1875 #undef FUNC_NAME
1876
1877 void
1878 scm_unget_bytes (const unsigned char *buf, size_t len, SCM port)
1879 {
1880 scm_i_unget_bytes (buf, len, port);
1881 }
1882
1883 void
1884 scm_unget_byte (int c, SCM port)
1885 {
1886 unsigned char byte;
1887
1888 byte = c;
1889 scm_i_unget_bytes (&byte, 1, port);
1890 }
1891
1892 void
1893 scm_ungetc (scm_t_wchar c, SCM port)
1894 #define FUNC_NAME "scm_ungetc"
1895 {
1896 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1897 char *result;
1898 char result_buf[10];
1899 const char *encoding;
1900 size_t len;
1901
1902 if (pt->encoding != NULL)
1903 encoding = pt->encoding;
1904 else
1905 encoding = "ISO-8859-1";
1906
1907 len = sizeof (result_buf);
1908 result = u32_conv_to_encoding (encoding,
1909 (enum iconv_ilseq_handler) pt->ilseq_handler,
1910 (uint32_t *) &c, 1, NULL,
1911 result_buf, &len);
1912
1913 if (SCM_UNLIKELY (result == NULL || len == 0))
1914 scm_encoding_error (FUNC_NAME, errno,
1915 "conversion to port encoding failed",
1916 SCM_BOOL_F, SCM_MAKE_CHAR (c));
1917
1918 scm_i_unget_bytes ((unsigned char *) result, len, port);
1919
1920 if (SCM_UNLIKELY (result != result_buf))
1921 free (result);
1922
1923 if (c == '\n')
1924 {
1925 /* What should col be in this case?
1926 * We'll leave it at -1.
1927 */
1928 SCM_LINUM (port) -= 1;
1929 }
1930 else
1931 SCM_COL(port) -= 1;
1932 }
1933 #undef FUNC_NAME
1934
1935
1936 void
1937 scm_ungets (const char *s, int n, SCM port)
1938 {
1939 /* This is simple minded and inefficient, but unreading strings is
1940 * probably not a common operation, and remember that line and
1941 * column numbers have to be handled...
1942 *
1943 * Please feel free to write an optimized version!
1944 */
1945 while (n--)
1946 scm_ungetc (s[n], port);
1947 }
1948
1949
1950 SCM_DEFINE (scm_peek_char, "peek-char", 0, 1, 0,
1951 (SCM port),
1952 "Return the next character available from @var{port},\n"
1953 "@emph{without} updating @var{port} to point to the following\n"
1954 "character. If no more characters are available, the\n"
1955 "end-of-file object is returned.\n"
1956 "\n"
1957 "The value returned by\n"
1958 "a call to @code{peek-char} is the same as the value that would\n"
1959 "have been returned by a call to @code{read-char} on the same\n"
1960 "port. The only difference is that the very next call to\n"
1961 "@code{read-char} or @code{peek-char} on that @var{port} will\n"
1962 "return the value returned by the preceding call to\n"
1963 "@code{peek-char}. In particular, a call to @code{peek-char} on\n"
1964 "an interactive port will hang waiting for input whenever a call\n"
1965 "to @code{read-char} would have hung.\n"
1966 "\n"
1967 "As for @code{read-char}, a @code{decoding-error} may be raised\n"
1968 "if such a situation occurs. However, unlike with @code{read-char},\n"
1969 "@var{port} still points at the beginning of the erroneous byte\n"
1970 "sequence when the error is raised.\n")
1971 #define FUNC_NAME s_scm_peek_char
1972 {
1973 int err;
1974 SCM result;
1975 scm_t_wchar c;
1976 char bytes[SCM_MBCHAR_BUF_SIZE];
1977 long column, line;
1978 size_t len;
1979
1980 if (SCM_UNBNDP (port))
1981 port = scm_current_input_port ();
1982 SCM_VALIDATE_OPINPORT (1, port);
1983
1984 column = SCM_COL (port);
1985 line = SCM_LINUM (port);
1986
1987 err = get_codepoint (port, &c, bytes, &len);
1988
1989 scm_i_unget_bytes ((unsigned char *) bytes, len, port);
1990
1991 SCM_COL (port) = column;
1992 SCM_LINUM (port) = line;
1993
1994 if (SCM_UNLIKELY (err != 0))
1995 {
1996 scm_decoding_error (FUNC_NAME, err, "input decoding error", port);
1997
1998 /* Shouldn't happen since `catch' always aborts to prompt. */
1999 result = SCM_BOOL_F;
2000 }
2001 else if (c == EOF)
2002 {
2003 scm_i_set_pending_eof (port);
2004 result = SCM_EOF_VAL;
2005 }
2006 else
2007 result = SCM_MAKE_CHAR (c);
2008
2009 return result;
2010 }
2011 #undef FUNC_NAME
2012
2013 SCM_DEFINE (scm_unread_char, "unread-char", 1, 1, 0,
2014 (SCM cobj, SCM port),
2015 "Place character @var{cobj} in @var{port} so that it will be\n"
2016 "read by the next read operation. If called multiple times, the\n"
2017 "unread characters will be read again in last-in first-out\n"
2018 "order. If @var{port} is not supplied, the current input port\n"
2019 "is used.")
2020 #define FUNC_NAME s_scm_unread_char
2021 {
2022 int c;
2023
2024 SCM_VALIDATE_CHAR (1, cobj);
2025 if (SCM_UNBNDP (port))
2026 port = scm_current_input_port ();
2027 SCM_VALIDATE_OPINPORT (2, port);
2028
2029 c = SCM_CHAR (cobj);
2030
2031 scm_ungetc (c, port);
2032 return cobj;
2033 }
2034 #undef FUNC_NAME
2035
2036 SCM_DEFINE (scm_unread_string, "unread-string", 2, 0, 0,
2037 (SCM str, SCM port),
2038 "Place the string @var{str} in @var{port} so that its characters will be\n"
2039 "read in subsequent read operations. If called multiple times, the\n"
2040 "unread characters will be read again in last-in first-out order. If\n"
2041 "@var{port} is not supplied, the current-input-port is used.")
2042 #define FUNC_NAME s_scm_unread_string
2043 {
2044 int n;
2045 SCM_VALIDATE_STRING (1, str);
2046 if (SCM_UNBNDP (port))
2047 port = scm_current_input_port ();
2048 SCM_VALIDATE_OPINPORT (2, port);
2049
2050 n = scm_i_string_length (str);
2051
2052 while (n--)
2053 scm_ungetc (scm_i_string_ref (str, n), port);
2054
2055 return str;
2056 }
2057 #undef FUNC_NAME
2058
2059 SCM_DEFINE (scm_seek, "seek", 3, 0, 0,
2060 (SCM fd_port, SCM offset, SCM whence),
2061 "Sets the current position of @var{fd_port} to the integer\n"
2062 "@var{offset}, which is interpreted according to the value of\n"
2063 "@var{whence}.\n"
2064 "\n"
2065 "One of the following variables should be supplied for\n"
2066 "@var{whence}:\n"
2067 "@defvar SEEK_SET\n"
2068 "Seek from the beginning of the file.\n"
2069 "@end defvar\n"
2070 "@defvar SEEK_CUR\n"
2071 "Seek from the current position.\n"
2072 "@end defvar\n"
2073 "@defvar SEEK_END\n"
2074 "Seek from the end of the file.\n"
2075 "@end defvar\n"
2076 "If @var{fd_port} is a file descriptor, the underlying system\n"
2077 "call is @code{lseek}. @var{port} may be a string port.\n"
2078 "\n"
2079 "The value returned is the new position in the file. This means\n"
2080 "that the current position of a port can be obtained using:\n"
2081 "@lisp\n"
2082 "(seek port 0 SEEK_CUR)\n"
2083 "@end lisp")
2084 #define FUNC_NAME s_scm_seek
2085 {
2086 int how;
2087
2088 fd_port = SCM_COERCE_OUTPORT (fd_port);
2089
2090 how = scm_to_int (whence);
2091 if (how != SEEK_SET && how != SEEK_CUR && how != SEEK_END)
2092 SCM_OUT_OF_RANGE (3, whence);
2093
2094 if (SCM_OPPORTP (fd_port))
2095 {
2096 scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (fd_port);
2097 scm_t_ptob_descriptor *ptob = scm_ptobs + SCM_PTOBNUM (fd_port);
2098 off_t_or_off64_t off = scm_to_off_t_or_off64_t (offset);
2099 off_t_or_off64_t rv;
2100
2101 if (!ptob->seek)
2102 SCM_MISC_ERROR ("port is not seekable",
2103 scm_cons (fd_port, SCM_EOL));
2104 else
2105 rv = ptob->seek (fd_port, off, how);
2106
2107 /* Set stream-start flags according to new position. */
2108 pti->at_stream_start_for_bom_read = (rv == 0);
2109 pti->at_stream_start_for_bom_write = (rv == 0);
2110
2111 scm_i_clear_pending_eof (fd_port);
2112
2113 return scm_from_off_t_or_off64_t (rv);
2114 }
2115 else /* file descriptor?. */
2116 {
2117 off_t_or_off64_t off = scm_to_off_t_or_off64_t (offset);
2118 off_t_or_off64_t rv;
2119 rv = lseek_or_lseek64 (scm_to_int (fd_port), off, how);
2120 if (rv == -1)
2121 SCM_SYSERROR;
2122 return scm_from_off_t_or_off64_t (rv);
2123 }
2124 }
2125 #undef FUNC_NAME
2126
2127 #ifndef O_BINARY
2128 #define O_BINARY 0
2129 #endif
2130
2131 /* Mingw has ftruncate(), perhaps implemented above using chsize, but
2132 doesn't have the filename version truncate(), hence this code. */
2133 #if HAVE_FTRUNCATE && ! HAVE_TRUNCATE
2134 static int
2135 truncate (const char *file, off_t length)
2136 {
2137 int ret, fdes;
2138
2139 fdes = open (file, O_BINARY | O_WRONLY);
2140 if (fdes == -1)
2141 return -1;
2142
2143 ret = ftruncate (fdes, length);
2144 if (ret == -1)
2145 {
2146 int save_errno = errno;
2147 close (fdes);
2148 errno = save_errno;
2149 return -1;
2150 }
2151
2152 return close (fdes);
2153 }
2154 #endif /* HAVE_FTRUNCATE && ! HAVE_TRUNCATE */
2155
2156 SCM_DEFINE (scm_truncate_file, "truncate-file", 1, 1, 0,
2157 (SCM object, SCM length),
2158 "Truncate file @var{object} to @var{length} bytes. @var{object}\n"
2159 "can be a filename string, a port object, or an integer file\n"
2160 "descriptor.\n"
2161 "The return value is unspecified.\n"
2162 "\n"
2163 "For a port or file descriptor @var{length} can be omitted, in\n"
2164 "which case the file is truncated at the current position (per\n"
2165 "@code{ftell} above).\n"
2166 "\n"
2167 "On most systems a file can be extended by giving a length\n"
2168 "greater than the current size, but this is not mandatory in the\n"
2169 "POSIX standard.")
2170 #define FUNC_NAME s_scm_truncate_file
2171 {
2172 int rv;
2173
2174 /* "object" can be a port, fdes or filename.
2175
2176 Negative "length" makes no sense, but it's left to truncate() or
2177 ftruncate() to give back an error for that (normally EINVAL).
2178 */
2179
2180 if (SCM_UNBNDP (length))
2181 {
2182 /* must supply length if object is a filename. */
2183 if (scm_is_string (object))
2184 SCM_MISC_ERROR("must supply length if OBJECT is a filename", SCM_EOL);
2185
2186 length = scm_seek (object, SCM_INUM0, scm_from_int (SEEK_CUR));
2187 }
2188
2189 object = SCM_COERCE_OUTPORT (object);
2190 if (scm_is_integer (object))
2191 {
2192 off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
2193 SCM_SYSCALL (rv = ftruncate_or_ftruncate64 (scm_to_int (object),
2194 c_length));
2195 }
2196 else if (SCM_OPOUTPORTP (object))
2197 {
2198 off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
2199 scm_t_port *pt = SCM_PTAB_ENTRY (object);
2200 scm_t_ptob_descriptor *ptob = scm_ptobs + SCM_PTOBNUM (object);
2201
2202 if (!ptob->truncate)
2203 SCM_MISC_ERROR ("port is not truncatable", SCM_EOL);
2204
2205 scm_i_clear_pending_eof (object);
2206 if (pt->rw_active == SCM_PORT_READ)
2207 scm_end_input (object);
2208 else if (pt->rw_active == SCM_PORT_WRITE)
2209 ptob->flush (object);
2210
2211 ptob->truncate (object, c_length);
2212 rv = 0;
2213 }
2214 else
2215 {
2216 off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
2217 char *str = scm_to_locale_string (object);
2218 int eno;
2219 SCM_SYSCALL (rv = truncate_or_truncate64 (str, c_length));
2220 eno = errno;
2221 free (str);
2222 errno = eno;
2223 }
2224 if (rv == -1)
2225 SCM_SYSERROR;
2226 return SCM_UNSPECIFIED;
2227 }
2228 #undef FUNC_NAME
2229
2230 SCM_DEFINE (scm_port_line, "port-line", 1, 0, 0,
2231 (SCM port),
2232 "Return the current line number for @var{port}.\n"
2233 "\n"
2234 "The first line of a file is 0. But you might want to add 1\n"
2235 "when printing line numbers, since starting from 1 is\n"
2236 "traditional in error messages, and likely to be more natural to\n"
2237 "non-programmers.")
2238 #define FUNC_NAME s_scm_port_line
2239 {
2240 port = SCM_COERCE_OUTPORT (port);
2241 SCM_VALIDATE_OPENPORT (1, port);
2242 return scm_from_long (SCM_LINUM (port));
2243 }
2244 #undef FUNC_NAME
2245
2246 SCM_DEFINE (scm_set_port_line_x, "set-port-line!", 2, 0, 0,
2247 (SCM port, SCM line),
2248 "Set the current line number for @var{port} to @var{line}. The\n"
2249 "first line of a file is 0.")
2250 #define FUNC_NAME s_scm_set_port_line_x
2251 {
2252 port = SCM_COERCE_OUTPORT (port);
2253 SCM_VALIDATE_OPENPORT (1, port);
2254 SCM_PTAB_ENTRY (port)->line_number = scm_to_long (line);
2255 return SCM_UNSPECIFIED;
2256 }
2257 #undef FUNC_NAME
2258
2259 SCM_DEFINE (scm_port_column, "port-column", 1, 0, 0,
2260 (SCM port),
2261 "Return the current column number of @var{port}.\n"
2262 "If the number is\n"
2263 "unknown, the result is #f. Otherwise, the result is a 0-origin integer\n"
2264 "- i.e. the first character of the first line is line 0, column 0.\n"
2265 "(However, when you display a file position, for example in an error\n"
2266 "message, we recommend you add 1 to get 1-origin integers. This is\n"
2267 "because lines and column numbers traditionally start with 1, and that is\n"
2268 "what non-programmers will find most natural.)")
2269 #define FUNC_NAME s_scm_port_column
2270 {
2271 port = SCM_COERCE_OUTPORT (port);
2272 SCM_VALIDATE_OPENPORT (1, port);
2273 return scm_from_int (SCM_COL (port));
2274 }
2275 #undef FUNC_NAME
2276
2277 SCM_DEFINE (scm_set_port_column_x, "set-port-column!", 2, 0, 0,
2278 (SCM port, SCM column),
2279 "Set the current column of @var{port}. Before reading the first\n"
2280 "character on a line the column should be 0.")
2281 #define FUNC_NAME s_scm_set_port_column_x
2282 {
2283 port = SCM_COERCE_OUTPORT (port);
2284 SCM_VALIDATE_OPENPORT (1, port);
2285 SCM_PTAB_ENTRY (port)->column_number = scm_to_int (column);
2286 return SCM_UNSPECIFIED;
2287 }
2288 #undef FUNC_NAME
2289
2290 SCM_DEFINE (scm_port_filename, "port-filename", 1, 0, 0,
2291 (SCM port),
2292 "Return the filename associated with @var{port}, or @code{#f}\n"
2293 "if no filename is associated with the port.")
2294 #define FUNC_NAME s_scm_port_filename
2295 {
2296 port = SCM_COERCE_OUTPORT (port);
2297 SCM_VALIDATE_OPENPORT (1, port);
2298 return SCM_FILENAME (port);
2299 }
2300 #undef FUNC_NAME
2301
2302 SCM_DEFINE (scm_set_port_filename_x, "set-port-filename!", 2, 0, 0,
2303 (SCM port, SCM filename),
2304 "Change the filename associated with @var{port}, using the current input\n"
2305 "port if none is specified. Note that this does not change the port's\n"
2306 "source of data, but only the value that is returned by\n"
2307 "@code{port-filename} and reported in diagnostic output.")
2308 #define FUNC_NAME s_scm_set_port_filename_x
2309 {
2310 port = SCM_COERCE_OUTPORT (port);
2311 SCM_VALIDATE_OPENPORT (1, port);
2312 /* We allow the user to set the filename to whatever he likes. */
2313 SCM_SET_FILENAME (port, filename);
2314 return SCM_UNSPECIFIED;
2315 }
2316 #undef FUNC_NAME
2317
2318 /* A fluid specifying the default encoding for newly created ports. If it is
2319 a string, that is the encoding. If it is #f, it is in the "native"
2320 (Latin-1) encoding. */
2321 SCM_VARIABLE (default_port_encoding_var, "%default-port-encoding");
2322
2323 static int scm_port_encoding_init = 0;
2324
2325 /* Use ENCODING as the default encoding for future ports. */
2326 void
2327 scm_i_set_default_port_encoding (const char *encoding)
2328 {
2329 if (!scm_port_encoding_init
2330 || !scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var)))
2331 scm_misc_error (NULL, "tried to set port encoding fluid before it is initialized",
2332 SCM_EOL);
2333
2334 if (encoding == NULL
2335 || c_strcasecmp (encoding, "ASCII") == 0
2336 || c_strcasecmp (encoding, "ANSI_X3.4-1968") == 0
2337 || c_strcasecmp (encoding, "ISO-8859-1") == 0)
2338 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var), SCM_BOOL_F);
2339 else
2340 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var),
2341 scm_from_locale_string (encoding));
2342 }
2343
2344 /* Return the name of the default encoding for newly created ports; a
2345 return value of NULL means "ISO-8859-1". */
2346 const char *
2347 scm_i_default_port_encoding (void)
2348 {
2349 if (!scm_port_encoding_init)
2350 return NULL;
2351 else if (!scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var)))
2352 return NULL;
2353 else
2354 {
2355 SCM encoding;
2356
2357 encoding = scm_fluid_ref (SCM_VARIABLE_REF (default_port_encoding_var));
2358 if (!scm_is_string (encoding))
2359 return NULL;
2360 else
2361 return scm_i_string_chars (encoding);
2362 }
2363 }
2364
2365 /* If the next LEN bytes from PORT are equal to those in BYTES, then
2366 return 1, else return 0. Leave the port position unchanged. */
2367 static int
2368 looking_at_bytes (SCM port, const unsigned char *bytes, int len)
2369 {
2370 scm_t_port *pt = SCM_PTAB_ENTRY (port);
2371 int i = 0;
2372
2373 while (i < len && scm_peek_byte_or_eof (port) == bytes[i])
2374 {
2375 pt->read_pos++;
2376 i++;
2377 }
2378 scm_i_unget_bytes (bytes, i, port);
2379 return (i == len);
2380 }
2381
2382 static const unsigned char scm_utf8_bom[3] = {0xEF, 0xBB, 0xBF};
2383 static const unsigned char scm_utf16be_bom[2] = {0xFE, 0xFF};
2384 static const unsigned char scm_utf16le_bom[2] = {0xFF, 0xFE};
2385 static const unsigned char scm_utf32be_bom[4] = {0x00, 0x00, 0xFE, 0xFF};
2386 static const unsigned char scm_utf32le_bom[4] = {0xFF, 0xFE, 0x00, 0x00};
2387
2388 /* Decide what byte order to use for a UTF-16 port. Return "UTF-16BE"
2389 or "UTF-16LE". MODE must be either SCM_PORT_READ or SCM_PORT_WRITE,
2390 and specifies which operation is about to be done. The MODE
2391 determines how we will decide the byte order. We deliberately avoid
2392 reading from the port unless the user is about to do so. If the user
2393 is about to read, then we look for a BOM, and if present, we use it
2394 to determine the byte order. Otherwise we choose big endian, as
2395 recommended by the Unicode Standard. Note that the BOM (if any) is
2396 not consumed here. */
2397 static const char *
2398 decide_utf16_encoding (SCM port, scm_t_port_rw_active mode)
2399 {
2400 if (mode == SCM_PORT_READ
2401 && SCM_PORT_GET_INTERNAL (port)->at_stream_start_for_bom_read
2402 && looking_at_bytes (port, scm_utf16le_bom, sizeof scm_utf16le_bom))
2403 return "UTF-16LE";
2404 else
2405 return "UTF-16BE";
2406 }
2407
2408 /* Decide what byte order to use for a UTF-32 port. Return "UTF-32BE"
2409 or "UTF-32LE". See the comment above 'decide_utf16_encoding' for
2410 details. */
2411 static const char *
2412 decide_utf32_encoding (SCM port, scm_t_port_rw_active mode)
2413 {
2414 if (mode == SCM_PORT_READ
2415 && SCM_PORT_GET_INTERNAL (port)->at_stream_start_for_bom_read
2416 && looking_at_bytes (port, scm_utf32le_bom, sizeof scm_utf32le_bom))
2417 return "UTF-32LE";
2418 else
2419 return "UTF-32BE";
2420 }
2421
2422 static void
2423 finalize_iconv_descriptors (void *ptr, void *data)
2424 {
2425 close_iconv_descriptors (ptr);
2426 }
2427
2428 static scm_t_iconv_descriptors *
2429 open_iconv_descriptors (const char *encoding, int reading, int writing)
2430 {
2431 scm_t_iconv_descriptors *id;
2432 iconv_t input_cd, output_cd;
2433
2434 input_cd = (iconv_t) -1;
2435 output_cd = (iconv_t) -1;
2436 if (reading)
2437 {
2438 /* Open an input iconv conversion descriptor, from ENCODING
2439 to UTF-8. We choose UTF-8, not UTF-32, because iconv
2440 implementations can typically convert from anything to
2441 UTF-8, but not to UTF-32 (see
2442 <http://lists.gnu.org/archive/html/bug-libunistring/2010-09/msg00007.html>). */
2443
2444 /* Assume opening an iconv descriptor causes about 16 KB of
2445 allocation. */
2446 scm_gc_register_allocation (16 * 1024);
2447
2448 input_cd = iconv_open ("UTF-8", encoding);
2449 if (input_cd == (iconv_t) -1)
2450 goto invalid_encoding;
2451 }
2452
2453 if (writing)
2454 {
2455 /* Assume opening an iconv descriptor causes about 16 KB of
2456 allocation. */
2457 scm_gc_register_allocation (16 * 1024);
2458
2459 output_cd = iconv_open (encoding, "UTF-8");
2460 if (output_cd == (iconv_t) -1)
2461 {
2462 if (input_cd != (iconv_t) -1)
2463 iconv_close (input_cd);
2464 goto invalid_encoding;
2465 }
2466 }
2467
2468 id = scm_gc_malloc_pointerless (sizeof (*id), "iconv descriptors");
2469 id->input_cd = input_cd;
2470 id->output_cd = output_cd;
2471
2472 /* Register a finalizer to close the descriptors. */
2473 scm_i_set_finalizer (id, finalize_iconv_descriptors, NULL);
2474
2475 return id;
2476
2477 invalid_encoding:
2478 {
2479 SCM err;
2480 err = scm_from_locale_string (encoding);
2481 scm_misc_error ("open_iconv_descriptors",
2482 "invalid or unknown character encoding ~s",
2483 scm_list_1 (err));
2484 }
2485 }
2486
2487 static void
2488 close_iconv_descriptors (scm_t_iconv_descriptors *id)
2489 {
2490 if (id->input_cd != (iconv_t) -1)
2491 iconv_close (id->input_cd);
2492 if (id->output_cd != (iconv_t) -1)
2493 iconv_close (id->output_cd);
2494 id->input_cd = (void *) -1;
2495 id->output_cd = (void *) -1;
2496 }
2497
2498 /* Return the iconv_descriptors, initializing them if necessary. MODE
2499 must be either SCM_PORT_READ or SCM_PORT_WRITE, and specifies which
2500 operation is about to be done. We deliberately avoid reading from
2501 the port unless the user was about to do so. */
2502 scm_t_iconv_descriptors *
2503 scm_i_port_iconv_descriptors (SCM port, scm_t_port_rw_active mode)
2504 {
2505 scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
2506
2507 assert (pti->encoding_mode == SCM_PORT_ENCODING_MODE_ICONV);
2508
2509 if (!pti->iconv_descriptors)
2510 {
2511 scm_t_port *pt = SCM_PTAB_ENTRY (port);
2512 const char *precise_encoding;
2513
2514 if (!pt->encoding)
2515 pt->encoding = "ISO-8859-1";
2516
2517 /* If the specified encoding is UTF-16 or UTF-32, then make
2518 that more precise by deciding what byte order to use. */
2519 if (c_strcasecmp (pt->encoding, "UTF-16") == 0)
2520 precise_encoding = decide_utf16_encoding (port, mode);
2521 else if (c_strcasecmp (pt->encoding, "UTF-32") == 0)
2522 precise_encoding = decide_utf32_encoding (port, mode);
2523 else
2524 precise_encoding = pt->encoding;
2525
2526 pti->iconv_descriptors =
2527 open_iconv_descriptors (precise_encoding,
2528 SCM_INPUT_PORT_P (port),
2529 SCM_OUTPUT_PORT_P (port));
2530 }
2531
2532 return pti->iconv_descriptors;
2533 }
2534
2535 void
2536 scm_i_set_port_encoding_x (SCM port, const char *encoding)
2537 {
2538 scm_t_port *pt;
2539 scm_t_port_internal *pti;
2540 scm_t_iconv_descriptors *prev;
2541
2542 /* Set the character encoding for this port. */
2543 pt = SCM_PTAB_ENTRY (port);
2544 pti = SCM_PORT_GET_INTERNAL (port);
2545 prev = pti->iconv_descriptors;
2546
2547 /* In order to handle cases where the encoding changes mid-stream
2548 (e.g. within an HTTP stream, or within a file that is composed of
2549 segments with different encodings), we consider this to be "stream
2550 start" for purposes of BOM handling, regardless of our actual file
2551 position. */
2552 pti->at_stream_start_for_bom_read = 1;
2553 pti->at_stream_start_for_bom_write = 1;
2554
2555 if (encoding == NULL)
2556 encoding = "ISO-8859-1";
2557
2558 /* If ENCODING is UTF-8, then no conversion descriptor is opened
2559 because we do I/O ourselves. This saves 100+ KiB for each
2560 descriptor. */
2561 pt->encoding = scm_gc_strdup (encoding, "port");
2562 if (c_strcasecmp (encoding, "UTF-8") == 0)
2563 pti->encoding_mode = SCM_PORT_ENCODING_MODE_UTF8;
2564 else
2565 pti->encoding_mode = SCM_PORT_ENCODING_MODE_ICONV;
2566
2567 pti->iconv_descriptors = NULL;
2568 if (prev)
2569 close_iconv_descriptors (prev);
2570 }
2571
2572 SCM_DEFINE (scm_port_encoding, "port-encoding", 1, 0, 0,
2573 (SCM port),
2574 "Returns, as a string, the character encoding that @var{port}\n"
2575 "uses to interpret its input and output.\n")
2576 #define FUNC_NAME s_scm_port_encoding
2577 {
2578 scm_t_port *pt;
2579 const char *enc;
2580
2581 SCM_VALIDATE_PORT (1, port);
2582
2583 pt = SCM_PTAB_ENTRY (port);
2584 enc = pt->encoding;
2585 if (enc)
2586 return scm_from_locale_string (pt->encoding);
2587 else
2588 return SCM_BOOL_F;
2589 }
2590 #undef FUNC_NAME
2591
2592 SCM_DEFINE (scm_set_port_encoding_x, "set-port-encoding!", 2, 0, 0,
2593 (SCM port, SCM enc),
2594 "Sets the character encoding that will be used to interpret all\n"
2595 "port I/O. New ports are created with the encoding\n"
2596 "appropriate for the current locale if @code{setlocale} has \n"
2597 "been called or ISO-8859-1 otherwise\n"
2598 "and this procedure can be used to modify that encoding.\n")
2599 #define FUNC_NAME s_scm_set_port_encoding_x
2600 {
2601 char *enc_str;
2602
2603 SCM_VALIDATE_PORT (1, port);
2604 SCM_VALIDATE_STRING (2, enc);
2605
2606 enc_str = scm_to_locale_string (enc);
2607 scm_i_set_port_encoding_x (port, enc_str);
2608 free (enc_str);
2609
2610 return SCM_UNSPECIFIED;
2611 }
2612 #undef FUNC_NAME
2613
2614
2615 /* A fluid specifying the default conversion handler for newly created
2616 ports. Its value should be one of the symbols below. */
2617 SCM_VARIABLE (default_conversion_strategy_var,
2618 "%default-port-conversion-strategy");
2619
2620 /* Whether the above fluid is initialized. */
2621 static int scm_conversion_strategy_init = 0;
2622
2623 /* The possible conversion strategies. */
2624 SCM_SYMBOL (sym_error, "error");
2625 SCM_SYMBOL (sym_substitute, "substitute");
2626 SCM_SYMBOL (sym_escape, "escape");
2627
2628 /* Return the default failed encoding conversion policy for new created
2629 ports. */
2630 scm_t_string_failed_conversion_handler
2631 scm_i_default_port_conversion_handler (void)
2632 {
2633 scm_t_string_failed_conversion_handler handler;
2634
2635 if (!scm_conversion_strategy_init
2636 || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var)))
2637 handler = SCM_FAILED_CONVERSION_QUESTION_MARK;
2638 else
2639 {
2640 SCM fluid, value;
2641
2642 fluid = SCM_VARIABLE_REF (default_conversion_strategy_var);
2643 value = scm_fluid_ref (fluid);
2644
2645 if (scm_is_eq (sym_substitute, value))
2646 handler = SCM_FAILED_CONVERSION_QUESTION_MARK;
2647 else if (scm_is_eq (sym_escape, value))
2648 handler = SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE;
2649 else
2650 /* Default to 'error also when the fluid's value is not one of
2651 the valid symbols. */
2652 handler = SCM_FAILED_CONVERSION_ERROR;
2653 }
2654
2655 return handler;
2656 }
2657
2658 /* Use HANDLER as the default conversion strategy for future ports. */
2659 void
2660 scm_i_set_default_port_conversion_handler (scm_t_string_failed_conversion_handler
2661 handler)
2662 {
2663 SCM strategy;
2664
2665 if (!scm_conversion_strategy_init
2666 || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var)))
2667 scm_misc_error (NULL, "tried to set conversion strategy fluid before it is initialized",
2668 SCM_EOL);
2669
2670 switch (handler)
2671 {
2672 case SCM_FAILED_CONVERSION_ERROR:
2673 strategy = sym_error;
2674 break;
2675
2676 case SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE:
2677 strategy = sym_escape;
2678 break;
2679
2680 case SCM_FAILED_CONVERSION_QUESTION_MARK:
2681 strategy = sym_substitute;
2682 break;
2683
2684 default:
2685 abort ();
2686 }
2687
2688 scm_fluid_set_x (SCM_VARIABLE_REF (default_conversion_strategy_var),
2689 strategy);
2690 }
2691
2692 SCM_DEFINE (scm_port_conversion_strategy, "port-conversion-strategy",
2693 1, 0, 0, (SCM port),
2694 "Returns the behavior of the port when handling a character that\n"
2695 "is not representable in the port's current encoding.\n"
2696 "It returns the symbol @code{error} if unrepresentable characters\n"
2697 "should cause exceptions, @code{substitute} if the port should\n"
2698 "try to replace unrepresentable characters with question marks or\n"
2699 "approximate characters, or @code{escape} if unrepresentable\n"
2700 "characters should be converted to string escapes.\n"
2701 "\n"
2702 "If @var{port} is @code{#f}, then the current default behavior\n"
2703 "will be returned. New ports will have this default behavior\n"
2704 "when they are created.\n")
2705 #define FUNC_NAME s_scm_port_conversion_strategy
2706 {
2707 scm_t_string_failed_conversion_handler h;
2708
2709 if (scm_is_false (port))
2710 h = scm_i_default_port_conversion_handler ();
2711 else
2712 {
2713 scm_t_port *pt;
2714
2715 SCM_VALIDATE_OPPORT (1, port);
2716 pt = SCM_PTAB_ENTRY (port);
2717
2718 h = pt->ilseq_handler;
2719 }
2720
2721 if (h == SCM_FAILED_CONVERSION_ERROR)
2722 return scm_from_latin1_symbol ("error");
2723 else if (h == SCM_FAILED_CONVERSION_QUESTION_MARK)
2724 return scm_from_latin1_symbol ("substitute");
2725 else if (h == SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE)
2726 return scm_from_latin1_symbol ("escape");
2727 else
2728 abort ();
2729
2730 /* Never gets here. */
2731 return SCM_UNDEFINED;
2732 }
2733 #undef FUNC_NAME
2734
2735 SCM_DEFINE (scm_set_port_conversion_strategy_x, "set-port-conversion-strategy!",
2736 2, 0, 0,
2737 (SCM port, SCM sym),
2738 "Sets the behavior of the interpreter when outputting a character\n"
2739 "that is not representable in the port's current encoding.\n"
2740 "@var{sym} can be either @code{'error}, @code{'substitute}, or\n"
2741 "@code{'escape}. If it is @code{'error}, an error will be thrown\n"
2742 "when an unconvertible character is encountered. If it is\n"
2743 "@code{'substitute}, then unconvertible characters will \n"
2744 "be replaced with approximate characters, or with question marks\n"
2745 "if no approximately correct character is available.\n"
2746 "If it is @code{'escape},\n"
2747 "it will appear as a hex escape when output.\n"
2748 "\n"
2749 "If @var{port} is an open port, the conversion error behavior\n"
2750 "is set for that port. If it is @code{#f}, it is set as the\n"
2751 "default behavior for any future ports that get created in\n"
2752 "this thread.\n")
2753 #define FUNC_NAME s_scm_set_port_conversion_strategy_x
2754 {
2755 scm_t_string_failed_conversion_handler handler;
2756
2757 if (scm_is_eq (sym, sym_error))
2758 handler = SCM_FAILED_CONVERSION_ERROR;
2759 else if (scm_is_eq (sym, sym_substitute))
2760 handler = SCM_FAILED_CONVERSION_QUESTION_MARK;
2761 else if (scm_is_eq (sym, sym_escape))
2762 handler = SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE;
2763 else
2764 SCM_MISC_ERROR ("unknown conversion strategy ~s", scm_list_1 (sym));
2765
2766 if (scm_is_false (port))
2767 scm_i_set_default_port_conversion_handler (handler);
2768 else
2769 {
2770 SCM_VALIDATE_OPPORT (1, port);
2771 SCM_PTAB_ENTRY (port)->ilseq_handler = handler;
2772 }
2773
2774 return SCM_UNSPECIFIED;
2775 }
2776 #undef FUNC_NAME
2777
2778
2779
2780 void
2781 scm_print_port_mode (SCM exp, SCM port)
2782 {
2783 scm_puts (SCM_CLOSEDP (exp)
2784 ? "closed: "
2785 : (SCM_RDNG & SCM_CELL_WORD_0 (exp)
2786 ? (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
2787 ? "input-output: "
2788 : "input: ")
2789 : (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
2790 ? "output: "
2791 : "bogus: ")),
2792 port);
2793 }
2794
2795 int
2796 scm_port_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
2797 {
2798 char *type = SCM_PTOBNAME (SCM_PTOBNUM (exp));
2799 if (!type)
2800 type = "port";
2801 scm_puts ("#<", port);
2802 scm_print_port_mode (exp, port);
2803 scm_puts (type, port);
2804 scm_putc (' ', port);
2805 scm_uintprint (SCM_CELL_WORD_1 (exp), 16, port);
2806 scm_putc ('>', port);
2807 return 1;
2808 }
2809
2810 \f
2811
2812 /* Void ports. */
2813
2814 scm_t_bits scm_tc16_void_port = 0;
2815
2816 static int fill_input_void_port (SCM port SCM_UNUSED)
2817 {
2818 return EOF;
2819 }
2820
2821 static void
2822 write_void_port (SCM port SCM_UNUSED,
2823 const void *data SCM_UNUSED,
2824 size_t size SCM_UNUSED)
2825 {
2826 }
2827
2828 static SCM
2829 scm_i_void_port (long mode_bits)
2830 {
2831 scm_i_scm_pthread_mutex_lock (&scm_i_port_table_mutex);
2832 {
2833 SCM answer = scm_new_port_table_entry (scm_tc16_void_port);
2834 scm_t_port * pt = SCM_PTAB_ENTRY(answer);
2835
2836 scm_port_non_buffer (pt);
2837
2838 SCM_SETSTREAM (answer, 0);
2839 SCM_SET_CELL_TYPE (answer, scm_tc16_void_port | mode_bits);
2840 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
2841 return answer;
2842 }
2843 }
2844
2845 SCM
2846 scm_void_port (char *mode_str)
2847 {
2848 return scm_i_void_port (scm_mode_bits (mode_str));
2849 }
2850
2851 SCM_DEFINE (scm_sys_make_void_port, "%make-void-port", 1, 0, 0,
2852 (SCM mode),
2853 "Create and return a new void port. A void port acts like\n"
2854 "@file{/dev/null}. The @var{mode} argument\n"
2855 "specifies the input/output modes for this port: see the\n"
2856 "documentation for @code{open-file} in @ref{File Ports}.")
2857 #define FUNC_NAME s_scm_sys_make_void_port
2858 {
2859 return scm_i_void_port (scm_i_mode_bits (mode));
2860 }
2861 #undef FUNC_NAME
2862
2863 \f
2864 /* Initialization. */
2865
2866 void
2867 scm_init_ports ()
2868 {
2869 /* lseek() symbols. */
2870 scm_c_define ("SEEK_SET", scm_from_int (SEEK_SET));
2871 scm_c_define ("SEEK_CUR", scm_from_int (SEEK_CUR));
2872 scm_c_define ("SEEK_END", scm_from_int (SEEK_END));
2873
2874 scm_tc16_void_port = scm_make_port_type ("void", fill_input_void_port,
2875 write_void_port);
2876
2877 cur_inport_fluid = scm_make_fluid ();
2878 cur_outport_fluid = scm_make_fluid ();
2879 cur_errport_fluid = scm_make_fluid ();
2880 cur_loadport_fluid = scm_make_fluid ();
2881
2882 scm_i_port_weak_hash = scm_make_weak_key_hash_table (SCM_I_MAKINUM(31));
2883
2884 #include "libguile/ports.x"
2885
2886 /* Use Latin-1 as the default port encoding. */
2887 SCM_VARIABLE_SET (default_port_encoding_var,
2888 scm_make_fluid_with_default (SCM_BOOL_F));
2889 scm_port_encoding_init = 1;
2890
2891 SCM_VARIABLE_SET (default_conversion_strategy_var,
2892 scm_make_fluid_with_default (sym_substitute));
2893 scm_conversion_strategy_init = 1;
2894
2895 /* These bindings are used when boot-9 turns `current-input-port' et
2896 al into parameters. They are then removed from the guile module. */
2897 scm_c_define ("%current-input-port-fluid", cur_inport_fluid);
2898 scm_c_define ("%current-output-port-fluid", cur_outport_fluid);
2899 scm_c_define ("%current-error-port-fluid", cur_errport_fluid);
2900 }
2901
2902 /*
2903 Local Variables:
2904 c-file-style: "gnu"
2905 End:
2906 */