port.c 51.7 KB
Newer Older
eg's avatar
eg committed
1
/*
Erick's avatar
Erick committed
2
 *  p o r t . c                 -- ports implementation
eg's avatar
eg committed
3
 *
Erick's avatar
Erick committed
4
 * Copyright © 1993-2018 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
5
 *
eg's avatar
eg committed
6 7 8 9
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
10
 *
eg's avatar
eg committed
11 12 13 14
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
15
 *
eg's avatar
eg committed
16 17
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
eg's avatar
eg committed
19 20 21 22
 * USA.
 *
 *            Author: Erick Gallesio [eg@unice.fr]
 *    Creation date: 17-Feb-1993 12:27
Erick's avatar
Erick committed
23
 * Last file update: 24-Aug-2018 16:25 (eg)
eg's avatar
eg committed
24 25 26 27 28
 *
 */

#include <ctype.h>
#include "stklos.h"
29
#include "vm.h"
eg's avatar
eg committed
30 31


Erick's avatar
Erick committed
32
#define INITIAL_LINE_SIZE 256           /* Initial size for readline */
eg's avatar
eg committed
33

Erick's avatar
Erick committed
34
static SCM CrLf;                        /* used in read-line only */
eg's avatar
eg committed
35 36

static SCM io_error, io_port_error, io_read_error, io_write_error,
37
  io_closed_error, io_fn_error, io_malformed, io_prot_error,
eg's avatar
eg committed
38 39 40 41 42 43
  io_ro_error, io_exists_error, io_no_file_error, io_bad_param;


static void general_io_error(SCM type, char *format, SCM f)
{
  STk_raise_exception(STk_make_C_cond(type,
Erick's avatar
Erick committed
44 45 46 47 48
                                      4,
                                      STk_false,
                                      STk_vm_bt(),
                                      STk_format_error(format, f),
                                      f));
eg's avatar
eg committed
49 50 51 52 53 54
}

static void error_closed_port(SCM p)
{
  general_io_error(io_closed_error, "port ~S is closed", p);
}
55 56 57

static void error_bad_utf8_character(int byte)
{
Erick's avatar
Erick committed
58
  general_io_error(io_read_error, "bad UTF-8 byte %S", MAKE_INT(byte));
59 60
}

eg's avatar
eg committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
void STk_error_bad_io_param(char *fmt, SCM p)
{
  general_io_error(io_bad_param, fmt, p);
}

void STk_error_file_name(char *fmt, SCM fn)
{
  general_io_error(io_fn_error, fmt, fn);
}


void STk_error_bad_port(SCM p)
{
  general_io_error(io_port_error, "bad port ~S", p);
}


void STk_error_bad_file_name(SCM f)
{
  general_io_error(io_malformed, "bad file name ~S", f);
}

void STk_error_cannot_load(SCM f)
{
  general_io_error(io_prot_error, "cannot load file ~S", f);
}

88 89 90 91 92 93 94 95 96 97
static void error_bad_binary_port(SCM port)
{
  general_io_error(io_malformed, "bad binary port ~S", port);
}

static void error_bad_textual_port(SCM port)
{
  general_io_error(io_malformed, "bad textual port ~S", port);
}

Erick's avatar
Erick committed
98 99 100 101
static void error_bad_string(SCM obj)
{
  general_io_error(io_bad_param, "bad string ~S", obj);
}
eg's avatar
eg committed
102 103 104 105


static SCM verify_port(SCM port, int mode)
{
106
  if (mode & PORT_WRITE) {
107
    if (!port) return STk_current_output_port();
eg's avatar
eg committed
108 109
    if (!OPORTP(port)) STk_error_bad_port(port);
  } else {
110
    if (!port) return STk_current_input_port();
eg's avatar
eg committed
111 112 113
    if (!IPORTP(port)) STk_error_bad_port(port);
  }
  if (PORT_IS_CLOSEDP(port)) error_closed_port(port);
114 115 116
  if ((mode & PORT_BINARY)  && !PORT_BINARYP(port))  error_bad_binary_port(port);
  if ((mode & PORT_TEXTUAL) && !PORT_TEXTUALP(port)) error_bad_textual_port(port);

eg's avatar
eg committed
117 118 119 120 121 122 123 124 125
  return port;
}


/*
<doc  input-port? output-port?
 * (input-port? obj)
 * (output-port? obj)
 *
126
 * Returns |#t| if |obj| is an input port or output port respectively,
eg's avatar
eg committed
127 128 129 130 131 132 133 134 135 136 137 138 139
 * otherwise returns #f.
doc>
 */
DEFINE_PRIMITIVE("input-port?", input_portp, subr1, (SCM port))
{
  return MAKE_BOOLEAN(IPORTP(port));
}

DEFINE_PRIMITIVE("output-port?", output_portp, subr1, (SCM port))
{
  return MAKE_BOOLEAN(OPORTP(port));
}

Erick's avatar
Erick committed
140
/*
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
<doc R7RS textual-port? binary-port?
 * (textual-port? obj)
 * (binary-port? obj)
 *
 * Returns |#t| if |obj| is an textual port or binary port respectively,
 * otherwise returns #f.
doc>
 */
DEFINE_PRIMITIVE("textual-port?", textual_portp, subr1, (SCM port))
{
  return MAKE_BOOLEAN(PORTP(port) && (PORT_FLAGS(port) & PORT_TEXTUAL));
}

DEFINE_PRIMITIVE("binary-port?", binary_portp, subr1, (SCM port))
{
  return MAKE_BOOLEAN(PORTP(port) && (PORT_FLAGS(port) & PORT_BINARY));
}


/*
<doc R7RS port?
Erick's avatar
Erick committed
162 163
 * (port? obj)
 *
164
 * Returns |#t| if |obj| is an input port or an output port,
Erick's avatar
Erick committed
165 166 167 168 169 170 171 172
 * otherwise returns #f.
doc>
 */
DEFINE_PRIMITIVE("port?", portp, subr1, (SCM port))
{
  return MAKE_BOOLEAN(PORTP(port));
}

eg's avatar
eg committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

/*
<doc EXT interactive-port?
 * (interactive-port? port)
 *
 * Returns |#t| if |port| is connected to a terminal and |#f| otherwise.
doc>
 */
DEFINE_PRIMITIVE("interactive-port?", interactive_portp, subr1, (SCM port))
{
  if (!PORTP(port)) STk_error_bad_port(port);

  return MAKE_BOOLEAN(PORT_FLAGS(port) & PORT_IS_INTERACTIVE);
}


/*
<doc  current-input-port current-output-port
 * (current-input-port obj)
 * (current-output-port obj)
 *
 * Returns the current default input or output port.
doc>
 */
DEFINE_PRIMITIVE("current-input-port",current_input_port, subr0, (void))
{
199
  return STk_get_current_vm()->iport;
eg's avatar
eg committed
200 201 202 203
}

DEFINE_PRIMITIVE("current-output-port",current_output_port, subr0, (void))
{
204
  return STk_get_current_vm()->oport;
eg's avatar
eg committed
205 206 207 208 209 210 211 212 213 214 215
}

/*
<doc EXT current-error-port
 * (current-error-port obj)
 *
 * Returns the current default error port.
doc>
 */
DEFINE_PRIMITIVE("current-error-port",current_error_port, subr0, (void))
{
216
  return STk_get_current_vm()->eport;
eg's avatar
eg committed
217 218 219 220 221
}


DEFINE_PRIMITIVE("%set-std-port!", set_std_port, subr2, (SCM index, SCM port))
{
222 223
  vm_thread_t *vm = STk_get_current_vm();

eg's avatar
eg committed
224
  switch (AS_LONG(index)) {
225 226 227
    case SCM_LONG(0): if (!IPORTP(port)) goto badport; vm->iport = port; break;
    case SCM_LONG(1): if (!OPORTP(port)) goto badport; vm->oport = port; break;
    case SCM_LONG(2): if (!OPORTP(port)) goto badport; vm->eport = port; break;
228
    default: STk_error_bad_io_param("bad port number ~S", index);
eg's avatar
eg committed
229 230 231 232 233 234 235 236 237
  }
  return STk_void;
badport:
  STk_error_bad_port(port);
  return STk_void;
}


/*=============================================================================*\
Erick's avatar
Erick committed
238
 *                              Read
eg's avatar
eg committed
239 240 241 242 243 244 245 246 247 248 249
\*=============================================================================*/

