This is gambit-c.info, produced by makeinfo version 4.8 from
gambit-c.txi.

START-INFO-DIR-ENTRY
* Gambit-C: (gambit-c).		A portable implementation of Scheme.
* gsi: (gambit-c) interpreter.	Gambit interpreter.
* gsc: (gambit-c) compiler.	Gambit compiler.
END-INFO-DIR-ENTRY

   This file documents Gambit-C, a portable implementation of Scheme.

   Copyright (C) 1994-2009 Marc Feeley.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that
the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the copyright holder.


File: gambit-c.info,  Node: Exception objects related to threads,  Next: Exception objects related to C-interface,  Prev: Exception objects related to the host environment,  Up: Exceptions

15.4 Exception objects related to threads
=========================================

 -- procedure: scheduler-exception? OBJ
 -- procedure: scheduler-exception-reason EXC
     Scheduler-exception objects are raised by the scheduler when some
     operation requested from the host operating system failed (e.g.
     checking the status of the devices in order to wake up threads
     waiting to perform I/O on these devices).  The parameter EXC must
     be a scheduler-exception object.

     The procedure `scheduler-exception?' returns `#t' when OBJ is a
     scheduler-exception object and `#f' otherwise.

     The procedure `scheduler-exception-reason' returns the
     os-exception object that describes the failure detected by the
     scheduler.


 -- procedure: deadlock-exception? OBJ
     Deadlock-exception objects are raised when the scheduler discovers
     that all threads are blocked and can make no further progress.  In
     that case the scheduler unblocks the primordial-thread and forces
     it to raise a deadlock-exception object.

     The procedure `deadlock-exception?' returns `#t' when OBJ is a
     deadlock-exception object and `#f' otherwise.

     For example:

          > (define (handler exc)
              (if (deadlock-exception? exc)
                  exc
                  'not-deadlock-exception))
          > (with-exception-catcher
              handler
              (lambda () (read (open-vector))))
          #<deadlock-exception #2>


 -- procedure: abandoned-mutex-exception? OBJ
     Abandoned-mutex-exception objects are raised when the current
     thread locks a mutex that was owned by a thread which terminated
     (see `mutex-lock!').

     The procedure `abandoned-mutex-exception?' returns `#t' when OBJ
     is a abandoned-mutex-exception object and `#f' otherwise.

     For example:

          > (define (handler exc)
              (if (abandoned-mutex-exception? exc)
                  exc
                  'not-abandoned-mutex-exception))
          > (with-exception-catcher
              handler
              (lambda ()
                (let ((m (make-mutex)))
                  (thread-join!
                    (thread-start!
                      (make-thread
                        (lambda () (mutex-lock! m)))))
                  (mutex-lock! m))))
          #<abandoned-mutex-exception #2>


 -- procedure: join-timeout-exception? OBJ
 -- procedure: join-timeout-exception-procedure EXC
 -- procedure: join-timeout-exception-arguments EXC
     Join-timeout-exception objects are raised when a call to the
     `thread-join!' procedure reaches its timeout before the target
     thread terminates and a timeout-value parameter is not specified.
     The parameter EXC must be a join-timeout-exception object.

     The procedure `join-timeout-exception?' returns `#t' when OBJ is a
     join-timeout-exception object and `#f' otherwise.

     The procedure `join-timeout-exception-procedure' returns the
     procedure that raised EXC.

     The procedure `join-timeout-exception-arguments' returns the list
     of arguments of the procedure that raised EXC.

     For example:

          > (define (handler exc)
              (if (join-timeout-exception? exc)
                  (list (join-timeout-exception-procedure exc)
                        (join-timeout-exception-arguments exc))
                  'not-join-timeout-exception))
          > (with-exception-catcher
              handler
              (lambda ()
                (thread-join!
                  (thread-start!
                    (make-thread
                      (lambda () (thread-sleep! 10))))
                  5)))
          (#<procedure #2 thread-join!> (#<thread #3> 5))


 -- procedure: started-thread-exception? OBJ
 -- procedure: started-thread-exception-procedure EXC
 -- procedure: started-thread-exception-arguments EXC
     Started-thread-exception objects are raised when the target thread
     of a call to the procedure `thread-start!' is already started.  The
     parameter EXC must be a started-thread-exception object.

     The procedure `started-thread-exception?' returns `#t' when OBJ is
     a started-thread-exception object and `#f' otherwise.

     The procedure `started-thread-exception-procedure' returns the
     procedure that raised EXC.

     The procedure `started-thread-exception-arguments' returns the
     list of arguments of the procedure that raised EXC.

     For example:

          > (define (handler exc)
              (if (started-thread-exception? exc)
                  (list (started-thread-exception-procedure exc)
                        (started-thread-exception-arguments exc))
                  'not-started-thread-exception))
          > (with-exception-catcher
              handler
              (lambda ()
                (let ((t (make-thread (lambda () (expt 2 1000)))))
                  (thread-start! t)
                  (thread-start! t))))
          (#<procedure #2 thread-start!> (#<thread #3>))


 -- procedure: terminated-thread-exception? OBJ
 -- procedure: terminated-thread-exception-procedure EXC
 -- procedure: terminated-thread-exception-arguments EXC
     Terminated-thread-exception objects are raised when the
     `thread-join!' procedure is called and the target thread has
     terminated as a result of a call to the `thread-terminate!'
     procedure.  The parameter EXC must be a
     terminated-thread-exception object.

     The procedure `terminated-thread-exception?' returns `#t' when OBJ
     is a terminated-thread-exception object and `#f' otherwise.

     The procedure `terminated-thread-exception-procedure' returns the
     procedure that raised EXC.

     The procedure `terminated-thread-exception-arguments' returns the
     list of arguments of the procedure that raised EXC.

     For example:

          > (define (handler exc)
              (if (terminated-thread-exception? exc)
                  (list (terminated-thread-exception-procedure exc)
                        (terminated-thread-exception-arguments exc))
                  'not-terminated-thread-exception))
          > (with-exception-catcher
              handler
              (lambda ()
                (thread-join!
                  (thread-start!
                    (make-thread
                      (lambda () (thread-terminate! (current-thread))))))))
          (#<procedure #2 thread-join!> (#<thread #3>))


 -- procedure: uncaught-exception? OBJ
 -- procedure: uncaught-exception-procedure EXC
 -- procedure: uncaught-exception-arguments EXC
 -- procedure: uncaught-exception-reason EXC
     Uncaught-exception objects are raised when an object is raised in a
     thread and that thread does not handle it (i.e. the thread
     terminated because it did not catch an exception it raised).  The
     parameter EXC must be an uncaught-exception object.

     The procedure `uncaught-exception?' returns `#t' when OBJ is an
     uncaught-exception object and `#f' otherwise.

     The procedure `uncaught-exception-procedure' returns the procedure
     that raised EXC.

     The procedure `uncaught-exception-arguments' returns the list of
     arguments of the procedure that raised EXC.

     The procedure `uncaught-exception-reason' returns the object that
     was raised by the thread and not handled by that thread.

     For example:

          > (define (handler exc)
              (if (uncaught-exception? exc)
                  (list (uncaught-exception-procedure exc)
                        (uncaught-exception-arguments exc)
                        (uncaught-exception-reason exc))
                  'not-uncaught-exception))
          > (with-exception-catcher
              handler
              (lambda ()
                (thread-join!
                  (thread-start!
                    (make-thread
                      (lambda () (open-input-file "data" 99)))))))
          (#<procedure #2 thread-join!>
           (#<thread #3>)
           #<wrong-number-of-arguments-exception #4>)



File: gambit-c.info,  Node: Exception objects related to C-interface,  Next: Exception objects related to the reader,  Prev: Exception objects related to threads,  Up: Exceptions

15.5 Exception objects related to C-interface
=============================================

 -- procedure: cfun-conversion-exception? OBJ
 -- procedure: cfun-conversion-exception-procedure EXC
 -- procedure: cfun-conversion-exception-arguments EXC
 -- procedure: cfun-conversion-exception-code EXC
 -- procedure: cfun-conversion-exception-message EXC
     Cfun-conversion-exception objects are raised by the C-interface
     when converting between the Scheme representation and the C
     representation of a value during a call from Scheme to C.  The
     parameter EXC must be a cfun-conversion-exception object.

     The procedure `cfun-conversion-exception?' returns `#t' when OBJ
     is a cfun-conversion-exception object and `#f' otherwise.

     The procedure `cfun-conversion-exception-procedure' returns the
     procedure that raised EXC.

     The procedure `cfun-conversion-exception-arguments' returns the
     list of arguments of the procedure that raised EXC.

     The procedure `cfun-conversion-exception-code' returns an exact
     integer error code that can be converted to a string by the
     `err-code->string' procedure.

     The procedure `cfun-conversion-exception-message' returns `#f' or
     a string giving details of the exception in a human-readable form.

     For example:

          $ cat test1.scm
          (define weird
            (c-lambda (char-string) nonnull-char-string
              "___result = ___arg1;"))
          $ gsc test1.scm
          $ gsi
          Gambit v4.7.1

          > (load "test1")
          "/Users/feeley/gambit/doc/test1.o1"
          > (weird "hello")
          "hello"
          > (define (handler exc)
              (if (cfun-conversion-exception? exc)
                  (list (cfun-conversion-exception-procedure exc)
                        (cfun-conversion-exception-arguments exc)
                        (err-code->string (cfun-conversion-exception-code exc))
                        (cfun-conversion-exception-message exc))
                  'not-cfun-conversion-exception))
          > (with-exception-catcher
              handler
              (lambda () (weird 'not-a-string)))
          (#<procedure #2 weird>
           (not-a-string)
           "(Argument 1) Can't convert to C char-string"
           #f)
          > (with-exception-catcher
              handler
              (lambda () (weird #f)))
          (#<procedure #2 weird>
           (#f)
           "Can't convert result from C nonnull-char-string"
           #f)


 -- procedure: sfun-conversion-exception? OBJ
 -- procedure: sfun-conversion-exception-procedure EXC
 -- procedure: sfun-conversion-exception-arguments EXC
 -- procedure: sfun-conversion-exception-code EXC
 -- procedure: sfun-conversion-exception-message EXC
     Sfun-conversion-exception objects are raised by the C-interface
     when converting between the Scheme representation and the C
     representation of a value during a call from C to Scheme.  The
     parameter EXC must be a sfun-conversion-exception object.

     The procedure `sfun-conversion-exception?' returns `#t' when OBJ
     is a sfun-conversion-exception object and `#f' otherwise.

     The procedure `sfun-conversion-exception-procedure' returns the
     procedure that raised EXC.

     The procedure `sfun-conversion-exception-arguments' returns the
     list of arguments of the procedure that raised EXC.

     The procedure `sfun-conversion-exception-code' returns an exact
     integer error code that can be converted to a string by the
     `err-code->string' procedure.

     The procedure `sfun-conversion-exception-message' returns `#f' or
     a string giving details of the exception in a human-readable form.

     For example:

          $ cat test2.scm
          (c-define (f str) (nonnull-char-string) int "f" ""
            (string->number str))
          (define t1 (c-lambda () int "___result = f (\"123\");"))
          (define t2 (c-lambda () int "___result = f (0);"))
          (define t3 (c-lambda () int "___result = f (\"1.5\");"))
          $ gsc test2.scm
          $ gsi
          Gambit v4.7.1

          > (load "test2")
          "/u/feeley/test2.o1"
          > (t1)
          123
          > (define (handler exc)
              (if (sfun-conversion-exception? exc)
                  (list (sfun-conversion-exception-procedure exc)
                        (sfun-conversion-exception-arguments exc)
                        (err-code->string (sfun-conversion-exception-code exc))
                        (sfun-conversion-exception-message exc))
                  'not-sfun-conversion-exception))
          > (with-exception-catcher handler t2)
          (#<procedure #2 f>
           ()
           "(Argument 1) Can't convert from C nonnull-char-string"
           #f)
          > (with-exception-catcher handler t3)
          (#<procedure #2 f> () "Can't convert result to C int" #f)


 -- procedure: multiple-c-return-exception? OBJ
     Multiple-c-return-exception objects are raised by the C-interface
     when a C to Scheme procedure call returns and that call's stack
     frame is no longer on the C stack because the call has already
     returned, or has been removed from the C stack by a `longjump'.

     The procedure `multiple-c-return-exception?' returns `#t' when OBJ
     is a multiple-c-return-exception object and `#f' otherwise.

     For example:

          $ cat test3.scm
          (c-define (f str) (char-string) scheme-object "f" ""
            (pp (list 'entry 'str= str))
            (let ((k (call-with-current-continuation (lambda (k) k))))
              (pp (list 'exit 'k= k))
              k))
          (define scheme-to-c-to-scheme-and-back
            (c-lambda (char-string) scheme-object
              "___result = f (___arg1);"))
          $ gsc test3.scm
          $ gsi
          Gambit v4.7.1

          > (load "test3")
          "/Users/feeley/gambit/doc/test3.o1"
          > (define (handler exc)
              (if (multiple-c-return-exception? exc)
                  exc
                  'not-multiple-c-return-exception))
          > (with-exception-catcher
              handler
              (lambda ()
                (let ((c (scheme-to-c-to-scheme-and-back "hello")))
                  (pp c)
                  (c 999))))
          (entry str= "hello")
          (exit k= #<procedure #2>)
          #<procedure #2>
          (exit k= 999)
          #<multiple-c-return-exception #3>



File: gambit-c.info,  Node: Exception objects related to the reader,  Next: Exception objects related to evaluation and compilation,  Prev: Exception objects related to C-interface,  Up: Exceptions

15.6 Exception objects related to the reader
============================================

 -- procedure: datum-parsing-exception? OBJ
 -- procedure: datum-parsing-exception-kind EXC
 -- procedure: datum-parsing-exception-parameters EXC
 -- procedure: datum-parsing-exception-readenv EXC
     Datum-parsing-exception objects are raised by the reader (i.e. the
     `read' procedure) when the input does not conform to the grammar
     for datum.  The parameter EXC must be a datum-parsing-exception
     object.

     The procedure `datum-parsing-exception?' returns `#t' when OBJ is
     a datum-parsing-exception object and `#f' otherwise.

     The procedure `datum-parsing-exception-kind' returns a symbol
     denoting the kind of parsing error that was encountered by the
     reader when it raised EXC.  Here is a table of the possible return
     values:

     `datum-or-eof-expected'            Datum or EOF expected
     `datum-expected'                   Datum expected
     `improperly-placed-dot'            Improperly placed dot
     `incomplete-form-eof-reached'      Incomplete form, EOF reached
     `incomplete-form'                  Incomplete form
     `character-out-of-range'           Character out of range
     `invalid-character-name'           Invalid '#\' name
     `illegal-character'                Illegal character
     `s8-expected'                      Signed 8 bit exact integer
                                        expected
     `u8-expected'                      Unsigned 8 bit exact integer
                                        expected
     `s16-expected'                     Signed 16 bit exact integer
                                        expected
     `u16-expected'                     Unsigned 16 bit exact integer
                                        expected
     `s32-expected'                     Signed 32 bit exact integer
                                        expected
     `u32-expected'                     Unsigned 32 bit exact integer
                                        expected
     `s64-expected'                     Signed 64 bit exact integer
                                        expected
     `u64-expected'                     Unsigned 64 bit exact integer
                                        expected
     `inexact-real-expected'            Inexact real expected
     `invalid-hex-escape'               Invalid hexadecimal escape
     `invalid-escaped-character'        Invalid escaped character
     `open-paren-expected'              '(' expected
     `invalid-token'                    Invalid token
     `invalid-sharp-bang-name'          Invalid '#!' name
     `duplicate-label-definition'       Duplicate definition for label
     `missing-label-definition'         Missing definition for label
     `illegal-label-definition'         Illegal definition of label
     `invalid-infix-syntax-character'   Invalid infix syntax character
     `invalid-infix-syntax-number'      Invalid infix syntax number
     `invalid-infix-syntax'             Invalid infix syntax

     The procedure `datum-parsing-exception-parameters' returns a list
     of the parameters associated with the parsing error that was
     encountered by the reader when it raised EXC.

     For example:

          > (define (handler exc)
              (if (datum-parsing-exception? exc)
                  (list (datum-parsing-exception-kind exc)
                        (datum-parsing-exception-parameters exc))
                  'not-datum-parsing-exception))
          > (with-exception-catcher
              handler
              (lambda ()
                (with-input-from-string "(s #\\pace)" read)))
          (invalid-character-name ("pace"))



File: gambit-c.info,  Node: Exception objects related to evaluation and compilation,  Next: Exception objects related to type checking,  Prev: Exception objects related to the reader,  Up: Exceptions

15.7 Exception objects related to evaluation and compilation
============================================================

 -- procedure: expression-parsing-exception? OBJ
 -- procedure: expression-parsing-exception-kind EXC
 -- procedure: expression-parsing-exception-parameters EXC
 -- procedure: expression-parsing-exception-source EXC
     Expression-parsing-exception objects are raised by the evaluator
     and compiler (i.e. the procedures `eval', `compile-file', etc)
     when the input does not conform to the grammar for expression.  The
     parameter EXC must be a expression-parsing-exception object.

     The procedure `expression-parsing-exception?' returns `#t' when
     OBJ is a expression-parsing-exception object and `#f' otherwise.

     The procedure `expression-parsing-exception-kind' returns a symbol
     denoting the kind of parsing error that was encountered by the
     evaluator or compiler when it raised EXC.  Here is a table of the
     possible return values:

     `id-expected'                      Identifier expected
     `ill-formed-namespace'             Ill-formed namespace
     `ill-formed-namespace-prefix'      Ill-formed namespace prefix
     `namespace-prefix-must-be-string'  Namespace prefix must be a string
     `macro-used-as-variable'           Macro name can't be used as a
                                        variable
     `variable-is-immutable'            Variable is immutable
     `ill-formed-macro-transformer'     Macro transformer must be a
                                        lambda expression
     `reserved-used-as-variable'        Reserved identifier can't be used
                                        as a variable
     `ill-formed-special-form'          Ill-formed special form
     `cannot-open-file'                 Can't open file
     `filename-expected'                Filename expected
     `ill-placed-define'                Ill-placed 'define'
     `ill-placed-**include'             Ill-placed '##include'
     `ill-placed-**define-macro'        Ill-placed '##define-macro'
     `ill-placed-**declare'             Ill-placed '##declare'
     `ill-placed-**namespace'           Ill-placed '##namespace'
     `ill-formed-expression'            Ill-formed expression
     `unsupported-special-form'         Interpreter does not support
     `ill-placed-unquote'               Ill-placed 'unquote'
     `ill-placed-unquote-splicing'      Ill-placed 'unquote-splicing'
     `parameter-must-be-id'             Parameter must be an identifier
     `parameter-must-be-id-or-default'  Parameter must be an identifier
                                        or default binding
     `duplicate-parameter'              Duplicate parameter in parameter
                                        list
     `ill-placed-dotted-rest-parameter' Ill-placed dotted rest parameter
     `parameter-expected-after-rest'    #!rest must be followed by a
                                        parameter
     `ill-formed-default'               Ill-formed default binding
     `ill-placed-optional'              Ill-placed #!optional
     `ill-placed-rest'                  Ill-placed #!rest
     `ill-placed-key'                   Ill-placed #!key
     `key-expected-after-rest'          #!key expected after rest
                                        parameter
     `ill-placed-default'               Ill-placed default binding
     `duplicate-variable-definition'    Duplicate definition of a variable
     `empty-body'                       Body must contain at least one
                                        expression
     `variable-must-be-id'              Defined variable must be an
                                        identifier
     `else-clause-not-last'             Else clause must be last
     `ill-formed-selector-list'         Ill-formed selector list
     `duplicate-variable-binding'       Duplicate variable in bindings
     `ill-formed-binding-list'          Ill-formed binding list
     `ill-formed-call'                  Ill-formed procedure call
     `ill-formed-cond-expand'           Ill-formed 'cond-expand'
     `unfulfilled-cond-expand'          Unfulfilled 'cond-expand'

     The procedure `expression-parsing-exception-parameters' returns a
     list of the parameters associated with the parsing error that was
     encountered by the evaluator or compiler when it raised EXC.

     For example:

          > (define (handler exc)
              (if (expression-parsing-exception? exc)
                  (list (expression-parsing-exception-kind exc)
                        (expression-parsing-exception-parameters exc))
                  'not-expression-parsing-exception))
          > (with-exception-catcher
              handler
              (lambda ()
                (eval '(+ do 1))))
          (reserved-used-as-variable (do))


 -- procedure: unbound-global-exception? OBJ
 -- procedure: unbound-global-exception-variable EXC
 -- procedure: unbound-global-exception-code EXC
 -- procedure: unbound-global-exception-rte EXC
     Unbound-global-exception objects are raised when an unbound global
     variable is accessed.  The parameter EXC must be an
     unbound-global-exception object.

     The procedure `unbound-global-exception?' returns `#t' when OBJ is
     an unbound-global-exception object and `#f' otherwise.

     The procedure `unbound-global-exception-variable' returns a symbol
     identifying the unbound global variable.

     For example:

          > (define (handler exc)
              (if (unbound-global-exception? exc)
                  (list 'variable= (unbound-global-exception-variable exc))
                  'not-unbound-global-exception))
          > (with-exception-catcher
              handler
              (lambda () foo))
          (variable= foo)



File: gambit-c.info,  Node: Exception objects related to type checking,  Next: Exception objects related to procedure call,  Prev: Exception objects related to evaluation and compilation,  Up: Exceptions

15.8 Exception objects related to type checking
===============================================

 -- procedure: type-exception? OBJ
 -- procedure: type-exception-procedure EXC
 -- procedure: type-exception-arguments EXC
 -- procedure: type-exception-arg-num EXC
 -- procedure: type-exception-type-id EXC
     Type-exception objects are raised when a primitive procedure is
     called with an argument of incorrect type (i.e. when a run time
     type-check fails).  The parameter EXC must be a type-exception
     object.

     The procedure `type-exception?' returns `#t' when OBJ is a
     type-exception object and `#f' otherwise.

     The procedure `type-exception-procedure' returns the procedure
     that raised EXC.

     The procedure `type-exception-arguments' returns the list of
     arguments of the procedure that raised EXC.

     The procedure `type-exception-arg-num' returns the position of the
     argument whose type is incorrect.  Position 1 is the first
     argument.

     The procedure `type-exception-type-id' returns an identifier of
     the type expected.  The type-id can be a symbol, such as `number'
     and `string-or-nonnegative-fixnum', or a record type descriptor.

     For example:

          > (define (handler exc)
              (if (type-exception? exc)
                  (list (type-exception-procedure exc)
                        (type-exception-arguments exc)
                        (type-exception-arg-num exc)
                        (type-exception-type-id exc))
                  'not-type-exception))
          > (with-exception-catcher
              handler
              (lambda () (vector-ref '#(a b c) 'foo)))
          (#<procedure #2 vector-ref> (#(a b c) foo) 2 exact-integer)
          > (with-exception-catcher
              handler
              (lambda () (time->seconds 'foo)))
          (#<procedure #3 time->seconds> (foo) 1 #<type #4 time>)


 -- procedure: range-exception? OBJ
 -- procedure: range-exception-procedure EXC
 -- procedure: range-exception-arguments EXC
 -- procedure: range-exception-arg-num EXC
     Range-exception objects are raised when a numeric parameter is not
     in the allowed range.  The parameter EXC must be a range-exception
     object.

     The procedure `range-exception?' returns `#t' when OBJ is a
     range-exception object and `#f' otherwise.

     The procedure `range-exception-procedure' returns the procedure
     that raised EXC.

     The procedure `range-exception-arguments' returns the list of
     arguments of the procedure that raised EXC.

     The procedure `range-exception-arg-num' returns the position of
     the argument which is not in the allowed range.  Position 1 is the
     first argument.

     For example:

          > (define (handler exc)
              (if (range-exception? exc)
                  (list (range-exception-procedure exc)
                        (range-exception-arguments exc)
                        (range-exception-arg-num exc))
                  'not-range-exception))
          > (with-exception-catcher
              handler
              (lambda () (string-ref "abcde" 10)))
          (#<procedure #2 string-ref> ("abcde" 10) 2)


 -- procedure: divide-by-zero-exception? OBJ
 -- procedure: divide-by-zero-exception-procedure EXC
 -- procedure: divide-by-zero-exception-arguments EXC
     Divide-by-zero-exception objects are raised when a division by
     zero is attempted.  The parameter EXC must be a
     divide-by-zero-exception object.

     The procedure `divide-by-zero-exception?' returns `#t' when OBJ is
     a divide-by-zero-exception object and `#f' otherwise.

     The procedure `divide-by-zero-exception-procedure' returns the
     procedure that raised EXC.

     The procedure `divide-by-zero-exception-arguments' returns the
     list of arguments of the procedure that raised EXC.

     For example:

          > (define (handler exc)
              (if (divide-by-zero-exception? exc)
                  (list (divide-by-zero-exception-procedure exc)
                        (divide-by-zero-exception-arguments exc))
                  'not-divide-by-zero-exception))
          > (with-exception-catcher
              handler
              (lambda () (/ 5 0 7)))
          (#<procedure #2 /> (5 0 7))


 -- procedure: improper-length-list-exception? OBJ
 -- procedure: improper-length-list-exception-procedure EXC
 -- procedure: improper-length-list-exception-arguments EXC
 -- procedure: improper-length-list-exception-arg-num EXC
     Improper-length-list-exception objects are raised by the `map' and
     `for-each' procedures when they are called with two or more list
     arguments and the lists are not of the same length.  The parameter
     EXC must be an improper-length-list-exception object.

     The procedure `improper-length-list-exception?' returns `#t' when
     OBJ is an improper-length-list-exception object and `#f' otherwise.

     The procedure `improper-length-list-exception-procedure' returns
     the procedure that raised EXC.

     The procedure `improper-length-list-exception-arguments' returns
     the list of arguments of the procedure that raised EXC.

     The procedure `improper-length-list-exception-arg-num' returns the
     position of the argument whose length is the shortest.  Position 1
     is the first argument.

     For example:

          > (define (handler exc)
              (if (improper-length-list-exception? exc)
                  (list (improper-length-list-exception-procedure exc)
                        (improper-length-list-exception-arguments exc)
                        (improper-length-list-exception-arg-num exc))
                  'not-improper-length-list-exception))
          > (with-exception-catcher
              handler
              (lambda () (map + '(1 2) '(3) '(4 5))))
          (#<procedure #2 map> (#<procedure #3 +> (1 2) (3) (4 5)) 3)



File: gambit-c.info,  Node: Exception objects related to procedure call,  Next: Other exception objects,  Prev: Exception objects related to type checking,  Up: Exceptions

15.9 Exception objects related to procedure call
================================================

 -- procedure: wrong-number-of-arguments-exception? OBJ
 -- procedure: wrong-number-of-arguments-exception-procedure EXC
 -- procedure: wrong-number-of-arguments-exception-arguments EXC
     Wrong-number-of-arguments-exception objects are raised when a
     procedure is called with the wrong number of arguments.  The
     parameter EXC must be a wrong-number-of-arguments-exception object.

     The procedure `wrong-number-of-arguments-exception?' returns `#t'
     when OBJ is a wrong-number-of-arguments-exception object and `#f'
     otherwise.

     The procedure `wrong-number-of-arguments-exception-procedure'
     returns the procedure that raised EXC.

     The procedure `wrong-number-of-arguments-exception-arguments'
     returns the list of arguments of the procedure that raised EXC.

     For example:

          > (define (handler exc)
              (if (wrong-number-of-arguments-exception? exc)
                  (list (wrong-number-of-arguments-exception-procedure exc)
                        (wrong-number-of-arguments-exception-arguments exc))
                  'not-wrong-number-of-arguments-exception))
          > (with-exception-catcher
              handler
              (lambda () (open-input-file "data" 99)))
          (#<procedure #2 open-input-file> ("data" 99))


 -- procedure: number-of-arguments-limit-exception? OBJ
 -- procedure: number-of-arguments-limit-exception-procedure EXC
 -- procedure: number-of-arguments-limit-exception-arguments EXC
     Number-of-arguments-limit-exception objects are raised by the
     `apply' procedure when the procedure being called is passed more
     than 8192 arguments.  The parameter EXC must be a
     number-of-arguments-limit-exception object.

     The procedure `number-of-arguments-limit-exception?' returns `#t'
     when OBJ is a number-of-arguments-limit-exception object and `#f'
     otherwise.

     The procedure `number-of-arguments-limit-exception-procedure'
     returns the target procedure of the call to `apply' that raised
     EXC.

     The procedure `number-of-arguments-limit-exception-arguments'
     returns the list of arguments of the target procedure of the call
     to `apply' that raised EXC.

     For example:

          > (define (iota n) (if (= n 0) '() (cons n (iota (- n 1)))))
          > (define (handler exc)
              (if (number-of-arguments-limit-exception? exc)
                  (list (number-of-arguments-limit-exception-procedure exc)
                        (length (number-of-arguments-limit-exception-arguments exc)))
                  'not-number-of-arguments-limit-exception))
          > (with-exception-catcher
              handler
              (lambda () (apply + 1 2 3 (iota 8190))))
          (#<procedure #2 +> 8193)


 -- procedure: nonprocedure-operator-exception? OBJ
 -- procedure: nonprocedure-operator-exception-operator EXC
 -- procedure: nonprocedure-operator-exception-arguments EXC
 -- procedure: nonprocedure-operator-exception-code EXC
 -- procedure: nonprocedure-operator-exception-rte EXC
     Nonprocedure-operator-exception objects are raised when a procedure
     call is executed and the operator position is not a procedure.  The
     parameter EXC must be an nonprocedure-operator-exception object.

     The procedure `nonprocedure-operator-exception?' returns `#t' when
     OBJ is an nonprocedure-operator-exception object and `#f'
     otherwise.

     The procedure `nonprocedure-operator-exception-operator' returns
     the value in operator position of the procedure call that raised
     EXC.

     The procedure `nonprocedure-operator-exception-arguments' returns
     the list of arguments of the procedure call that raised EXC.

     For example:

          > (define (handler exc)
              (if (nonprocedure-operator-exception? exc)
                  (list (nonprocedure-operator-exception-operator exc)
                        (nonprocedure-operator-exception-arguments exc))
                  'not-nonprocedure-operator-exception))
          > (with-exception-catcher
              handler
              (lambda () (11 22 33)))
          (11 (22 33))


 -- procedure: unknown-keyword-argument-exception? OBJ
 -- procedure: unknown-keyword-argument-exception-procedure EXC
 -- procedure: unknown-keyword-argument-exception-arguments EXC
     Unknown-keyword-argument-exception objects are raised when a
     procedure accepting keyword arguments is called and one of the
     keywords supplied is not among those that are expected.  The
     parameter EXC must be an unknown-keyword-argument-exception object.

     The procedure `unknown-keyword-argument-exception?' returns `#t'
     when OBJ is an unknown-keyword-argument-exception object and `#f'
     otherwise.

     The procedure `unknown-keyword-argument-exception-procedure'
     returns the procedure that raised EXC.

     The procedure `unknown-keyword-argument-exception-arguments'
     returns the list of arguments of the procedure that raised EXC.

     For example:

          > (define (handler exc)
              (if (unknown-keyword-argument-exception? exc)
                  (list (unknown-keyword-argument-exception-procedure exc)
                        (unknown-keyword-argument-exception-arguments exc))
                  'not-unknown-keyword-argument-exception))
          > (with-exception-catcher
              handler
              (lambda () ((lambda (#!key (foo 5)) foo) bar: 11)))
          (#<procedure #2> (bar: 11))


 -- procedure: keyword-expected-exception? OBJ
 -- procedure: keyword-expected-exception-procedure EXC
 -- procedure: keyword-expected-exception-arguments EXC
     Keyword-expected-exception objects are raised when a procedure
     accepting keyword arguments is called and a nonkeyword was supplied
     where a keyword was expected.  The parameter EXC must be an
     keyword-expected-exception object.

     The procedure `keyword-expected-exception?' returns `#t' when OBJ
     is an keyword-expected-exception object and `#f' otherwise.

     The procedure `keyword-expected-exception-procedure' returns the
     procedure that raised EXC.

     The procedure `keyword-expected-exception-arguments' returns the
     list of arguments of the procedure that raised EXC.

     For example:

          > (define (handler exc)
              (if (keyword-expected-exception? exc)
                  (list (keyword-expected-exception-procedure exc)
                        (keyword-expected-exception-arguments exc))
                  'not-keyword-expected-exception))
          > (with-exception-catcher
              handler
              (lambda () ((lambda (#!key (foo 5)) foo) 11 22)))
          (#<procedure #2> (11 22))



File: gambit-c.info,  Node: Other exception objects,  Prev: Exception objects related to procedure call,  Up: Exceptions

15.10 Other exception objects
=============================

 -- procedure: error-exception? OBJ
 -- procedure: error-exception-message EXC
 -- procedure: error-exception-parameters EXC
 -- procedure: error MESSAGE OBJ...
     Error-exception objects are raised when the `error' procedure is
     called.  The parameter EXC must be an error-exception object.

     The procedure `error-exception?' returns `#t' when OBJ is an
     error-exception object and `#f' otherwise.

     The procedure `error-exception-message' returns the first argument
     of the call to `error' that raised EXC.

     The procedure `error-exception-parameters' returns the list of
     arguments, starting with the second argument, of the call to
     `error' that raised EXC.

     The `error' procedure raises an error-exception object whose
     message field is MESSAGE and parameters field is the list of
     values OBJ....

     For example:

          > (define (handler exc)
              (if (error-exception? exc)
                  (list (error-exception-message exc)
                        (error-exception-parameters exc))
                  'not-error-exception))
          > (with-exception-catcher
              handler
              (lambda () (error "unexpected object:" 123)))
          ("unexpected object:" (123))



File: gambit-c.info,  Node: Host environment,  Next: I/O and ports,  Prev: Exceptions,  Up: Top

16 Host environment
*******************

The host environment is the set of resources, such as the filesystem,
network and processes, that are managed by the operating system within
which the Scheme program is executing.  This chapter specifies how the
host environment can be accessed from within the Scheme program.

   In this chapter we say that the Scheme program being executed is a
process, even though the concept of process does not exist in some
operating systems supported by Gambit (e.g. MSDOS).

* Menu:

* Handling of file names::                  Handling of file names
* Filesystem operations::                   Filesystem operations
* Shell command execution::                 Shell command execution
* Process termination::                     Process termination
* Command line arguments::                  Command line arguments
* Environment variables::                   Environment variables
* Measuring time::                          Measuring time
* File information::                        File information
* Group information::                       Group information
* User information::                        User information   .
* Host information::                        Host information
* Service information::                     Service information
* Protocol information::                    Protocol information
* Network information::                     Network information


File: gambit-c.info,  Node: Handling of file names,  Next: Filesystem operations,  Prev: Host environment,  Up: Host environment

16.1 Handling of file names
===========================

Gambit uses a naming convention for files that is compatible with the
one used by the host environment but extended to allow referring to the
"home directory" of the current user or some specific user and the
"installation directories".

   A "path" is a string that denotes a file, for example
`"src/readme.txt"'.  Each component of a path is separated by a `/'
under UNIX and Mac OS X and by a `/' or `\' under MSDOS and Microsoft
Windows.  A leading separator indicates an absolute path under UNIX,
Mac OS X, MSDOS and Microsoft Windows.  A path which does not contain a
path separator is relative to the "current working directory" on all
operating systems.  A volume specifier such as `C:' may prefix a file
name under MSDOS and Microsoft Windows.

   A path which starts with the characters `~~' denotes a file in an
installation directory.  If nothing follows the `~~' then the directory
denoted is the central installation directory.  Otherwise what follows
the `~~' is the name of the installation directory, for example `~~lib'
denotes the `lib' installation directory.  Note that the location of
the installation directories may be overridden by using the
`-:=DIRECTORY' and `-:~~DIR=DIRECTORY' runtime options or by defining
the `GAMBCOPT' environment variable.

   A path which starts with the character `~' not followed by `~'
denotes a file in the user's home directory.  The user's home directory
is contained in the `HOME' environment variable under UNIX, Mac OS X,
MSDOS and Microsoft Windows.  Under MSDOS and Microsoft Windows, if the
`HOME' environment variable is not defined, the environment variables
`HOMEDRIVE' and `HOMEPATH' are concatenated if they are defined.  If
this fails to yield a home directory, the central installation
directory is used instead.

   A path which starts with the characters `~USERNAME' denotes a file
in the home directory of the given user.  Under UNIX and Mac OS X this
is found using the password file.  There is no equivalent under MSDOS
and Microsoft Windows.

 -- procedure: current-directory [NEW-CURRENT-DIRECTORY]
     The parameter object `current-directory' is bound to the current
     working directory.  Calling this procedure with no argument returns
     the absolute "normalized path" of the directory and calling this
     procedure with one argument sets the directory to
     NEW-CURRENT-DIRECTORY.  The initial binding of this parameter
     object is the current working directory of the current process.
     The path returned by `current-directory' always contains a trailing
     directory separator.  Modifications of the parameter object do not
     change the current working directory of the current process (i.e.
     that is accessible with the UNIX `getcwd()' function and the
     Microsoft Windows `GetCurrentDirectory' function).  It is an error
     to mutate the string returned by `current-directory'.

     For example under UNIX:

          > (current-directory)
          "/Users/feeley/gambit/doc/"
          > (current-directory "..")
          > (current-directory)
          "/Users/feeley/gambit/"
          > (path-expand "foo" "~~")
          "/usr/local/Gambit-C/foo"
          > (parameterize ((current-directory "~~")) (path-expand "foo"))
          "/usr/local/Gambit-C/foo"


 -- procedure: path-expand PATH [ORIGIN-DIRECTORY]
     The procedure `path-expand' takes the path of a file or directory
     and returns an expanded path, which is an absolute path when PATH
     or ORIGIN-DIRECTORY are absolute paths.  The optional
     ORIGIN-DIRECTORY parameter, which defaults to the current working
     directory, is the directory used to resolve relative paths.
     Components of the paths PATH and ORIGIN-DIRECTORY need not exist.

     For example under UNIX:

          > (path-expand "foo")
          "/Users/feeley/gambit/doc/foo"
          > (path-expand "~/foo")
          "/Users/feeley/foo"
          > (path-expand "~~lib/foo")
          "/usr/local/Gambit-C/lib/foo"
          > (path-expand "../foo")
          "/Users/feeley/gambit/doc/../foo"
          > (path-expand "foo" "")
          "foo"
          > (path-expand "foo" "/tmp")
          "/tmp/foo"
          > (path-expand "this/file/does/not/exist")
          "/Users/feeley/gambit/doc/this/file/does/not/exist"
          > (path-expand "")
          "/Users/feeley/gambit/doc/"


 -- procedure: path-normalize PATH [ALLOW-RELATIVE? [ORIGIN-DIRECTORY]]
     The procedure `path-normalize' takes a path of a file or directory
     and returns its normalized path.  The optional ORIGIN-DIRECTORY
     parameter, which defaults to the current working directory, is the
     directory used to resolve relative paths.  All components of the
     paths PATH and ORIGIN-DIRECTORY must exist, except possibly the
     last component of PATH.  A normalized path is a path containing no
     redundant parts and which is consistent with the current structure
     of the filesystem.  A normalized path of a directory will always
     end with a path separator (i.e. `/', `\', or `:' depending on the
     operating system).  The optional ALLOW-RELATIVE? parameter, which
     defaults to `#f', indicates if the path returned can be expressed
     relatively to ORIGIN-DIRECTORY: a `#f' requests an absolute path,
     the symbol `shortest' requests the shortest of the absolute and
     relative paths, and any other value requests the relative path.
     The shortest path is useful for interaction with the user because
     short relative paths are typically easier to read than long
     absolute paths.

     For example under UNIX:

          > (path-expand "../foo")
          "/Users/feeley/gambit/doc/../foo"
          > (path-normalize "../foo")
          "/Users/feeley/gambit/foo"
          > (path-normalize "this/file/does/not/exist")
          *** ERROR IN (console)@3.1 -- No such file or directory
          (path-normalize "this/file/does/not/exist")


 -- procedure: path-extension PATH
 -- procedure: path-strip-extension PATH
 -- procedure: path-directory PATH
 -- procedure: path-strip-directory PATH
 -- procedure: path-strip-trailing-directory-separator PATH
 -- procedure: path-volume PATH
 -- procedure: path-strip-volume PATH
     These procedures extract various parts of a path, which need not
     be a normalized path.  The procedure `path-extension' returns the
     file extension (including the period) or the empty string if there
     is no extension.  The procedure `path-strip-extension' returns the
     path with the extension stripped off.  The procedure
     `path-directory' returns the file's directory (including the last
     path separator) or the empty string if no directory is specified
     in the path.  The procedure `path-strip-directory' returns the
     path with the directory stripped off.  The procedure
     `path-strip-trailing-directory-separator' returns the path with
     the directory separator stripped off if one is at the end of the
     path.  The procedure `path-volume' returns the file's volume
     (including the last path separator) or the empty string if no
     volume is specified in the path.  The procedure
     `path-strip-volume' returns the path with the volume stripped off.

     For example under UNIX:

          > (path-extension "/tmp/foo")
          ""
          > (path-extension "/tmp/foo.txt")
          ".txt"
          > (path-strip-extension "/tmp/foo.txt")
          "/tmp/foo"
          > (path-directory "/tmp/foo.txt")
          "/tmp/"
          > (path-strip-directory "/tmp/foo.txt")
          "foo.txt"
          > (path-strip-trailing-directory-separator "/usr/local/bin/")
          "/usr/local/bin"
          > (path-strip-trailing-directory-separator "/usr/local/bin")
          "/usr/local/bin"
          > (path-volume "/tmp/foo.txt")
          ""
          > (path-volume "C:/tmp/foo.txt")
          "" ; result is "C:" under Microsoft Windows
          > (path-strip-volume "C:/tmp/foo.txt")
          "C:/tmp/foo.txt" ; result is "/tmp/foo.txt" under Microsoft Windows



File: gambit-c.info,  Node: Filesystem operations,  Next: Shell command execution,  Prev: Handling of file names,  Up: Host environment

16.2 Filesystem operations
==========================

 -- procedure: create-directory PATH-OR-SETTINGS
     This procedure creates a directory.  The argument PATH-OR-SETTINGS
     is either a string denoting a filesystem path or a list of port
     settings which must contain a `path:' setting.  Here are the
     settings allowed:

        * `path:' STRING

          This setting indicates the location of the directory to
          create in the filesystem.  There is no default value for this
          setting.

        * `permissions:' 12-BIT-EXACT-INTEGER

          This setting controls the UNIX permissions that will be
          attached to the file if it is created.  The default value of
          this setting is `#o777'.


     For example:

          > (create-directory "newdir")
          > (create-directory "newdir")
          *** ERROR IN (console)@2.1 -- File exists
          (create-directory "newdir")


 -- procedure: create-fifo PATH-OR-SETTINGS
     This procedure creates a FIFO.  The argument PATH-OR-SETTINGS is
     either a string denoting a filesystem path or a list of port
     settings which must contain a `path:' setting.  Here are the
     settings allowed:

        * `path:' STRING

          This setting indicates the location of the FIFO to create in
          the filesystem.  There is no default value for this setting.

        * `permissions:' 12-BIT-EXACT-INTEGER

          This setting controls the UNIX permissions that will be
          attached to the file if it is created.  The default value of
          this setting is `#o666'.


     For example:

          > (create-fifo "fifo")
          > (define a (open-input-file "fifo"))
          > (define b (open-output-file "fifo"))
          > (display "1 22 333" b)
          > (force-output b)
          > (read a)
          1
          > (read a)
          22


 -- procedure: create-link SOURCE-PATH DESTINATION-PATH
     This procedure creates a hard link between SOURCE-PATH and
     DESTINATION-PATH.  The argument SOURCE-PATH must be a string
     denoting the path of an existing file.  The argument
     DESTINATION-PATH must be a string denoting the path of the link to
     create.


 -- procedure: create-symbolic-link SOURCE-PATH DESTINATION-PATH
     This procedure creates a symbolic link between SOURCE-PATH and
     DESTINATION-PATH.  The argument SOURCE-PATH must be a string
     denoting the path of an existing file.  The argument
     DESTINATION-PATH must be a string denoting the path of the
     symbolic link to create.


 -- procedure: rename-file SOURCE-PATH DESTINATION-PATH
     This procedure renames the file SOURCE-PATH to DESTINATION-PATH.
     The argument SOURCE-PATH must be a string denoting the path of an
     existing file.  The argument DESTINATION-PATH must be a string
     denoting the new path of the file.


 -- procedure: copy-file SOURCE-PATH DESTINATION-PATH
     This procedure copies the file SOURCE-PATH to DESTINATION-PATH.
     The argument SOURCE-PATH must be a string denoting the path of an
     existing file.  The argument DESTINATION-PATH must be a string
     denoting the path of the file to create.


 -- procedure: delete-file PATH
     This procedure deletes the file PATH.  The argument PATH must be a
     string denoting the path of an existing file.


 -- procedure: delete-directory PATH
     This procedure deletes the directory PATH.  The argument PATH must
     be a string denoting the path of an existing directory.


 -- procedure: directory-files [PATH-OR-SETTINGS]
     This procedure returns the list of the files in a directory.  The
     argument PATH-OR-SETTINGS is either a string denoting a filesystem
     path to a directory or a list of settings which must contain a
     `path:' setting.  If it is not specified, PATH-OR-SETTINGS
     defaults to the current directory (the value bound to the
     `current-directory' parameter object).  Here are the settings
     allowed:

        * `path:' STRING

          This setting indicates the location of the directory in the
          filesystem.  There is no default value for this setting.

        * `ignore-hidden:' ( `#f' | `#t' | `dot-and-dot-dot' )

          This setting controls whether hidden-files will be returned.
          Under UNIX and Mac OS X hidden-files are those that start
          with a period (such as `.', `..', and `.profile').  Under
          Microsoft Windows hidden files are the `.' and `..' entries
          and the files whose "hidden file" attribute is set.  A
          setting of `#f' will enumerate all the files.  A setting of
          `#t' will only enumerate the files that are not hidden.  A
          setting of `dot-and-dot-dot' will enumerate all the files
          except for the `.' and `..' hidden files.  The default value
          of this setting is `#t'.


     For example:

          > (directory-files)
          ("complex" "README" "simple")
          > (directory-files "../include")
          ("config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")
          > (directory-files (list path: "../include" ignore-hidden: #f))
          ("." ".." "config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")



File: gambit-c.info,  Node: Shell command execution,  Next: Process termination,  Prev: Filesystem operations,  Up: Host environment

16.3 Shell command execution
============================

 -- procedure: shell-command COMMAND
     The procedure `shell-command' calls up the shell to execute
     COMMAND which must be a string.  This procedure returns the exit
     status of the shell in the form that the C library's `system'
     routine returns.

     For example under UNIX:

          > (shell-command "ls -sk f*.scm")
          4 fact.scm   4 fib.scm
          0



File: gambit-c.info,  Node: Process termination,  Next: Command line arguments,  Prev: Shell command execution,  Up: Host environment

16.4 Process termination
========================

 -- procedure: exit [STATUS]
     The procedure `exit' causes the process to terminate with the
     status STATUS which must be an exact integer in the range 0 to
     255.  If it is not specified, STATUS defaults to 0.

     For example under UNIX:

          $ gsi
          Gambit v4.7.1

          > (exit 42)
          $ echo $?
          42



File: gambit-c.info,  Node: Command line arguments,  Next: Environment variables,  Prev: Process termination,  Up: Host environment

16.5 Command line arguments
===========================

 -- procedure: command-line
     This procedure returns a list of strings corresponding to the
     command line arguments, including the program file name as the
     first element of the list.  When the interpreter executes a Scheme
     script, the list returned by `command-line' contains the script's
     absolute path followed by the remaining command line arguments.

     For example under UNIX:

          $ gsi -:d -e "(pretty-print (command-line))"
          ("gsi" "-e" "(pretty-print (command-line))")
          $ cat foo
          #!/usr/local/Gambit-C/bin/gsi-script
          (pretty-print (command-line))
          $ ./foo 1 2 "3 4"
          ("/u/feeley/./foo" "1" "2" "3 4")



File: gambit-c.info,  Node: Environment variables,  Next: Measuring time,  Prev: Command line arguments,  Up: Host environment

16.6 Environment variables
==========================

 -- procedure: getenv NAME [DEFAULT]
 -- procedure: setenv NAME [NEW-VALUE]
     The procedure `getenv' returns the value of the environment
     variable NAME of the current process.  Variable names are denoted
     with strings.  A string is returned if the environment variable is
     bound, otherwise DEFAULT is returned if it is specified, otherwise
     an exception is raised.

     The procedure `setenv' changes the binding of the environment
     variable NAME to NEW-VALUE which must be a string.  If NEW-VALUE
     is not specified the binding is removed.

     For example under UNIX:

          > (getenv "HOME")
          "/Users/feeley"
          > (getenv "DOES_NOT_EXIST" #f)
          #f
          > (setenv "DOES_NOT_EXIST" "it does now")
          > (getenv "DOES_NOT_EXIST" #f)
          "it does now"
          > (setenv "DOES_NOT_EXIST")
          > (getenv "DOES_NOT_EXIST" #f)
          #f
          > (getenv "DOES_NOT_EXIST")
          *** ERROR IN (console)@7.1 -- Unbound OS environment variable
          (getenv "DOES_NOT_EXIST")



File: gambit-c.info,  Node: Measuring time,  Next: File information,  Prev: Environment variables,  Up: Host environment

16.7 Measuring time
===================

Procedures are available for measuring real time (aka "wall" time) and
cpu time (the amount of time the cpu has been executing the process).
The resolution of the real time and cpu time clock is operating system
dependent.  Typically the resolution of the cpu time clock is rather
coarse (measured in "ticks" of 1/60th or 1/100th of a second).  Real
time is internally computed relative to some arbitrary point in time
using floating point numbers, which means that there is a gradual loss
of resolution as time elapses.  Moreover, some operating systems report
time in number of ticks using a 32 bit integer so the value returned by
the time related procedures may wraparound much before any significant
loss of resolution occurs (for example 2.7 years if ticks are 1/50th of
a second).

 -- procedure: current-time
 -- procedure: time? OBJ
 -- procedure: time->seconds TIME
 -- procedure: seconds->time X
     The procedure `current-time' returns a "time object" representing
     the current point in real time.

     The procedure `time?' returns `#t' when OBJ is a time object and
     `#f' otherwise.

     The procedure `time->seconds' converts the time object TIME into
     an inexact real number representing the number of seconds elapsed
     since the "epoch" (which is 00:00:00 Coordinated Universal Time
     01-01-1970).

     The procedure `seconds->time' converts the real number X
     representing the number of seconds elapsed since the "epoch" into a
     time object.

     For example:

          > (current-time)
          #<time #2>
          > (time? (current-time))
          #t
          > (time? 123)
          #f
          > (time->seconds (current-time))
          1083118758.63973
          > (time->seconds (current-time))
          1083118759.909163
          > (seconds->time (+ 10 (time->seconds (current-time))
          #<time #3>  ; a time object representing 10 seconds in the future


 -- procedure: process-times
 -- procedure: cpu-time
 -- procedure: real-time
     The procedure `process-times' returns a three element f64vector
     containing the cpu time that has been used by the program and the
     real time that has elapsed since it was started.  The first element
     corresponds to "user" time in seconds, the second element
     corresponds to "system" time in seconds and the third element is
     the elapsed real time in seconds.  On operating systems that can't
     differentiate user and system time, the system time is zero.  On
     operating systems that can't measure cpu time, the user time is
     equal to the elapsed real time and the system time is zero.

     The procedure `cpu-time' returns the cpu time in seconds that has
     been used by the program (user time plus system time).

     The procedure `real-time' returns the real time that has elapsed
     since the program was started.

     For example:

          > (process-times)
          #f64(.02794 .021754 .159926176071167)
          > (cpu-time)
          .051223
          > (real-time)
          .40660619735717773


 -- special form: time expr [PORT]
     The `time' special form evaluates expr and returns the result.  As
     a side effect it displays a message on the port PORT which
     indicates various statistics about the evaluation of expr
     including how long the evaluation took (in real time and cpu time),
     how much time was spent in the garbage collector, how much memory
     was allocated during the evaluation and how many minor and major
     page faults occured (0 is reported if not running under UNIX).  If
     it is not specified, PORT defaults to the interaction channel
     (i.e. the output will appear at the REPL).

     For example:

          > (define (f x)
              (let loop ((x x) (lst '()))
                (if (= x 0)
                    lst
                    (loop (- x 1) (cons x lst)))))
          > (length (time (f 100000)))
          (time (f 100000))
              683 ms real time
              558 ms cpu time (535 user, 23 system)
              8 collections accounting for 102 ms real time (70 user, 5 system)
              6400160 bytes allocated
              no minor faults
              no major faults
          100000



File: gambit-c.info,  Node: File information,  Next: Group information,  Prev: Measuring time,  Up: Host environment

16.8 File information
=====================

 -- procedure: file-exists? PATH [CHASE?]
     The PATH argument must be a string.  This procedure returns `#t'
     when a file by that name exists, and returns `#f' otherwise.

     When CHASE? is present and `#f', symbolic links will not be
     chased, in other words if PATH refers to a symbolic link,
     `file-exists?' will return `#t' whether or not it points to an
     existing file.

     For example:

          > (file-exists? "nofile")
          #f


 -- procedure: file-info PATH [CHASE?]
     This procedure accesses the filesystem to get information about the
     file whose location is given by the string PATH.  A
     file-information record is returned that contains the file's type,
     the device number, the inode number, the mode (permission bits),
     the number of links, the file's user id, the file's group id, the
     file's size in bytes, the times of last-access, last-modification
     and last-change, the attributes, and the creation time.

     When CHASE? is present and `#f', symbolic links will not be
     chased, in other words if PATH refers to a symbolic link the
     `file-info' procedure will return information about the link
     rather than the file it links to.

     For example:

          > (file-info "/dev/tty")
          #<file-info #2
             type: character-special
             device: 19513156
             inode: 20728196
             mode: 438
             number-of-links: 1
             owner: 0
             group: 0
             size: 0
             last-access-time: #<time #3>
             last-modification-time: #<time #4>
             last-change-time: #<time #5>
             attributes: 128
             creation-time: #<time #6>>


 -- procedure: file-info? OBJ
     This procedure returns `#t' when OBJ is a file-information record
     and `#f' otherwise.

     For example:

          > (file-info? (file-info "/dev/tty"))
          #t
          > (file-info? 123)
          #f


 -- procedure: file-info-type FILE-INFO
     Returns the type field of the file-information record FILE-INFO.
     The type is denoted by a symbol.  The following types are possible:

    `regular'
          Regular file

    `directory'
          Directory

    `character-special'
          Character special device

    `block-special'
          Block special device

    `fifo'
          FIFO

    `symbolic-link'
          Symbolic link

    `socket'
          Socket

    `unknown'
          File is of an unknown type

     For example:

          > (file-info-type (file-info "/dev/tty"))
          character-special
          > (file-info-type (file-info "/dev"))
          directory


 -- procedure: file-info-device FILE-INFO
     Returns the device field of the file-information record FILE-INFO.

     For example:

          > (file-info-device (file-info "/dev/tty"))
          19513156


 -- procedure: file-info-inode FILE-INFO
     Returns the inode field of the file-information record FILE-INFO.

     For example:

          > (file-info-inode (file-info "/dev/tty"))
          20728196


 -- procedure: file-info-mode FILE-INFO
     Returns the mode field of the file-information record FILE-INFO.

     For example:

          > (file-info-mode (file-info "/dev/tty"))
          438


 -- procedure: file-info-number-of-links FILE-INFO
     Returns the number-of-links field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-number-of-links (file-info "/dev/tty"))
          1


 -- procedure: file-info-owner FILE-INFO
     Returns the owner field of the file-information record FILE-INFO.

     For example:

          > (file-info-owner (file-info "/dev/tty"))
          0


 -- procedure: file-info-group FILE-INFO
     Returns the group field of the file-information record FILE-INFO.

     For example:

          > (file-info-group (file-info "/dev/tty"))
          0


 -- procedure: file-info-size FILE-INFO
     Returns the size field of the file-information record FILE-INFO.

     For example:

          > (file-info-size (file-info "/dev/tty"))
          0


 -- procedure: file-info-last-access-time FILE-INFO
     Returns the last-access-time field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-last-access-time (file-info "/dev/tty"))
          #<time #2>


 -- procedure: file-info-last-modification-time FILE-INFO
     Returns the last-modification-time field of the file-information
     record FILE-INFO.

     For example:

          > (file-info-last-modification-time (file-info "/dev/tty"))
          #<time #2>


 -- procedure: file-info-last-change-time FILE-INFO
     Returns the last-change-time field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-last-change-time (file-info "/dev/tty"))
          #<time #2>


 -- procedure: file-info-attributes FILE-INFO
     Returns the attributes field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-attributes (file-info "/dev/tty"))
          128


 -- procedure: file-info-creation-time FILE-INFO
     Returns the creation-time field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-creation-time (file-info "/dev/tty"))
          #<time #2>


 -- procedure: file-type PATH
 -- procedure: file-device PATH
 -- procedure: file-inode PATH
 -- procedure: file-mode PATH
 -- procedure: file-number-of-links PATH
 -- procedure: file-owner PATH
 -- procedure: file-group PATH
 -- procedure: file-size PATH
 -- procedure: file-last-access-time PATH
 -- procedure: file-last-modification-time PATH
 -- procedure: file-last-change-time PATH
 -- procedure: file-attributes PATH
 -- procedure: file-creation-time PATH
     These procedures combine a call to the `file-info' procedure and a
     call to a file-information record field accessor.  For instance
     `(file-type PATH)' is equivalent to `(file-info-type (file-info
     PATH))'.



File: gambit-c.info,  Node: Group information,  Next: User information,  Prev: File information,  Up: Host environment

16.9 Group information
======================

 -- procedure: group-info GROUP-NAME-OR-ID
     This procedure accesses the group database to get information
     about the group identified by GROUP-NAME-OR-ID, which is the
     group's symbolic name (string) or the group's GID (exact integer).
     A group-information record is returned that contains the group's
     symbolic name, the group's id (GID), and the group's members (list
     of symbolic user names).

     For example:

          > (group-info "staff")
          #<group-info #2 name: "staff" gid: 20 members: ("root")>
          > (group-info 29)
          #<group-info #3
             name: "certusers"
             gid: 29
             members: ("root" "jabber" "postfix" "cyrusimap")>
          > (group-info 5000)
          *** ERROR IN (console)@3.1 -- Resource temporarily unavailable
          (group-info 5000)


 -- procedure: group-info? OBJ
     This procedure returns `#t' when OBJ is a group-information record
     and `#f' otherwise.

     For example:

          > (group-info? (group-info "daemon"))
          #t
          > (group-info? 123)
          #f


 -- procedure: group-info-name GROUP-INFO
     Returns the symbolic name field of the group-information record
     GROUP-INFO.

     For example:

          > (group-info-name (group-info 29))
          "certusers"


 -- procedure: group-info-gid GROUP-INFO
     Returns the group id field of the group-information record
     GROUP-INFO.

     For example:

          > (group-info-gid (group-info "staff"))
          20


 -- procedure: group-info-members GROUP-INFO
     Returns the members field of the group-information record
     GROUP-INFO.

     For example:

          > (group-info-members (group-info "staff"))
          ("root")



File: gambit-c.info,  Node: User information,  Next: Host information,  Prev: Group information,  Up: Host environment

16.10 User information
======================

 -- procedure: user-name
     This procedure returns the user's name as a string.

     For example:

          > (user-name)
          "feeley"


 -- procedure: user-info USER-NAME-OR-ID
     This procedure accesses the user database to get information about
     the user identified by USER-NAME-OR-ID, which is the user's
     symbolic name (string) or the user's UID (exact integer).  A
     user-information record is returned that contains the user's
     symbolic name, the user's id (UID), the user's group id (GID), the
     path to the user's home directory, and the user's login shell.

     For example:

          > (user-info "feeley")
          #<user-info #2
             name: "feeley"
             uid: 506
             gid: 506
             home: "/Users/feeley"
             shell: "/bin/bash">
          > (user-info 0)
          #<user-info #3 name: "root" uid: 0 gid: 0 home: "/var/root" shell: "/bin/sh">
          > (user-info 5000)
          *** ERROR IN (console)@3.1 -- Resource temporarily unavailable
          (user-info 5000)


 -- procedure: user-info? OBJ
     This procedure returns `#t' when OBJ is a user-information record
     and `#f' otherwise.

     For example:

          > (user-info? (user-info "feeley"))
          #t
          > (user-info? 123)
          #f


 -- procedure: user-info-name USER-INFO
     Returns the symbolic name field of the user-information record
     USER-INFO.

     For example:

          > (user-info-name (user-info 0))
          "root"


 -- procedure: user-info-uid USER-INFO
     Returns the user id field of the user-information record USER-INFO.

     For example:

          > (user-info-uid (user-info "feeley"))
          506


 -- procedure: user-info-gid USER-INFO
     Returns the group id field of the user-information record
     USER-INFO.

     For example:

          > (user-info-gid (user-info "feeley"))
          506


 -- procedure: user-info-home USER-INFO
     Returns the home directory field of the user-information record
     USER-INFO.

     For example:

          > (user-info-home (user-info 0))
          "/var/root"


 -- procedure: user-info-shell USER-INFO
     Returns the shell field of the user-information record USER-INFO.

     For example:

          > (user-info-shell (user-info 0))
          "/bin/sh"



File: gambit-c.info,  Node: Host information,  Next: Service information,  Prev: User information,  Up: Host environment

16.11 Host information
======================

 -- procedure: host-name
     This procedure returns the machine's host name as a string.

     For example:

          > (host-name)
          "mega.iro.umontreal.ca"


 -- procedure: host-info HOST-NAME
     This procedure accesses the internet host database to get
     information about the machine whose name is denoted by the string
     HOST-NAME.  A host-information record is returned that contains
     the official name of the machine, a list of aliases (alternative
     names), and a non-empty list of IP addresses for this machine.  An
     exception is raised when HOST-NAME does not appear in the database.

     For example:

          > (host-info "www.google.com")
          #<host-info #2
             name: "www.l.google.com"
             aliases: ("www.google.com")
             addresses: (#u8(66 249 85 99) #u8(66 249 85 104))>
          > (host-info "unknown.domain")
          *** ERROR IN (console)@2.1 -- Unknown host
          (host-info "unknown.domain")


 -- procedure: host-info? OBJ
     This procedure returns `#t' when OBJ is a host-information record
     and `#f' otherwise.

     For example:

          > (host-info? (host-info "www.google.com"))
          #t
          > (host-info? 123)
          #f


 -- procedure: host-info-name HOST-INFO
     Returns the official name field of the host-information record
     HOST-INFO.

     For example:

          > (host-info-name (host-info "www.google.com"))
          "www.l.google.com"


 -- procedure: host-info-aliases HOST-INFO
     Returns the aliases field of the host-information record
     HOST-INFO.  This field is a possibly empty list of strings.

     For example:

          > (host-info-aliases (host-info "www.google.com"))
          ("www.google.com")


 -- procedure: host-info-addresses HOST-INFO
     Returns the addresses field of the host-information record
     HOST-INFO.  This field is a non-empty list of u8vectors denoting
     IP addresses.

     For example:

          > (host-info-addresses (host-info "www.google.com"))
          (#u8(66 249 85 99) #u8(66 249 85 104))


 -- procedure: address-infos [`host:' HOST] [`service:' SERVICE]
          [`family:' FAMILY] [`socket-type:' SOCKET-TYPE] [`protocol:'
          PROTOCOL]
     This procedure is an interface to the `getaddrinfo' system call.
     It accesses the internet host database to get information about the
     machine whose name is denoted by the string HOST and service is
     denoted by the string SERVICE and network address family is FAMILY
     (`INET' or `INET6') and network socket-type is SOCKET-TYPE
     (`STREAM' or `DGRAM' or `RAW') and network protocol is SOCKET-TYPE
     (`TCP' or `UDP').  A list of address-information records is
     returned.

     For example:

          > (address-infos host: "ftp.at.debian.org")
          (#<address-info #2
              family: INET6
              socket-type: DGRAM
              protocol: UDP
              socket-info:
               #<socket-info #3
                  family: INET6
                  port-number: 0
                  address: #u16(8193 2136 2 1 0 0 0 16)>>
           #<address-info #4
              family: INET6
              socket-type: STREAM
              protocol: TCP
              socket-info:
               #<socket-info #5
                  family: INET6
                  port-number: 0
                  address: #u16(8193 2136 2 1 0 0 0 16)>>
           #<address-info #6
              family: INET
              socket-type: DGRAM
              protocol: UDP
              socket-info:
               #<socket-info #7
                  family: INET
                  port-number: 0
                  address: #u8(213 129 232 18)>>
           #<address-info #8
              family: INET
              socket-type: STREAM
              protocol: TCP
              socket-info:
               #<socket-info #9
                  family: INET
                  port-number: 0
                  address: #u8(213 129 232 18)>>)
          > (address-infos host: "ftp.at.debian.org"
                           family: 'INET
                           protocol: 'TCP)
          (#<address-info #10
              family: INET
              socket-type: STREAM
              protocol: TCP
              socket-info:
               #<socket-info #11
                  family: INET
                  port-number: 0
                  address: #u8(213 129 232 18)>>)
          > (address-infos host: "unknown.domain")
          *** ERROR IN (console)@5.1 -- nodename nor servname provided, or not known
          (address-infos host: "unknown.domain")


 -- procedure: address-info? OBJ
     This procedure returns `#t' when OBJ is an address-information
     record and `#f' otherwise.

     For example:

          > (map address-info?
                 (address-infos host: "ftp.at.debian.org"))
          (#t #t #t #t)
          > (address-info? 123)
          #f


 -- procedure: address-info-family ADDRESS-INFO
     Returns the family field of the address-information record
     ADDRESS-INFO.

     For example:

          > (map address-info-family
                 (address-infos host: "ftp.at.debian.org"))
          (INET6 INET6 INET INET)


 -- procedure: address-info-socket-type ADDRESS-INFO
     Returns the socket-type field of the address-information record
     ADDRESS-INFO.

     For example:

          > (map address-info-socket-type
                 (address-infos host: "ftp.at.debian.org"))
          (DGRAM STREAM DGRAM STREAM)


 -- procedure: address-info-protocol ADDRESS-INFO
     Returns the protocol field of the address-information record
     ADDRESS-INFO.

     For example:

          > (map address-info-protocol
                 (address-infos host: "ftp.at.debian.org"))
          (UDP TCP UDP TCP)


 -- procedure: address-info-socket-info ADDRESS-INFO
     Returns the socket-info field of the address-information record
     ADDRESS-INFO.

     For example:

          > (map address-info-socket-info
                 (address-infos host: "ftp.at.debian.org"))
          (#<socket-info #2
              family: INET6
              port-number: 0
              address: #u16(8193 2136 2 1 0 0 0 16)>
           #<socket-info #3
              family: INET6
              port-number: 0
              address: #u16(8193 2136 2 1 0 0 0 16)>
           #<socket-info #4
              family: INET
              port-number: 0
              address: #u8(213 129 232 18)>
           #<socket-info #5
              family: INET
              port-number: 0
              address: #u8(213 129 232 18)>)



File: gambit-c.info,  Node: Service information,  Next: Protocol information,  Prev: Host information,  Up: Host environment

16.12 Service information
=========================

 -- procedure: service-info SERVICE-NAME-OR-ID
     This procedure accesses the service database to get information
     about the service identified by SERVICE-NAME-OR-ID, which is the
     service's symbolic name (string) or the service's port number
     (exact integer).  A service-information record is returned that
     contains the service's symbolic name, a list of aliases
     (alternative names), the port number (exact integer), and the
     protocol name (string).  An exception is raised when
     SERVICE-NAME-OR-ID does not appear in the database.

     For example:

          > (service-info "http")
          #<service-info #2
             name: "http"
             aliases: ("www" "www-http")
             port-number: 80
             protocol: "udp">
          > (service-info 80)
          #<service-info #3
             name: "http"
             aliases: ("www" "www-http")
             port-number: 80
             protocol: "udp">


 -- procedure: service-info? OBJ
     This procedure returns `#t' when OBJ is a service-information
     record and `#f' otherwise.

     For example:

          > (service-info? (service-info "http"))
          #t
          > (service-info? 123)
          #f


 -- procedure: service-info-name SERVICE-INFO
     Returns the symbolic name field of the service-information record
     SERVICE-INFO.

     For example:

          > (service-info-name (service-info 80))
          "http"


 -- procedure: service-info-aliases SERVICE-INFO
     Returns the aliases field of the service-information record
     SERVICE-INFO.  This field is a possibly empty list of strings.

     For example:

          > (service-info-aliases (service-info "http"))
          ("www" "www-http")


 -- procedure: service-info-port-number SERVICE-INFO
     Returns the service port number field of the service-information
     record SERVICE-INFO.

     For example:

          > (service-info-port-number (service-info "http"))
          80


 -- procedure: service-info-protocol SERVICE-INFO
     Returns the service protocol name field of the service-information
     record SERVICE-INFO.

     For example:

          > (service-info-protocol (service-info "http"))
          "udp"



File: gambit-c.info,  Node: Protocol information,  Next: Network information,  Prev: Service information,  Up: Host environment

16.13 Protocol information
==========================

 -- procedure: protocol-info PROTOCOL-NAME-OR-ID
     This procedure accesses the protocol database to get information
     about the protocol identified by PROTOCOL-NAME-OR-ID, which is the
     protocol's symbolic name (string) or the protocol's number (exact
     integer).  A protocol-information record is returned that contains
     the protocol's symbolic name, a list of aliases (alternative
     names), and the protocol number (32 bit unsigned exact integer).
     An exception is raised when PROTOCOL-NAME-OR-ID does not appear in
     the database.

     For example:

          > (protocol-info "tcp")
          #<protocol-info #2 name: "tcp" aliases: ("TCP") number: 6>
          > (protocol-info 6)
          #<protocol-info #2 name: "tcp" aliases: ("TCP") number: 6>


 -- procedure: protocol-info? OBJ
     This procedure returns `#t' when OBJ is a protocol-information
     record and `#f' otherwise.

     For example:

          > (protocol-info? (protocol-info "tcp"))
          #t
          > (protocol-info? 123)
          #f


 -- procedure: protocol-info-name PROTOCOL-INFO
     Returns the symbolic name field of the protocol-information record
     PROTOCOL-INFO.

     For example:

          > (protocol-info-name (protocol-info 6))
          "tcp"


 -- procedure: protocol-info-aliases PROTOCOL-INFO
     Returns the aliases field of the protocol-information record
     PROTOCOL-INFO.  This field is a possibly empty list of strings.

     For example:

          > (protocol-info-aliases (protocol-info "tcp"))
          ("TCP")


 -- procedure: protocol-info-number PROTOCOL-INFO
     Returns the protocol number field of the protocol-information
     record PROTOCOL-INFO.

     For example:

          > (protocol-info-number (protocol-info "tcp"))
          6



File: gambit-c.info,  Node: Network information,  Prev: Protocol information,  Up: Host environment

16.14 Network information
=========================

 -- procedure: network-info NETWORK-NAME-OR-ID
     This procedure accesses the network database to get information
     about the network identified by NETWORK-NAME-OR-ID, which is the
     network's symbolic name (string) or the network's number (exact
     integer).  A network-information record is returned that contains
     the network's symbolic name, a list of aliases (alternative
     names), and the network number (32 bit unsigned exact integer).
     An exception is raised when NETWORK-NAME-OR-ID does not appear in
     the database.

     For example:

          > (network-info "loopback")
          #<network-info #2
             name: "loopback"
             aliases: ("loopback-net")
             number: 127>
          > (network-info 127)
          #<network-info #3
             name: "loopback"
             aliases: ("loopback-net")
             number: 127>


 -- procedure: network-info? OBJ
     This procedure returns `#t' when OBJ is a network-information
     record and `#f' otherwise.

     For example:

          > (network-info? (network-info "loopback"))
          #t
          > (network-info? 123)
          #f


 -- procedure: network-info-name NETWORK-INFO
     Returns the symbolic name field of the network-information record
     NETWORK-INFO.

     For example:

          > (network-info-name (network-info 127))
          "loopback"


 -- procedure: network-info-aliases NETWORK-INFO
     Returns the aliases field of the network-information record
     NETWORK-INFO.  This field is a possibly empty list of strings.

     For example:

          > (network-info-aliases (network-info "loopback"))
          ("loopback-net")


 -- procedure: network-info-number NETWORK-INFO
     Returns the network number field of the network-information record
     NETWORK-INFO.

     For example:

          > (network-info-number (network-info "loopback"))
          127



File: gambit-c.info,  Node: I/O and ports,  Next: Lexical syntax and readtables,  Prev: Host environment,  Up: Top

17 I/O and ports
****************

* Menu:

* Unidirectional and bidirectional ports::  Unidirectional and bidirectional ports
* Port classes::                            Port classes
* Port settings::                           Port settings
* Object-ports::                            Object-ports
* Character-ports::                         Character-ports
* Byte-ports::                              Byte-ports
* Device-ports::                            Device-ports
* Directory-ports::                         Directory-ports
* Vector-ports::                            Vector-ports
* String-ports::                            String-ports
* U8vector-ports::                          U8vector-ports
* Other procedures related to I/O::         Other procedures related to I/O


File: gambit-c.info,  Node: Unidirectional and bidirectional ports,  Next: Port classes,  Prev: I/O and ports,  Up: I/O and ports

17.1 Unidirectional and bidirectional ports
===========================================

Unidirectional ports allow communication between a producer of
information and a consumer.  An input-port's producer is typically a
resource managed by the operating system (such as a file, a process or
a network connection) and the consumer is the Scheme program.  The
roles are reversed for an output-port.

   Associated with each port are settings that affect I/O operations on
that port (encoding of characters to bytes, end-of-line encoding, type
of buffering, etc).  Port settings are specified when the port is
created.  Some port settings can be changed after a port is created.

   Bidirectional ports, also called input-output-ports, allow
communication in both directions.  They are best viewed as an object
that groups two separate unidirectional ports (one in each direction).
Each direction has its own port settings and can be closed
independently from the other direction.


File: gambit-c.info,  Node: Port classes,  Next: Port settings,  Prev: Unidirectional and bidirectional ports,  Up: I/O and ports

17.2 Port classes
=================

The four classes of ports listed below form an inheritance hierarchy.
Operations possible for a certain class of port are also possible for
the subclasses.  Only device-ports are connected to a device managed by
the operating system.  For instance it is possible to create ports that
behave as a FIFO where the Scheme program is both the producer and
consumer of information (possibly one thread is the producer and
another thread is the consumer).

  1. An "object-port" (or simply a port) provides operations to read
     and write Scheme data (i.e. any Scheme object) to/from the port.
     It also provides operations to force output to occur, to change
     the way threads block on the port, and to close the port.  Note
     that the class of objects for which write/read invariance is
     guaranteed depends on the particular class of port.

  2. A "character-port" provides all the operations of an object-port,
     and also operations to read and write individual characters to/from
     the port.  When a Scheme object is written to a character-port, it
     is converted into the sequence of characters that corresponds to
     its external-representation.  When reading a Scheme object, an
     inverse conversion occurs.  Note that some Scheme objects do not
     have an external textual representation that can be read back.

  3. A "byte-port" provides all the operations of a character-port, and
     also operations to read and write individual bytes to/from the
     port.  When a character is written to a byte-port, some encoding
     of that character into a sequence of bytes will occur (for example,
     `#\newline' will be encoded as the 2 bytes CR-LF when using
     ISO-8859-1 character encoding and `cr-lf' end-of-line encoding, and
     a non-ASCII character will generate more than 1 byte when using
     UTF-8 character encoding).  When reading a character, a similar
     decoding occurs.

  4. A "device-port" provides all the operations of a byte-port, and
     also operations to control the operating system managed device
     (file, network connection, terminal, etc) that is connected to the
     port.



File: gambit-c.info,  Node: Port settings,  Next: Object-ports,  Prev: Port classes,  Up: I/O and ports

17.3 Port settings
==================

Some port settings are only valid for specific port classes whereas
some others are valid for all ports.  Port settings are specified when
a port is created.  The settings that are not specified will default to
some reasonable values.  Keyword objects are used to name the settings
to be set.  As a simple example, a device-port connected to the file
`"foo"' can be created using the call

     (open-input-file "foo")

   This will use default settings for the character encoding, buffering,
etc.  If the UTF-8 character encoding is desired, then the port could
be opened using the call

     (open-input-file (list path: "foo" char-encoding: 'UTF-8))

   Here the argument of the procedure `open-input-file' has been
replaced by a "port settings list" which specifies the value of each
port setting that should not be set to the default value.  Note that
some port settings have no useful default and it is therefore required
to specify a value for them, such as the `path:' in the case of the
file opening procedures.  All port creation procedures (i.e. named
`open-...') take a single argument that can either be a port settings
list or a value of a type that depends on the kind of port being
created (a path string for files, an IP port number for socket servers,
etc).


File: gambit-c.info,  Node: Object-ports,  Next: Character-ports,  Prev: Port settings,  Up: I/O and ports

17.4 Object-ports
=================

* Menu:

* Object-port settings::             Object-port settings
* Object-port operations::           Object-port operations


File: gambit-c.info,  Node: Object-port settings,  Next: Object-port operations,  Prev: Object-ports,  Up: Object-ports

17.4.1 Object-port settings
---------------------------

The following is a list of port settings that are valid for all types
of ports.

   * `direction:' ( `input' | `output' | `input-output' )

     This setting controls the direction of the port.  The symbol
     `input' indicates a unidirectional input-port, the symbol `output'
     indicates a unidirectional output-port, and the symbol
     `input-output' indicates a bidirectional port.  The default value
     of this setting depends on the port creation procedure.

   * `buffering:' ( `#f' | `#t' | `line' )

     This setting controls the buffering of the port.  To set each
     direction separately the keywords `input-buffering:' and
     `output-buffering:' must be used instead of `buffering:'.  The
     value `#f' selects unbuffered I/O, the value `#t' selects fully
     buffered I/O, and the symbol `line' selects line buffered I/O (the
     output buffer is drained when a `#\newline' character is written).
     Line buffered I/O only applies to character-ports.  The default
     value of this setting is operating system dependent except
     consoles which are unbuffered.



File: gambit-c.info,  Node: Object-port operations,  Prev: Object-port settings,  Up: Object-ports

17.4.2 Object-port operations
-----------------------------

 -- procedure: input-port? OBJ
 -- procedure: output-port? OBJ
 -- procedure: port? OBJ
     The procedure `input-port?' returns `#t' when OBJ is a
     unidirectional input-port or a bidirectional port and `#f'
     otherwise.

     The procedure `output-port?' returns `#t' when OBJ is a
     unidirectional output-port or a bidirectional port and `#f'
     otherwise.

     The procedure `port?' returns `#t' when OBJ is a port (either
     unidirectional or bidirectional) and `#f' otherwise.

     For example:

          > (input-port? (current-input-port))
          #t
          > (call-with-input-string "some text" output-port?)
          #f
          > (port? (current-output-port))
          #t


 -- procedure: read [PORT]
     This procedure reads and returns the next Scheme datum from the
     input-port PORT.  The end-of-file object is returned when the end
     of the stream is reached.  If it is not specified, PORT defaults
     to the current input-port.

     For example:

          > (call-with-input-string "some text" read)
          some
          > (call-with-input-string "" read)
          #!eof


 -- procedure: read-all [PORT [READER]]
     This procedure repeatedly calls the procedure READER with PORT as
     the sole argument and accumulates a list of each value returned up
     to the end-of-file object.  The procedure `read-all' returns the
     accumulated list without the end-of-file object.  If it is not
     specified, PORT defaults to the current input-port.  If it is not
     specified, READER defaults to the procedure `read'.

     For example:

          > (call-with-input-string "3,2,1\ngo!" read-all)
          (3 ,2 ,1 go!)
          > (call-with-input-string "3,2,1\ngo!"
                                    (lambda (p) (read-all p read-char)))
          (#\3 #\, #\2 #\, #\1 #\newline #\g #\o #\!)
          > (call-with-input-string "3,2,1\ngo!"
                                    (lambda (p) (read-all p read-line)))
          ("3,2,1" "go!")


 -- procedure: write OBJ [PORT]
     This procedure writes the Scheme datum OBJ to the output-port PORT
     and the value returned is unspecified.  If it is not specified,
     PORT defaults to the current output-port.

     For example:

          > (write (list 'compare (list 'quote '@x) 'and (list 'unquote '@x)))
          (compare '@x and , @x)>


 -- procedure: newline [PORT]
     This procedure writes an "object separator" to the output-port
     PORT and the value returned is unspecified.  The separator ensures
     that the next Scheme datum written with the `write' procedure will
     not be confused with the latest datum that was written.  On
     character-ports this is done by writing the character `#\newline'.
     On ports where successive objects are implicitly distinct (such
     as "vector ports") this procedure does nothing.

     Regardless of the class of a port P and assuming that the external
     textual representation of the object X is readable, the expression
     `(begin (write X P) (newline P))' will write to P a representation
     of X that can be read back with the procedure `read'.  If it is
     not specified, PORT defaults to the current output-port.

     For example:

          > (begin (write 123) (newline) (write 456) (newline))
          123
          456


 -- procedure: force-output [PORT [LEVEL]]
     The procedure `force-output' causes the data that was written to
     the output-port PORT to be moved closer to its destination
     according to LEVEL, an exact integer in the range 0 to 2.  If PORT
     is not specified, the current output-port is used.  If LEVEL is
     not specified, it defaults to 0.  Values of LEVEL above 0 are
     equivalent to LEVEL = 0 except for device ports as explained below.

     When LEVEL is 0, the output buffers of PORT which are managed in
     the Scheme process are drained (i.e.  the output operation that
     was delayed due to buffering is actually performed).  In the case
     of a device port the data is passed to the operating system and it
     becomes its responsibility to transmit the data to the device.  The
     operating system may implement its own buffering approach which
     delays the transmission of the data to the device.

     When LEVEL is 1, in addition to the operations for LEVEL = 0 and
     if the operating system supports the functionality, the operating
     system is requested to transmit the data to the device.  On UNIX
     this corresponds to a `fsync' system call.

     When LEVEL is 2, in addition to the operations for LEVEL = 1 and
     if the operating system supports the functionality, the operating
     system is requested to wait until the device reports that the data
     was saved by the device (e.g. actually written to disk in the case
     of a file).  This operation can take a long time on some operating
     systems.  On Mac OS X this corresponds to a `fcntl' system call
     with operation `F_FULLFSYNC'.

     For example:

          > (define p (open-tcp-client "www.iro.umontreal.ca:80"))
          > (display "GET /\n" p)
          > (force-output p)
          > (read-line p)
          "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""


 -- procedure: close-input-port PORT
 -- procedure: close-output-port PORT
 -- procedure: close-port PORT
     The PORT argument of these procedures must be a unidirectional or
     a bidirectional port.  For all three procedures the value returned
     is unspecified.

     The procedure `close-input-port' closes the input-port side of
     PORT, which must not be a unidirectional output-port.

     The procedure `close-output-port' closes the output-port side of
     PORT, which must not be a unidirectional input-port.  The ouput
     buffers are drained before PORT is closed.

     The procedure `close-port' closes all sides of the PORT.  Unless
     PORT is a unidirectional input-port, the output buffers are
     drained before PORT is closed.

     For example:

          > (define p (open-tcp-client "www.iro.umontreal.ca:80"))
          > (display "GET /\n" p)
          > (close-output-port p)
          > (read-line p)
          "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""


 -- procedure: input-port-timeout-set! PORT TIMEOUT [THUNK]
 -- procedure: output-port-timeout-set! PORT TIMEOUT [THUNK]
     When a thread tries to perform an I/O operation on a port, the
     requested operation may not be immediately possible and the thread
     must wait.  For example, the thread may be trying to read a line of
     text from the console and the user has not typed anything yet, or
     the thread may be trying to write to a network connection faster
     than the network can handle.  In such situations the thread
     normally blocks until the operation becomes possible.

     It is sometimes necessary to guarantee that the thread will not
     block too long.  For this purpose, to each input-port and
     output-port is attached a "timeout" and "timeout-thunk".  The
     timeout indicates the point in time beyond which the thread should
     stop waiting on an input and output operation respectively.  When
     the timeout is reached, the thread calls the port's timeout-thunk.
     If the timeout-thunk returns `#f' the thread abandons trying to
     perform the operation (in the case of an input operation an
     end-of-file is read and in the case of an output operation an
     exception is raised).  Otherwise, the thread will block again
     waiting for the operation to become possible (note that if the
     port's timeout has not changed the thread will immediately call
     the timeout-thunk again).

     The procedure `input-port-timeout-set!' sets the timeout of the
     input-port PORT to TIMEOUT and the timeout-thunk to THUNK.  The
     procedure `output-port-timeout-set!' sets the timeout of the
     output-port PORT to TIMEOUT and the timeout-thunk to THUNK.  If it
     is not specified, the THUNK defaults to a thunk that returns `#f'.
     The TIMEOUT is either a time object indicating an absolute point
     in time, or it is a real number which indicates the number of
     seconds relative to the moment the procedure is called.  For both
     procedures the value returned is unspecified.

     When a port is created the timeout is set to infinity (`+inf.0').
     This causes the thread to wait as long as needed for the operation
     to become possible.  Setting the timeout to a point in the past
     (`-inf.0') will cause the thread to attempt the I/O operation and
     never block (i.e. the timeout-thunk is called if the operation is
     not immediately possible).

     The following example shows how to cause the REPL to terminate
     when the user does not enter an expression within the next 60
     seconds.

          > (input-port-timeout-set! (repl-input-port) 60)
          >
          *** EOF again to exit



File: gambit-c.info,  Node: Character-ports,  Next: Byte-ports,  Prev: Object-ports,  Up: I/O and ports

17.5 Character-ports
====================

* Menu:

* Character-port settings::          Character-port settings
* Character-port operations::        Character-port operations


File: gambit-c.info,  Node: Character-port settings,  Next: Character-port operations,  Prev: Character-ports,  Up: Character-ports

17.5.1 Character-port settings
------------------------------

The following is a list of port settings that are valid for
character-ports.

   * `readtable:' READTABLE

     This setting determines the readtable attached to the
     character-port.  To set each direction separately the keywords
     `input-readtable:' and `output-readtable:' must be used instead of
     `readtable:'.  Readtables control the external textual
     representation of Scheme objects, that is the encoding of Scheme
     objects using characters.  The behavior of the `read' procedure
     depends on the port's input-readtable and the behavior of the
     procedures `write', `pretty-print', and related procedures is
     affected by the port's output-readtable.  The default value of this
     setting is the value bound to the parameter object
     `current-readtable'.

   * `output-width:' POSITIVE-INTEGER

     This setting indicates the width of the character output-port in
     number of characters.  This information is used by the
     pretty-printer.  The default value of this setting is 80.



File: gambit-c.info,  Node: Character-port operations,  Prev: Character-port settings,  Up: Character-ports

17.5.2 Character-port operations
--------------------------------

 -- procedure: input-port-line PORT
 -- procedure: input-port-column PORT
 -- procedure: output-port-line PORT
 -- procedure: output-port-column PORT
     The current character location of a character input-port is the
     location of the next character to read.  The current character
     location of a character output-port is the location of the next
     character to write.  Location is denoted by a line number (the
     first line is line 1) and a column number, that is the location on
     the current line (the first column is column 1).  The procedures
     `input-port-line' and `input-port-column' return the line location
     and the column location respectively of the character input-port
     PORT.  The procedures `output-port-line' and `output-port-column'
     return the line location and the column location respectively of
     the character output-port PORT.

     For example:

          > (call-with-output-string
              '()
              (lambda (p)
                (display "abc\n123def" p)
                (write (list (output-port-line p) (output-port-column p))
                       p)))
          "abc\n123def(2 7)"


 -- procedure: output-port-width PORT
     This procedure returns the width, in characters, of the character
     output-port PORT.  The value returned is the port's output-width
     setting.

     For example:

          > (output-port-width (repl-output-port))
          80


 -- procedure: read-char [PORT]
     This procedure reads the character input-port PORT and returns the
     character at the current character location and advances the
     current character location to the next character, unless the PORT
     is already at end-of-file in which case `read-char' returns the
     end-of-file object.  If it is not specified, PORT defaults to the
     current input-port.

     For example:

          > (call-with-input-string
              "some text"
              (lambda (p)
                (let ((a (read-char p))) (list a (read-char p)))))
          (#\s #\o)
          > (call-with-input-string "" read-char)
          #!eof


 -- procedure: peek-char [PORT]
     This procedure returns the same result as `read-char' but it does
     not advance the current character location of the input-port PORT.
     If it is not specified, PORT defaults to the current input-port.

     For example:

          > (call-with-input-string
              "some text"
              (lambda (p)
                (let ((a (peek-char p))) (list a (read-char p)))))
          (#\s #\s)
          > (call-with-input-string "" peek-char)
          #!eof


 -- procedure: write-char CHAR [PORT]
     This procedure writes the character CHAR to the character
     output-port PORT and advances the current character location of
     that output-port.  The value returned is unspecified.  If it is not
     specified, PORT defaults to the current output-port.

     For example:

          > (write-char #\=)
          =>


 -- procedure: read-line [PORT [SEPARATOR [INCLUDE-SEPARATOR?
          [MAX-LENGTH]]]]
     This procedure reads characters from the character input-port PORT
     until a specific SEPARATOR or the end-of-file is encountered and
     returns a string containing the sequence of characters read.  If
     it is specified, MAX-LENGTH must be a nonnegative exact integer
     and it places an upper limit on the number of characters that are
     read.

     The SEPARATOR is included at the end of the string only if it was
     the last character read and INCLUDE-SEPARATOR? is not `#f'.  The
     SEPARATOR must be a character or `#f' (in which case all the
     characters until the end-of-file are read).  If it is not
     specified, PORT defaults to the current input-port.  If it is not
     specified, SEPARATOR defaults to `#\newline'.  If it is not
     specified, INCLUDE-SEPARATOR? defaults to `#f'.

     For example:

          > (define (split sep)
              (lambda (str)
                (call-with-input-string
                  str
                  (lambda (p)
                    (read-all p (lambda (p) (read-line p sep)))))))
          > ((split #\,) "a,b,c")
          ("a" "b" "c")
          > (map (split #\,)
                 (call-with-input-string "1,2,3\n4,5"
                                         (lambda (p) (read-all p read-line))))
          (("1" "2" "3") ("4" "5"))
          > (read-line (current-input-port) #\newline #f 2)1234
          "12"
          > 34


 -- procedure: read-substring STRING START END [PORT [NEED]]
 -- procedure: write-substring STRING START END [PORT]
     These procedures support bulk character I/O.  The part of the
     string STRING starting at index START and ending just before index
     END is used as a character buffer that will be the target of
     `read-substring' or the source of the `write-substring'.  The
     `read-substring' also accepts a NEED parameter which must be a
     nonnegative fixnum.  Up to END-START characters will be
     transferred.  The number of characters transferred, possibly zero,
     is returned by these procedures.  Fewer characters will be read by
     `read-substring' if an end-of-file is read, or a timeout occurs
     before all the requested characters are transferred and the
     timeout thunk returns `#f' (see the procedure
     `input-port-timeout-set!'), or NEED is specified and at least that
     many characters have been read (in other words the procedure does
     not block for more characters but may transfer more characters if
     they are immediately available).  Fewer characters will be written
     by `write-substring' if a timeout occurs before all the requested
     characters are transferred and the timeout thunk returns `#f' (see
     the procedure `output-port-timeout-set!').  If it is not
     specified, PORT defaults to the current input-port and current
     output-port respectively.

     For example:

          > (define s (make-string 10 #\x))
          > (read-substring s 2 5)123456789
          3
          > 456789
          > s
          "xx123xxxxx"
          > (read-substring s 2 10 (current-input-port) 3)abcd
          5
          > s
          "xxabcd\nxxx"


 -- procedure: input-port-readtable PORT
 -- procedure: output-port-readtable PORT
     These procedures return the readtable attached to the
     character-port PORT.  The PORT parameter of `input-port-readtable'
     must be an input-port.  The PORT parameter of
     `output-port-readtable' must be an output-port.


 -- procedure: input-port-readtable-set! PORT READTABLE
 -- procedure: output-port-readtable-set! PORT READTABLE
     These procedures change the readtable attached to the
     character-port PORT to the readtable READTABLE.  The PORT parameter
     of `input-port-readtable-set!'  must be an input-port.  The PORT
     parameter of `output-port-readtable-set!' must be an output-port.
     The value returned is unspecified.



File: gambit-c.info,  Node: Byte-ports,  Next: Device-ports,  Prev: Character-ports,  Up: I/O and ports

17.6 Byte-ports
===============

* Menu:

* Byte-port settings::               Byte-port settings
* Byte-port operations::             Byte-port operations


File: gambit-c.info,  Node: Byte-port settings,  Next: Byte-port operations,  Prev: Byte-ports,  Up: Byte-ports

17.6.1 Byte-port settings
-------------------------

The following is a list of port settings that are valid for byte-ports.

   * `char-encoding:' ENCODING

     This setting controls the character encoding of the byte-port.  For
     bidirectional byte-ports, the character encoding for input and
     output is set.  To set each direction separately the keywords
     `input-char-encoding:' and `output-char-encoding:' must be used
     instead of `char-encoding:'.  The default value of this setting is
     operating system dependent, but this can be overridden through the
     runtime options (*note Runtime options::).  The following
     encodings are supported:

    `ISO-8859-1'
          ISO-8859-1 character encoding.  Each character is encoded by
          a single byte.  Only Unicode characters with a code in the
          range 0 to 255 are allowed.

    `ASCII'
          ASCII character encoding.  Each character is encoded by a
          single byte.  In principle only Unicode characters with a
          code in the range 0 to 127 are allowed but most types of
          ports treat this exactly like `ISO-8859-1'.

    `UTF-8'
          UTF-8 character encoding.  Each character is encoded by a
          sequence of one to four bytes.  The minimum length UTF-8
          encoding is used.  If a BOM is needed at the beginning of the
          stream then it must be explicitly written.

    `UTF-16'
          UTF-16 character encoding.  Each character is encoded by one
          or two 16 bit integers (2 or 4 bytes).  The 16 bit integers
          may be encoded using little-endian encoding or big-endian
          encoding.  If the port is an input-port and the first two
          bytes read are a BOM ("Byte Order Mark" character with
          hexadecimal code FEFF) then the BOM will be discarded and the
          endianness will be set accordingly, otherwise the endianness
          depends on the operating system and how the Gambit runtime was
          compiled.  If the port is an output-port then a BOM will be
          output at the beginning of the stream and the endianness
          depends on the operating system and how the Gambit runtime
          was compiled.

    `UTF-16LE'
          UTF-16 character encoding with little-endian endianness.  It
          is like `UTF-16' except the endianness is set to
          little-endian and there is no BOM processing.  If a BOM is
          needed at the beginning of the stream then it must be
          explicitly written.

    `UTF-16BE'
          UTF-16 character encoding with big-endian endianness.  It is
          like `UTF-16LE' except the endianness is set to big-endian.

    `UTF / UTF-fallback-ASCII / UTF-fallback-ISO-8859-1 / UTF-fallback-UTF-16 / UTF-fallback-UTF-16LE / UTF-fallback-UTF-16BE'
          These encodings combine the UTF-8 and UTF-16 encodings.  When
          one of these character encodings is used for an output port,
          characters will be encoded using the UTF-8 encoding.  The
          first character, if there is one, is prefixed with a UTF-8
          BOM (the three byte sequence EF BB BF in hexadecimal).  When
          one of these character encodings is used for an input port,
          the character encoding depends on the first few bytes.  If
          the first bytes of the stream are a UTF-16LE BOM (FF FE in
          hexadecimal), or a UTF-16BE BOM (FE FF in hexadecimal), or a
          UTF-8 BOM (EF BB BF in hexadecimal), then the BOM is
          discarded and the remaining bytes of the stream are decoded
          using the corresponding character encoding.  If a BOM is not
          present, then the stream is decoded using the fallback
          encoding specified.  The encoding `UTF' is a synonym for
          `UTF-fallback-UTF-8'.  Note that the `UTF' character encoding
          for input will correctly handle streams produced using the
          encodings `UTF', `UTF-8', `UTF-16', `ASCII', and if an
          explicit BOM is output, the encodings `UTF-16LE', and
          `UTF-16BE'.

    `UCS-2'
          UCS-2 character encoding.  Each character is encoded by a 16
          bit integer (2 bytes).  The 16 bit integers may be encoded
          using little-endian encoding or big-endian encoding.  If the
          port is an input-port and the first two bytes read are a BOM
          ("Byte Order Mark" character with hexadecimal code FEFF) then
          the BOM will be discarded and the endianness will be set
          accordingly, otherwise the endianness depends on the
          operating system and how the Gambit runtime was compiled.  If
          the port is an output-port then a BOM will be output at the
          beginning of the stream and the endianness depends on the
          operating system and how the Gambit runtime was compiled.

    `UCS-2LE'
          UCS-2 character encoding with little-endian endianness.  It
          is like `UCS-2' except the endianness is set to little-endian
          and there is no BOM processing.  If a BOM is needed at the
          beginning of the stream then it must be explicitly written.

    `UCS-2BE'
          UCS-2 character encoding with big-endian endianness.  It is
          like `UCS-2LE' except the endianness is set to big-endian.

    `UCS-4'
          UCS-4 character encoding.  Each character is encoded by a 32
          integer (4 bytes).  The 32 bit integers may be encoded using
          little-endian encoding or big-endian encoding.  If the port
          is an input-port and the first four bytes read are a BOM
          ("Byte Order Mark" character with hexadecimal code 0000FEFF)
          then the BOM will be discarded and the endianness will be set
          accordingly, otherwise the endianness depends on the
          operating system and how the Gambit runtime was compiled.  If
          the port is an output-port then a BOM will be output at the
          beginning of the stream and the endianness depends on the
          operating system and how the Gambit runtime was compiled.

    `UCS-4LE'
          UCS-4 character encoding with little-endian endianness.  It
          is like `UCS-4' except the endianness is set to little-endian
          and there is no BOM processing.  If a BOM is needed at the
          beginning of the stream then it must be explicitly written.

    `UCS-4BE'
          UCS-4 character encoding with big-endian endianness.  It is
          like `UCS-4LE' except the endianness is set to big-endian.


   * `char-encoding-errors:' ( `#f' | `#t' )

     This setting controls whether illegal character encodings are
     silently replaced with the Unicode character #xfffd (replacement
     character) or raise an error.  To set each direction separately
     the keywords `input-char-encoding-errors:' and
     `output-char-encoding-errors:' must be used instead of
     `char-encoding-errors:'.  The default value of this setting is
     `#t'.

   * `eol-encoding:' ENCODING

     This setting controls the end-of-line encoding of the byte-port.
     To set each direction separately the keywords `input-eol-encoding:'
     and `output-eol-encoding:' must be used instead of
     `eol-encoding:'.  The default value of this setting is operating
     system dependent, but this can be overridden through the runtime
     options (*note Runtime options::).  Note that for output-ports the
     end-of-line encoding is applied before the character encoding, and
     for input-ports it is applied after.  The following encodings are
     supported:

    `lf'
          For an output-port, writing a `#\newline' character outputs a
          `#\linefeed' character to the stream (Unicode character code
          10).  For an input-port, a `#\newline' character is read when
          a `#\linefeed' character is encountered on the stream.  Note
          that `#\linefeed' and `#\newline' are two names for the same
          character, so this end-of-line encoding is actually the
          identity function.  Text files created by UNIX applications
          typically use this end-of-line encoding.

    `cr'
          For an output-port, writing a `#\newline' character outputs a
          `#\return' character to the stream (Unicode character code
          13).  For an input-port, a `#\newline' character is read when
          a `#\linefeed' character or a `#\return' character is
          encountered on the stream.  Text files created by Classic Mac
          OS applications typically use this end-of-line encoding.

    `cr-lf'
          For an output-port, writing a `#\newline' character outputs to
          the stream a `#\return' character followed by a `#\linefeed'
          character.  For an input-port, a `#\newline' character is read
          when a `#\linefeed' character or a `#\return' character is
          encountered on the stream.  Moreover, if this character is
          immediately followed by the opposite character (`#\linefeed'
          followed by `#\return' or `#\return' followed by
          `#\linefeed') then the second character is ignored.  In other
          words, all four possible end-of-line encodings are read as a
          single `#\newline' character.  Text files created by DOS and
          Microsoft Windows applications typically use this end-of-line
          encoding.




File: gambit-c.info,  Node: Byte-port operations,  Prev: Byte-port settings,  Up: Byte-ports

17.6.2 Byte-port operations
---------------------------

 -- procedure: read-u8 [PORT]
     This procedure reads the byte input-port PORT and returns the byte
     at the current byte location and advances the current byte
     location to the next byte, unless the PORT is already at
     end-of-file in which case `read-u8' returns the end-of-file
     object.  If it is not specified, PORT defaults to the current
     input-port.

     This procedure must be called when the port's input character
     buffer is empty otherwise the character-stream and byte-stream may
     be out of sync due to buffering.  The input character buffer is
     used for bulk decoding of encoded characters (i.e. to translate
     the byte-stream into a character-stream).  The input character
     buffer is initially empty.  It is only when characters are read
     that it is filled with characters obtained by decoding the
     byte-stream.

     One way to ensure that the port's input character buffer is empty
     is to call `read-u8' strictly before any use of the port in a
     character input operation (i.e. a call to the procedures `read',
     `read-char', `peek-char', etc).  Alternatively
     `input-port-characters-buffered' can be used to get the number of
     characters in the port's input character buffer, and to empty the
     buffer with calls to `read-char' or `read-substring'.

     For example:

          > (call-with-input-u8vector
              '#u8(11 22 33 44)
              (lambda (p)
                (let ((a (read-u8 p))) (list a (read-u8 p)))))
          (11 22)
          > (call-with-input-u8vector '#u8() read-u8)
          #!eof


 -- procedure: write-u8 N [PORT]
     This procedure writes the byte N to the byte output-port PORT and
     advances the current byte location of that output-port.  The value
     returned is unspecified.  If it is not specified, PORT defaults to
     the current output-port.

     For example:

          > (call-with-output-u8vector '() (lambda (p) (write-u8 33 p)))
          #u8(33)


 -- procedure: read-subu8vector U8VECTOR START END [PORT [NEED]]
 -- procedure: write-subu8vector U8VECTOR START END [PORT]
     These procedures support bulk byte I/O.  The part of the u8vector
     U8VECTOR starting at index START and ending just before index END
     is used as a byte buffer that will be the target of
     `read-subu8vector' or the source of the `write-subu8vector'.  The
     `read-subu8vector' also accepts a NEED parameter which must be a
     nonnegative fixnum.  Up to END-START bytes will be transferred.
     The number of bytes transferred, possibly zero, is returned by
     these procedures.  Fewer bytes will be read by `read-subu8vector'
     if an end-of-file is read, or a timeout occurs before all the
     requested bytes are transferred and the timeout thunk returns `#f'
     (see the procedure `input-port-timeout-set!'), or NEED is
     specified and at least that many bytes have been read (in other
     words the procedure does not block for more bytes but may transfer
     more bytes if they are immediately available).  Fewer bytes will
     be written by `write-subu8vector' if a timeout occurs before all
     the requested bytes are transferred and the timeout thunk returns
     `#f' (see the procedure `output-port-timeout-set!').  If it is not
     specified, PORT defaults to the current input-port and current
     output-port respectively.

     The procedure `read-subu8vector' must be called before any use of
     the port in a character input operation (i.e. a call to the
     procedures `read', `read-char', `peek-char', etc) because
     otherwise the character-stream and byte-stream may be out of sync
     due to the port buffering.

     For example:

          > (define v (make-u8vector 10))
          > (read-subu8vector v 2 5)123456789
          3
          > 456789
          > v
          #u8(0 0 49 50 51 0 0 0 0 0)
          > (read-subu8vector v 2 10 (current-input-port) 3)abcd
          5
          > v
          #u8(0 0 97 98 99 100 10 0 0 0)



File: gambit-c.info,  Node: Device-ports,  Next: Directory-ports,  Prev: Byte-ports,  Up: I/O and ports

17.7 Device-ports
=================

* Menu:

* Filesystem devices::            Filesystem devices
* Process devices::               Process devices
* Network devices::               Network devices


File: gambit-c.info,  Node: Filesystem devices,  Next: Process devices,  Prev: Device-ports,  Up: Device-ports

17.7.1 Filesystem devices
-------------------------

 -- procedure: open-file PATH-OR-SETTINGS
 -- procedure: open-input-file PATH-OR-SETTINGS
 -- procedure: open-output-file PATH-OR-SETTINGS
 -- procedure: call-with-input-file PATH-OR-SETTINGS PROC
 -- procedure: call-with-output-file PATH-OR-SETTINGS PROC
 -- procedure: with-input-from-file PATH-OR-SETTINGS THUNK
 -- procedure: with-output-to-file PATH-OR-SETTINGS THUNK
     All of these procedures create a port to interface to a byte-stream
     device (such as a file, console, serial port, named pipe, etc)
     whose name is given by a path of the filesystem.  The `direction:'
     setting will default to the value `input' for the procedures
     `open-input-file', `call-with-input-file' and
     `with-input-from-file', to the value `output' for the procedures
     `open-output-file', `call-with-output-file' and
     `with-output-to-file', and to the value `input-output' for the
     procedure `open-file'.

     The procedures `open-file', `open-input-file' and
     `open-output-file' return the port that is created.  The
     procedures `call-with-input-file' and `call-with-output-file' call
     the procedure PROC with the port as single argument, and then
     return the value(s) of this call after closing the port.  The
     procedures `with-input-from-file' and `with-output-to-file'
     dynamically bind the current input-port and current output-port
     respectively to the port created for the duration of a call to the
     procedure THUNK with no argument.  The value(s) of the call to
     THUNK are returned after closing the port.

     The first argument of these procedures is either a string denoting
     a filesystem path or a list of port settings which must contain a
     `path:' setting.  Here are the settings allowed in addition to the
     generic settings of byte-ports:

        * `path:' STRING

          This setting indicates the location of the file in the
          filesystem.  There is no default value for this setting.

        * `append:' ( `#f' | `#t' )

          This setting controls whether output will be added to the end
          of the file.  This is useful for writing to log files that
          might be open by more than one process.  The default value of
          this setting is `#f'.

        * `create:' ( `#f' | `#t' | `maybe' )

          This setting controls whether the file will be created when
          it is opened.  A setting of `#f' requires that the file exist
          (otherwise an exception is raised).  A setting of `#t'
          requires that the file does not exist (otherwise an exception
          is raised).  A setting of `maybe' will create the file if it
          does not exist.  The default value of this setting is `maybe'
          for output-ports and `#f' for input-ports and bidirectional
          ports.

        * `permissions:' 12-BIT-EXACT-INTEGER

          This setting controls the UNIX permissions that will be
          attached to the file if it is created.  The default value of
          this setting is `#o666'.

        * `truncate:' ( `#f' | `#t' )

          This setting controls whether the file will be truncated when
          it is opened.  For input-ports, the default value of this
          setting is `#f'.  For output-ports, the default value of this
          setting is `#t' when the `append:' setting is `#f', and `#f'
          otherwise.


     For example:

          > (with-output-to-file
              (list path: "nofile"
                    create: #f)
              (lambda ()
                (display "hello world!\n")))
          *** ERROR IN (console)@1.1 -- No such file or directory
          (with-output-to-file '(path: "nofile" create: #f) '#<procedure #2>)


 -- procedure: input-port-byte-position PORT [POSITION [WHENCE]]
 -- procedure: output-port-byte-position PORT [POSITION [WHENCE]]
     When called with a single argument these procedures return the byte
     position where the next I/O operation would take place in the file
     attached to the given PORT (relative to the beginning of the
     file).  When called with two or three arguments, the byte position
     for subsequent I/O operations on the given PORT is changed to
     POSITION, which must be an exact integer.  When WHENCE is omitted
     or is 0, the POSITION is relative to the beginning of the file.
     When WHENCE is 1, the POSITION is relative to the current byte
     position of the file.  When WHENCE is 2, the POSITION is relative
     to the end of the file.  The return value is the new byte
     position.  On most operating systems the byte position for reading
     and writing of a given bidirectional port are the same.

     When `input-port-byte-position' is called to change the byte
     position of an input-port, all input buffers will be flushed so
     that the next byte read will be the one at the given position.

     When `output-port-byte-position' is called to change the byte
     position of an output-port, there is an implicit call to
     `force-output' before the position is changed.

     For example:

          > (define p  ; p is an input-output-port
              (open-file '(path: "test" char-encoding: ISO-8859-1 create: maybe)))
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (0 0)
          > (display "abcdefghij\n" p)
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (0 0)
          > (force-output p)
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (11 11)
          > (input-port-byte-position p 2)
          2
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (2 2)
          > (peek-char p)
          #\c
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (11 11)
          > (output-port-byte-position p -7 2)
          4
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (4 4)
          > (write-char #\! p)
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (4 4)
          > (force-output p)
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (5 5)
          > (input-port-byte-position p 1)
          1
          > (read p)
          bcd!fghij



File: gambit-c.info,  Node: Process devices,  Next: Network devices,  Prev: Filesystem devices,  Up: Device-ports

17.7.2 Process devices
----------------------

 -- procedure: open-process PATH-OR-SETTINGS
 -- procedure: open-input-process PATH-OR-SETTINGS
 -- procedure: open-output-process PATH-OR-SETTINGS
 -- procedure: call-with-input-process PATH-OR-SETTINGS PROC
 -- procedure: call-with-output-process PATH-OR-SETTINGS PROC
 -- procedure: with-input-from-process PATH-OR-SETTINGS THUNK
 -- procedure: with-output-to-process PATH-OR-SETTINGS THUNK
     All of these procedures start a new operating system process and
     create a bidirectional port which allows communication with that
     process on its standard input and standard output.  The
     `direction:' setting will default to the value `input' for the
     procedures `open-input-process', `call-with-input-process' and
     `with-input-from-process', to the value `output' for the
     procedures `open-output-process', `call-with-output-process' and
     `with-output-to-process', and to the value `input-output' for the
     procedure `open-process'.  If the `direction:' setting is `input',
     the output-port side is closed.  If the `direction:' setting is
     `output', the input-port side is closed.

     The procedures `open-process', `open-input-process' and
     `open-output-process' return the port that is created.  The
     procedures `call-with-input-process' and
     `call-with-output-process' call the procedure PROC with the port
     as single argument, and then return the value(s) of this call
     after closing the port and waiting for the process to terminate.
     The procedures `with-input-from-process' and
     `with-output-to-process' dynamically bind the current input-port
     and current output-port respectively to the port created for the
     duration of a call to the procedure THUNK with no argument.  The
     value(s) of the call to THUNK are returned after closing the port
     and waiting for the process to terminate.

     The first argument of this procedure is either a string denoting a
     filesystem path of an executable program or a list of port settings
     which must contain a `path:' setting.  Here are the settings
     allowed in addition to the generic settings of byte-ports:

        * `path:' STRING

          This setting indicates the location of the executable program
          in the filesystem.  There is no default value for this
          setting.

        * `arguments:' LIST-OF-STRINGS

          This setting indicates the string arguments that are passed
          to the program.  The default value of this setting is the
          empty list (i.e. no arguments).

        * `environment:' LIST-OF-STRINGS

          This setting indicates the set of environment variable
          bindings that the process receives.  Each element of the list
          is a string of the form "`VAR=VALUE'", where `VAR' is the
          name of the variable and `VALUE' is its binding.  When
          LIST-OF-STRINGS is `#f', the process inherits the environment
          variable bindings of the Scheme program.  The default value
          of this setting is `#f'.

        * `directory:' DIR

          This setting indicates the current working directory of the
          process.  When DIR is `#f', the process uses the value of
          `(current-directory)'.  The default value of this setting is
          `#f'.

        * `stdin-redirection:' ( `#f' | `#t' )

          This setting indicates how the standard input of the process
          is redirected.  A setting of `#t' will redirect the standard
          input from the process-port (i.e. what is written to the
          process-port will be available on the standard input).  A
          setting of `#f' will leave the standard input as-is, which
          typically results in input coming from the console.  The
          default value of this setting is `#t'.

        * `stdout-redirection:' ( `#f' | `#t' )

          This setting indicates how the standard output of the process
          is redirected.  A setting of `#t' will redirect the standard
          output to the process-port (i.e. all output to standard
          output can be read from the process-port).  A setting of `#f'
          will leave the standard output as-is, which typically results
          in the output going to the console.  The default value of
          this setting is `#t'.

        * `stderr-redirection:' ( `#f' | `#t' )

          This setting indicates how the standard error of the process
          is redirected.  A setting of `#t' will redirect the standard
          error to the process-port (i.e. all output to standard error
          can be read from the process-port).  A setting of `#f' will
          leave the standard error as-is, which typically results in
          error messages being output to the console.  The default
          value of this setting is `#f'.

        * `pseudo-terminal:' ( `#f' | `#t' )

          This setting applies to UNIX.  It indicates what type of
          device will be bound to the process' standard input and
          standard output.  A setting of `#t' will use a
          pseudo-terminal device (this is a device that behaves like a
          tty device even though there is no real terminal or user
          directly involved).  A setting of `#f' will use a pair of
          pipes.  The difference is important for programs which behave
          differently when they are used interactively, for example
          shells.  The default value of this setting is `#f'.

        * `show-console:' ( `#f' | `#t' )

          This setting applies to Microsoft Windows.  It controls
          whether the process' console window will be hidden or
          visible.  The default value of this setting is `#t' (i.e.
          show the console window).


     For example:

          > (with-input-from-process "date" read-line)
          "Sun Jun 14 15:06:41 EDT 2009"
          > (define p (open-process (list path: "ls"
                                          arguments: '("../examples"))))
          > (read-line p)
          "README"
          > (read-line p)
          "Xlib-simple"
          > (close-port p)
          > (define p (open-process "/usr/bin/dc"))
          > (display "2 100 ^ p\n" p)
          > (force-output p)
          > (read-line p)
          "1267650600228229401496703205376"


 -- procedure: process-pid PROCESS-PORT
     This procedure returns the PID (Process Identifier) of the process
     of PROCESS-PORT.  The PID is a small exact integer.

     For example:

          > (let ((p (open-process "sort")))
              (process-pid p))
          318


 -- procedure: process-status PROCESS-PORT [TIMEOUT [TIMEOUT-VAL]]
     This procedure causes the current thread to wait until the process
     of PROCESS-PORT terminates (normally or not) or until the timeout
     is reached if TIMEOUT is supplied.  If the timeout is reached,
     PROCESS-STATUS returns TIMEOUT-VAL if it is supplied, otherwise an
     unterminated-process-exception object is raised.  The procedure
     returns the process exit status as encoded by the operating
     system.  Typically, if the process exited normally the return
     value is the process exit status multiplied by 256.

     For example:

          > (let ((p (open-process "sort")))
              (for-each (lambda (x) (pretty-print x p))
                        '(22 11 33))
              (close-output-port p)
              (let ((r (read-all p)))
                (close-input-port p)
                (list (process-status p) r)))
          (0 (11 22 33))


 -- procedure: unterminated-process-exception? OBJ
 -- procedure: unterminated-process-exception-procedure EXC
 -- procedure: unterminated-process-exception-arguments EXC
     Unterminated-process-exception objects are raised when a call to
     the `process-status' procedure reaches its timeout before the
     target process terminates and a timeout-value parameter is not
     specified.  The parameter EXC must be an
     unterminated-process-exception object.

     The procedure `unterminated-process-exception?' returns `#t' when
     OBJ is an unterminated-process-exception object and `#f' otherwise.

     The procedure `unterminated-process-exception-procedure' returns
     the procedure that raised EXC.

     The procedure `unterminated-process-exception-arguments' returns
     the list of arguments of the procedure that raised EXC.

     For example:

          > (define (handler exc)
              (if (unterminated-process-exception? exc)
                  (list (unterminated-process-exception-procedure exc)
                        (unterminated-process-exception-arguments exc))
                  'not-unterminated-process-exception))
          > (with-exception-catcher
              handler
              (lambda ()
                (let ((p (open-process "sort")))
                  (process-status p 1))))
          (#<procedure #2 process-status> (#<input-output-port #3 (process "sort")>))



File: gambit-c.info,  Node: Network devices,  Prev: Process devices,  Up: Device-ports

17.7.3 Network devices
----------------------

 -- procedure: open-tcp-client PORT-NUMBER-OR-ADDRESS-OR-SETTINGS
     This procedure opens a network connection to a socket server and
     returns a tcp-client-port (a subtype of device-port) that
     represents this connection and allows communication with that
     server.  The default value of the `direction:' setting is
     `input-output', i.e. the Scheme program can send information to
     the server and receive information from the server.  The sending
     direction can be "shutdown" using the `close-output-port'
     procedure and the receiving direction can be "shutdown" using the
     `close-input-port' procedure.  The `close-port' procedure closes
     both directions of the connection.

     The parameter of this procedure is an IP port number (16-bit
     nonnegative exact integer), a string of the form `"HOST:PORT"' or
     a list of port settings.  When the parameter is the number PORT it
     is handled as if it was the setting `port-number:' PORT.  When the
     parameter is the string `"HOST:PORT"' it is handled as if it was
     the setting `server-address:' `"HOST:PORT"'.

     Here are the settings allowed in addition to the generic settings
     of byte-ports:

        * `server-address:' STRING-OR-IP-ADDRESS

          This setting indicates the internet address of the server, and
          possibly the IP port number.  When this parameter is not
          specified or is `""', the connection requests are sent to the
          loopback interface (with IP address 127.0.0.1).  The
          parameter can be a string denoting a host name, which will be
          translated to an IP address by the `host-info' procedure, or
          a 4 element u8vector which contains the 32-bit IPv4 address
          or an 8 element u16vector which contains the 128-bit IPv6
          address.  A string of the form `"HOST:PORT"' is handled as if
          it was the combination of settings `server-address:' `"HOST"'
          `port-number:' PORT.

        * `port-number:' 16-BIT-EXACT-INTEGER

          This setting indicates the IP port number of the server to
          connect to (e.g. 80 for the standard HTTP server, 23 for the
          standard telnet server).  There is no default value for this
          setting.

        * `keep-alive:' ( `#f' | `#t' )

          This setting controls the use of the "keep alive" option on
          the connection.  The "keep alive" option will periodically
          send control packets on otherwise idle network connections to
          ensure that the server host is active and reachable.  The
          default value of this setting is `#f'.

        * `coalesce:' ( `#f' | `#t' )

          This setting controls the use of TCP's "Nagle algorithm" which
          reduces the number of small packets by delaying their
          transmission and coalescing them into larger packets.  A
          setting of `#t' will coalesce small packets into larger ones.
          A setting of `#f' will transmit packets as soon as possible.
          The default value of this setting is `#t'.  Note that this
          setting does not affect the buffering of the port.


     Below is an example of the client-side code that opens a
     connection to an HTTP server on port 8080 of the loopback
     interface (with IP address 127.0.0.1).  For the server-side code
     see the example for the procedure `open-tcp-server'.

          > (define p (open-tcp-client (list port-number: 8080
                                             eol-encoding: 'cr-lf)))
          > p
          #<input-output-port #2 (tcp-client #u8(127 0 0 1) 8080)>
          > (display "GET /\n" p)
          > (force-output p)
          > (read-line p)
          "<HTML>"


 -- procedure: open-tcp-server PORT-NUMBER-OR-ADDRESS-OR-SETTINGS
     This procedure sets up a socket to accept network connection
     requests from clients and returns a tcp-server-port from which
     network connections to clients are obtained.  Tcp-server-ports are
     a direct subtype of object-ports (i.e. they are not
     character-ports) and are input-ports.  Reading from a
     tcp-server-port with the `read' procedure will block until a
     network connection request is received from a client.  The `read'
     procedure will then return a tcp-client-port (a subtype of
     device-port) that represents this connection and allows
     communication with that client.  Closing a tcp-server-port with
     either the `close-input-port' or `close-port' procedures will
     cause the network subsystem to stop accepting connections on that
     socket.

     The parameter of this procedure is an IP port number (16-bit
     nonnegative exact integer), a string of the form `"INTF:PORT"' or
     a list of port settings which must contain a `port-number:'
     setting.  When the parameter is the number PORT it is handled as
     if it was the setting `port-number:' PORT.  When the parameter is
     the string `"INTF:PORT"' it is handled as if it was the setting
     `server-address:' `"INTF:PORT"'.

     Below is a list of the settings allowed in addition to the settings
     `keep-alive:' and `coalesce:' allowed by the `open-tcp-client'
     procedure and the generic settings of byte-ports.  The settings
     which are not listed below apply to the tcp-client-port that is
     returned by `read' when a connection is accepted and have the same
     meaning as if they were used in a call to the `open-tcp-client'
     procedure.

        * `server-address:' STRING-OR-IP-ADDRESS

          This setting indicates the internet address of the network
          interface on which connections requests are accepted, and
          possibly the IP port number.  When this parameter is not
          specified or is `""', the connection requests are accepted
          only on the loopback interface (with IP address 127.0.0.1).
          When this parameter is `"*"', the connection requests are
          accepted on all network interfaces (i.e. address INADDR_ANY).
          The parameter can be a string denoting a host name, which
          will be translated to an IP address by the `host-info'
          procedure, or a 4 element u8vector which contains the 32-bit
          IPv4 address or an 8 element u16vector which contains the
          128-bit IPv6 address.  A string of the form `"INTF:PORT"' is
          handled as if it was the combination of settings
          `server-address:' `"INTF"' `port-number:' PORT.

        * `port-number:' 16-BIT-EXACT-INTEGER

          This setting indicates the IP port number assigned to the
          socket which accepts connection requests from clients.  So
          called "well-known ports", which are reserved for standard
          services, have a port number below 1024 and can only be
          assigned to a socket by a process with superuser priviledges
          (e.g. 80 for the HTTP service, 23 for the telnet service).
          No special priviledges are needed to assign higher port
          numbers to a socket.  The special value 0 requests that a
          currently unused port number be assigned to the socket (the
          port number assigned can be retrieved using the procedure
          `tcp-server-socket-info').  There is no default value for this
          setting.

        * `backlog:' POSITIVE-EXACT-INTEGER

          This setting indicates the maximum number of connection
          requests that can be waiting to be accepted by a call to
          `read' (technically it is the value passed as the second
          argument of the UNIX `listen()' function).  The default value
          of this setting is 128.

        * `reuse-address:' ( `#f' | `#t' )

          This setting controls whether it is possible to assign a port
          number that is currently active.  Note that when a server
          process terminates, the socket it was using to accept
          connection requests does not become inactive immediately.
          Instead it remains active for a few minutes to ensure clean
          termination of the connections.  A setting of `#f' will cause
          an exception to be raised in that case.  A setting of `#t'
          will allow a port number to be used even if it is active.
          The default value of this setting is `#t'.


     Below is an example of the server-side code that accepts
     connections on port 8080 of any network interface.  For the
     client-side code see the example for the procedure
     `open-tcp-client'.

          > (define s (open-tcp-server (list server-address: "*"
                                             port-number: 8080
                                             eol-encoding: 'cr-lf)))
          > (define p (read s))  ; blocks until client connects
          > p
          #<input-output-port #2 (tcp-client 8080)>
          > (read-line p)
          "GET /"
          > (display "<HTML>\n" p)
          > (force-output p)


 -- procedure: tcp-service-register! PORT-NUMBER-OR-ADDRESS-OR-SETTINGS
          THUNK [THREAD-GROUP]
 -- procedure: tcp-service-unregister!
          PORT-NUMBER-OR-ADDRESS-OR-SETTINGS
     The procedure `tcp-service-register!' sets up a socket to accept
     network connection requests from clients and creates a "service"
     thread which processes the incoming connections.  The parameter
     PORT-NUMBER-OR-ADDRESS-OR-SETTINGS has the same meaning as for the
     procedure `open-tcp-server'.

     For each connection established the service thread creates a
     "handler" thread which executes a call to the procedure THUNK with
     no argument.  The handler thread's current input-port and current
     output-port are both set to the tcp-client-port created for the
     connection.  There is no need for the THUNK to close the
     tcp-client-port, as this is done by the handler thread when the
     THUNK returns normally.

     The procedure `tcp-service-unregister!' terminates the service
     thread which was registered by `tcp-service-register!' with the
     same network interface and port number (if a service thread is
     still registered).  The procedure `tcp-service-register!'
     implicitly calls `tcp-service-unregister!' before registering the
     new service thread.

          > (tcp-service-register!
             8000
             (lambda () (display "hello\n")))
          > (define p (open-tcp-client 8000))
          > (read-line p)
          "hello"
          > (tcp-service-unregister! 8000)



File: gambit-c.info,  Node: Directory-ports,  Next: Vector-ports,  Prev: Device-ports,  Up: I/O and ports

17.8 Directory-ports
====================

 -- procedure: open-directory PATH-OR-SETTINGS
     This procedure opens a directory of the filesystem for reading its
     entries and returns a directory-port from which the entries can be
     enumerated.  Directory-ports are a direct subtype of object-ports
     (i.e. they are not character-ports) and are input-ports.  Reading
     from a directory-port with the `read' procedure returns the next
     file name in the directory as a string.  The end-of-file object is
     returned when all the file names have been enumerated.  Another
     way to get the list of all files in a directory is the
     `directory-files' procedure which returns a list of the files in
     the directory.  The advantage of using directory-ports is that it
     allows iterating over the files in a directory in constant space,
     which is interesting when the number of files in the directory is
     not known in advance and may be large.  Note that the order in
     which the names are returned is operating-system dependent.

     The parameter of this procedure is either a string denoting a
     filesystem path to a directory or a list of port settings which
     must contain a `path:' setting.  Here are the settings allowed in
     addition to the generic settings of object-ports:

        * `path:' STRING

          This setting indicates the location of the directory in the
          filesystem.  There is no default value for this setting.

        * `ignore-hidden:' ( `#f' | `#t' | `dot-and-dot-dot' )

          This setting controls whether hidden-files will be returned.
          Under UNIX and Mac OS X hidden-files are those that start
          with a period (such as `.', `..', and `.profile').  Under
          Microsoft Windows hidden files are the `.' and `..' entries
          and the files whose "hidden file" attribute is set.  A
          setting of `#f' will enumerate all the files.  A setting of
          `#t' will only enumerate the files that are not hidden.  A
          setting of `dot-and-dot-dot' will enumerate all the files
          except for the `.' and `..' hidden files.  The default value
          of this setting is `#t'.


     For example:

          > (let ((p (open-directory (list path: "../examples"
                                           ignore-hidden: #f))))
              (let loop ()
                (let ((fn (read p)))
                  (if (string? fn)
                      (begin
                        (pp (path-expand fn))
                        (loop)))))
              (close-input-port p))
          "/u/feeley/examples/."
          "/u/feeley/examples/.."
          "/u/feeley/examples/complex"
          "/u/feeley/examples/README"
          "/u/feeley/examples/simple"
          > (define x (open-directory "../examples"))
          > (read-all x)
          ("complex" "README" "simple")



File: gambit-c.info,  Node: Vector-ports,  Next: String-ports,  Prev: Directory-ports,  Up: I/O and ports

17.9 Vector-ports
=================

 -- procedure: open-vector [VECTOR-OR-SETTINGS]
 -- procedure: open-input-vector [VECTOR-OR-SETTINGS]
 -- procedure: open-output-vector [VECTOR-OR-SETTINGS]
 -- procedure: call-with-input-vector VECTOR-OR-SETTINGS PROC
 -- procedure: call-with-output-vector VECTOR-OR-SETTINGS PROC
 -- procedure: with-input-from-vector VECTOR-OR-SETTINGS THUNK
 -- procedure: with-output-to-vector VECTOR-OR-SETTINGS THUNK
     Vector-ports represent streams of Scheme objects.  They are a
     direct subtype of object-ports (i.e. they are not
     character-ports).  All of these procedures create vector-ports
     that are either unidirectional or bidirectional.  The `direction:'
     setting will default to the value `input' for the procedures
     `open-input-vector', `call-with-input-vector' and
     `with-input-from-vector', to the value `output' for the procedures
     `open-output-vector', `call-with-output-vector' and
     `with-output-to-vector', and to the value `input-output' for the
     procedure `open-vector'.  Bidirectional vector-ports behave like
     FIFOs: data written to the port is added to the end of the stream
     that is read.  It is only when a bidirectional vector-port's
     output-side is closed with a call to the `close-output-port'
     procedure that the stream's end is known (when the stream's end is
     reached, reading the port returns the end-of-file object).

     The procedures `open-vector', `open-input-vector' and
     `open-output-vector' return the port that is created.  The
     procedures `call-with-input-vector' and `call-with-output-vector'
     create a vector port, call the procedure PROC with the port as
     single argument and then close the port.  The procedures
     `with-input-from-vector' and `with-output-to-vector' create a
     vector port, dynamically bind the current input-port and current
     output-port respectively to the port created for the duration of a
     call to the procedure THUNK with no argument, and then close the
     port.  The procedures `call-with-input-vector' and
     `with-input-from-vector' return the value returned by the
     procedures PROC and THUNK respectively.  The procedures
     `call-with-output-vector' and `with-output-to-vector' return the
     vector accumulated in the port (see `get-output-vector').

     The first parameter of these procedures is either a vector of the
     elements used to initialize the stream or a list of port settings.
     If it is not specified, the parameter of the `open-vector',
     `open-input-vector', and `open-output-vector' procedures defaults
     to an empty list of port settings.  Here are the settings allowed
     in addition to the generic settings of object-ports:

        * `init:' VECTOR

          This setting indicates the initial content of the stream.
          The default value of this setting is an empty vector.

        * `permanent-close:' ( `#f' | `#t' )

          This setting controls whether a call to the procedures
          `close-output-port' will close the output-side of a
          bidirectional vector-port permanently or not.  A permanently
          closed bidirectional vector-port whose end-of-file has been
          reached on the input-side will return the end-of-file object
          for all subsequent calls to the `read' procedure.  A
          non-permanently closed bidirectional vector-port will return
          to its opened state when its end-of-file is read.  The
          default value of this setting is `#t'.


     For example:

          > (define p (open-vector))
          > (write 1 p)
          > (write 2 p)
          > (write 3 p)
          > (force-output p)
          > (read p)
          1
          > (read p)
          2
          > (close-output-port p)
          > (read p)
          3
          > (read p)
          #!eof
          > (with-output-to-vector '() (lambda () (write 1) (write 2)))
          #(1 2)


 -- procedure: open-vector-pipe [VECTOR-OR-SETTINGS1
          [VECTOR-OR-SETTINGS2]]
     The procedure `open-vector-pipe' creates two vector-ports and
     returns these two ports.  The two ports are interrelated as
     follows: the first port's output-side is connected to the second
     port's input-side and the first port's input-side is connected to
     the second port's output-side.  The value VECTOR-OR-SETTINGS1 is
     used to setup the first vector-port and VECTOR-OR-SETTINGS2 is
     used to setup the second vector-port.  The same settings as for
     `open-vector' are allowed.  The default `direction:' setting is
     `input-output' (i.e. a bidirectional port is created).  If it is
     not specified VECTOR-OR-SETTINGS1 defaults to the empty list.  If
     it is not specified VECTOR-OR-SETTINGS2 defaults to
     VECTOR-OR-SETTINGS1 but with the `init:' setting set to the empty
     vector and with the input and output settings exchanged (e.g. if
     the first port is an input-port then the second port is an
     output-port, if the first port's input-side is non-buffered then
     the second port's output-side is non-buffered).

     For example:

          > (define (server op)
              (receive (c s) (open-vector-pipe)  ; client-side and server-side ports
                (thread-start!
                  (make-thread
                    (lambda ()
                      (let loop ()
                        (let ((request (read s)))
                          (if (not (eof-object? request))
                              (begin
                                (write (op request) s)
                                (newline s)
                                (force-output s)
                                (loop))))))))
                c))
          > (define a (server (lambda (x) (expt 2 x))))
          > (define b (server (lambda (x) (expt 10 x))))
          > (write 100 a)
          > (write 30 b)
          > (read a)
          1267650600228229401496703205376
          > (read b)
          1000000000000000000000000000000


 -- procedure: get-output-vector VECTOR-PORT
     The procedure `get-output-vector' takes an output vector-port or a
     bidirectional vector-port as parameter and removes all the objects
     currently on the output-side, returning them in a vector.  The port
     remains open and subsequent output to the port and calls to the
     procedure `get-output-vector' are possible.

     For example:

          > (define p (open-vector '#(1 2 3)))
          > (write 4 p)
          > (get-output-vector p)
          #(1 2 3 4)
          > (write 5 p)
          > (write 6 p)
          > (get-output-vector p)
          #(5 6)



File: gambit-c.info,  Node: String-ports,  Next: U8vector-ports,  Prev: Vector-ports,  Up: I/O and ports

17.10 String-ports
==================

 -- procedure: open-string [STRING-OR-SETTINGS]
 -- procedure: open-input-string [STRING-OR-SETTINGS]
 -- procedure: open-output-string [STRING-OR-SETTINGS]
 -- procedure: call-with-input-string STRING-OR-SETTINGS PROC
 -- procedure: call-with-output-string STRING-OR-SETTINGS PROC
 -- procedure: with-input-from-string STRING-OR-SETTINGS THUNK
 -- procedure: with-output-to-string STRING-OR-SETTINGS THUNK
 -- procedure: open-string-pipe [STRING-OR-SETTINGS1
          [STRING-OR-SETTINGS2]]
 -- procedure: get-output-string STRING-PORT
     String-ports represent streams of characters.  They are a direct
     subtype of character-ports.  These procedures are the string-port
     analog of the procedures specified in the vector-ports section.
     Note that these procedures are a superset of the procedures
     specified in the "Basic String Ports SRFI" (SRFI 6).

     For example:

          > (define p (open-string))
          > (write 1 p)
          > (write 2 p)
          > (write 3 p)
          > (force-output p)
          > (read-char p)
          #\1
          > (read-char p)
          #\2
          > (close-output-port p)
          > (read-char p)
          #\3
          > (read-char p)
          #!eof
          > (with-output-to-string '() (lambda () (write 1) (write 2)))
          "12"


 -- procedure: object->string OBJ [N]
     This procedure converts the object OBJ to its external
     representation and returns it in a string.  The parameter N
     specifies the maximal width of the resulting string.  If the
     external representation is wider than N, the resulting string will
     be truncated to N characters and the last 3 characters will be set
     to periods.  Note that the current readtable is used.

     For example:

          > (object->string (expt 2 100))
          "1267650600228229401496703205376"
          > (object->string (expt 2 100) 30)
          "126765060022822940149670320..."
          > (object->string (cons car cdr))
          "(#<procedure #2 car> . #<procedure #3 cdr>)"



File: gambit-c.info,  Node: U8vector-ports,  Next: Other procedures related to I/O,  Prev: String-ports,  Up: I/O and ports

17.11 U8vector-ports
====================

 -- procedure: open-u8vector [U8VECTOR-OR-SETTINGS]
 -- procedure: open-input-u8vector [U8VECTOR-OR-SETTINGS]
 -- procedure: open-output-u8vector [U8VECTOR-OR-SETTINGS]
 -- procedure: call-with-input-u8vector U8VECTOR-OR-SETTINGS PROC
 -- procedure: call-with-output-u8vector U8VECTOR-OR-SETTINGS PROC
 -- procedure: with-input-from-u8vector U8VECTOR-OR-SETTINGS THUNK
 -- procedure: with-output-to-u8vector U8VECTOR-OR-SETTINGS THUNK
 -- procedure: open-u8vector-pipe [U8VECTOR-OR-SETTINGS1
          [U8VECTOR-OR-SETTINGS2]]
 -- procedure: get-output-u8vector U8VECTOR-PORT
     U8vector-ports represent streams of bytes.  They are a direct
     subtype of byte-ports.  These procedures are the u8vector-port
     analog of the procedures specified in the vector-ports section.

     For example:

          > (define p (open-u8vector))
          > (write 1 p)
          > (write 2 p)
          > (write 3 p)
          > (force-output p)
          > (read-u8 p)
          49
          > (read-u8 p)
          50
          > (close-output-port p)
          > (read-u8 p)
          51
          > (read-u8 p)
          #!eof
          > (with-output-to-u8vector '() (lambda () (write 1) (write 2)))
          #u8(49 50)



File: gambit-c.info,  Node: Other procedures related to I/O,  Prev: U8vector-ports,  Up: I/O and ports

17.12 Other procedures related to I/O
=====================================

 -- procedure: current-input-port [NEW-VALUE]
 -- procedure: current-output-port [NEW-VALUE]
 -- procedure: current-error-port [NEW-VALUE]
 -- procedure: current-readtable [NEW-VALUE]
     These procedures are parameter objects which represent
     respectively: the current input-port, the current output-port, the
     current error-port, and the current readtable.


 -- procedure: print [`port:' PORT] OBJ...
 -- procedure: println [`port:' PORT] OBJ...
     The `print' procedure writes a representation of each OBJ, from
     left to right, to PORT.  When a compound object is encountered
     (pair, list, vector, box) the elements of that object are
     recursively written without the surrounding tokens (parentheses,
     spaces, dots, etc).  Strings, symbols, keywords and characters are
     written like the `display' procedure.  If there are more than one
     OBJ, the first OBJ must not be a keyword object.  If it is not
     specified, PORT defaults to the current output-port.  The
     procedure `print' returns an unspecified value.

     The `println' procedure does the same thing as the `print'
     procedure and then writes an end of line to PORT.

     For example:

          > (println "2*2 is " (* 2 2) " and 2+2 is " (+ 2 2))
          2*2 is 4 and 2+2 is 4
          > (define x (list "<i>" (list "<tt>" 123 "</tt>") "</i>"))
          > (println x)
          <i><tt>123</tt></i>
          > (define p (open-output-string))
          > (print port: p 1 #\2 "345")
          > (get-output-string p)
          "12345"



File: gambit-c.info,  Node: Lexical syntax and readtables,  Next: C-interface,  Prev: I/O and ports,  Up: Top

18 Lexical syntax and readtables
********************************

* Menu:

* Readtables::                        Readtables
* Boolean syntax::                    Boolean syntax
* Character syntax::                  Character syntax
* String syntax::                     String syntax
* Symbol syntax::                     Symbol syntax
* Keyword syntax::                    Keyword syntax
* Box syntax::                        Box syntax
* Number syntax::                     Number syntax
* Homogeneous vector syntax::         Homogeneous vector syntax
* Special #! syntax::                 Special #! syntax
* Multiline comment syntax::          Multiline comment syntax
* Scheme infix syntax extension::     Scheme infix syntax extension


File: gambit-c.info,  Node: Readtables,  Next: Boolean syntax,  Prev: Lexical syntax and readtables,  Up: Lexical syntax and readtables

18.1 Readtables
===============

Readtables control the external textual representation of Scheme
objects, that is the encoding of Scheme objects using characters.
Readtables affect the behavior of the reader (i.e. the `read' procedure
and the parser used by the `load' procedure and the interpreter and
compiler) and the printer (i.e. the procedures `write', `display',
`print', `println', `pretty-print', and `pp', and the procedure used by
the REPL to print results).  To preserve write/read invariance the
printer and reader must be using compatible readtables.  For example a
symbol which contains upper case letters will be printed with special
escapes if the readtable indicates that the reader is case-insensitive.

   Readtables are immutable records whose fields specify various textual
representation aspects.  There are accessor procedures to retrieve the
content of specific fields.  There are also functional update
procedures that create a copy of a readtable, with a specific field set
to a new value.

 -- procedure: readtable? OBJ
     This procedure returns `#t' when OBJ is a readtable and `#f'
     otherwise.

     For example:

          > (readtable? (current-readtable))
          #t
          > (readtable? 123)
          #f


 -- procedure: readtable-case-conversion? READTABLE
 -- procedure: readtable-case-conversion?-set READTABLE NEW-VALUE
     The procedure `readtable-case-conversion?' returns the content of
     the `case-conversion?' field of READTABLE.  When the content of
     this field is `#f', the reader preserves the case of symbols and
     keyword objects that are read (i.e. `Ice' and `ice' are distinct
     symbols).  When the content of this field is the symbol `upcase',
     the reader converts lowercase letters to uppercase when reading
     symbols and keywords (i.e. `Ice' is read as the symbol
     `(string->symbol "ICE")').  Otherwise the reader converts
     uppercase letters to lowercase when reading symbols and keywords
     (i.e. `Ice' is read as the symbol `(string->symbol "ice")').

     The procedure `readtable-case-conversion?-set' returns a copy of
     READTABLE where only the `case-conversion?' field has been changed
     to NEW-VALUE.

     For example:

          > (output-port-readtable-set!
              (repl-output-port)
              (readtable-case-conversion?-set
                (output-port-readtable (repl-output-port))
                #f))
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-case-conversion?-set
                (input-port-readtable (repl-input-port))
                #f))
          > 'Ice
          Ice
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-case-conversion?-set
                (input-port-readtable (repl-input-port))
                #t))
          > 'Ice
          ice
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-case-conversion?-set
                (input-port-readtable (repl-input-port))
                'upcase))
          > 'Ice
          ICE


 -- procedure: readtable-keywords-allowed? READTABLE
 -- procedure: readtable-keywords-allowed?-set READTABLE NEW-VALUE
     The procedure `readtable-keywords-allowed?' returns the content of
     the `keywords-allowed?' field of READTABLE.  When the content of
     this field is `#f', the reader does not recognize keyword objects
     (i.e. `:foo' and `foo:' are read as the symbols `(string->symbol
     ":foo")' and `(string->symbol "foo:")' respectively).  When the
     content of this field is the symbol `prefix', the reader
     recognizes keyword objects that start with a colon, as in Common
     Lisp (i.e. `:foo' is read as the keyword `(string->keyword
     "foo")').  Otherwise the reader recognizes keyword objects that
     end with a colon, as in DSSSL (i.e. `foo:' is read as the symbol
     `(string->symbol "foo")').

     The procedure `readtable-keywords-allowed?-set' returns a copy of
     READTABLE where only the `keywords-allowed?' field has been
     changed to NEW-VALUE.

     For example:

          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-keywords-allowed?-set
                (input-port-readtable (repl-input-port))
                #f))
          > (map keyword? '(foo :foo foo:))
          (#f #f #f)
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-keywords-allowed?-set
                (input-port-readtable (repl-input-port))
                #t))
          > (map keyword? '(foo :foo foo:))
          (#f #f #t)
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-keywords-allowed?-set
                (input-port-readtable (repl-input-port))
                'prefix))
          > (map keyword? '(foo :foo foo:))
          (#f #t #f)


 -- procedure: readtable-sharing-allowed? READTABLE
 -- procedure: readtable-sharing-allowed?-set READTABLE NEW-VALUE
     The procedure `readtable-sharing-allowed?' returns the content of
     the `sharing-allowed?' field of READTABLE.  The reader recognizes
     the `#N#' and `#N=DATUM' notation for circular structures and the
     printer uses this notation if and only if the content of the
     `sharing-allowed?' field is not `#f'.  Moreover when the content
     of the `sharing-allowed?' field is the symbol `serialize', the
     printer uses a special external representation that the reader
     understands and that extends write/read invariance to the
     following types: records, procedures and continuations.  Note that
     an object can be serialized and deserialized if and only if all of
     its components are serializable.

     The procedure `readtable-sharing-allowed?-set' returns a copy of
     READTABLE where only the `sharing-allowed?' field has been changed
     to NEW-VALUE.

     Here is a simple example:

          > (define (wr obj allow?)
              (call-with-output-string
                '()
                (lambda (p)
                  (output-port-readtable-set!
                    p
                    (readtable-sharing-allowed?-set
                      (output-port-readtable p)
                      allow?))
                  (write obj p))))
          > (define (rd str allow?)
              (call-with-input-string
                str
                (lambda (p)
                  (input-port-readtable-set!
                    p
                    (readtable-sharing-allowed?-set
                      (input-port-readtable p)
                      allow?))
                  (read p))))
          > (define x (list 1 2 3))
          > (set-car! (cdr x) (cddr x))
          > (wr x #f)
          "(1 (3) 3)"
          > (wr x #t)
          "(1 #0=(3) . #0#)"
          > (define y (rd (wr x #t) #t))
          > y
          (1 (3) 3)
          > (eq? (cadr y) (cddr y))
          #t
          > (define f #f)
          > (let ((free (expt 2 10)))
            (set! f (lambda (x) (+ x free))))
          > (define s (wr f 'serialize))
          > (string-length s)
          4196
          > (define g (rd s 'serialize))
          > (eq? f g)
          #f
          > (g 4)
          1028

     Continuations are tricky to serialize because they contain a
     dynamic environment and this dynamic environment may contain
     non-serializable objects, in particular ports attached to
     operating-system streams such as files, the console or standard
     input/output.  Indeed, all dynamic environments contain a binding
     for the `current-input-port' and `current-output-port'.  Moreover,
     any thread that has started a REPL has a continuation which refers
     to the "repl-context" object in its dynamic environment.  A
     repl-context object contains the interaction channel, which is
     typically connected to a non-serializable port, such as the
     console.  Another problem is that the `parameterize' form saves
     the old binding of the parameter in the continuation, so it is not
     possible to eliminate the references to these ports in the
     continuation by using the `parameterize' form alone.

     Serialization of continuations can be achieved dependably by taking
     advantage of string-ports, which are serializable objects (unless
     there is a blocked thread), and the following features of threads:
     they inherit the dynamic environment of the parent thread and they
     start with an initial continuation that contains only serializable
     objects.  So a thread created in a dynamic environment where
     `current-input-port' and `current-output-port' are bound to a
     dummy string-port has a serializable continuation.

     Here is an example where continuations are serialized:

          > (define (wr obj)
              (call-with-output-string
               '()
               (lambda (p)
                 (output-port-readtable-set!
                  p
                  (readtable-sharing-allowed?-set
                   (output-port-readtable p)
                   'serialize))
                 (write obj p))))
          > (define (rd str)
              (call-with-input-string
               str
               (lambda (p)
                 (input-port-readtable-set!
                  p
                  (readtable-sharing-allowed?-set
                   (input-port-readtable p)
                   'serialize))
                 (read p))))
          > (define fifo (open-vector))
          > (define (suspend-and-die!)
              (call-with-current-continuation
               (lambda (k)
                 (write (wr k) fifo)
                 (newline fifo)
                 (force-output fifo)
                 (thread-terminate! (current-thread)))))
          > (let ((dummy-port (open-string)))
              (parameterize ((current-input-port dummy-port)
                             (current-output-port dummy-port))
                (thread-start!
                 (make-thread
                  (lambda ()
                    (* 100
                       (suspend-and-die!)))))))
          #<thread #2>
          > (define s (read fifo))
          > (thread-join!
              (thread-start!
                (make-thread
                  (lambda ()
                    ((rd s) 111)))))
          11100
          > (thread-join!
              (thread-start!
                (make-thread
                  (lambda ()
                    ((rd s) 222)))))
          22200
          > (string-length s)
          13114


 -- procedure: readtable-eval-allowed? READTABLE
 -- procedure: readtable-eval-allowed?-set READTABLE NEW-VALUE
     The procedure `readtable-eval-allowed?' returns the content of the
     `eval-allowed?' field of READTABLE.  The reader recognizes the
     `#.EXPRESSION' notation for read-time evaluation if and only if
     the content of the `eval-allowed?' field is not `#f'.

     The procedure `readtable-eval-allowed?-set' returns a copy of
     READTABLE where only the `eval-allowed?' field has been changed to
     NEW-VALUE.

     For example:

          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-eval-allowed?-set
                (input-port-readtable (repl-input-port))
                #t))
          > '(5 plus 7 is #.(+ 5 7))
          (5 plus 7 is 12)
          > '(buf = #.(make-u8vector 25))
          (buf = #u8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))


 -- procedure: readtable-write-cdr-read-macros? READTABLE
 -- procedure: readtable-write-cdr-read-macros?-set READTABLE NEW-VALUE
 -- procedure: readtable-write-extended-read-macros? READTABLE
 -- procedure: readtable-write-extended-read-macros?-set READTABLE
          NEW-VALUE
     The procedure `readtable-write-cdr-read-macros?' returns the
     content of the `write-cdr-read-macros?' field of READTABLE.  The
     procedure `readtable-write-extended-read-macros?' returns the
     content of the `write-extended-read-macros?' field of READTABLE.

     At all times the printer uses read-macros in its output for datums
     of the form `(quote DATUM)', `(quasiquote DATUM)', `(unquote
     DATUM)', and `(unquote-splicing DATUM)'.  That is the following
     read-macro notations will be used respectively: `'DATUM', ``DATUM',
     `,DATUM', and `,@DATUM'.  Moreover, normally the read-macros will
     not be used when the form appears in the cdr of a list, for
     example `(foo quote bar)', `(foo . (quote bar))' and `(foo .
     'bar)' will all be printed as `(foo quote bar)'.

     When the content of the `write-cdr-read-macros?' field is not
     `#f', the printer will use read-macros when the forms appear in
     the cdr of a list.  For example `(foo quote bar)' will be printed
     as `(foo . 'bar)'.  When the content of the
     `write-extended-read-macros?' field is not `#f', the printer will
     also use extended read-macros, for example `#'DATUM' in place of
     `(syntax DATUM)'.

     The procedure `readtable-write-cdr-read-macros?-set' returns a
     copy of READTABLE where only the `write-cdr-read-macros?' field
     has been changed to NEW-VALUE.  The procedure
     `readtable-write-extended-read-macros?-set' returns a copy of
     READTABLE where only the `write-extended-read-macros?' field has
     been changed to NEW-VALUE.

     For example:

          > (output-port-readtable-set!
              (repl-output-port)
              (readtable-write-extended-read-macros?-set
                (output-port-readtable (repl-output-port))
                #t))
          > '(foo (syntax bar))
          (foo #'bar)
          > '(foo syntax bar)
          (foo syntax bar)
          > (output-port-readtable-set!
              (repl-output-port)
              (readtable-write-cdr-read-macros?-set
                (output-port-readtable (repl-output-port))
                #t))
          > '(foo syntax bar)
          (foo . #'bar)


 -- procedure: readtable-max-write-level READTABLE
 -- procedure: readtable-max-write-level-set READTABLE NEW-VALUE
     The procedure `readtable-max-write-level' returns the content of
     the `max-write-level' field of READTABLE.  The printer will
     display an ellipsis for the elements of lists and vectors that are
     nested deeper than this level.

     The procedure `readtable-max-write-level-set' returns a copy of
     READTABLE where only the `max-write-level' field has been changed
     to NEW-VALUE, which must be an nonnegative fixnum.

     For example:

          > (define (wr obj n)
              (call-with-output-string
                '()
                (lambda (p)
                  (output-port-readtable-set!
                    p
                    (readtable-max-write-level-set
                      (output-port-readtable p)
                      n))
                  (write obj p))))
          > (wr '(a #(b (c c) #u8(9 9 9) b) a) 3)
          "(a #(b (c c) #u8(9 9 9) b) a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) a) 2)
          "(a #(b (...) #u8(...) b) a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) a) 1)
          "(a #(...) a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) a) 0)
          "(...)"
          > (wr 'hello 0)
          "hello"


 -- procedure: readtable-max-write-length READTABLE
 -- procedure: readtable-max-write-length-set READTABLE NEW-VALUE
     The procedure `readtable-max-write-length' returns the content of
     the `max-write-length' field of READTABLE.  The printer will
     display an ellipsis for the elements of lists and vectors that are
     at an index beyond that length.

     The procedure `readtable-max-write-length-set' returns a copy of
     READTABLE where only the `max-write-length' field has been changed
     to NEW-VALUE, which must be an nonnegative fixnum.

     For example:

          > (define (wr obj n)
              (call-with-output-string
                '()
                (lambda (p)
                  (output-port-readtable-set!
                    p
                    (readtable-max-write-length-set
                      (output-port-readtable p)
                      n))
                  (write obj p))))
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 4)
          "(a #(b (c c) #u8(9 9 9) b) . a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 3)
          "(a #(b (c c) #u8(9 9 9) ...) . a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 2)
          "(a #(b (c c) ...) . a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 1)
          "(a ...)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 0)
          "(...)"


 -- procedure: readtable-max-unescaped-char READTABLE
 -- procedure: readtable-max-unescaped-char-set READTABLE NEW-VALUE
     The procedure `readtable-max-unescaped-char' returns the content
     of the `max-unescaped-char' field of READTABLE.  The printer will
     display using an escape sequence any character within symbols,
     strings and character objects greater than `max-unescaped-char'

     The procedure `readtable-max-unescaped-char-set' returns a copy of
     READTABLE where only the `max-unescaped-char' field has been
     changed to NEW-VALUE, which must be a character.

     For example:

          > (define rt (output-port-readtable (repl-output-port)))
          > (readtable-max-unescaped-char rt)
          #\delete
          > (string (integer->char 233))
          "\351"
          > (define (f c)
              (with-output-to-string
               (list readtable: (readtable-max-unescaped-char-set rt c))
               (lambda () (write (string (integer->char 233))))))
          > (f #\delete)
          "\"\\351\""
          > (string-length (f #\delete))
          6
          > (f #\U0010ffff)
          "\"\351\""
          > (string-length (f #\U0010ffff))
          3
          > (output-port-readtable-set!
             (repl-output-port)
             (readtable-max-unescaped-char-set rt #\U0010ffff))
          > (string (integer->char 233))
          "é"


 -- procedure: readtable-start-syntax READTABLE
 -- procedure: readtable-start-syntax-set READTABLE NEW-VALUE
     The procedure `readtable-start-syntax' returns the content of the
     `start-syntax' field of READTABLE.  The reader uses this field to
     determine in which syntax to start parsing the input.  When the
     content of this field is the symbol `six', the reader starts in
     the infix syntax.  Otherwise the reader starts in the prefix
     syntax.

     The procedure `readtable-start-syntax-set' returns a copy of
     READTABLE where only the `start-syntax' field has been changed to
     NEW-VALUE.

     For example:

          > (+ 2 3)
          5
          > (input-port-readtable-set!
             (repl-input-port)
             (readtable-start-syntax-set
               (input-port-readtable (repl-input-port))
               'six))
          > 2+3;
          5
          > exit();



File: gambit-c.info,  Node: Boolean syntax,  Next: Character syntax,  Prev: Readtables,  Up: Lexical syntax and readtables

18.2 Boolean syntax
===================

Booleans are required to be followed by a delimiter (i.e. `#f64()' is
not the boolean `#f' followed by the number `64' and the empty list).


File: gambit-c.info,  Node: Character syntax,  Next: String syntax,  Prev: Boolean syntax,  Up: Lexical syntax and readtables

18.3 Character syntax
=====================

Characters are required to be followed by a delimiter (i.e.
`#\spaceballs' is not the character `#\space' followed by the symbol
`balls').  The lexical syntax of characters is extended to allow the
following:

`#\nul'
     Unicode character 0

`#\alarm'
     Unicode character 7

`#\backspace'
     Unicode character 8

`#\tab'
     Unicode character 9

`#\newline'
     Unicode character 10 (newline character)

`#\linefeed'
     Unicode character 10

`#\vtab'
     Unicode character 11

`#\page'
     Unicode character 12

`#\return'
     Unicode character 13

`#\esc'
     Unicode character 27

`#\space'
     Unicode character 32 (space character)

`#\delete'
     Unicode character 127

`#\xHH'
     character encoded in hexadecimal (>= 1 hexadecimal digit)

`#\uHHHH'
     character encoded in hexadecimal (exactly 4 hexadecimal digits)

`#\UHHHHHHHH'
     character encoded in hexadecimal (exactly 8 hexadecimal digits)


File: gambit-c.info,  Node: String syntax,  Next: Symbol syntax,  Prev: Character syntax,  Up: Lexical syntax and readtables

18.4 String syntax
==================

The lexical syntax of quoted strings is extended to allow the following
escape codes:

`\a'
     Unicode character 7

`\b'
     Unicode character 8

`\t'
     Unicode character 9

`\n'
     Unicode character 10 (newline character)

`\v'
     Unicode character 11

`\f'
     Unicode character 12

`\r'
     Unicode character 13

`\"'
     `"'

`\\'
     `\'

`\|'
     `|'

`\?'
     `?'

`\OOO'
     character encoded in octal (1 to 3 octal digits, first digit must
     be less than 4 when there are 3 octal digits)

`\xHH'
     character encoded in hexadecimal (>= 1 hexadecimal digit)

`\uHHHH'
     character encoded in hexadecimal (exactly 4 hexadecimal digits)

`\UHHHHHHHH'
     character encoded in hexadecimal (exactly 8 hexadecimal digits)

`\<space>'
     Unicode character 32 (space character)

`\<newline><whitespace-except-newline>*'
     This sequence expands to nothing (it is useful for splitting a long
     string literal on multiple lines while respecting proper
     indentation of the source code)

   Gambit also supports a "here string" syntax that is similar to shell
"here documents".  For example:

     > (pretty-print #<<THE-END
     hello
     world
     THE-END
     )
     "hello\nworld"

   The here string starts with the sequence `#<<'.  The part of the
line after the `#<<' up to and including the newline character is the
key. The first line afterward that matches the key marks the end of the
here string.  The string contains all the characters between the start
key and the end key, with the exception of the newline character before
the end key.


File: gambit-c.info,  Node: Symbol syntax,  Next: Keyword syntax,  Prev: String syntax,  Up: Lexical syntax and readtables

18.5 Symbol syntax
==================

The lexical syntax of symbols is extended to allow a leading and
trailing vertical bar (e.g. `|a\|b"c:|').  The symbol's name
corresponds verbatim to the characters between the vertical bars except
for escaped characters.  The same escape sequences as for strings are
permitted except that `"' does not need to be escaped and `|' needs to
be escaped.

   For example:

     > (symbol->string '|a\|b"c:|)
     "a|b\"c:"


File: gambit-c.info,  Node: Keyword syntax,  Next: Box syntax,  Prev: Symbol syntax,  Up: Lexical syntax and readtables

18.6 Keyword syntax
===================

The lexical syntax of keywords is like symbols, but with a colon at the
end (note that this can be changed to a leading colon by setting the
`keywords-allowed?' field of the readtable to the symbol `prefix').  A
colon by itself is not a keyword, it is a symbol.  Vertical bars can be
used like symbols but the colon must be outside the vertical bars.
Note that the string returned by the `keyword->string' procedure does
not include the colon.

   For example:

     > (keyword->string 'foo:)
     "foo"
     > (map keyword? '(|ab()cd:| |ab()cd|: : ||:))
     (#f #t #f #t)


File: gambit-c.info,  Node: Box syntax,  Next: Number syntax,  Prev: Keyword syntax,  Up: Lexical syntax and readtables

18.7 Box syntax
===============

The lexical syntax of boxes is `#&OBJ' where OBJ is the content of the
box.

   For example:

     > (list '#&"hello" '#&123)
     (#&"hello" #&123)
     > (box (box (+ 10 20)))
     #&#&30


File: gambit-c.info,  Node: Number syntax,  Next: Homogeneous vector syntax,  Prev: Box syntax,  Up: Lexical syntax and readtables

18.8 Number syntax
==================

The lexical syntax of the special inexact real numbers is as follows:

`+inf.0'
     positive infinity

`-inf.0'
     negative infinity

`+nan.0'
     "not a number"

`-0.'
     negative zero (`0.' is the positive zero)


File: gambit-c.info,  Node: Homogeneous vector syntax,  Next: Special #! syntax,  Prev: Number syntax,  Up: Lexical syntax and readtables

18.9 Homogeneous vector syntax
==============================

Homogeneous vectors are vectors containing raw numbers of the same type
(signed or unsigned exact integers or inexact reals).  There are 10
types of homogeneous vectors: `s8vector' (vector of 8 bit signed
integers), `u8vector' (vector of 8 bit unsigned integers), `s16vector'
(vector of 16 bit signed integers), `u16vector' (vector of 16 bit
unsigned integers), `s32vector' (vector of 32 bit signed integers),
`u32vector' (vector of 32 bit unsigned integers), `s64vector' (vector
of 64 bit signed integers), `u64vector' (vector of 64 bit unsigned
integers), `f32vector' (vector of 32 bit floating point numbers), and
`f64vector' (vector of 64 bit floating point numbers).

   The external representation of homogeneous vectors is similar to
normal vectors but with the `#(' prefix replaced respectively with
`#s8(', `#u8(', `#s16(', `#u16(', `#s32(', `#u32(', `#s64(', `#u64(',
`#f32(', and `#f64('.

   The elements of the integer homogeneous vectors must be exact
integers fitting in the given precision.  The elements of the floating
point homogeneous vectors must be inexact reals.


File: gambit-c.info,  Node: Special #! syntax,  Next: Multiline comment syntax,  Prev: Homogeneous vector syntax,  Up: Lexical syntax and readtables

18.10 Special `#!' syntax
=========================

The lexical syntax of the special `#!' objects is as follows:

`#!eof'
     end-of-file object

`#!void'
     void object

`#!optional'
     optional object

`#!rest'
     rest object

`#!key'
     key object


File: gambit-c.info,  Node: Multiline comment syntax,  Next: Scheme infix syntax extension,  Prev: Special #! syntax,  Up: Lexical syntax and readtables

18.11 Multiline comment syntax
==============================

Multiline comments are delimited by the tokens `#|' and `|#'.  These
comments can be nested.


File: gambit-c.info,  Node: Scheme infix syntax extension,  Prev: Multiline comment syntax,  Up: Lexical syntax and readtables

18.12 Scheme infix syntax extension
===================================

The reader supports an infix syntax extension which is called SIX
(Scheme Infix eXtension).  This extension is both supported by the
`read' procedure and in program source code.

   The backslash character is a delimiter that marks the beginning of a
single datum expressed in the infix syntax (the details are given
below).  One way to think about it is that the backslash character
escapes the prefix syntax temporarily to use the infix syntax.  For
example a three element list could be written as `(X \Y Z)', the
elements X and Z are expressed using the normal prefix syntax and Y is
expressed using the infix syntax.

   When the reader encounters an infix datum, it constructs a syntax
tree for that particular datum.  Each node of this tree is represented
with a list whose first element is a symbol indicating the type of node.
For example, `(six.identifier abc)' is the representation of the infix
identifier `abc' and `(six.index (six.identifier abc) (six.identifier
i))' is the representation of the infix datum `abc[i];'.

18.12.1 SIX grammar
-------------------

The SIX grammar is given below.  On the left hand side are the
production rules.  On the right hand side is the datum that is
constructed by the reader.  The notation $I denotes the datum that is
constructed by the reader for the Ith part of the production rule.

<infix datum> ::=                           
<stat>                                      $1
<stat> ::=                                  
<if stat>                                   $1
| <for stat>                                $1
| <while stat>                              $1
| <do stat>                                 $1
| <switch stat>                             $1
| <case stat>                               $1
| <break stat>                              $1
| <continue stat>                           $1
| <label stat>                              $1
| <goto stat>                               $1
| <return stat>                             $1
| <expression stat>                         $1
| <procedure definition>                    $1
| <variable definition> `;'                 $1
| <clause stat>                             $1
| <compound stat>                           $1
| `;'                                       `(six.compound)'
<if stat> ::=                               
`if' `(' <pexpr> `)' <stat>                 `(six.if $3 $5)'
| `if' `(' <pexpr> `)' <stat> `else'        `(six.if $3 $5 $7)'
<stat>                                      
<for stat> ::=                              
`for' `(' <stat> `;' <oexpr> `;' <oexpr>    `(six.for $3 $5 $7 $9)'
`)' <stat>                                  
<while stat> ::=                            
`while' `(' <pexpr> `)' <stat>              `(six.while $3 $5)'
<do stat> ::=                               
`do' <stat> `while' `(' <pexpr> `)' `;'     `(six.do-while $2 $5)'
<switch stat> ::=                           
`switch' `(' <pexpr> `)' <stat>             `(six.switch $3 $5)'
<case stat> ::=                             
`case' <expr> `:' <stat>                    `(six.case $2 $4)'
<break stat> ::=                            
`break' `;'                                 `(six.break)'
<continue stat> ::=                         
`continue' `;'                              `(six.continue)'
<label stat> ::=                            
<identifier> `:' <stat>                     `(six.label $1 $3)'
<goto stat> ::=                             
`goto' <expr> `;'                           `(six.goto $2)'
<return stat> ::=                           
`return' `;'                                `(six.return)'
| `return' <expr> `;'                       `(six.return $2)'
<expression stat> ::=                       
<expr> `;'                                  $1
<clause stat> ::=                           
<expr> `.'                                  `(six.clause $1)'
<pexpr> ::=                                 
<procedure definition>                      $1
| <variable definition>                     $1
| <expr>                                    $1
<procedure definition> ::=                  
<type> <id-or-prefix> `(' <parameters> `)'  `(six.define-procedure $2
<body>                                      (six.procedure $1 $4 $6))'
<variable definition> ::=                   
<type> <id-or-prefix> <dimensions> <iexpr>  `(six.define-variable $2 $1
                                            $3 $4)'
<iexpr> ::=                                 
`=' <expr>                                  $2
|                                           `#f'
<dimensions> ::=                            
| `[' <expr> `]' <dimensions>               `($2 . $4)'
|                                           `()'
<oexpr> ::=                                 
<expr>                                      $1
|                                           `#f'
<expr> ::=                                  
<expr18>                                    $1
<expr18> ::=                                
<expr17> `:-' <expr18>                      `(six.x:-y $1 $3)'
| <expr17>                                  $1
<expr17> ::=                                
<expr17> `,' <expr16>                       `(|six.x,y| $1 $3)'
| <expr16>                                  $1
<expr16> ::=                                
<expr15> `:=' <expr16>                      `(six.x:=y $1 $3)'
| <expr15>                                  $1
<expr15> ::=                                
<expr14> `%=' <expr15>                      `(six.x%=y $1 $3)'
| <expr14> `&=' <expr15>                    `(six.x&=y $1 $3)'
| <expr14> `*=' <expr15>                    `(six.x*=y $1 $3)'
| <expr14> `+=' <expr15>                    `(six.x+=y $1 $3)'
| <expr14> `-=' <expr15>                    `(six.x-=y $1 $3)'
| <expr14> `/=' <expr15>                    `(six.x/=y $1 $3)'
| <expr14> `<<=' <expr15>                   `(six.x<<=y $1 $3)'
| <expr14> `=' <expr15>                     `(six.x=y $1 $3)'
| <expr14> `>>=' <expr15>                   `(six.x>>=y $1 $3)'
| <expr14> `^=' <expr15>                    `(six.x^=y $1 $3)'
| <expr14> `|=' <expr15>                    `(|six.x\|=y| $1 $3)'
| <expr14>                                  $1
<expr14> ::=                                
<expr13> `:' <expr14>                       `(six.x:y $1 $3)'
| <expr13>                                  $1
<expr13> ::=                                
<expr12> `?' <expr> `:' <expr13>            `(six.x?y:z $1 $3 $5)'
| <expr12>                                  $1
<expr12> ::=                                
<expr12> `||' <expr11>                      `(|six.x\|\|y| $1 $3)'
| <expr11>                                  $1
<expr11> ::=                                
<expr11> `&&' <expr10>                      `(six.x&&y $1 $3)'
| <expr10>                                  $1
<expr10> ::=                                
<expr10> `|' <expr9>                        `(|six.x\|y| $1 $3)'
| <expr9>                                   $1
<expr9> ::=                                 
<expr9> `^' <expr8>                         `(six.x^y $1 $3)'
| <expr8>                                   $1
<expr8> ::=                                 
<expr8> `&' <expr7>                         `(six.x&y $1 $3)'
| <expr7>                                   $1
<expr7> ::=                                 
<expr7> `!=' <expr6>                        `(six.x!=y $1 $3)'
| <expr7> `==' <expr6>                      `(six.x==y $1 $3)'
| <expr6>                                   $1
<expr6> ::=                                 
<expr6> `<' <expr5>                         `(six.x<y $1 $3)'
| <expr6> `<=' <expr5>                      `(six.x<=y $1 $3)'
| <expr6> `>' <expr5>                       `(six.x>y $1 $3)'
| <expr6> `>=' <expr5>                      `(six.x>=y $1 $3)'
| <expr5>                                   $1
<expr5> ::=                                 
<expr5> `<<' <expr4>                        `(six.x<<y $1 $3)'
| <expr5> `>>' <expr4>                      `(six.x>>y $1 $3)'
| <expr4>                                   $1
<expr4> ::=                                 
<expr4> `+' <expr3>                         `(six.x+y $1 $3)'
| <expr4> `-' <expr3>                       `(six.x-y $1 $3)'
| <expr3>                                   $1
<expr3> ::=                                 
<expr3> `%' <expr2>                         `(six.x%y $1 $3)'
| <expr3> `*' <expr2>                       `(six.x*y $1 $3)'
| <expr3> `/' <expr2>                       `(six.x/y $1 $3)'
| <expr2>                                   $1
<expr2> ::=                                 
`&' <expr2>                                 `(six.&x $2)'
| `+' <expr2>                               `(six.+x $2)'
| `-' <expr2>                               `(six.-x $2)'
| `*' <expr2>                               `(six.*x $2)'
| `!' <expr2>                               `(six.!x $2)'
| `!'                                       `(six.!)'
| `++' <expr2>                              `(six.++x $2)'
| `--' <expr2>                              `(six.--x $2)'
| `~' <expr2>                               `(six.~x $2)'
| `new' <id-or-prefix> `(' <arguments> `)'  `(six.new $2 . $4)'
| <expr1>                                   $1
<expr1> ::=                                 
<expr1> `++'                                `(six.x++ $1)'
| <expr1> `--'                              `(six.x-- $1)'
| <expr1> `(' <arguments> `)'               `(six.call $1 . $3)'
| <expr1> `[' <expr> `]'                    `(six.index $1 $3)'
| <expr1> `->' <id-or-prefix>               `(six.arrow $1 $3)'
| <expr1> `.' <id-or-prefix>                `(six.dot $1 $3)'
| <expr0>                                   $1
<expr0> ::=                                 
<id-or-prefix>                              $1
| <string>                                  `(six.literal $1)'
| <char>                                    `(six.literal $1)'
| <number>                                  `(six.literal $1)'
| `(' <expr> `)'                            $2
| `(' <block stat> `)'                      $2
| <datum-starting-with-#-or-backquote>      `(six.prefix $1)'
| `[' <elements> `]'                        $2
| <type> `(' <parameters> `)' <body>        `(six.procedure $1 $3 $5)'
<block stat> ::=                            
`{' <stat list> `}'                         `(six.compound . $2)'
<body> ::=                                  
`{' <stat list> `}'                         `(six.procedure-body . $2)'
<stat list> ::=                             
<stat> <stat list>                          `($1 . $2)'
|                                           `()'
<parameters> ::=                            
<nonempty parameters>                       $1
|                                           `()'
<nonempty parameters> ::=                   
<parameter> `,' <nonempty parameters>       `($1 . $3)'
| <parameter>                               `($1)'
<parameter> ::=                             
<type> <id-or-prefix>                       `($2 $1)'
<arguments> ::=                             
<nonempty arguments>                        $1
|                                           `()'
<nonempty arguments> ::=                    
<expr> `,' <nonempty arguments>             `($1 . $3)'
| <expr>                                    `($1)'
<elements> ::=                              
<nonempty elements>                         $1
|                                           `(six.null)'
<nonempty elements> ::=                     
<expr>                                      `(six.list $1 (six.null))'
| <expr> `,' <nonempty elements>            `(six.list $1 $3)'
| <expr> `|' <expr>                         `(six.cons $1 $3)'
<id-or-prefix> ::=                          
<identifier>                                `(six.identifier $1)'
| `\' <datum>                               `(six.prefix $2)'
<type> ::=                                  
`int'                                       `int'
| `char'                                    `char'
| `bool'                                    `bool'
| `void'                                    `void'
| `float'                                   `float'
| `double'                                  `double'
| `obj'                                     `obj'

18.12.2 SIX semantics
---------------------

The semantics of SIX depends on the definition of the `six.XXX'
identifiers (as functions and macros).  Many of these identifiers are
predefined macros which give SIX a semantics that is close to C's.  The
user may override these definitions to change the semantics either
globally or locally.  For example, `six.x^y' is a predefined macro that
expands `(six.x^y x y)' into `(bitwise-xor x y)'.  If the user prefers
the `^' operator to express exponentiation in a specific function, then
in that function `six.x^y' can be redefined as a macro that expands
`(six.x^y x y)' into `(expt x y)'.  Note that the associativity and
precedence of operators cannot be changed as that is a syntactic issue.

   Note that the following identifiers are not predefined, and
consequently they do not have a predefined semantics: `six.label',
`six.goto', `six.switch', `six.case', `six.break', `six.continue',
`six.return', `six.clause', `six.x:-y', and `six.!'.

   The following is an example showing some of the predefined semantics
of SIX:

     > (list (+ 1 2) \3+4; (+ 5 6))
     (3 7 11)
     > \[ 1+2, \(+ 3 4), 5+6 ];
     (3 7 11)
     > (map (lambda (x) \(x*x-1)/log(x+1);) '(1 2 3 4))
     (0 2.730717679880512 5.7707801635558535 9.320024018394177)
     > \obj n = expt(10,5);
     > n
     100000
     > \obj t[3][10] = 88;
     > \t[0][9] = t[2][1] = 11;
     11
     > t
     #(#(88 88 88 88 88 88 88 88 88 11)
       #(88 88 88 88 88 88 88 88 88 88)
       #(88 11 88 88 88 88 88 88 88 88))
     > \obj radix = new parameter (10);
     > \radix(2);
     > \radix();
     2
     > \for (int i=0; i<5; i++) pp(1<<i*8);
     1
     256
     65536
     16777216
     4294967296
     > \obj \make-adder (obj x) { obj (obj y) { x+y; }; }
     > \map (new adder (100), [1,2,3,4]);
     (101 102 103 104)
     > (map (make-adder 100) (list 1 2 3 4))
     (101 102 103 104)


File: gambit-c.info,  Node: C-interface,  Next: System limitations,  Prev: Lexical syntax and readtables,  Up: Top

19 C-interface
**************

The Gambit Scheme system offers a mechanism for interfacing Scheme code
and C code called the "C-interface".  A Scheme program indicates which
C functions it needs to have access to and which Scheme procedures can
be called from C, and the C interface automatically constructs the
corresponding Scheme procedures and C functions.  The conversions needed
to transform data from the Scheme representation to the C representation
(and back), are generated automatically in accordance with the argument
and result types of the C function or Scheme procedure.

   The C-interface places some restrictions on the types of data that
can be exchanged between C and Scheme.  The mapping of data types
between C and Scheme is discussed in the next section.  The remaining
sections of this chapter describe each special form of the C-interface.

* Menu:

* mapping of types::                The mapping of types between C and Scheme
* c-declare::                       The `c-declare' special form
* c-initialize::                    The `c-initialize' special form
* c-lambda::                        The `c-lambda' special form
* c-define::                        The `c-define' special form
* c-define-type::                   The `c-define-type' special form
* continuations::                   Continuations and the C-interface


File: gambit-c.info,  Node: mapping of types,  Next: c-declare,  Prev: C-interface,  Up: C-interface

19.1 The mapping of types between C and Scheme
==============================================

Scheme and C do not provide the same set of built-in data types so it is
important to understand which Scheme type is compatible with which C
type and how values get mapped from one environment to the other.  To
improve compatibility a new type is added to Scheme, the `foreign'
object type, and the following data types are added to C:

`scheme-object'
     denotes the universal type of Scheme objects (type `___SCMOBJ'
     defined in `gambit.h')

`bool'
     denotes the C++ `bool' type or the C `int' type (type `___BOOL'
     defined in `gambit.h')

`int8'
     8 bit signed integer (type `___S8' defined in `gambit.h')

`unsigned-int8'
     8 bit unsigned integer (type `___U8' defined in `gambit.h')

`int16'
     16 bit signed integer (type `___S16' defined in `gambit.h')

`unsigned-int16'
     16 bit unsigned integer (type `___U16' defined in `gambit.h')

`int32'
     32 bit signed integer (type `___S32' defined in `gambit.h')

`unsigned-int32'
     32 bit unsigned integer (type `___U32' defined in `gambit.h')

`int64'
     64 bit signed integer (type `___S64' defined in `gambit.h')

`unsigned-int64'
     64 bit unsigned integer (type `___U64' defined in `gambit.h')

`float32'
     32 bit floating point number (type `___F32' defined in `gambit.h')

`float64'
     64 bit floating point number (type `___F64' defined in `gambit.h')

`ISO-8859-1'
     denotes ISO-8859-1 encoded characters (8 bit unsigned integer,
     type `___ISO_8859_1' defined in `gambit.h')

`UCS-2'
     denotes UCS-2 encoded characters (16 bit unsigned integer, type
     `___UCS_2' defined in `gambit.h')

`UCS-4'
     denotes UCS-4 encoded characters (32 bit unsigned integer, type
     `___UCS_4' defined in `gambit.h')

`char-string'
     denotes the C `char*' type when used as a null terminated string

`nonnull-char-string'
     denotes the nonnull C `char*' type when used as a null terminated
     string

`nonnull-char-string-list'
     denotes an array of nonnull C `char*' terminated with a null
     pointer

`ISO-8859-1-string'
     denotes ISO-8859-1 encoded strings (null terminated string of 8
     bit unsigned integers, i.e. `___ISO_8859_1*')

`nonnull-ISO-8859-1-string'
     denotes nonnull ISO-8859-1 encoded strings (null terminated string
     of 8 bit unsigned integers, i.e. `___ISO_8859_1*')

`nonnull-ISO-8859-1-stringlist'
     denotes an array of nonnull ISO-8859-1 encoded strings terminated
     with a null pointer

`UTF-8-string'
     denotes UTF-8 encoded strings (null terminated string of `char',
     i.e. `char*')

`nonnull-UTF-8-string'
     denotes nonnull UTF-8 encoded strings (null terminated string of
     `char', i.e. `char*')

`nonnull-UTF-8-string-list'
     denotes an array of nonnull UTF-8 encoded strings terminated with
     a null pointer

`UTF-16-string'
     denotes UTF-16 encoded strings (null terminated string of `char',
     i.e. `char*')

`nonnull-UTF-16-string'
     denotes nonnull UTF-16 encoded strings (null terminated string of
     `char', i.e. `char*')

`nonnull-UTF-16-string-list'
     denotes an array of nonnull UTF-16 encoded strings terminated with
     a null pointer

`UCS-2-string'
     denotes UCS-2 encoded strings (null terminated string of 16 bit
     unsigned integers, i.e. `___UCS_2*')

`nonnull-UCS-2-string'
     denotes nonnull UCS-2 encoded strings (null terminated string of
     16 bit unsigned integers, i.e. `___UCS_2*')

`nonnull-UCS-2-string-list'
     denotes an array of nonnull UCS-2 encoded strings terminated with
     a null pointer

`UCS-4-string'
     denotes UCS-4 encoded strings (null terminated string of 32 bit
     unsigned integers, i.e. `___UCS_4*')

`nonnull-UCS-4-string'
     denotes nonnull UCS-4 encoded strings (null terminated string of
     32 bit unsigned integers, i.e. `___UCS_4*')

`nonnull-UCS-4-string-list'
     denotes an array of nonnull UCS-4 encoded strings terminated with
     a null pointer

`wchar_t-string'
     denotes `wchar_t' encoded strings (null terminated string of
     `wchar_t', i.e. `wchar_t*')

`nonnull-wchar_t-string'
     denotes nonnull `wchar_t' encoded strings (null terminated string
     of `wchar_t', i.e. `wchar_t*')

`nonnull-wchar_t-string-list'
     denotes an array of nonnull `wchar_t' encoded strings terminated
     with a null pointer

   To specify a particular C type inside the `c-lambda', `c-define' and
`c-define-type' forms, the following "Scheme notation" is used:

`Scheme notation'
     C type

`void'
     `void'

`bool'
     `bool'

`char'
     `char'  (may be signed or unsigned depending on the C compiler)

`signed-char'
     `signed char'

`unsigned-char'
     `unsigned char'

`ISO-8859-1'
     `ISO-8859-1'

`UCS-2'
     `UCS-2'

`UCS-4'
     `UCS-4'

`wchar_t'
     `wchar_t'

`size_t'
     `size_t' (type `___SIZE_T' defined in `gambit.h')

`ssize_t'
     `ssize_t' (type `___SSIZE_T' defined in `gambit.h')

`ptrdiff_t'
     `ptrdiff_t' (type `___PTRDIFF_T' defined in `gambit.h')

`short'
     `short'

`unsigned-short'
     `unsigned short'

`int'
     `int'

`unsigned-int'
     `unsigned int'

`long'
     `long'

`unsigned-long'
     `unsigned long'

`long-long'
     `long long'

`unsigned-long-long'
     `unsigned long long'

`float'
     `float'

`double'
     `double'

`int8'
     `int8'

`unsigned-int8'
     `unsigned-int8'

`int16'
     `int16'

`unsigned-int16'
     `unsigned-int16'

`int32'
     `int32'

`unsigned-int32'
     `unsigned-int32'

`int64'
     `int64'

`unsigned-int64'
     `unsigned-int64'

`float32'
     `float32'

`float64'
     `float64'

`(struct "C-STRUCT-ID" [TAGS [RELEASE-FUNCTION]])'
     `struct C-STRUCT-ID'  (where C-STRUCT-ID is the name of a C
     structure; see below for the meaning of TAGS and RELEASE-FUNCTION)

`(union "C-UNION-ID" [TAGS [RELEASE-FUNCTION]])'
     `union C-UNION-ID'  (where C-UNION-ID is the name of a C union;
     see below for the meaning of TAGS and RELEASE-FUNCTION)

`(type "C-TYPE-ID" [TAGS [RELEASE-FUNCTION]])'
     `C-TYPE-ID'  (where C-TYPE-ID is an identifier naming a C type;
     see below for the meaning of TAGS and RELEASE-FUNCTION)

`(pointer TYPE [TAGS [RELEASE-FUNCTION]])'
     `T*'  (where T is the C equivalent of TYPE which must be the
     Scheme notation of a C type; see below for the meaning of TAGS and
     RELEASE-FUNCTION)

`(nonnull-pointer TYPE [TAGS [RELEASE-FUNCTION]])'
     same as `(pointer TYPE [TAGS [RELEASE-FUNCTION]])' except the
     `NULL' pointer is not allowed

`(function (TYPE1...) RESULT-TYPE)'
     function with the given argument types and result type

`(nonnull-function (TYPE1...) RESULT-TYPE)'
     same as `(function (TYPE1...) RESULT-TYPE)' except the `NULL'
     pointer is not allowed

`char-string'
     `char-string'

`nonnull-char-string'
     `nonnull-char-string'

`nonnull-char-string-list'
     `nonnull-char-string-list'

`ISO-8859-1-string'
     `ISO-8859-1-string'

`nonnull-ISO-8859-1-string'
     `nonnull-ISO-8859-1-string'

`nonnull-ISO-8859-1-string-list'
     `nonnull-ISO-8859-1-string-list'

`UTF-8-string'
     `UTF-8-string'

`nonnull-UTF-8-string'
     `nonnull-UTF-8-string'

`nonnull-UTF-8-string-list'
     `nonnull-UTF-8-string-list'

`UTF-16-string'
     `UTF-16-string'

`nonnull-UTF-16-string'
     `nonnull-UTF-16-string'

`nonnull-UTF-16-string-list'
     `nonnull-UTF-16-string-list'

`UCS-2-string'
     `UCS-2-string'

`nonnull-UCS-2-string'
     `nonnull-UCS-2-string'

`nonnull-UCS-2-string-list'
     `nonnull-UCS-2-string-list'

`UCS-4-string'
     `UCS-4-string'

`nonnull-UCS-4-string'
     `nonnull-UCS-4-string'

`nonnull-UCS-4-string-list'
     `nonnull-UCS-4-string-list'

`wchar_t-string'
     `wchar_t-string'

`nonnull-wchar_t-string'
     `nonnull-wchar_t-string'

`nonnull-wchar_t-string-list'
     `nonnull-wchar_t-string-list'

`scheme-object'
     `scheme-object'

`NAME'
     appropriate translation of NAME (where NAME is a C type defined
     with `c-define-type')

`"C-TYPE-ID"'
     C-TYPE-ID (this form is equivalent to `(type "C-TYPE-ID")')

   The `struct', `union', `type', `pointer' and `nonnull-pointer' types
are "foreign types" and they are represented on the Scheme side as
"foreign objects".  A foreign object is internally represented as a
pointer.  This internal pointer is identical to the C pointer being
represented in the case of the `pointer' and `nonnull-pointer' types.

   In the case of the `struct', `union' and `type' types, the internal
pointer points to a copy of the C data type being represented.  When an
instance of one of these types is converted from C to Scheme, a block
of memory is allocated from the C heap and initialized with the
instance and then a foreign object is allocated from the Scheme heap
and initialized with the pointer to this copy.  This approach may
appear overly complex, but it allows the conversion of C++ classes that
do not have a zero parameter constructor or an assignment method (i.e.
when compiling with a C++ compiler an instance is copied using `new
TYPE (INSTANCE)', which calls the copy-constructor of TYPE if it is a
class; TYPE's assignment operator is never used).  Conversion from
Scheme to C simply dereferences the internal pointer (no allocation
from the C heap is performed).  Deallocation of the copy on the C heap
is under the control of the release function attached to the foreign
object (see below).

   The optional TAGS field of foreign type specifications is used for
type checking on the Scheme side.  The TAGS field must be `#f', a
symbol or a non-empty list of symbols.  When it is not specified the
TAGS field defaults to a symbol whose name, as returned by
`symbol->string', is the C type declaration for that type.  For example
the symbol `char**' is the default for the type `(pointer (pointer
char))'.  A TAGS field that is a single symbol is equivalent to a list
containing only that symbol.  The first symbol in the list of tags is
the primary tag.  For example the primary tag of the type `(pointer
char)' is `char*' and the primary tag of the type `(pointer char (foo
bar))' is `foo'.

   Type compatibility between two foreign types depends on their tags.
An instance of a foreign type T can be used where a foreign type E is
expected if and only if

   * T's TAGS field is `#f', or

   * E's TAGS field is `#f', or

   * T's primary tag is a member of E's tags.


   For the safest code a TAGS field of `#f' should be used sparingly,
as it completely bypasses type checking.  The external representation
of Scheme foreign objects (used by the `write' procedure) contains the
primary tag (if the TAGS field is not `#f'), and the hexadecimal
address denoted by the internal pointer, for example `#<char** #2
0x2AAC535C>'.  Note that the hexadecimal address is in C notation,
which can be easily transferred to a C debugger with a "cut-and-paste".

   A RELEASE-FUNCTION can also be specified within a foreign type
specification.  The RELEASE-FUNCTION must be `#f' or a string naming a
C function with a single parameter of type `void*' (in which the
internal pointer is passed) and with a result of type `___SCMOBJ' (for
returning an error code).  When the RELEASE-FUNCTION is not specified
or is `#f' a default function is constructed by the C-interface.  This
default function does nothing in the case of the `pointer' and
`nonnull-pointer' types (deallocation is not the responsibility of the
C-interface) and returns the fixnum `___FIX(___NO_ERR)' to indicate no
error.  In the case of the `struct', `union' and `type' types, the
default function reclaims the copy on the C heap referenced by the
internal pointer (when using a C++ compiler this is done using `delete
(TYPE*)INTERNAL-POINTER', which calls the destructor of TYPE if it is a
class) and returns `___FIX(___NO_ERR)'.  In many situations the default
RELEASE-FUNCTION will perform the appropriate cleanup for the foreign
type.  However, in certain cases special operations (such as
decrementing a reference count, removing the object from a table, etc)
must be performed.  For such cases a user supplied RELEASE-FUNCTION is
needed.

   The RELEASE-FUNCTION is invoked at most once for any foreign object.
After the RELEASE-FUNCTION is invoked, the foreign object is
considered "released" and can no longer be used in a foreign type
conversion.  When the garbage collector detects that a foreign object
is no longer reachable by the program, it will invoke the
RELEASE-FUNCTION if the foreign object is not yet released.  When there
is a need to release the foreign object promptly, the program can
explicitly call `(foreign-release! OBJ)' which invokes the
RELEASE-FUNCTION if the foreign object is not yet released, and does
nothing otherwise.  The call `(foreign-released? OBJ)' returns a
boolean indicating whether the foreign object OBJ has been released yet
or not.  The call `(foreign-address OBJ)' returns the address denoted
by the internal pointer of foreign object OBJ or 0 if it has been
released.  The call `(foreign? OBJ)' tests that OBJ is a foreign
object.  Finally the call `(foreign-tags OBJ)' returns the list of tags
of foreign object OBJ, or `#f'.

   The following table gives the C types to which each Scheme type can
be converted:

Scheme type
     Allowed target C types

boolean `#f'
     `scheme-object'; `bool'; `pointer'; `function'; `char-string';
     `ISO-8859-1-string'; `UTF-8-string'; `UTF-16-string';
     `UCS-2-string'; `UCS-4-string'; `wchar_t-string'

boolean `#t'
     `scheme-object'; `bool'

character
     `scheme-object'; `bool'; [`[un]signed'] `char'; `ISO-8859-1';
     `UCS-2'; `UCS-4'; `wchar_t'

exact integer
     `scheme-object'; `bool'; [`unsigned-']
     `int8'/`int16'/`int32'/`int64'; [`unsigned'] `short'/`int'/`long';
     `size_t'/`ssize_t'/`ptrdiff_t'

inexact real
     `scheme-object'; `bool'; `float'; `double'; `float32'; `float64'

string
     `scheme-object'; `bool'; `char-string'; `nonnull-char-string';
     `ISO-8859-1-string'; `nonnull-ISO-8859-1-string'; `UTF-8-string';
     `nonnull-UTF-8-string'; `UTF-16-string'; `nonnull-UTF-16-string';
     `UCS-2-string'; `nonnull-UCS-2-string'; `UCS-4-string';
     `nonnull-UCS-4-string'; `wchar_t-string'; `nonnull-wchar_t-string'

foreign object
     `scheme-object'; `bool';
     `struct'/`union'/`type'/`pointer'/`nonnull-pointer' with the
     appropriate tags

vector
     `scheme-object'; `bool'

symbol
     `scheme-object'; `bool'

procedure
     `scheme-object'; `bool'; `function'; `nonnull-function'

other objects
     `scheme-object'; `bool'

   The following table gives the Scheme types to which each C type will
be converted:

C type
     Resulting Scheme type

scheme-object
     the Scheme object encoded

bool
     boolean

[`[un]signed'] `char'; `ISO-8859-1'; `UCS-2'; `UCS-4'; `wchar_t'
     character

[`unsigned-'] `int8'/`int16'/`int32'/`int64'; [`unsigned'] `short'/`int'/`long'; `size_t'/`ssize_t'/`ptrdiff_t'
     exact integer

`float'; `double'; `float32'; `float64'
     inexact real

`char-string'; `ISO-8859-1-string'; `UTF-8-string'; `UTF-16-string'; `UCS-2-string'; `UCS-4-string'; `wchar_t-string'
     string or `#f' if it is equal to `NULL'

`nonnull-char-string'; `nonnull-ISO-8859-1-string'; `nonnull-UTF-8-string'; `nonnull-UTF-16-string'; `nonnull-UCS-2-string'; `nonnull-UCS-4-string'; `nonnull-wchar_t-string'
     string

`struct'/`union'/`type'/`pointer'/`nonnull-pointer'
     foreign object with the appropriate tags or `#f' in the case of a
     `pointer' equal to `NULL'

`function'
     procedure or `#f' if it is equal to `NULL'

`nonnull-function'
     procedure

`void'
     void object

   All Scheme types are compatible with the C types `scheme-object' and
`bool'.  Conversion to and from the C type `scheme-object' is the
identity function on the object encoding.  This provides a low-level
mechanism for accessing Scheme's object representation from C (with the
help of the macros in the `gambit.h' header file).  When a C `bool'
type is expected, an extended Scheme boolean can be passed (`#f' is
converted to 0 and all other values are converted to 1).

   The Scheme boolean `#f' can be passed to the C environment where a
`char-string', `ISO-8859-1-string', `UTF-8-string', `UTF-16-string',
`UCS-2-string', `UCS-4-string', `wchar_t-string', `pointer' or
`function' type is expected.  In this case, `#f' is converted to the
`NULL' pointer.  C `bool's are extended booleans so any value different
from 0 represents true.  Thus, a C `bool' passed to the Scheme
environment is mapped as follows: 0 to `#f' and all other values to
`#t'.

   A Scheme character passed to the C environment where any C character
type is expected is converted to the corresponding character in the C
environment.  An error is signaled if the Scheme character does not fit
in the C character.  Any C character type passed to Scheme is converted
to the corresponding Scheme character.  An error is signaled if the C
character does not fit in the Scheme character.

   A Scheme exact integer passed to the C environment where a C integer
type (other than `char') is expected is converted to the corresponding
integral value.  An error is signaled if the value falls outside of the
range representable by that integral type.  C integer values passed to
the Scheme environment are mapped to the same Scheme exact integer.  If
the value is outside the fixnum range, a bignum is created.

   A Scheme inexact real passed to the C environment is converted to the
corresponding `float', `double', `float32' or `float64' value.  C
`float', `double', `float32' and `float64' values passed to the Scheme
environment are mapped to the closest Scheme inexact real.

   Scheme's rational numbers and complex numbers are not compatible with
any C numeric type.

   A Scheme string passed to the C environment where any C string type
is expected is converted to a null terminated string using the
appropriate encoding.  The C string is a fresh copy of the Scheme
string.  If the C string was created for an argument of a `c-lambda',
the C string will be reclaimed when the `c-lambda' returns.  If the C
string was created for returning the result of a `c-define' to C, the
caller is responsible for reclaiming the C string with a call to the
`___release_string' function (see below for an example).  Any C string
type passed to the Scheme environment causes the creation of a fresh
Scheme string containing a copy of the C string (unless the C string is
equal to `NULL', in which case it is converted to `#f').

   A foreign type passed to the Scheme environment causes the creation
and initialization of a Scheme foreign object with the appropriate tags
(except for the case of a `pointer' equal to `NULL' which is converted
to `#f').  A Scheme foreign object can be passed where a foreign type
is expected, on the condition that the tags are compatible and the
Scheme foreign object is not yet released.  The value `#f' is also
acceptable for a `pointer' type, and is converted to `NULL'.

   Scheme procedures defined with the `c-define' special form can be
passed where the `function' and `nonnull-function' types are expected.
The value `#f' is also acceptable for a `function' type, and is
converted to `NULL'.  No other Scheme procedures are acceptable.
Conversion from the `function' and `nonnull-function' types to Scheme
procedures is not currently implemented.


File: gambit-c.info,  Node: c-declare,  Next: c-initialize,  Prev: mapping of types,  Up: C-interface

19.2 The `c-declare' special form
=================================

 -- special form: c-declare c-declaration
     Initially, the C file produced by `gsc' contains only an
     `#include' of `gambit.h'.  This header file provides a number of
     macro and procedure declarations to access the Scheme object
     representation.  The special form `c-declare' adds c-declaration
     (which must be a string containing the C declarations) to the C
     file.  This string is copied to the C file on a new line so it can
     start with preprocessor directives.  All types of C declarations
     are allowed (including type declarations, variable declarations,
     function declarations, `#include' directives, `#define's, and so
     on).  These declarations are visible to subsequent `c-declare's,
     `c-initialize's, and `c-lambda's, and `c-define's in the same
     module.  The most common use of this special form is to declare
     the external functions that are referenced in `c-lambda' special
     forms.  Such functions must either be declared explicitly or by
     including a header file which contains the appropriate C
     declarations.

     The `c-declare' special form does not return a value.  It can only
     appear at top level.

     For example:

          (c-declare #<<c-declare-end

          #include <stdio.h>

          extern char *getlogin ();

          #ifdef sparc
          char *host = "sparc";
          #else
          char *host = "unknown";
          #endif

          FILE *tfile;

          c-declare-end
          )



File: gambit-c.info,  Node: c-initialize,  Next: c-lambda,  Prev: c-declare,  Up: C-interface

19.3 The `c-initialize' special form
====================================

 -- special form: c-initialize c-code
     Just after the program is loaded and before control is passed to
     the Scheme code, each C file is initialized by calling its
     associated initialization function.  The body of this function is
     normally empty but it can be extended by using the `c-initialize'
     form.  Each occurence of the `c-initialize' form adds code to the
     body of the initialization function in the order of appearance in
     the source file.  c-code must be a string containing the C code to
     execute.  This string is copied to the C file on a new line so it
     can start with preprocessor directives.

     The `c-initialize' special form does not return a value.  It can
     only appear at top level.

     For example:

          (c-initialize "tfile = tmpfile ();")



File: gambit-c.info,  Node: c-lambda,  Next: c-define,  Prev: c-initialize,  Up: C-interface

19.4 The `c-lambda' special form
================================

 -- special form: c-lambda (type1...) result-type c-name-or-code
     The `c-lambda' special form makes it possible to create a Scheme
     procedure that will act as a representative of some C function or
     C code sequence.  The first subform is a list containing the type
     of each argument.  The type of the function's result is given
     next.  Finally, the last subform is a string that either contains
     the name of the C function to call or some sequence of C code to
     execute.  Variadic C functions are not supported.  The resulting
     Scheme procedure takes exactly the number of arguments specified
     and delivers them in the same order to the C function.  When the
     Scheme procedure is called, the arguments will be converted to
     their C representation and then the C function will be called.
     The result returned by the C function will be converted to its
     Scheme representation and this value will be returned from the
     Scheme procedure call.  An error will be signaled if some
     conversion is not possible.  The temporary memory allocated from
     the C heap for the conversion of the arguments and result will be
     reclaimed whether there is an error or not.

     When c-name-or-code is not a valid C identifier, it is treated as
     an arbitrary piece of C code.  Within the C code the variables
     `___arg1', `___arg2', etc. can be referenced to access the
     converted arguments.  Similarly, the result to be returned from the
     call should be assigned to the variable `___result' except when
     the result is of type `struct', `union', `type', `pointer',
     `nonnull-pointer', `function' or `nonnull-function' in which case
     a pointer must be assigned to the variable `___result_voidstar'
     which is of type `void*'.  For results of type `pointer',
     `nonnull-pointer', `function' and `nonnull-function', the value
     assigned to the variable `___result_voidstar' must be the pointer
     or function cast to `void*'.  For results of type `struct',
     `union', and `type', the value assigned to the variable
     `___result_voidstar' must be a pointer to a memory allocated block
     containing a copy of the result.  Note that this block will be
     reclaimed by the RELEASE-FUNCTION associated with the type.  If no
     result needs to be returned, the result-type should be `void' and
     no assignment to the variable `___result' or `___result_voidstar'
     should take place.  Note that the C code should not contain
     `return' statements as this is meaningless.  Control must always
     fall off the end of the C code.  The C code is copied to the C
     file on a new line so it can start with preprocessor directives.
     Moreover the C code is always placed at the head of a compound
     statement whose lifetime encloses the C to Scheme conversion of
     the result.  Consequently, temporary storage (strings in
     particular) declared at the head of the C code can be returned by
     assigning them to `___result' or `___result_voidstar'.  In the
     c-name-or-code, the macro `___AT_END' may be defined as the piece
     of C code to execute before control is returned to Scheme but
     after the result is converted to its Scheme representation.  This
     is mainly useful to deallocate temporary storage contained in the
     result.

     When passed to the Scheme environment, the C `void' type is
     converted to the void object.

     For example:

          (define fopen
            (c-lambda (nonnull-char-string nonnull-char-string)
                      (pointer "FILE")
             "fopen"))

          (define fgetc
            (c-lambda ((pointer "FILE"))
                      int
             "fgetc"))

          (let ((f (fopen "datafile" "r")))
            (if f (write (fgetc f))))

          (define char-code
            (c-lambda (char) int "___result = ___arg1;"))

          (define host
            ((c-lambda () nonnull-char-string "___result = host;")))

          (define stdin
            ((c-lambda () (pointer "FILE") "___result_voidstar = stdin;")))

          ((c-lambda () void
          #<<c-lambda-end
            printf( "hello\n" );
            printf( "world\n" );
          c-lambda-end
          ))

          (define pack-1-char
            (c-lambda (char)
                      nonnull-char-string
          #<<c-lambda-end
             ___result = malloc (2);
             if (___result != NULL) { ___result[0] = ___arg1; ___result[1] = 0; }
             #define ___AT_END if (___result != NULL) free (___result);
          c-lambda-end
          ))

          (define pack-2-chars
            (c-lambda (char char)
                      nonnull-char-string
          #<<c-lambda-end
             char s[3];
             s[0] = ___arg1;
             s[1] = ___arg2;
             s[2] = 0;
             ___result = s;
          c-lambda-end
          ))



File: gambit-c.info,  Node: c-define,  Next: c-define-type,  Prev: c-lambda,  Up: C-interface

19.5 The `c-define' special form
================================

 -- special form: c-define (variable define-formals) (type1...)
          result-type c-name scope body
     The `c-define' special form makes it possible to create a C
     function that will act as a representative of some Scheme
     procedure.  A C function named c-name as well as a Scheme
     procedure bound to the variable variable are defined.  The
     parameters of the Scheme procedure are define-formals and its body
     is at the end of the form.  The type of each argument of the C
     function, its result type and c-name (which must be a string) are
     specified after the parameter specification of the Scheme
     procedure.  When the C function c-name is called from C, its
     arguments are converted to their Scheme representation and passed
     to the Scheme procedure.  The result of the Scheme procedure is
     then converted to its C representation and the C function c-name
     returns it to its caller.

     The scope of the C function can be changed with the scope
     parameter, which must be a string.  This string is placed
     immediately before the declaration of the C function.  So if scope
     is the string `"static"', the scope of c-name is local to the
     module it is in, whereas if scope is the empty string, c-name is
     visible from other modules.

     The `c-define' special form does not return a value.  It can only
     appear at top level.

     For example:

          (c-define (proc x #!optional (y x) #!rest z) (int int char float) int "f" ""
            (write (cons x (cons y z)))
            (newline)
            (+ x y))

          (proc 1 2 #\x 1.5) => 3 and prints (1 2 #\x 1.5)
          (proc 1)           => 2 and prints (1 1)

          ; if f is called from C with the call  f (1, 2, 'x', 1.5)
          ; the value 3 is returned and (1 2 #\x 1.5) is printed.
          ; f has to be called with 4 arguments.

     The `c-define' special form is particularly useful when the
     driving part of an application is written in C and Scheme
     procedures are called directly from C.  The Scheme part of the
     application is in a sense a "server" that is providing services to
     the C part.  The Scheme procedures that are to be called from C
     need to be defined using the `c-define' special form.  Before it
     can be used, the Scheme part must be initialized with a call to
     the function `___setup'.  Before the program terminates, it must
     call the function `___cleanup' so that the Scheme part may do final
     cleanup.  A sample application is given in the file
     `tests/server.scm'.



File: gambit-c.info,  Node: c-define-type,  Next: continuations,  Prev: c-define,  Up: C-interface

19.6 The `c-define-type' special form
=====================================

 -- special form: c-define-type name type [c-to-scheme scheme-to-c
          [cleanup]]
     This form associates the type identifier name to the C type type.
     The name must not clash with predefined types (e.g. `char-string',
     `ISO-8859-1', etc.) or with types previously defined with
     `c-define-type' in the same file.  The `c-define-type' special
     form does not return a value.  It can only appear at top level.

     If only the two parameters name and type are supplied then after
     this definition, the use of name in a type specification is
     synonymous to type.

     For example:

          (c-define-type FILE "FILE")
          (c-define-type FILE* (pointer FILE))
          (c-define-type time-struct-ptr (pointer (struct "tms")))
          (define fopen (c-lambda (char-string char-string) FILE* "fopen"))
          (define fgetc (c-lambda (FILE*) int "fgetc"))

     Note that identifiers are not case-sensitive in standard Scheme
     but it is good programming practice to use a name with the same
     case as in C.

     If four or more parameters are supplied, then type must be a
     string naming the C type, c-to-scheme and scheme-to-c must be
     strings suffixing the C macros that convert data of that type
     between C and Scheme.  If cleanup is supplied it must be a boolean
     indicating whether it is necessary to perform a cleanup operation
     (such as freeing memory) when data of that type is converted from
     Scheme to C (it defaults to `#t').  The cleanup information is
     used when the C stack is unwound due to a continuation invocation
     (see *Note continuations::).  Although it is safe to always
     specify `#t', it is more efficient in time and space to specify
     `#f' because the unwinding mechanism can skip C-interface frames
     which only contain conversions of data types requiring no cleanup.
     Two pairs of C macros need to be defined for conversions
     performed by `c-lambda' forms and two pairs for conversions
     performed by `c-define' forms:

          ___BEGIN_CFUN_scheme-to-c(___SCMOBJ, type, int)
          ___END_CFUN_scheme-to-c(___SCMOBJ, type, int)

          ___BEGIN_CFUN_c-to-scheme(type, ___SCMOBJ)
          ___END_CFUN_c-to-scheme(type, ___SCMOBJ)

          ___BEGIN_SFUN_c-to-scheme(type, ___SCMOBJ, int)
          ___END_SFUN_c-to-scheme(type, ___SCMOBJ, int)

          ___BEGIN_SFUN_scheme-to-c(___SCMOBJ, type)
          ___END_SFUN_scheme-to-c(___SCMOBJ, type)

     The macros prefixed with `___BEGIN' perform the conversion and
     those prefixed with `___END' perform any cleanup necessary (such as
     freeing memory temporarily allocated for the conversion).  The
     macro `___END_CFUN_scheme-to-c' must free the result of the
     conversion if it is memory allocated, and
     `___END_SFUN_scheme-to-c' must not (i.e. it is the responsibility
     of the caller to free the result).

     The first parameter of these macros is the C variable that
     contains the value to be converted, and the second parameter is
     the C variable in which to store the converted value.  The third
     parameter, when present, is the index (starting at 1) of the
     parameter of the `c-lambda' or `c-define' form that is being
     converted (this is useful for reporting precise error information
     when a conversion is impossible).

     To allow for type checking, the first three `___BEGIN' macros must
     expand to an unterminated compound statement prefixed by an `if',
     conditional on the absence of type check error:

          if ((___err = CONVERSION_OPERATION) == ___FIX(___NO_ERR)) {

     The last `___BEGIN' macro must expand to an unterminated compound
     statement:

          { ___err = CONVERSION_OPERATION;

     If type check errors are impossible then a `___BEGIN' macro can
     simply expand to an unterminated compound statement performing the
     conversion:

          { CONVERSION_OPERATION;

     The `___END' macros must expand to a statement, or to nothing if no
     cleanup is required, followed by a closing brace (to terminate the
     compound statement started at the corresponding `___BEGIN' macro).

     The CONVERSION_OPERATION is typically a function call that returns
     an error code value of type `___SCMOBJ' (the error codes are
     defined in `gambit.h', and the error code `___FIX(___UNKNOWN_ERR)'
     is available for generic errors).  CONVERSION_OPERATION can also
     set the variable `___errmsg' of type `___SCMOBJ' to a specific
     Scheme string error message.

     Below is a simple example showing how to interface to an `EBCDIC'
     character type.  Memory allocation is not needed for conversion
     and type check errors are impossible when converting EBCDIC to
     Scheme characters, but they are possible when converting from
     Scheme characters to EBCDIC since Gambit supports Unicode
     characters.

          (c-declare #<<c-declare-end

          typedef char EBCDIC; /* EBCDIC encoded characters */

          void put_char (EBCDIC c) { ... } /* EBCDIC I/O functions */
          EBCDIC get_char (void) { ... }

          char EBCDIC_to_ISO_8859_1[256] = { ... }; /* conversion tables */
          char ISO_8859_1_to_EBCDIC[256] = { ... };

          ___SCMOBJ SCMOBJ_to_EBCDIC (___SCMOBJ src, EBCDIC *dst)
          {
            int x = ___INT(src); /* convert from Scheme character to int */
            if (x > 255) return ___FIX(___UNKNOWN_ERR);
            *dst = ISO_8859_1_to_EBCDIC[x];
            return ___FIX(___NO_ERR);
          }

          #define ___BEGIN_CFUN_SCMOBJ_to_EBCDIC(src,dst,i) \
          if ((___err = SCMOBJ_to_EBCDIC (src, &dst)) == ___FIX(___NO_ERR)) {
          #define ___END_CFUN_SCMOBJ_to_EBCDIC(src,dst,i) }

          #define ___BEGIN_CFUN_EBCDIC_to_SCMOBJ(src,dst) \
          { dst = ___CHR(EBCDIC_to_ISO_8859_1[src]);
          #define ___END_CFUN_EBCDIC_to_SCMOBJ(src,dst) }

          #define ___BEGIN_SFUN_EBCDIC_to_SCMOBJ(src,dst,i) \
          { dst = ___CHR(EBCDIC_to_ISO_8859_1[src]);
          #define ___END_SFUN_EBCDIC_to_SCMOBJ(src,dst,i) }

          #define ___BEGIN_SFUN_SCMOBJ_to_EBCDIC(src,dst) \
          { ___err = SCMOBJ_to_EBCDIC (src, &dst);
          #define ___END_SFUN_SCMOBJ_to_EBCDIC(src,dst) }

          c-declare-end
          )

          (c-define-type EBCDIC "EBCDIC" "EBCDIC_to_SCMOBJ" "SCMOBJ_to_EBCDIC" #f)

          (define put-char (c-lambda (EBCDIC) void "put_char"))
          (define get-char (c-lambda () EBCDIC "get_char"))

          (c-define (write-EBCDIC c) (EBCDIC) void "write_EBCDIC" ""
            (write-char c))

          (c-define (read-EBCDIC) () EBCDIC "read_EBCDIC" ""
            (read-char))

     Below is a more complex example that requires memory allocation
     when converting from C to Scheme.  It is an interface to a 2D
     `point' type which is represented in Scheme by a pair of integers.
     The conversion of the `x' and `y' components is done by calls to
     the conversion macros for the `int' type (defined in `gambit.h').
     Note that no cleanup is necessary when converting from Scheme to C
     (i.e. the last parameter of the `c-define-type' is `#f').

          (c-declare #<<c-declare-end

          typedef struct { int x, y; } point;

          void line_to (point p) { ... }
          point get_mouse (void) { ... }
          point add_points (point p1, point p2) { ... }

          ___SCMOBJ SCMOBJ_to_POINT (___SCMOBJ src, point *dst, int arg_num)
          {
            ___SCMOBJ ___err = ___FIX(___NO_ERR);
            if (!___PAIRP(src))
              ___err = ___FIX(___UNKNOWN_ERR);
            else
              {
                ___SCMOBJ car = ___CAR(src);
                ___SCMOBJ cdr = ___CDR(src);
                ___BEGIN_CFUN_SCMOBJ_TO_INT(car,dst->x,arg_num)
                ___BEGIN_CFUN_SCMOBJ_TO_INT(cdr,dst->y,arg_num)
                ___END_CFUN_SCMOBJ_TO_INT(cdr,dst->y,arg_num)
                ___END_CFUN_SCMOBJ_TO_INT(car,dst->x,arg_num)
              }
            return ___err;
          }

          ___SCMOBJ POINT_to_SCMOBJ (point src, ___SCMOBJ *dst, int arg_num)
          {
            ___SCMOBJ ___err = ___FIX(___NO_ERR);
            ___SCMOBJ x_scmobj;
            ___SCMOBJ y_scmobj;
            ___BEGIN_SFUN_INT_TO_SCMOBJ(src.x,x_scmobj,arg_num)
            ___BEGIN_SFUN_INT_TO_SCMOBJ(src.y,y_scmobj,arg_num)
            *dst = ___EXT(___make_pair) (x_scmobj, y_scmobj, ___STILL);
            if (___FIXNUMP(*dst))
              ___err = *dst; /* return allocation error */
            ___END_SFUN_INT_TO_SCMOBJ(src.y,y_scmobj,arg_num)
            ___END_SFUN_INT_TO_SCMOBJ(src.x,x_scmobj,arg_num)
            return ___err;
          }

          #define ___BEGIN_CFUN_SCMOBJ_to_POINT(src,dst,i) \
          if ((___err = SCMOBJ_to_POINT (src, &dst, i)) == ___FIX(___NO_ERR)) {
          #define ___END_CFUN_SCMOBJ_to_POINT(src,dst,i) }

          #define ___BEGIN_CFUN_POINT_to_SCMOBJ(src,dst) \
          if ((___err = POINT_to_SCMOBJ (src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) {
          #define ___END_CFUN_POINT_to_SCMOBJ(src,dst) \
          ___EXT(___release_scmobj) (dst); }

          #define ___BEGIN_SFUN_POINT_to_SCMOBJ(src,dst,i) \
          if ((___err = POINT_to_SCMOBJ (src, &dst, i)) == ___FIX(___NO_ERR)) {
          #define ___END_SFUN_POINT_to_SCMOBJ(src,dst,i) \
          ___EXT(___release_scmobj) (dst); }

          #define ___BEGIN_SFUN_SCMOBJ_to_POINT(src,dst) \
          { ___err = SCMOBJ_to_POINT (src, &dst, ___RETURN_POS);
          #define ___END_SFUN_SCMOBJ_to_POINT(src,dst) }

          c-declare-end
          )

          (c-define-type point "point" "POINT_to_SCMOBJ" "SCMOBJ_to_POINT" #f)

          (define line-to (c-lambda (point) void "line_to"))
          (define get-mouse (c-lambda () point "get_mouse"))
          (define add-points (c-lambda (point point) point "add_points"))

          (c-define (write-point p) (point) void "write_point" ""
            (write p))

          (c-define (read-point) () point "read_point" ""
            (read))

     An example that requires memory allocation when converting from C
     to Scheme and Scheme to C is shown below.  It is an interface to a
     "null-terminated array of strings" type which is represented in
     Scheme by a list of strings.  Note that some cleanup is necessary
     when converting from Scheme to C.

          (c-declare #<<c-declare-end

          #include <stdlib.h>
          #include <unistd.h>

          extern char **environ;

          char **get_environ (void) { return environ; }

          void free_strings (char **strings)
          {
            char **ptr = strings;
            while (*ptr != NULL)
              {
                ___EXT(___release_string) (*ptr);
                ptr++;
              }
            free (strings);
          }

          ___SCMOBJ SCMOBJ_to_STRINGS (___SCMOBJ src, char ***dst, int arg_num)
          {
            /*
             * Src is a list of Scheme strings.  Dst will be a null terminated
             * array of C strings.
             */

            int i;
            ___SCMOBJ lst = src;
            int len = 4; /* start with a small result array */
            char **result = (char**) malloc (len * sizeof (char*));

            if (result == NULL)
              return ___FIX(___HEAP_OVERFLOW_ERR);

            i = 0;
            result[i] = NULL; /* always keep array null terminated */

            while (___PAIRP(lst))
              {
                ___SCMOBJ scm_str = ___CAR(lst);
                char *c_str;
                ___SCMOBJ ___err;

                if (i >= len-1) /* need to grow the result array? */
                  {
                    char **new_result;
                    int j;

                    len = len * 3 / 2;
                    new_result = (char**) malloc (len * sizeof (char*));
                    if (new_result == NULL)
                      {
                        free_strings (result);
                        return ___FIX(___HEAP_OVERFLOW_ERR);
                      }
                    for (j=i; j>=0; j--)
                      new_result[j] = result[j];
                    free (result);
                    result = new_result;
                  }

                ___err = ___EXT(___SCMOBJ_to_CHARSTRING) (scm_str, &c_str, arg_num);

                if (___err != ___FIX(___NO_ERR))
                  {
                    free_strings (result);
                    return ___err;
                  }

                result[i++] = c_str;
                result[i] = NULL;
                lst = ___CDR(lst);
              }

            if (!___NULLP(lst))
              {
                free_strings (result);
                return ___FIX(___UNKNOWN_ERR);
              }

            /*
             * Note that the caller is responsible for calling free_strings
             * when it is done with the result.
             */

            *dst = result;
            return ___FIX(___NO_ERR);
          }

          ___SCMOBJ STRINGS_to_SCMOBJ (char **src, ___SCMOBJ *dst, int arg_num)
          {
            ___SCMOBJ ___err = ___FIX(___NO_ERR);
            ___SCMOBJ result = ___NUL; /* start with the empty list */
            int i = 0;

            while (src[i] != NULL)
              i++;

            /* build the list of strings starting at the tail */

            while (--i >= 0)
              {
                ___SCMOBJ scm_str;
                ___SCMOBJ new_result;

                /*
                 * Invariant: result is either the empty list or a ___STILL pair
                 * with reference count equal to 1.  This is important because
                 * it is possible that ___CHARSTRING_to_SCMOBJ and ___make_pair
                 * will invoke the garbage collector and we don't want the
                 * reference in result to become invalid (which would be the
                 * case if result was a ___MOVABLE pair or if it had a zero
                 * reference count).
                 */

                ___err = ___EXT(___CHARSTRING_to_SCMOBJ) (src[i], &scm_str, arg_num);

                if (___err != ___FIX(___NO_ERR))
                  {
                    ___EXT(___release_scmobj) (result); /* allow GC to reclaim result */
                    return ___FIX(___UNKNOWN_ERR);
                  }

                /*
                 * Note that scm_str will be a ___STILL object with reference
                 * count equal to 1, so there is no risk that it will be
                 * reclaimed or moved if ___make_pair invokes the garbage
                 * collector.
                 */

                new_result = ___EXT(___make_pair) (scm_str, result, ___STILL);

                /*
                 * We can zero the reference count of scm_str and result (if
                 * not the empty list) because the pair now references these
                 * objects and the pair is reachable (it can't be reclaimed
                 * or moved by the garbage collector).
                 */

                ___EXT(___release_scmobj) (scm_str);
                ___EXT(___release_scmobj) (result);

                result = new_result;

                if (___FIXNUMP(result))
                  return result; /* allocation failed */
              }

            /*
             * Note that result is either the empty list or a ___STILL pair
             * with a reference count equal to 1.  There will be a call to
             * ___release_scmobj later on (in ___END_CFUN_STRINGS_to_SCMOBJ
             * or ___END_SFUN_STRINGS_to_SCMOBJ) that will allow the garbage
             * collector to reclaim the whole list of strings when the Scheme
             * world no longer references it.
             */

            *dst = result;
            return ___FIX(___NO_ERR);
          }

          #define ___BEGIN_CFUN_SCMOBJ_to_STRINGS(src,dst,i) \
          if ((___err = SCMOBJ_to_STRINGS (src, &dst, i)) == ___FIX(___NO_ERR)) {
          #define ___END_CFUN_SCMOBJ_to_STRINGS(src,dst,i) \
          free_strings (dst); }

          #define ___BEGIN_CFUN_STRINGS_to_SCMOBJ(src,dst) \
          if ((___err = STRINGS_to_SCMOBJ (src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) {
          #define ___END_CFUN_STRINGS_to_SCMOBJ(src,dst) \
          ___EXT(___release_scmobj) (dst); }

          #define ___BEGIN_SFUN_STRINGS_to_SCMOBJ(src,dst,i) \
          if ((___err = STRINGS_to_SCMOBJ (src, &dst, i)) == ___FIX(___NO_ERR)) {
          #define ___END_SFUN_STRINGS_to_SCMOBJ(src,dst,i) \
          ___EXT(___release_scmobj) (dst); }

          #define ___BEGIN_SFUN_SCMOBJ_to_STRINGS(src,dst) \
          { ___err = SCMOBJ_to_STRINGS (src, &dst, ___RETURN_POS);
          #define ___END_SFUN_SCMOBJ_to_STRINGS(src,dst) }

          c-declare-end
          )

          (c-define-type char** "char**" "STRINGS_to_SCMOBJ" "SCMOBJ_to_STRINGS")

          (define execv (c-lambda (char-string char**) int "execv"))
          (define get-environ (c-lambda () char** "get_environ"))

          (c-define (write-strings x) (char**) void "write_strings" ""
            (write x))

          (c-define (read-strings) () char** "read_strings" ""
            (read))



File: gambit-c.info,  Node: continuations,  Prev: c-define-type,  Up: C-interface

19.7 Continuations and the C-interface
======================================

The C-interface allows C to Scheme calls to be nested.  This means that
during a call from C to Scheme another call from C to Scheme can be
performed.  This case occurs in the following program:

     (c-declare #<<c-declare-end

     int p (char *); /* forward declarations */
     int q (void);

     int a (char *x) { return 2 * p (x+1); }
     int b (short y) { return y + q (); }

     c-declare-end
     )

     (define a (c-lambda (char-string) int "a"))
     (define b (c-lambda (short) int "b"))

     (c-define (p z) (char-string) int "p" ""
       (+ (b 10) (string-length z)))

     (c-define (q) () int "q" ""
       123)

     (write (a "hello"))

   In this example, the main Scheme program calls the C function `a'
which calls the Scheme procedure `p' which in turn calls the C function
`b' which finally calls the Scheme procedure `q'.

   Gambit-C maintains the Scheme continuation separately from the C
stack, thus allowing the Scheme continuation to be unwound
independently from the C stack.  The C stack frame created for the C
function `f' is only removed from the C stack when control returns from
`f' or when control returns to a C function "above" `f'.  Special care
is required for programs which escape to Scheme (using first-class
continuations) from a Scheme to C (to Scheme) call because the C stack
frame will remain on the stack.  The C stack may overflow if this
happens in a loop with no intervening return to a C function.  To avoid
this problem make sure the C stack gets cleaned up by executing a normal
return from a Scheme to C call.


File: gambit-c.info,  Node: System limitations,  Next: Copyright and license,  Prev: C-interface,  Up: Top

20 System limitations
*********************

   * On some systems floating point overflows will cause the program to
     terminate with a floating point exception.

   * On some systems floating point operations involving `+nan.0'
     `+inf.0', `-inf.0', or `-0.' do not return the value required by
     the IEEE 754 floating point standard.

   * The compiler will not properly compile files with more than one
     definition (with `define') of the same procedure.  Replace all but
     the first `define' with assignments (`set!').

   * The maximum number of arguments that can be passed to a procedure
     by the `apply' procedure is 8192.