/*
<doc read
 * (read)
 * (read port)
 *
 * |Read| converts external representations of Scheme objects into the
 * objects themselves. |Read| returns the next object parsable from the given
 * input port, updating port to point to the first character past the end of
 * the external representation of the object.
250
 * @l
eg's avatar
eg committed
251 252 253 254
 * If an end of file is encountered in the input before any characters are found
 * that can begin an object, then an end of file object is returned. The port
 * remains open, and further attempts to read will also return an end of file
 * object. If an end of file is encountered after the beginning of an object's
255
 * external representation, but the external representation is incomplete
eg's avatar
eg committed
256
 * and therefore not parsable, an error is signalled.
257
 * @l
eg's avatar
eg committed
258 259
 * The port argument may be omitted, in which case it defaults to the value
 * returned by |current-input-port|. It is an error to read from a closed port.
260
 * @l
eg's avatar
eg committed
261
 * ,(stklos) |read| supports the ,(link-srfi 10) |#,()| form that can be used
262
 * to denote values that do not have a convenient printed representation. See
eg's avatar
eg committed
263 264 265 266 267 268 269 270 271 272
 * the SRFI document for more information.
doc>
 */
/*
<doc EXT read-with-shared-structure
 * (read-with-shared-structure)
 * (read-with-shared-structure  port)
 * (read/ss)
 * (read/ss port)
 *
273 274 275
 * |read-with-shared-structure| is identical to |read|. It has been added to
 * be compatible with ,(link-srfi 38). STklos always knew how to deal with
 * recursive input data. |read/ss| is only a shorter name for
eg's avatar
eg committed
276
 * |read-with-shared-structure|.
277
 *
eg's avatar
eg committed
278 279 280
doc>
<doc EXT define-reader-ctor
 * (define-reader-ctor tag proc)
281
 *
eg's avatar
eg committed
282
 * This procedure permits to define a new user to reader constructor procedure
283
 * at run-time. It is defined in ,(link-srfi 10) document. See  SRFI document
eg's avatar
eg committed
284 285 286 287 288 289 290 291 292 293
 * for more information.
 * @lisp
 * (define-reader-ctor 'rev (lambda (x y) (cons y x)))
 * (with-input-from-string "#,(rev 1 2)" read)
 *                              => (2 . 1)
 * @end lisp
doc>
 */
DEFINE_PRIMITIVE("read", scheme_read, subr01, (SCM port))
{
294
  port = verify_port(port, PORT_READ | PORT_TEXTUAL);
295
  return STk_read(port, PORT_CASE_SENSITIVEP(port));
eg's avatar
eg committed
296 297 298 299 300 301 302
}



/* The same one but for reading code => code is really constant */
DEFINE_PRIMITIVE("%read", scheme_read_cst, subr01, (SCM port))
{
303
  port = verify_port(port, PORT_READ | PORT_TEXTUAL);
304
  return STk_read_constant(port, PORT_CASE_SENSITIVEP(port));
eg's avatar
eg committed
305 306 307 308 309 310 311 312 313
}


/*
<doc  read-char
 * (read-char)
 * (read-char port)
 *
 * Returns the next character available from the input |port|, updating the |port|
314 315
 * to point to the following character. If no more characters are available,
 * an end of file object is returned. |Port| may be omitted, in which case
eg's avatar
eg committed
316 317 318 319 320 321 322
 * it defaults to the value returned by |current-input-port|.
doc>
 */
DEFINE_PRIMITIVE("read-char", read_char, subr01, (SCM port))
{
  int c;

323
  port = verify_port(port, PORT_READ | PORT_TEXTUAL);
Erick's avatar
.  
Erick committed
324 325 326 327
  c = STk_get_character(port);
  if (c == UTF8_INCORRECT_SEQUENCE)
    error_bad_utf8_character(c);
  return (c == EOF) ? STk_eof : MAKE_CHARACTER(c);
328 329 330
}


eg's avatar
eg committed
331
/*
Erick's avatar
Erick committed
332
<doc EXT read-chars read-bytes
333 334
 * (read-bytes size)
 * (read-bytes size port)
eg's avatar
eg committed
335 336 337
 *
 * Returns a newly allocated string made of |size| characters read from |port|.
 * If less than |size| characters are available on the input port, the returned
338
 * string is smaller than |size| and its size is the number of available
eg's avatar
eg committed
339 340
 * characters. |Port| may be omitted, in which case it defaults to the
 * value returned by |current-input-port|.
341 342 343
 * @l
 * ,(bold "Note:") This function was previously called |read-chars|. Usage
 * of the old name is deprecated.
Erick's avatar
Erick committed
344
doc>
eg's avatar
eg committed
345
 */
346
DEFINE_PRIMITIVE("read-bytes", read_bytes, subr12, (SCM size, SCM port))
eg's avatar
eg committed
347 348 349 350 351 352 353 354 355 356
{
  int count, n = STk_integer_value(size);
  SCM z;

  port = verify_port(port, PORT_READ);
  if (n < 0) STk_error("bad length");

  /* Allocate a new string for result  */
  z     = STk_makestring(n, NULL);
  count = STk_read_buffer(port, STRING_CHARS(z), n);
357 358

  if (count == 0)
eg's avatar
eg committed
359 360 361 362 363 364 365 366 367
    return STk_eof;
  if (count < n) {
    /* String is shorter than the allocated one */
    STRING_CHARS(z)[count] = '\0';
    return STk_makestring(count, STRING_CHARS(z));
  }
  return z;
}

368 369

/*
Erick's avatar
Erick committed
370
<doc EXT read-chars! read-bytes!
371 372
 * (read-bytes! str)
 * (read-bytes! str port)
eg's avatar
eg committed
373 374 375
 *
 * This function reads the characters available from |port| in the string |str|
 * by chuncks whose size is equal to the length of |str|.
376
 * The value returned by |read-bytes!|is an integer indicating the number
eg's avatar
eg committed
377
 * of characters read. |Port| may be omitted, in which case it defaults to the
378
 * value returned by |current-input-port|.
379
 * @l
380
 * This function is similar to |read-bytes| except that it avoids to allocate
381
 * a new string for each read.
eg's avatar
eg committed
382 383 384 385 386 387 388
 * @lisp
 * (define (copy-file from to)
 *   (let* ((size 1024)
 *          (in  (open-input-file from))
 *          (out (open-output-file to))
 *          (s   (make-string size)))
 *     (let Loop ()
389
 *       (let ((n (read-bytes! s in)))
eg's avatar
eg committed
390 391 392 393 394 395 396 397
 *         (cond
 *           ((= n size)
 *              (write-chars s out)
 *              (Loop))
 *           (else
 *              (write-chars (substring s 0 n) out)
 *              (close-port out)))))))
 * @end lisp
Erick's avatar
Erick committed
398 399 400
 *
 * ,(bold "Note:") This function was previously called |read-chars!|. Usage
 * of the old name is deprecated.
eg's avatar
eg committed
401 402
doc>
 */
403 404 405
DEFINE_PRIMITIVE("read-bytes!", d_read_bytes, subr12, (SCM str, SCM port))
{
  port = verify_port(port, PORT_READ);
Erick's avatar
Erick committed
406
  if (!STRINGP(str)) error_bad_string(str);
407 408 409 410 411

  return MAKE_INT(STk_read_buffer(port, STRING_CHARS(str), STRING_LENGTH(str)));
}


412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
/*
<doc R7RS read-bytevector
 * (read-bytevector k)
 * (read-bytevector k port)
 *
 * Reads the next |k| bytes, or as many as are available
 * before the end of file, from the textual input |port| into a
 * newly allocated string in left-to-right order and returns the
 * string. If no characters are available before the end of file,
 * an end-of-file object is returned.
doc>
*/
DEFINE_PRIMITIVE("read-bytevector", read_bytevector, subr12, (SCM size, SCM port))
{
  long count, n = STk_integer_value(size);
  SCM z;

429
  port = verify_port(port, PORT_READ | PORT_BINARY);
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
  if (n < 0) STk_error("bad length");

  /* Allocate a new bytevector for result */
  z     = STk_make_C_bytevector(n);
  count = STk_read_buffer(port, UVECTOR_DATA(z), n);

  if (n && !count)
    return STk_eof;
  if (count < n) {
    /* result is shorter than the allocated bytevector */
    return STk_make_bytevector_from_C_string(UVECTOR_DATA(z), count);
  }
  return z;
}


446
DEFINE_PRIMITIVE("%read-bytevector!", d_read_bytevector, subr4,
447
                 (SCM bv, SCM port, SCM start, SCM end))
eg's avatar
eg committed
448
{
449 450
  long vstart = STk_integer_value(start);
  long vend   = STk_integer_value(end);
451
  long count, n;
452

453
  port = verify_port(port, PORT_READ | PORT_BINARY);
454
  if (!BYTEVECTORP(bv)) STk_error("bad bytevector ~S", bv);
eg's avatar
eg committed
455

456
  if (vstart < 0) STk_error("bad start value ~S", start);
457
  if (vend == LONG_MIN || vend > UVECTOR_SIZE(bv))
Erick's avatar
Erick committed
458
    STk_error("bad end value ~S", end);
459
  if (vstart > vend) STk_error("start index is bigger than end index");
460

461 462 463 464 465 466
  n     = vend - vstart;
  count = STk_read_buffer(port, UVECTOR_DATA(bv)+ vstart, vend - vstart);

  if (n && !count)
    return STk_eof;
  return MAKE_INT(n);
eg's avatar
eg committed
467 468
}

469

470

471 472 473 474 475 476
/*
<doc EXT read-byte
 * (read-byte)
 * (read-byte port)
 *
 * Returns the next character available from the input |port| as an integer.
477
 * If the end of file is reached, this function returns the end of file
478 479 480 481 482 483 484 485 486
 * object.
doc>
*/
DEFINE_PRIMITIVE("read-byte", read_byte, subr01, (SCM port))
{
  int c;

  port = verify_port(port, PORT_READ);
  c = STk_getc(port);
487
  return (c == EOF) ? STk_eof : MAKE_INT(c);
488 489
}

eg's avatar
eg committed
490 491 492 493 494
/*
<doc  peek-char
 * (peek-char)
 * (peek-char port)
 *
495
 * Returns the next character available from the input |port|, without updating
eg's avatar
eg committed
496 497 498
 * the port to point to the following character. If no more characters are
 * available, an end of file object is returned. |Port| may be omitted, in
 * which case it defaults to the value returned by |current-input-port|.
499
 * @l
eg's avatar
eg committed
500 501
 * ,(bold "Note:") The value returned by a call to |peek-char| is the same as the
 * value that would have been returned by a call to |read-char| with the same
502
 * port. The only difference is that the very next call to |read-char| or
eg's avatar
eg committed
503 504 505 506 507 508 509 510 511 512
 * |peek-char| on that port will return the value returned by the preceding
 * call to |peek-char|. In particular, a call to |peek-char| on an interactive
 * port will hang waiting for input whenever a call to |read-char| would have
 * hung.
doc>
 */
DEFINE_PRIMITIVE("peek-char", peek_char, subr01, (SCM port))
{
  int c;

513
  port = verify_port(port, PORT_READ | PORT_TEXTUAL);
Erick's avatar
.  
Erick committed
514 515 516

  c = STk_get_character(port);
  if (c == UTF8_INCORRECT_SEQUENCE) error_bad_utf8_character(c);
eg's avatar
eg committed
517 518 519 520 521
  STk_ungetc(c, port);

  return (c == EOF) ? STk_eof : MAKE_CHARACTER(c);
}

522 523 524 525 526
/*
<doc EXT peek-byte
 * (peek-byte)
 * (peek-byte port)
 *
527 528 529
 * Returns the next character available from the input |port|, without updating
 * the port to point to the following character. Whereas |peek-char|
 * returns a character, this function returns an integer between 0and 255.
530 531
doc>
*/
532
DEFINE_PRIMITIVE("peek-byte", peek_byte, subr01, (SCM port))
533 534 535 536 537 538 539 540 541 542
{
  int c;

  port = verify_port(port, PORT_READ);
  c = STk_getc(port);
  STk_ungetc(c, port);

  return (c == EOF) ? STk_eof : MAKE_INT(c);
}

eg's avatar
eg committed
543 544 545 546 547

/*
<doc  eof-object?
 * (eof-object? obj)
 *
548
 * Returns |#t| if |obj| is an end of file object, otherwise returns |#f|.
eg's avatar
eg committed
549 550 551 552 553 554 555 556 557 558 559
doc>
 */
DEFINE_PRIMITIVE("eof-object?", eof_objectp, subr1, (SCM obj))
{
  return MAKE_BOOLEAN(obj == STk_eof);
}


/*
<doc EXT eof-object
 * (eof-object)
560
 *
eg's avatar
eg committed
561
 * ,(index "#eof")
562
 * Returns an end of file object. Note that the special notation |#eof| is
eg's avatar
eg committed
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
 * another way to return such an end of file object.
doc>
 */
DEFINE_PRIMITIVE("eof-object", eof_object, subr0, (void))
{
  return STk_eof;
}


/*
<doc  char-ready?
 * (char-ready?)
 * (char-ready? port)
 *
 * Returns |#t| if a character is ready on the input port and returns |#f|
 * otherwise. If char-ready returns |#t| then the next read-char operation on
 * the given port is guaranteed not to hang. If the port is at end of file
 * then |char-ready?| returns |#t|. Port may be omitted, in which case it
 * defaults to the value returned by |current-input-port|.
doc>
 */
DEFINE_PRIMITIVE("char-ready?", char_readyp, subr01, (SCM port))
{
586
  port = verify_port(port, PORT_READ | PORT_TEXTUAL);
eg's avatar
eg committed
587 588 589
  return MAKE_BOOLEAN(STk_readyp(port));
}

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

/*
<doc R7RS u8-ready?
 * (u8-ready?)
 * (u8-ready? port)
 *
 * Returns #t if a byte is ready on the binary input |port| and
 * returns #f otherwise. If |u8-ready?| returns #t then the
 * next read-u8 operation on the given port is guaranteed
 * not to hang. If the |port| is at end of file then |u8-ready?|
 * returns #t.
doc>
*/
DEFINE_PRIMITIVE("u8-ready?", u8_readyp, subr01, (SCM port))
{
  port = verify_port(port, PORT_READ | PORT_BINARY);
  return MAKE_BOOLEAN(STk_readyp(port));
}


eg's avatar
eg committed
610
/*=============================================================================*\
Erick's avatar
Erick committed
611
 *                              Write
eg's avatar
eg committed
612 613 614 615 616 617 618 619 620
\*=============================================================================*/


/*
<doc  write
 * (write obj)
 * (write obj port)
 *
 * Writes a written representation of |obj| to the given |port|. Strings that
621
 * appear in the written representation are enclosed in doublequotes, and
eg's avatar
eg committed
622
 * within those strings backslash and doublequote characters are escaped
623
 * by backslashes. Character objects are written using the ,(emph "#\\") notation.
eg's avatar
eg committed
624 625 626 627 628 629 630 631 632 633 634 635 636
 * |Write| returns an unspecified value. The |port| argument may be omitted, in
 * which case it defaults to the value returned by |current-output-port|.
doc>
 */
DEFINE_PRIMITIVE("write", write, subr12, (SCM expr, SCM port))
{
  port = verify_port(port, PORT_WRITE);
  STk_print(expr, port, WRT_MODE);
  return STk_void;
}


/*
Erick's avatar
Erick committed
637
<doc R7RS write-shared write*
638 639
 * (write-shared obj)
 * (write-shared obj port)
eg's avatar
eg committed
640 641 642
 *
 * Writes a written representation of |obj| to the given port.  The
 * main difference with the |write| procedure is that |write*|
643
 * handles data structures with cycles. Circular structure written by
eg's avatar
eg committed
644 645
 * this procedure use the ,(code (q "#n=")) and ,(code (q "#n#"))
 * notations (see ,(ref :mark "Circular structure")).
646 647 648 649
 * @l
 * ,(bold "Note:") This function is also called |write*|.
 * The name |write*| was the name used by ,(stklos) for
 * |write-shared| before it was introduced in ,(rseven).
650
 *
eg's avatar
eg committed
651 652 653 654 655 656 657 658 659
doc>
<doc EXT write-with-shared-structure
 * (write-with-shared-structure obj)
 * (write-with-shared-structure obj port)
 * (write-with-shared-structure obj port optarg)
 * (write/ss obj)
 * (write/ss obj port)
 * (write/ss obj port optarg)
 *
660 661 662
 * |write-with-shared-structure| has been added to be compatible with
 * ,(link-srfi 38). It is is identical to |write*|, except that it accepts one
 * more parameter (|optarg|). This parameter, which is not specified
eg's avatar
eg committed
663 664
 * in ,(srfi 38), is always ignored. |write/ss| is only a shorter name for
 * |write-with-shared-structure|.
665
 *
eg's avatar
eg committed
666 667 668 669
doc>
*/
DEFINE_PRIMITIVE("write*", write_star, subr12, (SCM expr, SCM port))
{
670
  port = verify_port(port, PORT_WRITE | PORT_TEXTUAL);
671
  STk_print_star(expr, port, WRT_MODE);
eg's avatar
eg committed
672 673 674 675
  return STk_void;
}

/*
676
<doc display
eg's avatar
eg committed
677 678 679 680 681 682 683 684 685 686
 * (display obj)
 * (display obj port)
 *
 * Writes a representation of |obj| to the given |port|. Strings that
 * appear in the written representation are not enclosed in
 * doublequotes, and no characters are escaped within those
 * strings. Character objects appear in the representation as if
 * written by |write-char| instead of by |write|. |Display| returns an
 * unspecified value. The |port| argument may be omitted, in which
 * case it defaults to the value returned by |current-output-port|.
687
 * @l
eg's avatar
eg committed
688
 * ,(bold "Rationale:") |Write| is intended for producing machine-readable
689
 * output and |display| is for producing human-readable output.
690
 * @l
Erick's avatar
Erick committed
691
 * ,(bold "Note:") As required by ,(rseven) does not loop forever when
692
 * |obj| contains self-references.
eg's avatar
eg committed
693 694 695 696
doc>
 */
DEFINE_PRIMITIVE("display", display, subr12, (SCM expr, SCM port))
{
697
  port = verify_port(port, PORT_WRITE | PORT_TEXTUAL);
698
  STk_print_star(expr, port, DSP_MODE);
eg's avatar
eg committed
699 700 701
  return STk_void;
}

702

703 704 705 706 707 708
/*
<doc EXT display-simple
 * (display-simple obj)
 * (display-simple obj port)
 *
 * The |display-simple| procedure is the same as |display|, except
Erick's avatar
Erick committed
709
 * that shared structure is never represented using datum labels.
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
 * This can cause |display-simple| not to terminate if |obj|
 * contains circular structure.
doc>
 */
DEFINE_PRIMITIVE("display-simple", display_simple, subr12, (SCM expr, SCM port))
{
  port = verify_port(port, PORT_WRITE | PORT_TEXTUAL);
  STk_print(expr, port, DSP_MODE);
  return STk_void;
}
/*
<doc EXT display-shared
 * (display-shared obj)
 * (display-shared obj port)
 *
 * The |display-shared| procedure is the same as |display|, except
 * that shared structure are represented using datum labels.
doc>
 */

/* Aliased to display in lib/bonus.stk */


eg's avatar
eg committed
733 734 735 736 737 738 739 740 741 742 743 744 745
/*
<doc  newline
 * (newline)
 * (newline port)
 *
 * Writes an end of line to |port|. Exactly how this is done differs from
 * one operating system to another. Returns an unspecified value. The |port|
 * argument may be omitted, in which case it defaults to the value returned
 * by |current-output-port|.
doc>
 */
DEFINE_PRIMITIVE("newline", newline, subr01, (SCM port))
{
746
  port = verify_port(port, PORT_WRITE | PORT_TEXTUAL);
eg's avatar
eg committed
747 748 749 750 751 752 753 754 755 756 757 758
  STk_putc('\n', port);
  return STk_void;
}



/*
<doc  write-char
 * (write-char char)
 * (write-char char port)
 *
 * Writes the character |char| (not an external representation of the
759
 * character) to the given |port| and returns an unspecified value.
eg's avatar
eg committed
760 761 762 763 764 765 766
 * The |port| argument may be omitted, in which case it defaults to the
 * value returned by |current-output-port|.
doc>
 */
DEFINE_PRIMITIVE("write-char", write_char, subr12, (SCM c, SCM port))
{
  if (!CHARACTERP(c)) STk_error_bad_io_param("bad character ~S", c);
767
  port = verify_port(port, PORT_WRITE | PORT_TEXTUAL);
768
  STk_put_character(CHARACTER_VAL(c), port);
eg's avatar
eg committed
769 770 771
  return STk_void;
}

Erick's avatar
Erick committed
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
DEFINE_PRIMITIVE("%write-string", write_string, subr4, (SCM str, SCM port,
                                                        SCM start, SCM end))
{
  long vstart = STk_integer_value(start);
  long vend   = STk_integer_value(end);

  if (!STRINGP(str)) error_bad_string(str);
  verify_port(port, PORT_WRITE | PORT_TEXTUAL);

  if (vstart < 0) STk_error("bad start value ~S", start);
  if (vend == LONG_MIN || vend > STRING_LENGTH(str))
    STk_error("bad end value ~S", end);
  if (vstart > vend) STk_error("start index is bigger than end index");

  if (STk_use_utf8 && !STRING_MONOBYTE(str)) {
    char *adr_start = STk_utf8_index(STRING_CHARS(str), vstart, STRING_SIZE(str));
    char *adr_end   = STk_utf8_index(STRING_CHARS(str), vend,   STRING_SIZE(str));

    STk_write_buffer(port, adr_start, adr_end - adr_start);
  }
  else {
    STk_write_buffer(port, STRING_CHARS(str)+vstart, vend -vstart);
  }
  return STk_void;
}

eg's avatar
eg committed
798 799 800 801 802

/*
<doc EXT write-chars
 * (write-chars str)
 * (write-char str port)
803
 *
eg's avatar
eg committed
804 805 806
 * Writes the character of string |str| to the given |port| and
 * returns an unspecified value.  The |port| argument may be omitted,
 * in which case it defaults to the value returned by
807
 * |current-output-port|.
Erick's avatar
Erick committed
808 809
 * @l
 * ,(bold "Note:") This function is generally
810
 * faster than |display| for strings. Furthermore, this primitive does
eg's avatar
eg committed
811
 * not use the buffer associated to |port|.
812
 *
eg's avatar
eg committed
813 814 815 816
doc>
 */
DEFINE_PRIMITIVE("write-chars", write_chars, subr12, (SCM str, SCM port))
{
Erick's avatar
Erick committed
817
  if (!STRINGP(str)) error_bad_string(str);
eg's avatar
eg committed
818 819 820 821 822 823
  port = verify_port(port, PORT_WRITE);
  STk_write_buffer(port, STRING_CHARS(str), STRING_SIZE(str));
  return STk_void;
}


824 825 826 827 828 829 830 831 832 833 834 835 836

/*
<doc EXT write-byte
 * (write-byte b)
 * (write-byte b port)
 *
 * Write byte |b| to the port. |b| must be an exact integer in range between 0
 * and 255.
doc>
*/
DEFINE_PRIMITIVE("write-byte", write_byte, subr12, (SCM byte, SCM port))
{
  int b = STk_integer_value(byte);
837

838
  if ((b < 0) || (b > 255))
Erick's avatar
.  
Erick committed
839
    STk_error_bad_io_param("bad byte value ~S", byte);
840 841 842 843 844 845 846
  port = verify_port(port, PORT_WRITE);
  STk_putc(b, port);
  return STk_void;

}


eg's avatar
eg committed
847
/*===========================================================================*\
848
 *
Erick's avatar
Erick committed
849
 *                      S T k   b o n u s
eg's avatar
eg committed
850 851 852 853 854 855
 *
\*===========================================================================*/
#define FMT_SIZE 7


static SCM internal_format(int argc, SCM *argv, int error)
856
     /* a very simple and poor format */
eg's avatar
eg committed
857 858 859 860
{
  SCM port, fmt;
  int format_in_string = 0;
  char *p, *start_fmt = "", prev_char;
861

eg's avatar
eg committed
862 863 864 865 866 867 868 869 870 871 872 873 874 875
  if (error) {
    if (argc < 1) goto Bad_list;
    format_in_string = 1;
    port = STk_open_output_string();
    argc -= 1;
  }
  else {
    if (STRINGP(*argv)) {
      /* This is a SRFI-28 format */
      format_in_string = 1;
      port = STk_open_output_string();
      argc -= 1;
    } else {
      if (argc < 2) goto Bad_list;
876
      port = *argv--;
eg's avatar
eg committed
877
      argc -= 2;
878

eg's avatar
eg committed
879
      if (BOOLEANP(port)){
Erick's avatar
Erick committed
880 881 882 883 884
        if (port == STk_true) port = STk_current_output_port();
        else {
          format_in_string = 1;
          port = STk_open_output_string();
        }
eg's avatar
eg committed
885
      } else {
886
        verify_port(port, PORT_WRITE | PORT_TEXTUAL);
eg's avatar
eg committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
      }
    }
  }

  fmt = *argv--;
  if (!STRINGP(fmt)) STk_error_bad_io_param("bad format string ~S", fmt);

  /* Parse the format string */
  start_fmt = STRING_CHARS(fmt);
  prev_char = '\n';

  for(p = start_fmt; *p; p++) {
    if (*p == '~') {
      switch(*(++p)) {
        case 'A':
Erick's avatar
Erick committed
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
        case 'a': {
                    SCM tmp;

                    if (argc-- <= 0) goto TooMuch;
                    tmp = *argv--;
                    if (STRINGP(tmp)) {
                      if (STRING_SIZE(tmp) > 0)
                        prev_char = STRING_CHARS(tmp)[STRING_SIZE(tmp) - 1];
                    }
                    else if (CHARACTERP(tmp))
                      prev_char= CHARACTER_VAL(tmp);

                    STk_print(tmp, port, DSP_MODE);
                    continue;           /* because we set ourselves prev_char */
                  }
eg's avatar
eg committed
917 918 919
        case 'S':
        case 's': if (argc-- <= 0) goto TooMuch;
                  STk_print(*argv--, port, WRT_MODE);
Erick's avatar
Erick committed
920
                  break;
eg's avatar
eg committed
921 922
        case 'W':
        case 'w': if (argc-- <= 0) goto TooMuch;
923
          STk_print_star(*argv--, port, WRT_MODE);
Erick's avatar
Erick committed
924
                  break;
eg's avatar
eg committed
925
        case 'X':
926
        case 'x': if (argc-- <= 0) goto TooMuch;
Erick's avatar
Erick committed
927 928
                  STk_print(STk_number2string(*argv--, MAKE_INT(16)),port,DSP_MODE);
                  break;
eg's avatar
eg committed
929
        case 'D':
930
        case 'd': if (argc-- <= 0) goto TooMuch;
Erick's avatar
Erick committed
931 932
                  STk_print(STk_number2string(*argv--, MAKE_INT(10)),port,DSP_MODE);
                  break;
933 934
        case 'O':
        case 'o': if (argc-- <= 0) goto TooMuch;
Erick's avatar
Erick committed
935 936
                  STk_print(STk_number2string(*argv--, MAKE_INT(8)),port,DSP_MODE);
                  break;
eg's avatar
eg committed
937
        case 'B':
938
        case 'b': if (argc-- <= 0) goto TooMuch;
Erick's avatar
Erick committed
939 940
                  STk_print(STk_number2string(*argv--, MAKE_INT(2)),port,DSP_MODE);
                  break;
eg's avatar
eg committed
941
        case 'C':
942
        case 'c': if (argc-- <= 0) goto TooMuch;
Erick's avatar
Erick committed
943 944 945 946 947
                  if (!CHARACTERP(*argv))
                    STk_error_bad_io_param("bad character ~S", *argv);
                  prev_char = CHARACTER_VAL(*argv);
                  STk_print(*argv--, port, DSP_MODE);
                  continue;     /* because we set ourselves prev_char */
eg's avatar
eg committed
948
        case 'Y':
Erick's avatar
Erick committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
        case 'y': {                                     /* Yuppify */
                      SCM ref, pp;

                      if (argc-- <= 0) goto TooMuch;
                      pp = STk_lookup(STk_intern("pp"),
                                      STk_current_module(),
                                      &ref,
                                      TRUE);
                      STk_print(STk_C_apply(pp, 3, *argv--,
                                            STk_makekey("port"),
                                            STk_false),
                                port,
                                WRT_MODE);
                      prev_char = '\n'; /* since our pp always add a newline */
                      continue;         /* because we set ourselves prev_char */
        }
eg's avatar
eg committed
965 966
        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9': {
Erick's avatar
Erick committed
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
                  char width[FMT_SIZE], digits[FMT_SIZE];
                  SCM ff, ref, tmp;
                  int i;

                  if (argc-- <= 0) goto TooMuch;

                  for (i=0; isdigit(*p); i++) {
                    if (i >= FMT_SIZE) goto Incorrect_format_width;
                    width[i] = *p++;
                  }
                  width[i] = '\0';

                  if (*p == ',') {
                    p++;
                    for (i=0; isdigit(*p); i++) {
                      if (i >= FMT_SIZE) goto Incorrect_format_width;
                      digits[i] = *p++;
                    }
                    digits[i] = '\0';
                  }
                  if (*p != 'f' && *p != 'F') goto Incorrect_format_width;

                  /* width and digits are strings which contains the width
                   * and the number of digits for the format
                   * Call the Scheme routine srfi48:format-fixed
                   */
                  ff = STk_lookup(STk_intern("srfi48:format-fixed"),
                                  STk_current_module(),
                                  &ref,
                                  TRUE);
                  tmp = STk_C_apply(ff, 3,
                                        *argv--,
                                        STk_Cstr2number(width, 10L),
                                    STk_Cstr2number(digits, 10L));
                  if (STRINGP(tmp)) {
                    if (STRING_SIZE(tmp) > 0)
                      prev_char = STRING_CHARS(tmp)[STRING_SIZE(tmp) - 1];
                  }
                  STk_print(tmp, port, DSP_MODE);
                  continue;
        }
        case '?':
eg's avatar
eg committed
1009 1010
        case 'K':
        case 'k': {
Erick's avatar
Erick committed
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
                    SCM fmt, ref,args;
                    int len;

                    if (argc-- <= 0) goto TooMuch;
                    fmt = *argv--;
                    if (!STRINGP(fmt))
                      STk_error_bad_io_param("bad string for ~~? format ~S", fmt);

                    if (argc-- <= 0) goto TooMuch;
                    args = *argv--;
                    len  = STk_int_length(args);
                    if (len < 0)
                      STk_error_bad_io_param("bad list for ~~? format ~S", args);

                    /* Do (apply format port fmt args) */
                    STk_C_apply_list(STk_lookup(STk_intern("format"),
                                                STk_current_module(), &ref, TRUE),
                                     STk_cons(port, STk_cons(fmt, args)));
                    break;
                  }
eg's avatar
eg committed
1031
        case 'H':
Erick's avatar
Erick committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
        case 'h': {                                     /* Help */
                     SCM ref, help;

                      help = STk_lookup(STk_intern("srfi48:help"),
                                        STk_current_module(),
                                        &ref,
                                        TRUE);
                      STk_C_apply(help, 1, port);
                      break;
        }
1042
        case 'T':
Erick's avatar
Erick committed
1043 1044
        case 't': STk_putc('\t', port);
                  break;
eg's avatar
eg committed
1045
        case '_': STk_putc(' ',port);
Erick's avatar
Erick committed
1046
                  break;
eg's avatar
eg committed
1047 1048
        case '&': if (prev_char == '\n') continue;
        case '%': STk_putc('\n', port);
Erick's avatar
Erick committed
1049
                  prev_char = '\n';
eg's avatar
eg committed
1050 1051 1052 1053
                  continue;
        case '~': STk_putc('~', port);
                  break;
        default:  STk_putc('~',  port);
Erick's avatar
Erick committed
1054
                  if (*p) STk_putc(*p, port);
eg's avatar
eg committed
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
      }
      prev_char = '?';
    } else {
      /* Not a ~ sequence */
      prev_char = *p;
      STk_putc(*p, port);
    }
  }

  /* Verify that it doesn't remain arguments on the list */
1065
  if (argc)
eg's avatar
eg committed
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    STk_error_bad_io_param("too few ``~~'' in format string %S", start_fmt);

  return format_in_string ? STk_get_output_string(port) : STk_void;

TooMuch:
  STk_error_bad_io_param("too many ``~~'' in format string %S", start_fmt);
Bad_list:
  STk_error_bad_io_param("bad list of parameters ~S", *argv);
Incorrect_format_width:
  STk_error_bad_io_param("Format too long or 'f' expected in %S", start_fmt);

  return STk_void;
}

/*
1081
<doc EXT format
eg's avatar
eg committed
1082 1083 1084 1085
 * (format port str obj ...)
 * (format str obj)
 *
 * Writes the |obj|s to the given |port|, according to the format
1086
 * string |str|. |Str| is written literally, except for the following
eg's avatar
eg committed
1087 1088 1089 1090 1091
 * sequences:
 *
 * ,(itemize
 * (item [|~a| or |~A| is replaced by the printed representation
 * of the next |obj|.])
1092
 *
eg's avatar
eg committed
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
 * (item [|~s| or |~S| is replaced by the ``slashified'' printed
 * representation of the next |obj|.])
 *
 * (item [|~w| or |~W| is replaced by the printed representation
 * of the next |obj| (circular structures are correctly handled and
 * printed using |write*|).])
 *
 * (item [|~d| or |~D| is replaced by the decimal printed representation
 * of the next |obj| (which must be a number).])
 *
 * (item [|~x| or |~X| is replaced by the hexadecimal printed representation
 * of the next |obj| (which must be a number).])
1105
 *
eg's avatar
eg committed
1106 1107
 * (item [|~o| or |~O| is replaced by the octal printed representation
 * of the next |obj| (which must be a number).])
1108
 *
eg's avatar
eg committed
1109 1110
 * (item [|~b| or |~B| is replaced by the binary printed representation
 * of the next |obj| (which must be a number).])
1111
 *
eg's avatar
eg committed
1112 1113
 * (item [|~c| or |~C| is replaced by the printed representation
 * of the next |obj| (which must be a character).])
1114
 *
eg's avatar
eg committed
1115 1116
 * (item [|~y| or |~Y| is replaced by the pretty-printed representation
 * of the next |obj|. The standard pretty-printer is used here.])
1117
 *
eg's avatar
eg committed
1118 1119
 * (item [|~?| is replaced by the result of the recursive call of |format|
 * with the two next |obj|.])
1120
 *
eg's avatar
eg committed
1121
 * (item [|~k| or |~K| is another name for |~?|])
1122
 *
eg's avatar
eg committed
1123 1124 1125 1126 1127 1128 1129 1130 1131
 * (item [|~\[w\[,d\]\]f| or |~\[w\[,d\]\]F| is replaced by the printed
 * representation of next |obj| (which must be a number) with width |w|
 * and |d| digits after the decimal. Eventually, |d| may be omitted.])
 *
 * (item [|~~| is replaced by a single tilde character.])
 *
 * (item [|~%| is replaced by a newline])
 *
 * (item [|~t| or |~t| is replaced by a tabulation character.])
1132
 *
eg's avatar
eg committed
1133 1134
 * (item [|~&| is replaced by a newline character if it is known that the
 * previous character was not a newline])
1135
 *
eg's avatar
eg committed
1136
 * (item [|~_| is replaced by a space])
1137
 *
eg's avatar
eg committed
1138
 * (item [|~h| or |~H| provides some help])
1139
 *
eg's avatar
eg committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
 * )
 *
 * |Port| can be a boolean or a port. If |port| is |#t|, output goes to
 * the current output port; if |port| is |#f|, the output is returned as a
 * string.  Otherwise, the output is printed on the specified port.
 * @lisp
 *    (format #f "A test.")        => "A test."
 *    (format #f "A ~a." "test")   => "A test."
 *    (format #f "A ~s." "test")   => "A \\"test\\"."
 *    (format "~8,2F" 1/3)         => "    0.33"
 *    (format "~6F" 32)            => "    32"
 *    (format "~1,2F" 4321)        => "4321.00"
 *    (format "~1,2F" (sqrt -3.9)) => "0.00+1.97i"
 *    (format "#d~d #x~x #o~o #b~b~%" 32 32 32 32)
 *                                 => "#d32 #x20 #o40 #b100000\\n"
 *    (format #f "~&1~&~&2~&~&~&3~%")
 *                                 => "1\\n2\\n3\\n"
 *    (format "~a ~? ~a" 'a "~s" '(new) 'test)
 *                                 => "a new test"
 * @end lisp
1160 1161
 *
 * ,(bold "Note:") The second form of |format| is compliant with
eg's avatar
eg committed
1162
 * ,(link-srfi 28). That is, when
1163
 * |port| is omitted, the output is returned as a string as if |port| was
eg's avatar
eg committed
1164
 * given the value |#f|.
1165
 * @l
1166
 * ,(bold "Note:") Since version 0.58, |format| is also compliant with
eg's avatar
eg committed
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
 * ,(link-srfi 48).
doc>
 */
DEFINE_PRIMITIVE("format", format, vsubr, (int argc, SCM *argv))
{
  return internal_format(argc, argv, FALSE);
}


/*
<doc EXT error
 * (error str obj ...)
 * (error name str obj ...)
 *
1181 1182
 * |error| is used to signal an error to the user. The second form
 * of |error| takes  a symbol as first parameter; it is generally used for the
eg's avatar
eg committed
1183
 * name of the procedure which raises the error.
1184
 * @l
1185 1186 1187 1188 1189 1190 1191
 * ,(bold "Note:") The specification string may follow the
 * ,(emph "tilde conventions")
 * of |format| (see ,(ref :mark "format")); in this case this procedure builds an
 * error message according to the specification given in |str|. Otherwise,
 * this procedure is conform to the |error| procedure defined in
 * ,(link-srfi 23) and  |str| is printed with the |display| procedure,
 * whereas the |obj|s are printed  with the |write| procedure.
eg's avatar
eg committed
1192
 *
1193
 * @l
eg's avatar
eg committed
1194 1195 1196 1197
 * Hereafter, are some calls of the |error| procedure using a formatted string
 * @lisp
 * (error "bad integer ~A" "a")
 *                      @print{} bad integer a
1198
 * (error 'vector-ref "bad integer ~S" "a")
eg's avatar
eg committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
 *                      @print{} vector-ref: bad integer "a"
 * (error 'foo "~A is not between ~A and ~A" "bar" 0 5)
 *                      @print{} foo: bar is not between 0 and 5
 * @end lisp
 *
 * and some conform to ,(srfi 23)
 * @lisp
 * (error "bad integer" "a")
 *                     @print{} bad integer "a"
 * (error 'vector-ref "bad integer" "a")
 *                    @print{} vector-ref: bad integer "a"
 * (error "bar" "is not between" 0 "and" 5)
 *                    @print{} bar "is not between" 0 "and" 5
 * @end lisp
doc>
 */
static SCM srfi_23_error(int argc, SCM *argv)
{
  SCM port = STk_open_output_string();

  STk_print(*argv--, port, DSP_MODE); /* the message (we know that it exists) */
  for (argc--; argc; argc--) {
    STk_putc(' ', port);
    STk_print(*argv--, port, WRT_MODE);
  }
  STk_close_port(port);
  return STk_get_output_string(port);
}

static int msg_use_tilde(char *s)
{
  char *p;
1231

eg's avatar
eg committed
1232 1233 1234 1235
  p = strchr(s, '~');
  return p ? (p[1] && strchr("aAsSwW~", p[1]) != NULL): 0;
}

1236
static SCM do_error(SCM type, int argc, SCM *argv)
eg's avatar
eg committed
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
{
  SCM who = STk_false;

  if (argc > 0) {
    if (SYMBOLP(*argv)) {
      who = *argv;
      argc -= 1;
      argv -= 1;
    }
    if (argc > 0) {
      SCM msg;
1248

eg's avatar
eg committed
1249 1250
      /* See if we have a formatted message or a plain SRFI-23 call */
      if (STRINGP(*argv) && !msg_use_tilde(STRING_CHARS(*argv)))
Erick's avatar
Erick committed
1251
        msg = srfi_23_error(argc, argv);
1252
      else
Erick's avatar
Erick committed
1253
        msg = internal_format(argc, argv, TRUE);
1254
      STk_signal_error(type, who, msg);
eg's avatar
eg committed
1255 1256
    }
  }
1257
  STk_signal_error(type, who, STk_Cstring2string(""));
eg's avatar
eg committed
1258 1259 1260 1261
  return STk_void;
}


1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
DEFINE_PRIMITIVE("error", scheme_error, vsubr, (int argc, SCM *argv))
{
  return do_error(STk_err_mess_condition, argc, argv);
}


/*
<doc EXT signal-error
 * (signal-error cond str obj ...)
 * (signal-error cond name str obj ...)
 *
1273 1274
 * This procedure is similar to error, except that the type of the error
 * can be passed as the first parameter. The type of the error must be a
Erick Gallesio's avatar
Erick Gallesio committed
1275
 * condition which inherits from |&error-message|.
1276
 * @l
1277
 * Note that |(error arg ...)| is equivalent to
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
 * @lisp
 * (signal-error &error-message arg ...)
 * @end lisp
doc>
*/
DEFINE_PRIMITIVE("signal-error", scheme_signal_error, vsubr, (int argc, SCM *argv))
{
  SCM type_error;

  if (! argc) STk_error("error condtion expected");

  type_error = *argv;
  argc -= 1;
  argv -= 1;
1292

1293 1294 1295 1296 1297
  if (STk_condition_type_is_a(type_error, STk_err_mess_condition) == STk_false)
    STk_error("bad &error-message ~S", type_error);
  return do_error(type_error, argc, argv);
}

eg's avatar
eg committed
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324

/*
<doc close-input-port close-output-port
 * (close-input-port port)
 * (close-output-port port)
 *
 * Closes the port associated with |port|, rendering the port incapable of
 * delivering or accepting characters. These routines have no effect if the
 * port has already been closed. The value returned is ,(emph "void").
doc>
 */
DEFINE_PRIMITIVE("close-input-port", close_input_port, subr1, (SCM port))
{
  if (!IPORTP(port)) STk_error_bad_port(port);
  STk_close(port);
  return STk_void;
}

DEFINE_PRIMITIVE("close-output-port", close_output_port, subr1, (SCM port))
{
  if (!OPORTP(port)) STk_error_bad_port(port);
  STk_close(port);
  return STk_void;
}


/*
1325
<doc R7RS close-port
eg's avatar
eg committed
1326 1327 1328 1329 1330 1331 1332 1333
 * (close-port port)
 *
 * Closes the port associated with |port|.
doc>
 */
DEFINE_PRIMITIVE("close-port", close_port, subr1, (SCM port))
{
  if (!PORTP(port)) STk_error_bad_port(port);
1334

eg's avatar
eg committed
1335 1336 1337 1338 1339
  STk_close(port);
  return STk_void;
}

/*
Erick's avatar
Erick committed
1340
<doc EXT port-open? port-closed?
eg's avatar
eg committed
1341
 * (port-closed? port)
1342
 * (port-open?  port)
eg's avatar
eg committed
1343
 *
1344 1345 1346 1347 1348 1349 1350
 * |port-closed| returns |#t| if |port| is closed and |#f| otherwise.
 * On the contrary, |port-open?| returns |#t| if |port| is open and
 * |#f| otherwise.
 * @l
 * ,(bold "Note:") |port-closed?| was the usual STklos function to
 * test if a port is closed. |port-open?| has been added to be the companion
 * of the ,(rseven) functions |input-port-open?| and |output-port-open?|
eg's avatar
eg committed
1351 1352 1353 1354 1355 1356 1357 1358 1359
doc>
*/
DEFINE_PRIMITIVE("port-closed?", port_closed, subr1, (SCM port))
{
  if (!PORTP(port)) STk_error_bad_port(port);

  return MAKE_BOOLEAN(PORT_IS_CLOSEDP(port));
}

1360 1361 1362 1363 1364 1365 1366
DEFINE_PRIMITIVE("port-open?", port_open, subr1, (SCM port))
{
  if (!PORTP(port)) STk_error_bad_port(port);

  return MAKE_BOOLEAN(!PORT_IS_CLOSEDP(port));
}

eg's avatar
eg committed
1367 1368 1369 1370 1371 1372 1373 1374 1375

/*
<doc EXT read-line
 * (read-line)
 * (read-line port)
 *
 * Reads the next line available from the input port |port|. This function
 * returns 2 values: the first one is is the string which contains the line
 * read, and the second one is the end of line delimiter. The end of line
1376 1377 1378
 * delimiter can be an end of file object, a character or a string in case
 * of a multiple character delimiter. If no more characters are available
 * on |port|, an end of file object is returned.  |Port| may be omitted,
eg's avatar
eg committed
1379
 * in which case it defaults to the value returned by |current-input-port|.
1380
 * @l
eg's avatar
eg committed
1381
 * ,(bold "Note:") As said in ,(ref :mark "values"), if |read-line| is not
1382
 * used in  the context of |call-with-values|, the second value returned by
eg's avatar
eg committed
1383
 * this procedure is ignored.
1384
doc>
eg's avatar
eg committed
1385 1386 1387 1388 1389 1390 1391 1392
*/
DEFINE_PRIMITIVE("read-line", read_line, subr01, (SCM port))
{
  int prev, c;
  char buffer[INITIAL_LINE_SIZE], *buff;
  size_t i, size = INITIAL_LINE_SIZE;
  SCM res, delim;

1393
  port = verify_port(port, PORT_READ | PORT_TEXTUAL);
eg's avatar
eg committed
1394 1395 1396 1397 1398 1399 1400 1401
  buff = buffer;
  prev = ' ';

  for (i = 0; ; i++) {
    if (i == size) {
      /* We must enlarge the buffer */
      size += size / 2;
      if (i == INITIAL_LINE_SIZE) {
Erick's avatar
Erick committed
1402 1403 1404
        /* This is the first resize. Pass from static to dynamic allocation */
        buff = STk_must_malloc(size);
        strncpy(buff, buffer, INITIAL_LINE_SIZE);
eg's avatar
eg committed
1405
      }
1406
      else
Erick's avatar
Erick committed
1407
        buff = STk_must_realloc(buff, size);
eg's avatar
eg committed
1408 1409
    }
    switch (c = STk_getc(port)) {
1410
      case EOF:  res = (i == 0) ? STk_eof : STk_makestring(i, buff);
Erick's avatar
Erick committed
1411 1412
                 if (buff != buffer) STk_free(buff);
                 return STk_n_values(2, res, STk_eof);
eg's avatar
eg committed
1413

1414
      case '\n': if (prev == '\r')
Erick's avatar
Erick committed
1415 1416 1417
                   { i -= 1; delim = CrLf; }
                 else
                   delim = MAKE_CHARACTER('\n');
1418

Erick's avatar
Erick committed
1419 1420 1421
                 res = STk_makestring(i, buff);
                 if (buff != buffer) STk_free(buff);
                 return STk_n_values(2, res, delim);
eg's avatar
eg committed
1422

1423
      default:  buff[i] = prev = c;
eg's avatar
eg committed
1424 1425 1426 1427 1428 1429 1430 1431 1432
    }
  }
}

/*
<doc EXT copy-port
 * (copy-port in out)
 * (copy-port in out max)
 *
1433
 * Copy the content of port |in|, which must be opened for reading, on
1434
 * port |out|, which must be opened for writing. If |max| is not specified,
eg's avatar
eg committed
1435
 * All the characters from the input port are copied on ouput port. If |max|
1436
 * is specified, it must be an integer indicating the maximum number of characters
eg's avatar
eg committed
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
 * which are copied from |in| to |out|.
doc>
*/
#define COPY_PORT_SIZE 4096
DEFINE_PRIMITIVE("copy-port", copy_port, subr23, (SCM p1, SCM p2, SCM max))
{
  char buffer[COPY_PORT_SIZE];
  int n, m, sz = -1;

  if (!IPORTP(p1)) STk_error_bad_port(p1);
  if (!OPORTP(p2)) STk_error_bad_port(p2);
  if (max) {
    sz = STk_integer_value(max);
1450
    if (sz < 0)
eg's avatar
eg committed
1451 1452
      STk_error("bad size ~S", max);
  }
1453

1454
  /* Copy at most sz characters from p1 to p2 */
eg's avatar
eg committed
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
  for ( ; ; ) {
    if (sz < 0) {
      n = COPY_PORT_SIZE;
    } else if (sz > COPY_PORT_SIZE) {
      n = COPY_PORT_SIZE;
      sz -= COPY_PORT_SIZE;
    } else {
      n = sz;
      sz = 0;
    }
1465

eg's avatar
eg committed
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    if (n == 0) break;
    if ((n = STk_read_buffer(p1, buffer, n)) > 0) {
      m = STk_write_buffer(p2, buffer, n);
      if (n != m) goto Error;
    }
    if (n <= 0) break;
  }
  if (n != 0) goto Error;
  return STk_void;

1476 1477
 Error:
  STk_error("problem while copying port ~S on port ~S (~S)",
Erick's avatar
Erick committed
1478
            p1 , p2, STk_Cstring2string(strerror(errno)));
eg's avatar
eg committed
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
  return STk_void;
}

/*
<doc EXT flush-output-port
 * (flush-output-port)
 * (flush-output-port port)
 *
 * Flushes the buffer associated with the given output |port|. The
 * |port| argument may be omitted, in which case it defaults to the value
 * returned by |current-output-port|
doc>
 */
DEFINE_PRIMITIVE("flush-output-port", port_flush, subr01, (SCM port))
{
  port = verify_port(port, PORT_WRITE);
  if (STk_flush(port))
    general_io_error(io_write_error, "cannot flush port ~S", port);
  return STk_void;
}


/*
<doc EXT port-current-line
 * (port-current-line)
 * (port-current-line port)
 *
 * Returns the current line number associated to the given input |port| as an
 * integer. The |port| argument may be omitted, in which case it defaults to
1508
 * the value returned by |current-input-port|.
1509
 * @l
eg's avatar
eg committed
1510
 * ,(bold "Note"): The |port-seek|, |read-chars| and |read-chars!| procedures
1511 1512
 * generally break the line-number. After using one of theses procedures, the
 * value returned by |port-current-line| will be |-1| (except a |port-seek|
eg's avatar
eg committed
1513 1514 1515 1516 1517
 * at the beginning of the port reinitializes the line counter).
doc>
 */
DEFINE_PRIMITIVE("port-current-line", port_current_line, subr01, (SCM port))
{
1518
  port = verify_port(port, PORT_READ | PORT_TEXTUAL);
eg's avatar
eg committed
1519 1520 1521 1522 1523 1524 1525 1526 1527
  return MAKE_INT(PORT_LINE(port));
}


/*
<doc EXT port-current-position
 * (port-current-position)
 * (port-current-position port)
 *
Erick's avatar
Erick committed
1528
 * Returns the position associated to the given |port| as an
1529
 * integer (i.e. number of characters from the beginning of the port).
eg's avatar
eg committed
1530 1531 1532 1533 1534 1535
 * The |port| argument may be omitted, in which case it defaults to
 * the value returned by |current-input-port|.
doc>
 */
DEFINE_PRIMITIVE("port-current-position", port_position, subr01, (SCM port))
{
1536
  if (!port)
Erick's avatar
Erick committed
1537 1538 1539
    port = STk_current_input_port();
  else
    if (!PORTP(port)) STk_error_bad_port(port);
eg's avatar
eg committed
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
  return MAKE_INT(STk_tell(port));
}


/*
<doc EXT seek-file-port
 * (port-seek port pos)
 * (port-seek port pos whence)
 *
 * Sets the file position for the given |port| to the position |pos|.
 * The new position, measured in bytes, is obtained by adding |pos|
 * bytes to the position specified by |whence|. If passed, |whence|
 * must be one of |:start|, |:current| or |:end|. The resulting
 * position is relative to the start of the file, the current position
 * indicator, or end-of-file, respectively. If |whence| is omitted, it
 * defaults to |:start|.
1556
 * @l
1557 1558
 * ,(bold "Note"): After using port-seek, the value returned by
 * |port-current-line| may be incorrect.
eg's avatar
eg committed
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
doc>
 */
DEFINE_PRIMITIVE("port-seek", port_seek, subr23, (SCM port, SCM pos, SCM w))
{
  off_t n;
  long p = STk_integer_value(pos);
  int whence = -1;

  if (!PORTP(port))  STk_error_bad_port(port);
  if (p == LONG_MIN) STk_error_bad_io_param("bad offset ~S", pos);
  if (w) {
    if (KEYWORDP(w)) {
      char *s = KEYWORD_PNAME(w);
1572

eg's avatar
eg committed
1573 1574 1575 1576
      if (strcmp(s, "start") == 0) whence = SEEK_SET;
      else if (strcmp(s, "end") == 0) whence = SEEK_END;
      else if (strcmp(s, "current") == 0) whence = SEEK_CUR;
    }
1577 1578
  }
  else
eg's avatar
eg committed
1579
    whence = SEEK_SET;
1580

eg's avatar
eg committed
1581 1582
  if (whence < 0)
     STk_error_bad_io_param("bad keyword position ~S", w);
1583 1584

  /* ----------*/
eg's avatar
eg committed
1585 1586 1587 1588 1589
  STk_flush(port);
  n = STk_seek(port, (off_t) p, whence);

  if (n < 0)
    general_io_error(io_malformed, "cannot seek position ~S", pos);
1590

eg's avatar
eg committed
1591 1592 1593 1594 1595 1596 1597
  return STk_long2integer((long) n);
}

/*
<doc EXT port-rewind
 * (port-rewind port)
 *
1598
 * Sets the port position to the beginning of |port|. The value returned by
eg's avatar
eg committed
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
 * |port-rewind| is ,(emph "void").
doc>
 */
DEFINE_PRIMITIVE("port-rewind", port_rewind, subr1, (SCM port))
{
  if (!PORTP(port)) STk_error_bad_port(port);
  STk_rewind(port);
  return STk_void;
}

1609 1610 1611 1612 1613
/*
<doc EXT port-close-hook-set!
 * (port-close-hook-set! port thunk)
 *
 * Associate the procedure |thunk| to |port|. The thunk will be called
1614
 * the first time |port| is closed.
1615 1616 1617 1618 1619
 * @lisp
 * (let* ((tmp (temporary-file-name))
 *        (p   (open-output-file tmp))
 *        (foo #t))
 *   (port-close-hook-set! p
Erick's avatar
Erick committed
1620 1621 1622
 *                      (lambda()
 *                        (remove-file tmp)
 *                        (set! foo #t)))
1623 1624 1625 1626 1627
 *   (close-port p)
 *   foo)
 * @end lisp
doc>
*/
1628
DEFINE_PRIMITIVE("port-close-hook-set!", port_close_hook_set, subr2,
Erick's avatar
Erick committed
1629
                 (SCM port, SCM thunk))
1630 1631 1632
{
  if (!PORTP(port)) STk_error_bad_port(port);
  if (!STk_procedurep(thunk)) STk_error("bad procedure ~S", thunk);
1633

1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
  PORT_CLOSEHOOK(port) = thunk;
  return STk_void;
}


/*
<doc EXT port-close-hook
 * (port-close-hook port)
 *
 * Returns the user close procedure associated to the given |port|.
doc>
*/
DEFINE_PRIMITIVE("port-close-hook", port_close_hook, subr1, (SCM port))
{
  if (!PORTP(port)) STk_error_bad_port(port);
  return PORT_CLOSEHOOK(port);
}


eg's avatar
eg committed
1653
/*===========================================================================*\
1654
 *
eg's avatar
eg committed
1655
 * Initializations
1656
 *
eg's avatar
eg committed
1657 1658 1659
\*===========================================================================*/
static void initialize_io_conditions(void)
{
1660
  SCM module = STk_STklos_module;
eg's avatar
eg committed
1661

Erick's avatar
Erick committed
1662
#define DEFCOND(x, name, parent, slots)                 \
eg's avatar
eg committed
1663 1664
  x = STk_defcond_type(name, parent, slots, module)

eg's avatar
eg committed
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
  DEFCOND(io_error, "&i/o-error", STk_err_mess_condition, STk_nil);

  DEFCOND(io_port_error, "&i/o-port-error", io_error, LIST1(STk_intern("port")));
  DEFCOND(io_read_error, "&i/o-read-error", io_port_error, STk_nil);
  DEFCOND(io_write_error, "&i/o-write-error", io_port_error, STk_nil);
  DEFCOND(io_closed_error, "&i/o-closed-error", io_port_error, STk_nil);

  DEFCOND(io_fn_error,"&i/o-filename-error",io_error,LIST1(STk_intern("filename")));
  DEFCOND(io_malformed, "&i/o-malformed-filename-error", io_fn_error, STk_nil);
  DEFCOND(io_prot_error, "&i/o-file-protection-error", io_fn_error, STk_nil);
  DEFCOND(io_ro_error, "&i/o-file-is-read-only-error", io_prot_error, STk_nil);
  DEFCOND(io_exists_error, "&i/o-file-already-exists-error", io_fn_error, STk_nil);
  DEFCOND(io_no_file_error, "&i/o-no-such-file-error", io_fn_error, STk_nil);
  DEFCOND(io_bad_param,"&i/o-bad-parameter",io_error,LIST1(STk_intern("parameter")));
}


static void print_port(SCM obj, SCM port, int mode)
{
  PORT_PRINT(obj)(obj, port);
}


/* The stucture which describes the port type */
static struct extended_type_descr xtype_port = {
Erick's avatar
Erick committed
1690 1691
  "port",                       /* name */
  print_port                    /* print function */
eg's avatar
eg committed
1692 1693 1694 1695 1696 1697 1698 1699
};



/*===========================================================================*/

int STk_init_port(void)
{
1700 1701
  /* Define a constant for lines terminated by CR/LF to avoid multiple
   * allocations. Make it constant to avoid the user break it
eg's avatar
eg committed
1702
   */
Erick's avatar
Erick committed
1703
  CrLf                 = STk_Cstring2string("\r\n");
eg's avatar
eg committed
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
  BOXED_INFO(CrLf)    |= STRING_CONST;

  /* Define the port file */
  DEFINE_XTYPE(port, &xtype_port);

  /* Initialize  I/O Condition (aka SRFI-36) */
  initialize_io_conditions();

  /* and its associated primitives */
  ADD_PRIMITIVE(input_portp);
  ADD_PRIMITIVE(output_portp);
1715 1716
  ADD_PRIMITIVE(binary_portp);
  ADD_PRIMITIVE(textual_portp);
Erick's avatar
Erick committed
1717
  ADD_PRIMITIVE(portp);
eg's avatar
eg committed
1718 1719 1720 1721 1722 1723 1724 1725
  ADD_PRIMITIVE(interactive_portp);
  ADD_PRIMITIVE(current_input_port);
  ADD_PRIMITIVE