Debian Codegraph @

doc/ikarus-scheme-users-guide.tex

raw
1 %!TEX TS-program = xelatex
2
3 \documentclass[onecolumn, 12pt, twoside, openright, dvipdfm]{book}
4
5 \usepackage{fontspec}
6 \usepackage{hanging}
7 \usepackage{xltxtra}
8
9 \defaultfontfeatures{Scale=MatchLowercase}
10 %\setmainfont[Mapping=tex-text]{Cochin}
11 %\setmainfont[Mapping=tex-text]{Palatino}
12 %\setmainfont[Mapping=tex-text]{Baskerville}
13 %\setmainfont[Mapping=tex-text]{Perpetua}
14 %\setmainfont[Mapping=tex-text]{Lido STF}
15 %\setmainfont[Mapping=tex-text]{Perpetua}
16 \setmainfont[Mapping=tex-text]{Charis SIL}
17 %\setmainfont[Mapping=tex-text]{Gentium}
18 %\setmainfont[Mapping=tex-text]{DejaVu Serif}
19 %\setmainfont[Mapping=tex-text]{Palatino}
20 %\setmainfont[Mapping=tex-text]{URWPalladioL}
21 %\setmainfont[Mapping=tex-text]{GentiumAlt}
22 \setsansfont[Mapping=tex-text]{Geneva}
23 %\setmonofont{DejaVu Sans Mono}
24 %\setmonofont{Monaco}
25 \setmonofont[Scale=0.95]{Inconsolata}
26
27 \usepackage{fancyhdr}
28 \usepackage{makeidx}
29 \usepackage{fancyvrb}
30 \makeindex
31
32 \usepackage[dvipdfm,CJKbookmarks,bookmarks=true,bookmarksopen=true]{hyperref}
33 \hypersetup{
34 pdftitle={Ikarus Scheme User's Guide},
35 pdfauthor={Abdulaziz Ghuloum},
36 pdfkeywords={Scheme, R6RS, Compiler, Ikarus},
37 bookmarksnumbered=true,
38 pagebackref=true,
39 breaklinks=true,
40 % pdfview=FitH, % Or try pdfstartview={FitV}, This lead to uncorrect bookmarks
41 urlcolor=blue,
42 colorlinks=true,
43 citecolor=blue, %citeref's color
44 linkcolor=blue,
45 }
46
47 \usepackage{rotating}
48 \usepackage{multicol,ragged2e}
49
50
51 \renewcommand{\sectionmark}[1]{\markright{\thesection\ #1}}
52 \fancyhf{}
53 \fancyhead[LE,RO]{\bfseries\thepage}
54 \fancyhead[LO]{\bfseries\rightmark}
55 \fancyhead[RE]{\bfseries\leftmark}
56 \renewcommand{\headrulewidth}{0pt}
57 \renewcommand{\footrulewidth}{0pt}
58 \renewcommand{\headheight}{15pt}
59
60 \newcommand{\coderefpage}[1]{figure~\ref{#1}, p.~\pageref{#1}}
61 \newcommand{\figrefpage}[1]{figure~\ref{#1}, p.~\pageref{#1}}
62 \newcommand{\deflabelref}[2]{\texttt{#1}~(page~\pageref{#2})}
63 \newcommand{\defref}[1]{\deflabelref{#1}{#1}}
64
65 \newcommand{\coderef}[1]{figure~\ref{#1}}
66 \newcommand{\figref}[1]{figure~\ref{#1}}
67
68 \newcommand{\secref}[1]{section~\ref{#1}}
69 \newcommand{\rnrs}[1]{R$^{\mathrm{#1}}$RS}
70
71 \newcommand{\BoxedText}[2]{
72 \vspace{.05in}
73 \begin{center}
74 \begin{tabular}{|p{4.6in}|} {\large \emph{#1}} #2 \end{tabular}
75 \end{center}
76 \vspace{.05in}
77 }
78
79 \newcommand{\testfile}[2]{\texttt{tests-{\ref{#1}}-{#2}.ss}}
80
81 \newcommand{\idxtt}[1]{\index{#1 @ \texttt{#1}}\texttt{#1}}
82
83 \newenvironment{Language}
84 {
85 \begin{center}
86 \begin{tabular}{|p{4.5in}|} {\large \emph{Input Language:}}
87 \begin{center}
88 \begin{tabular}{@{}r@{ }c@{ }l@{}}
89 }{
90 \end{tabular}
91 \end{center}
92 \end{tabular}
93 \end{center}
94 }
95
96
97 \DefineVerbatimEnvironment{CodeInline}{Verbatim}
98 {gobble=0, xleftmargin=2em, xrightmargin=0em,
99 %numbers=left, numbersep=2mm,
100 frame=lines ,framerule=1pt}
101
102
103
104 \DefineVerbatimEnvironment{CodeInlineIdx}{Verbatim}
105 {gobble=0, xleftmargin=3em, xrightmargin=0em,
106 numbers=left, numbersep=1ex,
107 frame=lines ,framerule=1pt}
108
109 \newcommand{\idxlabeldefun}[5]{
110 \vspace{1ex}
111 \rule{\textwidth}{2pt}
112 {\phantomsection\index{#1@\texttt{#2}}\label{#3}{\Large\texttt{#4}}\hfill\textbf{#5}}\\}
113
114
115 \newcommand{\idxdefun}[3]{\idxlabeldefun{#1}{#2}{#1}{#2}{#3}}
116
117
118 \newcommand{\defun}[2]{\idxdefun{#1}{#1}{#2}}
119
120 \begin{document}
121 \frontmatter
122
123 \VerbatimFootnotes
124
125 \title{Ikarus Scheme User's Guide}
126
127 \author{Abdulaziz Ghuloum}
128
129 \pagestyle{empty}
130
131 \mbox{}
132 \vspace{3in}
133
134 \newcommand{\fstpagefont}[0]
135 {\fontspec{Charis SIL}}
136
137 { \fontsize{66}{66} \fstpagefont{}
138 \noindent Ikarus Scheme\\ User's Guide\\ }
139 \noindent \rule{\textwidth}{6pt}
140 {\fontsize{18}{18} \fstpagefont{}
141 \mbox{} \hfill Version~0.0.4 }
142 \vfill
143 { \fontsize{24}{24} \fstpagefont{}
144 \hfill{} Abdulaziz Ghuloum}
145
146 { \fontsize{18}{18} \fstpagefont{}
147 \hfill{} \today \\}
148
149 \newpage
150 \mbox{}
151 \vfill{}
152 %\addcontentsline{toc}{section}{Copyrights}
153 \noindent
154 Ikarus Scheme User's Guide \hfill{} (Version 0.0.4)\\
155 Copyright \copyright{} 2007,2008 Abdulaziz Ghuloum\\
156
157 {\small
158 \noindent
159 This program is free software: you can redistribute it and/or modify
160 it under the terms of the GNU General Public License version 3 as
161 published by the Free Software Foundation.
162 \\ \\
163 This program is distributed in the hope that it will be useful, but
164 WITHOUT ANY WARRANTY; without even the implied warranty of
165 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
166 General Public License for more details.
167 \\ \\
168 You should have received a copy of the GNU General Public License
169 along with this program. If not, see
170 \url{http://www.gnu.org/licenses/}.
171 }
172
173
174
175
176
177 % Permission is granted to copy, distribute and/or modify this
178 % document under the terms of the GNU Free Documentation License,
179 % Version 1.2 published by the Free Software
180 % Foundation; with no Invariant Sections, the Front-Cover Texts
181 % being \emph{``Ikarus Scheme User's Guide''}, and
182 % no Back-Cover Texts. A copy of the license is included in the
183 % section entitled ``GNU Free Documentation License''.
184
185 \newpage
186
187 \pagestyle{fancy}
188 \phantomsection
189 \addcontentsline{toc}{section}{Contents}
190 \tableofcontents
191
192 \newpage
193
194 \mainmatter
195 \setlength{\parindent}{0pt}
196 \setlength{\parskip}{2.0ex plus 0ex minus 0ex}
197 \chapter{Getting Started}
198 \section{Introduction}
199
200 Ikarus Scheme is an implementation of the Scheme programming
201 language. The preliminary release of Ikarus implements the majority
202 of the features found in the current standard, the
203 Revised$^\mathrm{6}$ report on the algorithmic language
204 Scheme\cite{r6rs} including full \rnrs{6} library and script syntax,
205 syntax-case, unicode strings, bytevectors, user-defined record
206 types, exception handling, conditions, and enumerations.
207 User-define \rnrs{6} libraries can be compiled in-memory on the fly
208 or compiled to disk and loaded in subsequent runs.
209
210 In addition to supporting \rnrs{6} (and most of the features found
211 in the the previous \rnrs{n} standards), Ikarus supports powerful
212 interprocess communication facilities including support for
213 communication with child processes via pipes and with remote
214 processes via TCP and UDP sockets. The facility also allows for
215 both synchronous and asynchronous communication so that a Scheme
216 program running in Ikarus can communicate with many processes
217 concurrently.
218
219 Ikarus also supports basic foreign function interface (FFI)
220 facilities. This allows the programmer to define accessors and
221 mutators for native data structures. It also allows for Scheme
222 programs to dynamically load any library found on the host machine.
223 Native procedures and Scheme procedures can call to each other by
224 the call-out and call-back facilities of Ikarus.
225
226 %The main purpose behind releasing Ikarus early is to give Scheme
227 %programmers the opportunity to experiment with the various new
228 %features that were newly introduced in \rnrs{6}. The most important
229 %of such features is the ability to structure large programs into
230 %libraries; where each library extends the language through
231 %procedural and syntactic abstractions. Many useful libraries can be
232 %written using the currently supported set of \rnrs{6} features
233 %including text processing tools, symbolic logic systems,
234 %interpreters and compilers, and many mathematical and scientific
235 %packages. It is my hope that this release will encourage the
236 %Scheme community to write and to share their most useful \rnrs{6}
237 %libraries.
238
239
240 \newpage
241
242 \section{Technology overview}
243
244 Ikarus Scheme provides the programmer with many advantages:
245
246 \textbf{Optimizing code generator:} The compiler's backend employs
247 state of the art technologies in code generation that produce fast
248 efficient machine code. When developing computationally intensive
249 programs, one is not constrained by using a slow interpreter.
250
251 \textbf{Fast incremental compilation:} Every library and script is
252 quickly compiled to native machine code. When developing large
253 software, one is not constrained by how slow the batch compiler
254 runs.
255
256 \textbf{Robust and fine-tuned standard libraries:} The standard
257 libraries are written such that they perform as much error checking
258 as required to provide a safe and fast runtime environment.
259
260 \textbf{Multi-generational garbage collector:} The
261 BiBOP\cite{dybvig:sm} based garbage collector used in Ikarus allows
262 the runtime system to expand its memory footprint as needed. The
263 entire 32-bit virtual address space could be used and unneeded
264 memory is released back to the operating system.
265
266 \textbf{32-bit and 64-bit computing:} Ikarus supports both the
267 Intel-x86 and the AMD-64 architectures. 64-bit computing allows the
268 programmer to utilize larger address space (larger than 4GB) and
269 provides a greater range for fixnums (61-bit fixnums). Running in
270 32-bit mode, however, makes more efficient utilization of resources
271 due to the smaller memory footprint for most data structures.\\
272 (64-bit support is experimental at this stage of development.)
273
274 \textbf{Supports many operating systems:} Ikarus runs on the most
275 popular and widely used operating systems for servers and personal
276 computers. The supported systems include Mac~OS~X,
277 GNU/Linux, FreeBSD, NetBSD, and Microsoft Windows.
278
279
280 \section{System requirements}
281
282 This section provides an overview of the hardware and software
283 requirements needed for running Ikarus.
284
285 \subsection{Hardware}
286
287 Ikarus Scheme runs in 32-bit mode on the IA-32 (\emph{x86})
288 architecture supporting SSE2 extensions. It also runs in 64-bit
289 mode on platforms supporing the AMD-64 architecture. This includes
290 the Athlon 64, Sempron 64, and Turion 64 processors from AMD and the
291 Pentium 4, Xeon, Celeron, Pentium M, Core, and Core2 processors from
292 Intel. Ikarus does not run on Intel Pentium III or earlier
293 processors.
294
295 The Ikarus compiler generates SSE2 instructions to handle Scheme's
296 IEEE floating point representation (\emph{flonums}) for inexact
297 numbers.
298
299 \subsection{Operating systems}
300
301 Ikarus is tested under the following operating systems:
302
303 \begin{itemize}
304 \item Mac OS X version 10.4 and 10.5.
305 \item Linux 2.6.18 (Debian, Fedora, Gentoo, and Ubuntu).
306 \item FreeBSD version 6.2.
307 \item NetBSD version 3.1.
308 \item Microsoft Windows XP (using Cygwin 1.5.24).
309 \end{itemize}
310
311 \subsection{Additional software}
312
313 \begin{itemize}
314 \item\textbf{GMP:} Ikarus uses the GNU Multiple Precision Arithmetic
315 Library (GMP) for some bignum arithmetic operations. To build
316 Ikarus from scratch, GMP version 4.2 or better must be installed
317 along with the required header files. Pre-built GMP packages are
318 available for most operating systems. Alternatively, GMP can be
319 downloaded from \\
320 \url{http://gmplib.org/}.
321
322
323 \item\textbf{FFI:}
324 The \texttt{libffi} library (version \texttt{3.0.6}) can be utilized
325 to enable Scheme procedures to call and be called from native
326 procedure (see Chapter~\ref{chapter:foreign} for details).
327 To enable
328 \texttt{libffi} while building Ikarus, one must pass
329 \texttt{--enable-libffi} to the \texttt{configure} script along with
330 the paths to \texttt{libffi}'s include and lib directory.
331 The \texttt{libffi} library can be obtained from
332 \url{http://sourceware.org/libffi/}.
333 FFI support is optional. It is not required if all one needs is
334 writing pure Scheme code.
335
336
337
338
339 \item\textbf{GCC:} The GNU C Compiler is required to build the Ikarus
340 executable (e.g. the garbage collector, loader, and OS-related
341 runtime). GCC versions 4.1 and 4.2 were successfully used to build
342 Ikarus.
343
344 \item\textbf{Autoconf and Automake:} The GNU Autoconf (version 2.61)
345 and GNU Automake (version 1.10) tools are required if one
346 wishes to modify the Ikarus source base. They are not
347 required to build the official release of Ikarus.
348
349 \item\textbf{\XeLaTeX{}:} The \XeLaTeX\ typesetting system is
350 required for building the documentation. \XeLaTeX\ (and \XeTeX) is
351 an implementation of the \LaTeX\ (and \TeX) typesetting system.
352 \XeLaTeX\ can be obtained from \url{http://scripts.sil.org/xetex}
353 and is included with \TeX-Live\footnote{
354 \url{http://tug.org/texlive/}} and and
355 Mac-\TeX\footnote{\url{http://tug.org/mactex/}} distributions.
356
357
358 \end{itemize}
359
360 \section{Installation}
361
362 If you are familiar with installing Unix software on your system,
363 then all you need to know is that Ikarus uses the standard
364 installation method found in most other Unix software. Simply run
365 the following commands from the shell:
366 \begin{verbatim}
367 $ tar -zxf ikarus-n.n.n.tar.gz
368 $ cd ikarus-n.n.n
369 $ ./configure [--prefix=path] [CFLAGS=-I/dir] [LDFLAGS=-L/dir]
370 $ make
371 $ make install
372 $
373 \end{verbatim}
374
375 The rest of this section describes the build process in more
376 details. It is targeted to users who are unfamiliar with steps
377 mentioned above.
378
379 \subsection{Installation details}
380
381 \begin{enumerate}
382
383 \item Download the Ikarus source distribution. The source is
384 distributed as a \texttt{gzip}-compressed \texttt{tar} file
385 (\texttt{ikarus-n.n.n.tar.gz} where \texttt{n.n.n} is a 3-digit
386 number indicating the current revision). The latest revision can be
387 downloaded from the following URL:\\
388 \url{http://www.cs.indiana.edu/~aghuloum/ikarus/}
389
390 \item Unpack the source distribution package. From your shell
391 command, type:
392 \begin{verbatim}
393 $ tar -zxf ikarus-n.n.n.tar.gz
394 $
395 \end{verbatim}
396 This creates the base directory \texttt{ikarus-n.n.n}.
397
398 \item Configure the build system by running the \texttt{configure}
399 script located in the base directory. To do this, type the
400 following commands:
401 \begin{verbatim}
402 $ cd ikarus-n.n.n
403 $ ./configure
404 checking build system type... i386-apple-darwin8.10.1
405 checking host system type... i386-apple-darwin8.10.1
406 ...
407 configure: creating ./config.status
408 config.status: creating Makefile
409 config.status: creating src/Makefile
410 config.status: creating scheme/Makefile
411 config.status: creating doc/Makefile
412 config.status: executing depfiles commands
413 $
414 \end{verbatim}
415
416 This configures the system to be built then installed in the
417 system-wide location (binaries are installed in
418 \texttt{/usr/local/bin}) . If you wish to install it
419 in another location (e.g. in your home directory), you can supply
420 a \texttt{--prefix} location to the \texttt{configure} script as
421 follows:
422
423 \begin{verbatim}
424 $ ./configure --prefix=/path/to/installation/location
425 \end{verbatim}
426
427 The \texttt{configure} script will fail if it cannot locate the
428 location where GMP is installed. If running \texttt{configure}
429 fails to locate GMP, you should supply the location in which the GMP
430 header file, \texttt{gmp.h}, and the GMP library file,
431 \texttt{libgmp.so}, are installed. This is done by supplying the
432 two paths in the \texttt{CFLAGS} and \texttt{LDFLAGS} arguments:
433
434 \begin{verbatim}
435 $ ./configure CFLAGS=-I/path/to/include LDFLAGS=-L/path/to/lib
436 \end{verbatim}
437
438
439 If you wish to enable support for accessing and calling to/from
440 foreign libraries, you need to configure Ikarus with the
441 \texttt{--enable-libffi} option and supply the approriate
442 \texttt{CFLAGS} and \texttt{LDFLAGS} as needed.
443
444 \begin{verbatim}
445 $ ./configure --enable-libffi \
446 [CFLAGS=/path/to/ffi.h] \
447 [LDFLAGS=/path/to/libffi.so|.dylib|.dll]
448 \end{verbatim}
449
450
451
452 \item Build the system by running:
453 \begin{verbatim}
454 $ make
455 \end{verbatim}
456 This performs two
457 tasks. First, it builds the \texttt{ikarus} executable from the C
458 files located in the \texttt{src} directory. It then uses the
459 \texttt{ikarus} executable and the pre-built
460 \texttt{ikarus.boot.orig} boot file to rebuild the Scheme boot image
461 file \texttt{ikarus.boot} from the Scheme sources located in the
462 \texttt{scheme} directory.
463
464 \item Install Ikarus by typing:
465 \begin{verbatim}
466 $ make install
467 \end{verbatim}
468 If you are installing Ikarus in a system-wide location, you might
469 need to have administrator privileges (use the \texttt{sudo} or
470 \texttt{su} commands).
471
472 \item Test that Ikarus runs from the command line.
473 \begin{verbatim}
474 $ ikarus
475 Ikarus Scheme version 0.0.4
476 Copyright (c) 2006-2008 Abdulaziz Ghuloum
477
478 >
479 \end{verbatim}
480 If you get the prompt, then Ikarus was successfully installed on
481 your system. You may need to update the \texttt{PATH} variable in
482 your environment to contain the directory in which the
483 \texttt{ikarus} executable was installed.
484
485 Do not delete the \texttt{ikarus-n.n.n} directory from which you
486 configured, built, and installed Ikarus. It will be needed if you
487 decide at a later time to uninstall Ikarus.
488
489 \end{enumerate}
490
491 \subsection{Uninstalling Ikarus}
492
493 To uninstall Ikarus, use the following steps:
494
495 \begin{verbatim}
496 $ cd path/to/ikarus-n.n.n
497 $ make uninstall
498 $
499 \end{verbatim}
500
501
502 \section{\index{Command-line switches}Command-line switches}
503
504 The \texttt{ikarus} executable recognizes a few command-line
505 switches that influence how Ikarus starts.
506
507 \begin{itemize}
508
509 \item \texttt{ikarus -h}
510
511 The presence of the \texttt{-h} flag causes \texttt{ikarus} to
512 display a help message then exits. The help message summarizes the
513 command-line switches. No further action is performed.
514
515 \item \texttt{ikarus -b path/to/boot/file.boot}
516
517 The \texttt{-b} flag (which requires an extra argument) directs
518 \texttt{ikarus} to use the specified boot file as the initial system
519 boot file. \index{Boot files} The boot file is a binary file that
520 contains all the code and data of the Scheme system. In the absence
521 of \texttt{-b} flag, the executable will use the default boot file.
522 Running \texttt{ikarus~-h} shows the location where the default boot
523 file was installed.
524
525 The rest of the command-line arguments are recognized by the
526 standard Scheme run time system. They are processed after the
527 boot file is loaded.
528
529 \item \texttt{ikarus files ... --r6rs-script script-file arguments ...}
530
531 \index{R6RS Script@\rnrs{6} Script} The \texttt{--r6rs-script}
532 argument instructs Ikarus that the supplied file is an \rnrs{6}
533 script. The optional list of \texttt{files} must be paths to files,
534 each containing a set of libraries that Ikarus must load,
535 sequentially, before running the \rnrs{6} script
536 \texttt{script-file}. See Section~\ref{sec:scripts} for a short
537 introduction to writing \rnrs{6} scripts. The script file name and
538 any additional optional \texttt{arguments} can be obtained by
539 calling the \idxtt{command-line} procedure.
540
541 \begin{verbatim}
542 $ cat test.ss
543 (import (rnrs))
544 (write (command-line))
545 (newline)
546
547 $ ikarus --r6rs-script test.ss hi there
548 ("test.ss" "hi" "there")
549 $
550 \end{verbatim}
551
552 \item \texttt{ikarus files ... [-- arguments ...]}
553
554 The lack of an \texttt{--r6rs-script} argument causes Ikarus to
555 start in interactive mode. Each of the \texttt{files} is first
556 loaded, in the interaction environment. The interaction environment
557 initially contains all the bindings exported from the
558 \texttt{(ikarus)} library (see Chapter~\ref{chapter:ikarus}). The
559 optional \texttt{arguments} following the \texttt{--} marker can be
560 obtained by calling the \texttt{command-line} procedure. In
561 interactive mode, the first element of the returned list will be the
562 string \texttt{"*interactive*"}, corresponding to the script name in
563 \rnrs{6}-script mode.
564
565
566 \BoxedText{Note:}{The interactive mode is intended for quickly
567 experimenting with the built-in features. It is intended neither
568 for developing applications nor for writing any substantial pieces
569 of code.}
570
571 \end{itemize}
572
573 \section{Using \texttt{scheme-script}}
574
575 Scheme scripts can be executed using the
576 \texttt{ikarus~--r6rs-script~\textit{script-name}} command as
577 described in the previous section. For convenience, Ikarus
578 follows the \rnrs{6} recommendations and installs a wrapper program
579 called \texttt{scheme-script}. Typically, a script you write would
580 start with a \texttt{\#!}\ line that directs your operating system
581 to the interpreter used to evaluate the script file. The following
582 example shows a very simple script that uses the
583 \texttt{scheme-script} command.
584
585 \begin{CodeInline}
586 #!/usr/bin/env scheme-script
587
588 (import (rnrs))
589 (display "Hello World\n")
590 \end{CodeInline}
591
592 If the above script was placed in a file called
593 \texttt{hello-world}, then one can make it executable using the
594 \texttt{chmod} Unix command.
595
596 \begin{verbatim}
597 $ cat hello-world
598 #!/usr/bin/env scheme-script
599
600 (import (rnrs))
601 (display "Hello World\n")
602
603 $ chmod 755 hello-world
604 $ ./hello-world
605 Hello World
606 $
607 \end{verbatim}
608
609 \BoxedText{Under Mac OS X,}{if a script name ends with the
610 \texttt{.command} extension, then it can be executed from the Finder
611 by double-clicking on it. This brings up a terminal window in which
612 the script is executed. The \texttt{.command} extension can be
613 hidden from the \emph{Get Info} item from the Finder's File menu.}
614
615
616 \section{Mapping library names to file names}
617
618 The name of an \rnrs{6} library consists of a non-empty list of
619 identifiers (symbols), followed by an optional version number. All
620 of the standard \rnrs{6} libraries are built into Ikarus, thus
621 importing any one of them does not require any special action other
622 than listing the library name in the \texttt{import} part of a
623 library or a script. The same holds for the \texttt{(ikarus)}
624 library (chapter~\ref{chapter:ikarus},
625 page~\pageref{chapter:ikarus}).
626
627 When importing a user library, Ikarus uses a simple mechanism
628 to map library names to file names. A library name is converted to
629 a file path by joining the library identifiers with a path
630 separator, e.g. \verb|"/"|.
631
632 \begin{center}
633 \begin{tabular}{lcl}
634 Library Name & \hspace{2em}$\Rightarrow$\hspace{2em} & File name \\
635 \hline
636 \verb|(foo)| & $\Rightarrow$ & \verb|foo| \\
637 \verb|(foo bar)| & $\Rightarrow$ & \verb|foo/bar| \\
638 \verb|(foo bar baz)| & $\Rightarrow$ & \verb|foo/bar/baz|
639 \end{tabular}
640 \end{center}
641
642
643 Having mapped a library name to a file path, Ikarus attempts to
644 locate that file in one of several locations. The locations
645 attempted depend on two settings: the search path and the file
646 extension set (e.g., \verb|.sls|, \verb|.ss|, \verb|.scm|, etc.).
647 First, Ikarus attempts to locate the file in the current working
648 directory from which Ikarus was invoked. In the current working
649 directory, Ikarus enumerates all file extensions first before
650 searching other locations. If the file is not found in the current
651 directory, Ikarus tries to find it in the Ikarus library directory.
652 The Ikarus library directory is determined when Ikarus is installed
653 (based on the \texttt{--prefix} argument that was passed to the
654 \texttt{configure} script). If Ikarus failes to locate the library
655 file, it raises an exception and exits.
656 %See
657 %Chapter~\ref{chapter:contributed} for more details about the library
658 %locations.
659
660
661 \BoxedText{Tip:}{Use simple library names for the libraries that
662 you define. Library names that contain non-printable characters,
663 complex punctuations, or unicode may pose a challenge for some
664 operating systems. If Ikarus cannot find a library, it will raise
665 an error listing the locations in which it looked, helping you move
666 the library file to a place where Ikarus can find it.}
667
668 \section{Writing cross-implementation libraries}
669
670 When searching for a library, Ikarus appends an extension (e.g.,
671 \verb|.ss|) to the appropriate file name (e.g., \verb|foo/bar|).
672 The initial set of file extensions are: \\
673 \verb|/main.ikarus.sls|,
674 \verb|/main.ikarus.ss|, \verb|/main.ikarus.scm|,
675 \verb|/main.sls|, \verb|/main.ss|, \verb|/main.scm|,
676 \verb|.ikarus.sls|,
677 \verb|.ikarus.ss|, \verb|.ikarus.scm|,
678 \verb|.sls|, \verb|.ss|, and \verb|.scm|.
679
680 The list of file extensions are searched sequentially. As a
681 consequence, files ending with the \verb|.ikarus.*| extensions are
682 given precedence over files that have generic Scheme extensions.
683 The rationale for this behavior is to facilitate writing
684 cross-implementation libraries: ones that take advantage of
685 implementation-specific features, while at the same time
686 provide a fail-safe alternative for other \rnrs{6}
687 implementations.
688
689 Consider for example a program which would like to use the
690 \verb|pretty-print| procedure to format some code, and suppose
691 further that pretty printing is just a nice add-on (e.g., using
692 \verb|write| suffices, but pretty-printing is \emph{just prettier})
693 Ikarus exports a good pretty-printing facility in its
694 \verb|(ikarus)| library. However, since \verb|pretty-print| is not
695 a standard procedure, a program that uses it would be rendered
696 unportable to other \rnrs{6} Scheme implementations.
697
698 The programmer can put the \verb|.ikarus.*| extensions to use in
699 this situation. First, the programmer writes two versions of a
700 \verb|(pretty-printing)| library: one for use by Ikarus, and one
701 portable for other implementations.
702
703 \begin{CodeInline}
704 (library (pretty-printing) ;;; this is pretty-printing.ikarus.ss
705 (export pretty-print) ;;; can only be used by Ikarus
706 (import (only (ikarus) pretty-print)))
707 \end{CodeInline}
708
709 \begin{CodeInline}
710 (library (pretty-printing) ;;; this is pretty-printing.sls
711 (export pretty-print) ;;; *portable* though not very pretty.
712 (import (rnrs)) ;;; for any other implementation
713 (define (pretty-print x port)
714 (write x port)
715 (newline port)))
716 \end{CodeInline}
717
718 The \verb|/main.*| extensions serve a different purpose. Often
719 times, a set of libraries are distributed together as a package and
720 it is convenient for the programmer to group related files in
721 directories. If a package contains the libraries \verb|(foo)|,
722 \verb|(foo core)|, and \verb|(foo compat)|, then putting all such
723 library files together in one directory makes it easier to
724 package, install, and remove these libraries en masse. The layout
725 of the package would look like:
726
727 \DefineVerbatimEnvironment{Code}{Verbatim}
728 {%baselinestretch=1.1,
729 %frame=single,
730 %framerule=0.5pt,
731 commandchars=\\\{\}}
732
733 \begin{Code}
734 foo/README : {\textrm{ignored by Ikarus}}
735 foo/COPYING :
736 foo/main.ss : (foo) {\textrm{implementation independent}}
737 foo/core.ss : (foo core)
738 foo/compat.ss : (foo compat) {\textrm{default \rnrs{6} library}}
739 foo/compat.ikarus.ss : {\textrm{specific for Ikarus}}
740 foo/compat.mzscheme.ss : {\textrm{specific for MzScheme}}
741 \end{Code}
742
743
744 By default, running the \texttt{configure} script
745 installs a set of contributed libraries into the
746 \verb|/usr/local/lib/ikarus| directory. If a \verb|--prefix DIR|
747 argument was supplied to \texttt{configure}, then the libraries are
748 installed in the \verb|DIR/ikarus/lib| directory.
749
750 You may install additional libraries into the Ikarus library
751 directory. Doing so makes them available for \texttt{import} into
752 other libraries and script regardless of where the importing code is
753 located or the current directory in which it is executed.
754
755 \section{Defining \texttt{IKARUS\_LIBRARY\_PATH}}
756 \index{ikarus library path@\texttt{IKARUS\_LIBRARY\_PATH}}
757
758 There may be situations in which you may wish to install your own
759 libraries into a different location. For example, you may not have
760 sufficient administrative privileges to write to the system
761 directory, or you may wish to keep your own libraries separate from
762 the standard libraries. Whatever the reason is, your can store your
763 library files in any location you want and set up the
764 \verb|IKARUS_LIBRARY_PATH| environment variable to point to these
765 locations. The value of \verb|IKARUS_LIBRARY_PATH| is a
766 colon-separated list of directories in which Ikarus will search.
767
768 For example, suppose your script imports the
769 \texttt{(streams~derived)} library. First, Ikarus will map the
770 library name to the file path \verb|streams/derived.ss|. Suppose
771 that Ikarus was installed using the \verb|--prefix /usr/local|
772 configuration option, and suppose further that the value of
773 \verb|IKARUS_LIBRARY_PATH| is set by the user to be
774 \verb|/home/john/ikarus-libraries:/home/john/srfis|. Ikarus will
775 search in the following locations in sequence until it finds the
776 file it is looking for.
777
778 \begin{verbatim}
779 ./streams/derived.ss
780 /home/john/ikarus-libraries/streams/derived.ss
781 /home/john/srfis/streams/derived.ss
782 /usr/local/lib/ikarus/streams/derived.ss
783 \end{verbatim}
784
785
786 The method in which the value of \verb|IKARUS_LIBRARY_PATH| is
787 defined is typically shell dependant. If you use GNU Bash, you
788 typically set the values of environment variables in the
789 \verb|~/.bash_profile| or \verb|~/.bashrc| file by adding the
790 following lines:
791
792 \begin{verbatim}
793 IKARUS_LIBRARY_PATH=/path/to/some/directory:/and/another
794 export IKARUS_LIBRARY_PATH
795 \end{verbatim}
796
797
798 \chapter{\rnrs{6} Crash Course}
799
800 The major difference between \rnrs{5} and \rnrs{6} is the way
801 in which programs are loaded and evaluated.
802
803 In \rnrs{5}, Scheme implementations typically start as an
804 interactive session (often referred to as the REPL, or
805 read-eval-print-loop). Inside the interactive session, the user
806 enters definitions and expressions one at a time using the keyboard.
807 Files, which also contain definitions and expressions, can be loaded
808 and reloaded by calling the \texttt{load} procedure. The
809 environment in which the interactive session starts often contains
810 implementation-specific bindings that are not found \rnrs{5} and
811 users may redefine any of the initial bindings. The semantics of
812 loading a file depends on the state of the environment at the time
813 the file contents are evaluated.
814
815 \index{R6RS Script@\rnrs{6} Script!Import}
816 %
817 \rnrs{6} differs from \rnrs{5} in that it specifies how \emph{whole
818 programs}, or scripts, are compiled and evaluated. An \rnrs{6}
819 script is closed in the sense that all the identifiers found in the
820 body of the script must either be defined in the script or imported
821 from a library. \rnrs{6} also specifies how \emph{libraries} can be
822 defined and used. While files in \rnrs{5} are typically
823 \emph{loaded} imperatively into the top-level environments, \rnrs{6}
824 libraries are \emph{imported} declaratively in scripts and in other
825 \rnrs{6} libraries.
826
827 \section{\label{sec:scripts}Writing a simple script}
828
829 An \rnrs{6} script is a set of definitions and expressions preceded
830 by an \texttt{import} form. The \texttt{import} form specifies
831 the language (i.e. the variable and keyword bindings) in which the
832 library body is written. A very simple example of an \rnrs{6}
833 script is listed below.
834
835 \index{Examples!Hello World}
836 \begin{CodeInline}
837 #!/usr/bin/env scheme-script
838 (import (rnrs))
839 (display "Hello World!\n")
840 \end{CodeInline}
841
842 The first line imports the \texttt{(rnrs)} library. All the
843 bindings exported from the \texttt{(rnrs)} library are made
844 available to be used within the body of the script.
845 The exports of the \texttt{(rnrs)} library include variables
846 (e.g. \texttt{cons}, \texttt{car}, \texttt{display}, etc.) and
847 keywords (e.g. \texttt{define}, \texttt{lambda}, \texttt{quote},
848 etc.). The second line displays the string \texttt{Hello World!}
849 followed by a new line character.
850
851 In addition to expressions, such as the call to \texttt{display} in
852 the previous example, a script may define some variables. The
853 script below defines the variable \texttt{greeting} and calls the
854 procedure bound to it.
855
856 \begin{CodeInline}
857 #!/usr/bin/env scheme-script
858 (import (rnrs))
859
860 (define greeting
861 (lambda ()
862 (display "Hello World!\n")))
863
864 (greeting)
865 \end{CodeInline}
866
867 Additional keywords may be defined within a script. In the example
868 below, we define the \texttt{(do-times n exprs ...)} macro that
869 evaluates the expressions \texttt{exprs} \texttt{n} times. Running
870 the script displays \texttt{Hello World} 3 times.
871 \newpage
872
873 \begin{CodeInline}
874 #!/usr/bin/env scheme-script
875 (import (rnrs))
876
877 (define greeting
878 (lambda ()
879 (display "Hello World!\n")))
880
881 (define-syntax do-times
882 (syntax-rules ()
883 [(_ n exprs ...)
884 (let f ([i n])
885 (unless (zero? i)
886 exprs ...
887 (f (- i 1))))]))
888
889 (do-times 3 (greeting))
890 \end{CodeInline}
891
892
893 \section{Writing simple libraries}
894
895 A script is intended to be a small piece of the program---useful
896 abstractions belong to libraries. The \texttt{do-times} macro that
897 was defined in the previous section may be useful in places other
898 than printing greeting messages. So, we can create a small library,
899 \texttt{(iterations)} that contains common iteration forms.
900
901 An \rnrs{6} library form is made of four essential parts: (1) the
902 library name, (2) the set of identifiers that the library exports,
903 (3) the set of libraries that the library imports, and (4) the body
904 of the library.
905
906
907 The library name can be any non-empty list of identifiers.
908 \rnrs{6}-defined libraries includes \texttt{(rnrs)},
909 \texttt{(rnrs~unicode)}, \texttt{(rnrs~bytevectors)}, and so on.
910
911 The library exports are a set of identifiers that are made available
912 to importing libraries. Every exported identifier must be bound: it
913 may either be defined in the library or imported using the
914 \texttt{import} form. Library exports include variables, keywords,
915 record names, and condition names.
916
917 Library imports are similar to script imports: they specify the set
918 of libraries whose exports are made visible within the body of the
919 library.
920
921 \index{Invoke}
922 The body of a library contains definitions (variable, keyword,
923 record, condition, etc.) followed by an optional set of expressions.
924 The expressions are evaluated for side effect when needed.
925
926
927 The \texttt{(iteration)} library may be written as follows:
928
929 \begin{CodeInline}
930 (library (iteration)
931 (export do-times)
932 (import (rnrs))
933
934 (define-syntax do-times
935 (syntax-rules ()
936 [(_ n exprs ...)
937 (let f ([i n])
938 (unless (zero? i)
939 exprs ...
940 (f (- i 1))))])))
941 \end{CodeInline}
942
943 To use the \texttt{(iteration)} library in our script, we add the
944 name of the library to the script's \texttt{import} form. This
945 makes all of \texttt{(iteration)}'s exported identifiers, e.g.
946 \texttt{do-times}, visible in the body of the script.
947
948 \begin{CodeInline}
949 #!/usr/bin/env scheme-script
950 (import (rnrs) (iteration))
951
952 (define greeting
953 (lambda ()
954 (display "Hello World!\n")))
955
956 (do-times 3 (greeting))
957 \end{CodeInline}
958
959 \section{\rnrs{6} record types}
960
961 \rnrs{6} provides ways for users to define new types, called record
962 types. A record is a fixed-size data structure with a unique type
963 (called a record type). A record may have any finite number of
964 fields that hold arbitrary values. This section briefly describes
965 what we expect to be the most commonly used features of the record
966 system. Full details are in the \rnrs{6} Standard Libraries
967 document\cite{r6rs:lib}.
968
969 \subsection{Defining new record types}
970
971 To define a new record type, use the \texttt{define-record-type}
972 form. For example, suppose we want to define a new record type for
973 describing points, where a point is a data structure that has two
974 fields to hold the point's $x$ and $y$ coordinates. The following
975 definition achieves just that:
976
977 \begin{CodeInline}
978 (define-record-type point
979 (fields x y))
980 \end{CodeInline}
981
982 The above use of \texttt{define-record-type} defines the following
983 procedures automatically for you:
984 \begin{itemize}
985 \item The constructor \texttt{make-point} that takes two arguments,
986 \texttt{x} and \texttt{y} and returns a new record whose type is
987 point.
988 \item The predicate \texttt{point?}\ that takes an arbitrary value
989 and returns \texttt{\#t} if that value is a point, \texttt{\#f}
990 otherwise.
991 \item The accessors \texttt{point-x} and \texttt{point-y} that,
992 given a record of type point, return the value stored in the
993 \texttt{x} and \texttt{y} fields.
994 \end{itemize}
995
996 Both the \texttt{x} and \texttt{y} fields of the \texttt{point}
997 record type are \emph{immutable}, meaning that once a record is
998 created with specific \texttt{x} and \texttt{y} values, they cannot
999 be changed later. If you want the fields to be \emph{mutable}, then
1000 you need to specify that explicitly as in the following example.
1001 \newpage
1002
1003 \begin{CodeInline}
1004 (define-record-type point
1005 (fields (mutable x) (mutable y)))
1006 \end{CodeInline}
1007
1008 This definition gives us, in addition to the constructor, predicate,
1009 and accessors, two additional procedures:
1010 \begin{itemize}
1011 \item The mutators \texttt{point-x-set!} and \texttt{point-y-set!} that,
1012 given a record of type point, and a new value, sets the value stored in the
1013 \texttt{x} field or \texttt{y} field to the new value.
1014 \end{itemize}
1015
1016
1017 \BoxedText{Note:}{Records in Ikarus have a printable representation
1018 in order to enable debugging programs that use records. Records are
1019 printed in the \texttt{\#[type-name field-values ...]} notation.
1020 For example, \texttt{(write (make-point 1 2))} produces
1021 \texttt{\#[point 1 2]}.}
1022
1023 \subsection{Extending existing record types}
1024
1025 A record type may be extended by defining new variants of a record
1026 with additional fields. In our running example, suppose we want
1027 to define a \texttt{colored-point} record type that, in addition to
1028 being a \texttt{point}, it has an additional field: a \emph{color}.
1029 A simple way of achieving that is by using the following record
1030 definition:
1031
1032 \begin{CodeInline}
1033 (define-record-type cpoint
1034 (parent point)
1035 (fields color))
1036 \end{CodeInline}
1037
1038 Here, the definition of \texttt{cpoint} gives us:
1039 \begin{itemize}
1040 \item A constructor \texttt{make-cpoint} that takes three arguments
1041 (\texttt{x}, \texttt{y}, and \texttt{color} in that order) and returns a
1042 \texttt{cpoint} record.
1043 \item A predicate \texttt{cpoint?}\ that takes a single argument and
1044 determines whether the argument is a \texttt{cpoint} record.
1045 \item An accessor \texttt{cpoint-color} that returns the value of
1046 the \texttt{color} field of a \texttt{cpoint} object.
1047 \end{itemize}
1048
1049 All procedures that are applicable to records of type
1050 \texttt{point} (\texttt{point?}, \texttt{point-x},
1051 \texttt{point-y}) are also applicable to records of type
1052 \texttt{cpoint} since a \texttt{cpoint} is also a \texttt{point}.
1053
1054 \subsection{Specifying custom constructors}
1055
1056 The record type definitions explained so far use the default
1057 constructor that takes as many arguments as there are fields and
1058 returns a new record type with the values of the fields initialized
1059 to the arguments' values. It is sometimes necessary or convenient
1060 to provide a constructor that performs more than the default
1061 constructor. For example, we can modify the definition of our
1062 \texttt{point} record so that the constructor takes either
1063 no arguments, in which case it would return a point located at the
1064 origin, or two arguments specifying the $x$ and $y$ coordinates. We
1065 use the \texttt{protocol} keyword for specifying such constructor as
1066 in the following example:
1067
1068 \begin{CodeInline}
1069 (define-record-type point
1070 (fields x y)
1071 (protocol
1072 (lambda (new)
1073 (case-lambda
1074 [(x y) (new x y)]
1075 [() (new 0 0)]))))
1076 \end{CodeInline}
1077
1078 The protocol here is a procedure that takes a constructor procedure
1079 \texttt{new} (\texttt{new} takes as many arguments as there are
1080 fields.) and returns the desired custom constructor that we want
1081 (The actual constructor will be the value of the
1082 \texttt{case-lambda} expression in the example above).
1083 Now the constructor \texttt{make-point} would either take two
1084 arguments which constructs a \texttt{point} record as before, or no
1085 arguments, in which case \texttt{(new 0 0)} is called to construct a
1086 point at the origin.
1087
1088 Another reason why one might want to use custom constructors is to
1089 precompute the initial values of some fields based on the values of
1090 other fields. An example of this case is adding a \texttt{distance}
1091 field to the record type which is computed as
1092 $d = \sqrt{x^2+y^2}$. The protocol in this case may be defined as:
1093
1094 \begin{CodeInline}
1095 (define-record-type point
1096 (fields x y distance)
1097 (protocol
1098 (lambda (new)
1099 (lambda (x y)
1100 (new x y (sqrt (+ (expt x 2) (expt y 2))))))))
1101 \end{CodeInline}
1102
1103 Note that derived record types need not be modified when additional
1104 fields are added to the parent record type. For example, our
1105 \texttt{cpoint} record type still works unmodified even after we
1106 added the new \texttt{distance} field to the parent.
1107 Calling \texttt{(point-distance (make-cpoint 3 4 \#xFF0000))}
1108 returns \texttt{5.0} as expected.
1109
1110 \subsection{Custom constructors for derived record types}
1111
1112 Just like how base record types (e.g. \texttt{point} in the running
1113 example) may have a custom constructor, derived record types can
1114 also have custom constructors that do other actions. Suppose that
1115 you want to construct \texttt{cpoint} records using an optional
1116 color that, if not supplied, defaults to the value 0. To do so, we
1117 supply a \texttt{protocol} argument to \texttt{define-record-type}.
1118 The only difference here is that the procedure \texttt{new} is a
1119 \emph{curried} constructor. It first takes as many arguments as the
1120 constructor of the parent record type, and returns a procedure that
1121 takes the initial values of the new fields.
1122
1123 In our example, the constructor for the \texttt{point} record type
1124 takes two arguments. \texttt{cpoint} extends \texttt{point} with
1125 one new field. Therefore, \texttt{new} in the definition below
1126 first takes the arguments for \texttt{point}'s constructor, then
1127 takes the initial color value. The definition below shows how the
1128 custom constructor may be defined.
1129
1130 \newpage
1131 \begin{CodeInline}
1132 (define-record-type cpoint
1133 (parent point)
1134 (fields color)
1135 (protocol
1136 (lambda (new)
1137 (case-lambda
1138 [(x y c) ((new x y) c)]
1139 [(x y) ((new x y) 0)]))))
1140 \end{CodeInline}
1141
1142
1143 \section{Exception handling}
1144
1145 The procedure \texttt{with-exception-handler} allows the programmer
1146 to specify how to handle exceptional situations. It takes two
1147 procedures as arguments:
1148 \begin{itemize}
1149 \item An exception handler which is a procedure that takes a
1150 single argument, the object that was raised.
1151 \item A body thunk which is a procedure with no arguments whose body
1152 is evaluated with the exception handler installed.
1153 \end{itemize}
1154
1155 In addition to installing exception handlers, \rnrs{6} provides two
1156 ways of raising exceptions: \texttt{raise} and
1157 \texttt{raise-continuable}. We describe the
1158 \texttt{raise-continuable} procedure
1159 first since it's the simpler of the two.
1160 For the code below, assume that \texttt{print} is defined as:
1161 \begin{CodeInline}
1162 (define (print who obj)
1163 (display who)
1164 (display ": ")
1165 (display obj)
1166 (newline))
1167 \end{CodeInline}
1168
1169 The first example, below, shows how a simple exception handler is
1170 installed. Here, the exception handler prints the object it
1171 receives and returns the symbol \texttt{there}. The call to
1172 \texttt{raise-continuable} calls the exception handler, passing it
1173 the symbol \texttt{here}. When the handler returns, the returned
1174 value becomes the value of the call to \texttt{raise-continuable}.
1175
1176 \begin{CodeInline}
1177 (with-exception-handler
1178 (lambda (obj) ;;; prints
1179 (print "handling" obj) ;;; handling: here
1180 'there) ;;; returned: there
1181 (lambda ()
1182 (print "returned" (raise-continuable 'here))))
1183 \end{CodeInline}
1184
1185 Exceptional handlers may nest, and in that case, if an exception is
1186 raised while evaluating an inner handler, the outer handler is
1187 called as the following example illustrates:
1188
1189 \begin{CodeInline}
1190 (with-exception-handler
1191 (lambda (obj) ;;; prints
1192 (print "outer" obj) ;;; inner: here
1193 'outer) ;;; outer: there
1194 (lambda () ;;; returned: outer
1195 (with-exception-handler
1196 (lambda (obj)
1197 (print "inner" obj)
1198 (raise-continuable 'there))
1199 (lambda ()
1200 (print "returned" (raise-continuable 'here))))))
1201 \end{CodeInline}
1202
1203 In short, \texttt{with-exception-handler} binds an exception handler
1204 within the dynamic context of evaluating the thunk, and
1205 \texttt{raise-continuable} calls it.
1206
1207 The procedure \texttt{raise} is similar to
1208 \texttt{raise-continuable} except that if the handler returns, a new
1209 exception is raised, calling the next handler in sequence until the
1210 list of handlers is exhausted.
1211
1212 \begin{CodeInline}
1213 (call/cc ;;; prints
1214 (lambda (escape) ;;; inner: here
1215 (with-exception-handler ;;; outer: #[condition ---]
1216 (lambda (obj) ;;; returns
1217 (print "outer" obj) ;;; 12
1218 (escape 12))
1219 (lambda ()
1220 (with-exception-handler
1221 (lambda (obj)
1222 (print "inner" obj)
1223 'there)
1224 (lambda ()
1225 (print "returned" (raise 'here))))))))
1226 \end{CodeInline}
1227
1228 Here, the call to \texttt{raise} calls the inner exception handler,
1229 which returns, causing \texttt{raise} to re-raise a non-continuable
1230 exception to the outer exception handler. The outer exception
1231 handler then calls the escape continuation.
1232
1233 The following procedure provides a useful example of using the
1234 exception handling mechanism. Consider a simple definition of the
1235 procedure \texttt{configuration-option} which returns the value
1236 associated with a key where the key/value pairs are stored in an
1237 association list in a configuration file.
1238
1239 \begin{CodeInline}
1240 (define (configuration-option filename key)
1241 (cdr (assq key (call-with-input-file filename read))))
1242 \end{CodeInline}
1243
1244 Possible things may go wrong with calling
1245 \texttt{configuration-option} including errors opening the file,
1246 errors reading from the file (file may be corrupt), error in
1247 \texttt{assq} since what's read may not be an association list, and
1248 error in \texttt{cdr} since the key may not be in the association
1249 list. Handling all error possibilities is tedious and error prone.
1250 Exceptions provide a clean way of solving the problem. Instead of
1251 guarding against all possible errors, we install a handler that
1252 suppresses all errors and returns a default value if things go
1253 wrong. Error handling for \texttt{configuration-option} may be
1254 added as follows:
1255
1256 \begin{CodeInline}
1257 (define (configuration-option filename key default)
1258 (define (getopt)
1259 (cdr (assq key (call-with-input-file filename read))))
1260 (call/cc
1261 (lambda (k)
1262 (with-exception-handler
1263 (lambda (_) (k default))
1264 getopt))))
1265 \end{CodeInline}
1266
1267
1268 \chapter{\label{chapter:ikarus}The \texttt{(ikarus)} library}
1269
1270 In addition to the libraries listed in the \rnrs{6} standard, Ikarus
1271 contains the \texttt{(ikarus)} library which provides additional
1272 useful features. The \texttt{(ikarus)} library is a composite
1273 library---it exports a superset of all the supported bindings of
1274 \rnrs{6}. While not all of the exports of \texttt{(ikarus)} are
1275 documented at this time, this chapter attempts to describe a few of
1276 these useful extensions. Extensions to Scheme's lexical syntax are
1277 also documented.
1278
1279 \idxlabeldefun{\#"!ikarus}{\#"!ikarus}{shebang-ikarus}{\#!ikarus}{reader syntax}
1280
1281 Ikarus extends Scheme's lexical syntax (\rnrs{6}~Chapter~4) in a
1282 variety of ways including:\\
1283 $\bullet$ end-of-file marker, \deflabelref{\#!eof}{shebang-eof}\\
1284 $\bullet$ gensym syntax, \deflabelref{\#\{gensym\}}{gensym syntax}\\
1285 $\bullet$ graph syntax, \deflabelref{\#nn= \#nn\#}{graph-syntax}
1286
1287 The syntax extensions are made available by default on all input
1288 ports, until the \texttt{\#!r6rs} token is read. Thus, reading the
1289 \texttt{\#!r6rs} token disables all extensions to the lexical syntax
1290 on the specific port, and the \texttt{\#!ikarus} enables them again.
1291
1292 If you are writing code that is intended to be portable across
1293 different Scheme implementations, we recommend adding the
1294 \texttt{\#!r6rs} token to the top of every script and library that
1295 you write. This allows Ikarus to alert you when using non-portable
1296 features. If you're writing code that's intended to be
1297 Ikarus-specific, we recommend adding the \texttt{\#!ikarus} token in
1298 order to get an immediate error when your code is run under other
1299 implementations.
1300
1301 \defun{port-mode}{procedure}
1302 \texttt{(port-mode ip)}
1303
1304 The \texttt{port-mode} procedure accepts an input port as an
1305 argument and returns one of \texttt{r6rs-mode} or
1306 \texttt{ikarus-mode} as a result. All input ports initially start
1307 in the \texttt{ikarus-mode} and thus accept Ikarus-specific reader
1308 extensions. When the \texttt{\#!r6rs} token is read from a port,
1309 its mode changes to \texttt{ikarus-mode}.
1310
1311 \begin{verbatim}
1312 > (port-mode (current-input-port))
1313 ikarus-mode
1314 > #!r6rs (port-mode (current-input-port))
1315 r6rs-mode
1316 > #!ikarus (port-mode (current-input-port))
1317 ikarus-mode
1318 \end{verbatim}
1319
1320 \idxlabeldefun{set-port-mode"!}{set-port-mode"!}{set-port-mode-bang}{set-port-mode!}{procedure}
1321 %\defun{set-port-mode!}{procedure}
1322 %\index{set-port-mode@\texttt{set-port-mode"!}}
1323 \texttt{(set-port-mode!\ ip mode)}
1324
1325 The \texttt{set-port-mode!} procedure modifies the lexical syntax
1326 accepted by subsequent calls to \texttt{read} on the input port.
1327 The mode is a symbol which should be one of \texttt{r6rs-mode} or
1328 \texttt{ikarus-mode}. The effect of setting the port mode is
1329 similar to that of reading the \texttt{\#!r6rs} or \texttt{\#ikarus}
1330 from that port.
1331
1332 \begin{verbatim}
1333 > (set-port-mode! (current-input-port) 'r6rs-mode)
1334 > (port-mode (current-input-port))
1335 r6rs-mode
1336 \end{verbatim}
1337
1338 \newpage
1339 \idxlabeldefun{\#"!eof}{\#"!eof}{shebang-eof}{\#!eof}{reader syntax}
1340
1341 The end-of-file marker, \texttt{\#!eof}, is an extension to the
1342 \rnrs{6} syntax. The primary utility of the \texttt{\#!eof} marker
1343 is to stop the reader (e.g. \texttt{read} and \texttt{get-datum})
1344 from reading the rest of the file.
1345 \begin{verbatim}
1346 #!/usr/bin/env scheme-script
1347 (import (ikarus))
1348 <some code>
1349 (display "goodbye\n")
1350
1351 #!eof
1352 <some junk>
1353 \end{verbatim}
1354
1355
1356 The \texttt{\#!eof} marker also serves as a datum in Ikarus, much
1357 like \texttt{\#t} and \texttt{\#f}, when it is found inside other
1358 expressions.
1359
1360 \begin{verbatim}
1361 > (eof-object)
1362 #!eof
1363 > (read (open-input-string ""))
1364 #!eof
1365 > (read (open-input-string "#!eof"))
1366 #!eof
1367 > (quote #!eof)
1368 #!eof
1369 > (eof-object? '#!eof)
1370 #t
1371 > #!r6rs #!eof
1372 Unhandled exception
1373 Condition components:
1374 1. &error
1375 2. &who: tokenize
1376 3. &message: "invalid syntax: #!e"
1377 > #!ikarus #!eof
1378 $
1379 \end{verbatim}
1380
1381 \newpage
1382 \section{Parameters}
1383
1384 Parameters in Ikarus\footnote{Parameters are found in many Scheme
1385 implementations such as Chez Scheme and MzScheme.} are intended for
1386 customizing the behavior of a procedure during the dynamic execution
1387 of some piece of code. Parameters are first class entities
1388 (represented as procedures) that hold the parameter value. A
1389 parameter procedure accepts either zero or one argument. If given
1390 no arguments, it returns the current value of the parameter. If
1391 given a single argument, it must set the state to the value of the
1392 argument. Parameters replace the older concept of using starred
1393 \texttt{*global*} customization variables. For example, instead of
1394 writing:
1395 \begin{verbatim}
1396 (define *screen-width* 72)
1397 \end{verbatim}
1398 and then mutating the variable \texttt{*screen-width*} with
1399 \texttt{set!}, we could wrap the variable \texttt{*screen-width*} with a
1400 \texttt{screen-width} parameter as follows:
1401 \begin{verbatim}
1402 (define *screen-width* 72)
1403 (define screen-width
1404 (case-lambda
1405 [() *screen-width*]
1406 [(x) (set! *screen-width* x)]))
1407 \end{verbatim}
1408
1409 The value of \texttt{screen-width} can now be passed as argument,
1410 returned as a value, and exported from libraries.
1411
1412 \defun{make-parameter}{procedure}
1413 \texttt{
1414 (make-parameter x)\\
1415 (make-parameter x f)
1416 }
1417
1418 As parameters are common in Ikarus, the procedure
1419 \texttt{make-parameter} is defined to model the common usage pattern
1420 of parameter construction.
1421
1422 \paragraph{\texttt{(make-parameter x)}} constructs a parameter
1423 with \texttt{x} as the initial value. For example, the code above
1424 could be written succinctly as:
1425 \begin{verbatim}
1426 (define screen-width (make-parameter 72))
1427 \end{verbatim}
1428
1429 \paragraph{\texttt{(make-parameter x f)}} constructs a parameter
1430 which filters the assigned values through the procedure \texttt{f}.
1431 The initial value of the parameter is the result of calling
1432 \texttt{(f~x)}. Typical uses of the filter procedure include
1433 checking some constraints on the passed argument or converting it to
1434 a different data type. The \texttt{screen-width} parameter may be
1435 constructed more robustly as:
1436 \begin{verbatim}
1437 (define screen-width
1438 (make-parameter 72
1439 (lambda (w)
1440 (assert (and (integer? w) (exact? w)))
1441 (max w 1))))
1442 \end{verbatim}
1443 This definition ensures, through \texttt{assert}, that the argument
1444 passed is an exact integer. It also ensures, through \texttt{max}
1445 that the assigned value is always positive.
1446
1447
1448 \defun{parameterize}{syntax}
1449 \texttt{(parameterize ([lhs* rhs*] ...) body body* ...)}
1450
1451 Parameters can be assigned to by simply calling the parameter
1452 procedure with a single argument. The \texttt{parameterize} syntax
1453 is used to set the value of a parameter within the dynamic extent of
1454 the \texttt{body~body*~...} expressions.
1455
1456 The \texttt{lhs* ...} are expressions, each of which must evaluate
1457 to a parameter. Such parameters are not necessarily constructed by
1458 \texttt{make-parameter}---any procedure that follows the parameters
1459 protocol works.
1460
1461 The advantage of using \texttt{parameterize} over explicitly
1462 assigning to parameters (same argument applies to global variables)
1463 is that you're guaranteed that whenever control exits the body of a
1464 \texttt{parameterize} expression, the value of the parameter is
1465 reset back to what it was before the body expressions were entered.
1466 This is true even in the presence of \texttt{call/cc}, errors, and
1467 exceptions.
1468
1469 The following example shows how to set the text property of a
1470 terminal window. The parameter \texttt{terminal-property} sends an
1471 ANSI escape sequence to the terminal whenever the parameter value is
1472 changed. The use of \texttt{terminal-property} within
1473 \texttt{parameterize} changes the property before
1474 \texttt{(display~"RED!")} is called and resets it back to normal
1475 when the body returns.
1476
1477 \begin{CodeInline}
1478 (define terminal-property
1479 (make-parameter "0"
1480 (lambda (x)
1481 (display "\x1b;[")
1482 (display x)
1483 (display "m")
1484 x)))
1485
1486 (display "Normal and ")
1487 (parameterize ([terminal-property "41;37"])
1488 (display "RED!"))
1489 (newline)
1490 \end{CodeInline}
1491
1492 \newpage
1493 \section{Local library imports}
1494 \defun{import}{syntax}
1495 \texttt{(import import-spec* ...)}
1496
1497 The \texttt{import} keyword which is exported from the
1498 \texttt{(ikarus)} library can be used anywhere definitions can
1499 occur: at a script body, library's top-level, or in internal
1500 definitions context. The syntax of the local \texttt{import} form
1501 is similar to the \texttt{import} that appears at the top of a
1502 library or a script form, and carries with it the same restrictions:
1503 no identifier name may be imported twice unless it denotes the same
1504 identifier; no identifier may be both imported and defined; and
1505 imported identifiers are immutable.
1506
1507 Local \texttt{import} forms are useful for two reasons: (1) they
1508 minimize the namespace clutter that usually occurs when many
1509 libraries are imported at the top level, and (2) they limit the
1510 scope of the import and thus help modularize a library's
1511 dependencies.
1512
1513 Suppose you are constructing a large library and at some point you
1514 realize that one of your procedures needs to make use of some other
1515 library for performing a specific task. Importing that library at
1516 top level makes it available for the entire library. Consequently,
1517 even if that library is no longer used anywhere in the code (say
1518 when the code that uses it is deleted), it becomes very hard to
1519 delete the import without first examiniming the entire library body
1520 for potential usage leaks. By locally importing a library into the
1521 appropriate scope, we gain the ability to delete the \texttt{import}
1522 form when the procedure that was using it is deleted.
1523
1524
1525 \newpage
1526 \section{Local modules}
1527
1528 This section is not documented yet.
1529 Please refer to Section~10.5 of Chez Scheme
1530 User's Guide~\cite{csug7}, Chapter~3 of Oscar Waddel's Ph.D
1531 Thesis~\cite{waddell-thesis}, and its POPL99
1532 paper~\cite{waddell-extending} for details on using the
1533 \texttt{module} and \texttt{import} keywords. Ikarus's internal
1534 module system is similar in spirit to that of Chez Scheme.
1535
1536
1537 \defun{module}{syntax}
1538 \texttt{(module M definitions ... expressions ...)}\\
1539 \texttt{(module definitions ... expressions ...)}
1540
1541 \defun{import}{syntax}
1542 \texttt{(import M)}
1543
1544
1545 \newpage
1546
1547 \section{\label{sec:gensyms}Gensyms}
1548
1549 Gensym stands for a \emph{generated symbol}---a fresh symbol that is
1550 generated at run time and is guaranteed to be \emph{not}
1551 \texttt{eq?} to any other symbol present in the system. Gensyms are
1552 useful in many applications including expanders, compilers, and
1553 interpreters when generating an arbitrary number of unique names is
1554 needed.
1555
1556 Ikarus is similar to Chez Scheme in that the readers (including the
1557 \texttt{read} procedure) and writers (including \texttt{write} and
1558 \texttt{pretty-print}) maintain the read/write invariance on
1559 gensyms. When a gensym is written to an output port, the system
1560 automatically generates a random unique identifier for the gensym.
1561 When the gensym is read back though the \verb|#{gensym}| read
1562 syntax, a new gensym is \emph{not} regenerated, but instead, it is
1563 looked up in the global symbol table.
1564
1565 A gensym's name is composed of two parts: a \emph{pretty} string and
1566 a \emph{unique} string. The Scheme procedure
1567 \texttt{symbol->string} returns the pretty string of the gensym and
1568 not its unique string. Gensyms are printed by default as \\
1569 \verb|#{pretty-string unique-string}|.
1570
1571 \defun{gensym}{procedure}
1572 \texttt{(gensym)}\\
1573 \texttt{(gensym string)}\\
1574 \texttt{(gensym symbol)}
1575
1576 The procedure \texttt{gensym} constructs a new gensym. If passed no
1577 arguments, it constructs a gensym with no pretty name. The pretty
1578 name is constructed when and if the pretty name of the resulting
1579 gensym is needed. If \texttt{gensym} is passed a string, that
1580 string is used as the pretty name. If \texttt{gensym} is passed a
1581 symbol, the pretty name of the symbol is used as the pretty name of
1582 the returned gensym.
1583 See \defref{gensym-prefix} and \defref{gensym-count} for details.
1584
1585 \begin{verbatim}
1586 > (gensym)
1587 #{g0 |y0zf>GlFvcTJE0xw|}
1588 > (gensym)
1589 #{g1 |U%X&sF6kX!YC8LW=|}
1590 > (eq? (gensym) (gensym))
1591 #f
1592 \end{verbatim}
1593
1594 \texttt{(gensym string)} constructs a new gensym with
1595 \texttt{string} as its pretty name. Similarly,
1596 \texttt{(gensym~symbol)} constructs a new gensym with the pretty
1597 name of \texttt{symbol}, if it has one, as its pretty name.
1598
1599 \begin{verbatim}
1600 > (gensym "foo")
1601 #{foo |>VgOllCM&$dSvRN=|}
1602 > (gensym 'foo)
1603 #{foo |!TqQLmtw2hoEYfU>|}
1604 > (gensym (gensym 'foo))
1605 #{foo |N2C>5O0>C?OROUBU|}
1606 \end{verbatim}
1607
1608
1609
1610 \defun{gensym?}{procedure}
1611 \texttt{(gensym? x)}
1612
1613 The \texttt{gensym?}\ predicate returns \texttt{\#t} if its argument
1614 is a gensym, and returns \texttt{\#f} otherwise.
1615
1616 \begin{verbatim}
1617 > (gensym? (gensym))
1618 #t
1619 > (gensym? 'foo)
1620 #f
1621 > (gensym? 12)
1622 #f
1623 \end{verbatim}
1624
1625 \defun{gensym->unique-string}{procedure}
1626 \texttt{(gensym->unique-string gensym)}
1627
1628 The \texttt{gensym->unique-string} procedure returns the unique name
1629 associated with the gensym argument.
1630
1631 \begin{verbatim}
1632 > (gensym->unique-string (gensym))
1633 "YukrolLMgP?%ElcR"
1634 \end{verbatim}
1635
1636
1637 \idxdefun{gensym syntax}{\#\{gensym\}}{reader syntax}
1638 \texttt{\#\{unique-name\}}
1639 \index{\#\{pretty unique\}@\texttt{\#\{pretty unique\}} reader syntax}
1640 \\
1641 \texttt{\#\{pretty-name unique-name\}}
1642 \index{\#\{unique\}@\texttt{\#\{unique\}} reader syntax}
1643 \\
1644 \texttt{\#:pretty-name}
1645 \index{\#:pretty@\texttt{\#:pretty} reader syntax}
1646
1647 Ikarus's \texttt{read} and \texttt{write} procedures extend the
1648 lexical syntax of Scheme by the ability to read and write gensyms
1649 using one of the three forms listed above.
1650
1651 \verb|#{unique-name}| constructs, at read time, a gensym whose
1652 unique name is the one specified. If a gensym with the same unique
1653 name already exists in the system's symbol table, that gensym is
1654 returned.
1655 \begin{verbatim}
1656 > '#{some-long-name}
1657 #{g0 |some-long-name|}
1658 > (gensym? '#{some-long-unique-name})
1659 #t
1660 > (eq? '#{another-unique-name} '#{another-unique-name})
1661 #t
1662 \end{verbatim}
1663
1664 The two-part \verb|#{pretty-name unique-name}| gensym syntax is
1665 similar to the syntax shown above with the exception that if a new
1666 gensym is constructed (that is, if the gensym did not already exist
1667 in the symbol table), the pretty name of the constructed gensym is
1668 set to \texttt{pretty-name}.
1669
1670 \begin{verbatim}
1671 > '#{foo unique-identifier}
1672 #{foo |unique-identifier|}
1673 > '#{unique-identifier}
1674 #{foo |unique-identifier|}
1675 > '#{bar unique-identifier}
1676 #{foo |unique-identifier|}
1677 \end{verbatim}
1678
1679 The \texttt{\#:pretty-name} form constructs, at read time, a gensym
1680 whose pretty name is \texttt{pretty-name} and whose unique name is
1681 fresh. This form guarantees that the resulting gensym is not
1682 \texttt{eq?}\ to any other symbol in the system.
1683
1684 \begin{verbatim}
1685 > '#:foo
1686 #{foo |j=qTGlEwS/Zlp2Dj|}
1687 > (eq? '#:foo '#:foo)
1688 #f
1689 \end{verbatim}
1690
1691 \defun{generate-temporaries}{example}
1692 \index{Examples!generate-temporaries@\texttt{generate-temporaries}}
1693
1694 The \texttt{(rnrs syntax-case)} library provides a
1695 \texttt{generate-temporaries} procedure, which takes a syntax object
1696 (representing a list of things) and returns a list of fresh
1697 identifiers. Using \texttt{gensym}, that procedure can be defined
1698 as follows:
1699
1700 \begin{CodeInline}
1701 (define (generate-temporaries* stx)
1702 (syntax-case stx ()
1703 [(x* ...)
1704 (map (lambda (x)
1705 (datum->syntax #'unimportant
1706 (gensym
1707 (if (identifier? x)
1708 (syntax->datum x)
1709 't))))
1710 #'(x* ...))]))
1711 \end{CodeInline}
1712
1713 The above definition works by taking the input \texttt{stx} and
1714 destructuring it into the list of syntax objects \texttt{x*~...}.
1715 The inner procedure maps each \texttt{x} into a new syntax object
1716 (constructed with \texttt{datum->syntax}). The datum is a gensym,
1717 whose name is the same name as \texttt{x} if \texttt{x} is an
1718 identifier, or the symbol \texttt{t} if \texttt{x} is not an
1719 identifier. The output of \texttt{generate-temporaries*} generates
1720 names similar to their input counterpart:
1721
1722 \begin{verbatim}
1723 > (print-gensym #f)
1724 > (generate-temporaries* #'(x y z 1 2))
1725 (#<syntax x> #<syntax y> #<syntax z> #<syntax t> #<syntax t>)
1726 \end{verbatim}
1727
1728 \newpage
1729 \section{Printing}
1730
1731 \defun{pretty-print}{procedure}
1732 \texttt{(pretty-print datum)}\\
1733 \texttt{(pretty-print datum output-port)}
1734
1735 The procedure \texttt{pretty-print} is intended for printing Scheme
1736 data, typically Scheme programs, in a format close to how a Scheme
1737 programmer would write it. Unlike \texttt{write}, which writes its
1738 input all in one line, \texttt{pretty-print} inserts spaces and new
1739 lines in order to produce more pleasant output.
1740
1741 \begin{verbatim}
1742 (define fact-code
1743 '(letrec ([fact (lambda (n) (if (zero? n) 1 (* n (fact (- n 1)))))])
1744 (fact 5)))
1745
1746 > (pretty-print fact-code)
1747 (letrec ((fact
1748 (lambda (n) (if (zero? n) 1 (* n (fact (- n 1)))))))
1749 (fact 5))
1750 \end{verbatim}
1751
1752 The second argument to \texttt{pretty-print}, if supplied, must be
1753 an output port. If not supplied, the \texttt{current-output-port}
1754 is used.
1755
1756 \BoxedText{Limitations:}{As shown in the output above, the current
1757 implementation of \texttt{pretty-print} does not handle printing of
1758 square brackets properly.}
1759
1760 \defun{pretty-width}{parameter}
1761 \texttt{(pretty-width)}\\
1762 \texttt{(pretty-width n)}
1763
1764 The parameter \texttt{pretty-width} controls the number of
1765 characters after which the \texttt{pretty-print} starts breaking
1766 long lines into multiple lines. The initial value of
1767 \texttt{pretty-width} is set to 60 characters, which is suitable for most
1768 terminals and printed material.
1769
1770 \begin{verbatim}
1771 > (parameterize ([pretty-width 40])
1772 (pretty-print fact-code))
1773 (letrec ((fact
1774 (lambda (n)
1775 (if (zero? n)
1776 1
1777 (* n (fact (- n 1)))))))
1778 (fact 5))
1779 \end{verbatim}
1780
1781 Note that \texttt{pretty-width} does not guarantee that
1782 the output will not extend beyond the specified number. Very long
1783 symbols, for examples, cannot be split into multiple lines and may
1784 force the printer to go beyond the value of \texttt{pretty-width}.
1785
1786 \defun{format}{procedure}
1787 \texttt{(format fmt-string args ...)}
1788
1789 The procedure \texttt{format} produces a string formatted according
1790 to \texttt{fmt-string} and the supplied
1791 arguments. The format string contains markers in which the string
1792 representation of each argument is placed. The markers include:
1793
1794
1795 \hangpara{2em}{1}
1796 \verb|"~s"| instructs the formatter to place the next argument
1797 as if the procedure \texttt{write} has printed it. If the argument
1798 contains a string, the string will be quoted and all quotes and
1799 backslashes in the string will be escaped. Similarly, characters
1800 will be printed using the \verb|#\x| notation.
1801
1802 \hangpara{2em}{1}
1803 \verb|"~a"| instructs the formatter to place the next argument
1804 as if the procedure \texttt{display} has printed it. Strings and
1805 characters are placed as they are in the output.
1806
1807 \hangpara{2em}{1}
1808 \verb|"~b"| instructs the formatter to convert the next
1809 argument to its binary (base 2) representation. The argument must be an
1810 exact number. Note that the \texttt{\#b} numeric prefix is not
1811 produced in the output.
1812
1813 \hangpara{2em}{1}
1814 \verb|"~o"| is similar to \verb|"~b"| except that
1815 the number is printed in octal (base 8).
1816
1817 \hangpara{2em}{1}
1818 \verb|"~x"| is similar to \verb|"~b"| except that
1819 the number is printed in hexadecimal (base 16).
1820
1821 \hangpara{2em}{1}
1822 \verb|"~d"| outputs the next argument, which can be an
1823 exact or inexact number, in its decimal (base 10) representation.
1824
1825 \hangpara{2em}{1}
1826 \verb|"~~"| instructs the formatter to place a tilde
1827 character, \verb|~|, in the output without consuming an
1828 argument.
1829
1830 Note that the \texttt{\#b}, \texttt{\#o}, and \texttt{\#x} numeric
1831 prefixes are not added to the output when \verb|~b|, \verb|~o|, and
1832 \verb|~x| are used.
1833
1834 \begin{verbatim}
1835 > (format "message: ~s, ~s, and ~s" 'symbol "string" #\c)
1836 "message: symbol, \"string\", and #\\c"
1837
1838 > (format "message: ~a, ~a, and ~a" 'symbol "string" #\c)
1839 "message: symbol, string, and c"
1840 \end{verbatim}
1841
1842 \defun{printf}{procedure}
1843 \texttt{(printf fmt-string args ...)}
1844
1845 The procedure \texttt{printf} is similar to \texttt{format} except
1846 that the output is sent to the \texttt{current-output-port} instead
1847 of being collected in a string.
1848
1849 \begin{verbatim}
1850 > (let ([n (+ (expt 2 32) #b11001)])
1851 (printf "~d = #b~b = #x~x\n" n n n))
1852 4294967321 = #b100000000000000000000000000011001 = #x100000019
1853 \end{verbatim}
1854
1855
1856 \defun{fprintf}{procedure}
1857 \texttt{(fprintf output-port fmt-string args ...)}
1858
1859 The procedure \texttt{fprintf} is similar to \texttt{printf} except
1860 that the output port to which the output is sent is specified as the
1861 first argument.
1862
1863 \defun{print-graph}{parameter}
1864 \texttt{(print-graph)} \\
1865 \texttt{(print-graph \#t)}\\
1866 \texttt{(print-graph \#f)}
1867
1868 \phantomsection
1869 \label{graph-syntax}
1870 The graph notation is a way of marking and referencing parts of a
1871 data structure and, consequently, creating shared and cyclic data
1872 structures at read time instead of resorting to explicit mutation at
1873 run time. The \texttt{\#$n$=} marks the following data structure with
1874 mark $n$, where $n$ is a nonnegative integer. The \texttt{\#$n$\#}
1875 references the data structure marked $n$. Marks can be assigned and
1876 referenced in any order but each mark must be assigned to exactly
1877 once in an expression.
1878
1879 \begin{verbatim}
1880 > (let ([x '#0=(1 2 3)])
1881 (eq? x '#0#))
1882 #t
1883 > (let ([x '#0#] [y '#0=(1 2 3)])
1884 (eq? x y))
1885 #t
1886 > (eq? (cdr '(12 . #1#)) '#1=(1 2 3))
1887 #t
1888 > (let ([x '#1=(#1# . #1#)])
1889 (and (eq? x (car x))
1890 (eq? x (cdr x))))
1891 #t
1892 \end{verbatim}
1893
1894 The \texttt{print-graph} parameter controls how the writers (e.g.
1895 \texttt{pretty-print} and \texttt{write}) handle shared and cyclic
1896 data structures. In Ikarus, all writers detect cyclic data
1897 structures and they all terminate on all input, cyclic or otherwise.
1898
1899 If the value of \texttt{print-graph} is set to \texttt{\#f} (the
1900 default), then the writers does not attempt to detect shared data
1901 structures. Any part of the input that is shared is printed as if
1902 no sharing is present.
1903 If the value of \texttt{print-graph} is set to \texttt{\#t}, all
1904 sharing of data structures is marked using the \texttt{\#$n$=} and
1905 \texttt{\#$n$\#} notation.
1906
1907
1908 \begin{verbatim}
1909 > (parameterize ([print-graph #f])
1910 (let ([x (list 1 2 3 4)])
1911 (pretty-print (list x x x))))
1912 ((1 2 3 4) (1 2 3 4) (1 2 3 4))
1913
1914 > (parameterize ([print-graph #t])
1915 (let ([x (list 1 2 3 4)])
1916 (pretty-print (list x x x))))
1917 (#0=(1 2 3 4) #0# #0#)
1918
1919 > (parameterize ([print-graph #f])
1920 (let ([x (list 1 2)])
1921 (let ([y (list x x x x)])
1922 (set-car! (last-pair y) y)
1923 (pretty-print (list y y)))))
1924 (#0=((1 2) (1 2) (1 2) #0#) #0#)
1925
1926 > (parameterize ([print-graph #t])
1927 (let ([x (list 1 2)])
1928 (let ([y (list x x x x)])
1929 (set-car! (last-pair y) y)
1930 (pretty-print (list y y)))))
1931 (#0=(#1=(1 2) #1# #1# #0#) #0#)
1932 \end{verbatim}
1933
1934
1935 % \defun{print-unicode}{parameter}
1936 % \texttt{(print-unicode)} \\
1937 % \texttt{(print-unicode \#t)} \\
1938 % \texttt{(print-unicode \#f)}
1939
1940
1941 \defun{print-gensym}{parameter}
1942 \texttt{(print-gensym)}\\
1943 \texttt{(print-gensym \#t)}\\
1944 \texttt{(print-gensym \#f)}\\
1945 \texttt{(print-gensym 'pretty)}
1946
1947 The parameter \texttt{print-gensym} controls how gensyms are printed
1948 by the various writers.
1949
1950 If the value of \texttt{print-gensym} is \texttt{\#f}, then gensym
1951 syntax is suppressed by the writers and only the gensyms' pretty
1952 names are printed. If the value of \texttt{print-gensym} is
1953 \texttt{\#t}, then the full \verb|#{pretty unique}| syntax is
1954 printed. Finally, if the value of \texttt{print-gensym} is the
1955 symbol \texttt{pretty}, then gensyms are printed using the
1956 \texttt{\#:pretty} notation.
1957
1958 \begin{verbatim}
1959 > (parameterize ([print-gensym #f])
1960 (pretty-print (list (gensym) (gensym))))
1961 (g0 g1)
1962
1963 > (parameterize ([print-gensym #t])
1964 (pretty-print (list (gensym) (gensym))))
1965 (#{g2 |KR1M2&CTt1<B0n/m|} #{g3 |FBAb&7NC6&=c82!O|})
1966
1967 > (parameterize ([print-gensym 'pretty])
1968 (pretty-print (list (gensym) (gensym))))
1969 (#:g4 #:g5)
1970 \end{verbatim}
1971
1972 The initial value of \texttt{print-gensym} is \texttt{\#t}.
1973
1974
1975 \defun{gensym-prefix}{parameter}
1976 \texttt{(gensym-prefix)}\\
1977 \texttt{(gensym-prefix string)}
1978
1979 The parameter \texttt{gensym-prefix} specifies the string to be used
1980 as the prefix to generated pretty names. The default value of
1981 \texttt{gensym-prefix} is the string \texttt{"g"}, which causes
1982 generated strings to have pretty names in the sequence \texttt{g0},
1983 \texttt{g1}, \texttt{g2}, etc.
1984
1985 \begin{verbatim}
1986 > (parameterize ([gensym-prefix "var"]
1987 [print-gensym #f])
1988 (pretty-print (list (gensym) (gensym) (gensym))))
1989 (var0 var1 var2)
1990 \end{verbatim}
1991
1992 Beware that the \texttt{gensym-prefix} controls how pretty names are
1993 generated, and has nothing to do with how \texttt{gensym} constructs
1994 a new gensym. In particular, notice the difference between the
1995 output in the first example with the output of the examples below:
1996
1997 \begin{verbatim}
1998 > (pretty-print
1999 (parameterize ([gensym-prefix "var"] [print-gensym #f])
2000 (list (gensym) (gensym) (gensym))))
2001 (g3 g4 g5)
2002
2003 > (let ([ls (list (gensym) (gensym) (gensym))])
2004 (parameterize ([gensym-prefix "var"] [print-gensym #f])
2005 (pretty-print ls)))
2006 (var5 var6 var7)
2007 \end{verbatim}
2008
2009
2010
2011 \defun{gensym-count}{parameter}
2012 \texttt{(gensym-count)}\\
2013 \texttt{(gensym-count n)}
2014
2015 The parameter \texttt{gensym-count} determines the number
2016 which is attached to the \texttt{gensym-prefix} when gensyms'
2017 pretty names are generated. The initial value of \texttt{gensym-count}
2018 is 0 and is incremented every time a
2019 pretty name is generated. It might be set to any non-negative
2020 integer value.
2021
2022 \begin{verbatim}
2023 > (let ([x (gensym)])
2024 (parameterize ([gensym-count 100] [print-gensym #f])
2025 (pretty-print (list (gensym) x (gensym)))))
2026 (g100 g101 g102)
2027 \end{verbatim}
2028
2029 Notice from all the examples so far that pretty names are generated
2030 in the order at which the gensyms are printed, not in the order in
2031 which gensyms were created.
2032
2033 \newpage
2034 \section{Tracing}
2035
2036 \defun{trace-define}{syntax}
2037 \texttt{(trace-define (name . args) body body* ...)}\\
2038 \texttt{(trace-define name expression)}
2039
2040 The \texttt{trace-define} syntax is similar to \texttt{define}
2041 except that the bound value, which must be a procedure, becomes a
2042 traced procedure. A traced procedure prints its arguments when it
2043 is called and prints its values when it returns.
2044
2045 \begin{verbatim}
2046 > (trace-define (fact n)
2047 (if (zero? n) 1 (* n (fact (- n 1)))))
2048 > (fact 5)
2049 |(fact 5)
2050 | (fact 4)
2051 | |(fact 3)
2052 | | (fact 2)
2053 | | |(fact 1)
2054 | | | (fact 0)
2055 | | | 1
2056 | | |1
2057 | | 2
2058 | |6
2059 | 24
2060 |120
2061 120
2062 \end{verbatim}
2063
2064 The tracing facility in Ikarus preserves and shows tail recursion
2065 and distinguishes it from non-tail recursion by showing tail calls
2066 starting at the same line in which their parent was called.
2067
2068 \begin{verbatim}
2069 > (trace-define (fact n)
2070 (trace-define (fact-aux n m)
2071 (if (zero? n) m (fact-aux (- n 1) (* n m))))
2072 (fact-aux n 1))
2073 > (fact 5)
2074 |(fact 5)
2075 |(fact-aux 5 1)
2076 |(fact-aux 4 5)
2077 |(fact-aux 3 20)
2078 |(fact-aux 2 60)
2079 |(fact-aux 1 120)
2080 |(fact-aux 0 120)
2081 |120
2082 120
2083 \end{verbatim}
2084
2085 Moreover, the tracing facility interacts well with continuations and
2086 exceptions.
2087
2088 \begin{verbatim}
2089 > (call/cc
2090 (lambda (k)
2091 (trace-define (loop n)
2092 (if (zero? n)
2093 (k 'done)
2094 (+ (loop (- n 1)) 1)))
2095 (loop 5)))
2096 |(loop 5)
2097 | (loop 4)
2098 | |(loop 3)
2099 | | (loop 2)
2100 | | |(loop 1)
2101 | | | (loop 0)
2102 done
2103 \end{verbatim}
2104
2105
2106 \defun{trace-lambda}{syntax}
2107 \texttt{(trace-lambda name args body body* ...)}
2108
2109 The \texttt{trace-lambda} macro is similar to \texttt{lambda} except
2110 that the resulting procedure is traced: it prints the arguments it
2111 receives and the results it returns.
2112
2113 \newpage
2114
2115 \defun{make-traced-procedure}{procedure}
2116 \texttt{(make-traced-procedure name proc)}
2117
2118 The procedure \texttt{make-traced-procedure} takes a name (typically
2119 a symbol) and a procedure. It returns a procedure similar to
2120 \texttt{proc} except that it traces its arguments and values.
2121
2122 \begin{verbatim}
2123 > (define (fact n)
2124 (if (zero? n)
2125 (lambda (k) (k 1))
2126 (lambda (k)
2127 ((fact (- n 1))
2128 (make-traced-procedure `(k ,n)
2129 (lambda (v)
2130 (k (* v n))))))))
2131 > (call/cc
2132 (lambda (k)
2133 ((fact 5) (make-traced-procedure 'K k))))
2134 |((k 1) 1)
2135 |((k 2) 1)
2136 |((k 3) 2)
2137 |((k 4) 6)
2138 |((k 5) 24)
2139 |(K 120)
2140 120
2141 \end{verbatim}
2142
2143
2144 \newpage
2145 \section{Timing}
2146
2147 This section describes some of Ikarus's timing facilities which may
2148 be useful for benchmarking and performance tuning.
2149
2150 \defun{time}{syntax}
2151 \texttt{(time expression)}
2152
2153 The \texttt{time} macro performs the following: it evaluates
2154 \texttt{expression}, then prints a summary of the run time
2155 statistics, then returns the values returned by \texttt{expression}.
2156 The run-time summary includes the number of bytes allocated, the
2157 number of garbage collection runs, and the time spent in both the
2158 mutator and the collector.
2159
2160
2161 \begin{verbatim}
2162 > (let () ;;; 10 million
2163 (define ls (time (vector->list (make-vector 10000000))))
2164 (time (append ls ls))
2165 (values))
2166 running stats for (vector->list (make-vector 10000000)):
2167 3 collections
2168 672 ms elapsed cpu time, including 547 ms collecting
2169 674 ms elapsed real time, including 549 ms collecting
2170 120012328 bytes allocated
2171 running stats for (append ls ls):
2172 4 collections
2173 1536 ms elapsed cpu time, including 1336 ms collecting
2174 1538 ms elapsed real time, including 1337 ms collecting
2175 160000040 bytes allocated
2176 \end{verbatim}
2177
2178 Note: The output listed above is \emph{just a sample} that was
2179 taken at some point on some machine. The output on your
2180 machine at the time you read this may vary.
2181
2182 \newpage
2183 \defun{time-it}{procedure}
2184 \texttt{(time-it who thunk)}
2185
2186 The procedure \texttt{time-it} takes a datum denoting the name of
2187 the computation and a thunk (i.e. a
2188 procedure with no arguments), invokes the thunk, prints the stats,
2189 and returns the values obtained from invoking the thunk.
2190 If the value of \texttt{who} is non-false, \texttt{who}
2191 is used when displaying the run-time statistics. If the value of
2192 \texttt{who} is \texttt{\#f}, then no name for the computation is
2193 displayed.
2194
2195 \begin{verbatim}
2196 > (time-it "a very fast computation"
2197 (lambda () (values 1 2 3)))
2198 running stats for a very fast computation:
2199 no collections
2200 0 ms elapsed cpu time, including 0 ms collecting
2201 0 ms elapsed real time, including 0 ms collecting
2202 24 bytes allocated
2203 1
2204 2
2205 3
2206
2207 > (time-it #f (lambda () 12))
2208 running stats:
2209 no collections
2210 0 ms elapsed cpu time, including 0 ms collecting
2211 0 ms elapsed real time, including 0 ms collecting
2212 0 bytes allocated
2213 12
2214 \end{verbatim}
2215
2216 \chapter{The \texttt{(ikarus ipc)} library}
2217
2218 \ref{sec:environment-variables}
2219 \ref{sec:subprocess}
2220 \ref{sec:sockets}
2221
2222 \newpage
2223
2224 \section{\label{sec:environment-variables}Environment variables}
2225
2226 When the operating system starts a process, it starts the process in
2227 some environment that maps environment variables to values. Typical
2228 keys found in the environment are \texttt{HOME} (pointing to the
2229 home directory of the user), \texttt{PATH} (containing a
2230 colon-separated list of directories to be searched when running a
2231 command from the shell), \texttt{SHELL}, \texttt{EDITOR}, and
2232 \texttt{PAGER}. This section describes the procedures provided by
2233 Ikarus for manipulating this environment.
2234
2235 The environment procedures are placed in the \texttt{(ikarus~ipc)}
2236 library because they provide a (limited) way for one process to
2237 communicate to a subprocess, akin to parameter passing.
2238
2239 \defun{getenv}{procedure}
2240 \texttt{(getenv key)}
2241
2242 The procedure \texttt{getenv} retrieves the value associated with
2243 \texttt{key} (which must be a string) in the environment. The value
2244 returned is a (utf8-decoded) string, or \texttt{\#f} if there is no
2245 mapping for \texttt{key} in the environment.
2246
2247
2248 \defun{setenv}{procedure}
2249 \texttt{(setenv key value)}\\
2250 \texttt{(setenv key value overwrite?)}
2251
2252 The procedure \texttt{setenv} sets the mapping of \texttt{key} to
2253 \texttt{value} in the environment. Both \texttt{key} and
2254 \texttt{value} must be strings. If the \texttt{overwrite?} argument
2255 is provided and is \texttt{\#f}, \texttt{setenv} does not overwrite
2256 a value associated with \texttt{key} if one already exists. The
2257 procedure \texttt{setenv} may raise an exception if the operating
2258 system cannot allocate enough memory to hold the new mapping.
2259
2260 \defun{unsetenv}{procedure}
2261 \texttt{(unsetenv key)}
2262
2263 The procedure \texttt{unsetenv} removes \texttt{key} and its
2264 associated value (if one exists) from the environment.
2265
2266
2267 \BoxedText{Caveat:}{The underlying system procedure \texttt{setenv}
2268 may leak some memory in some operating systems when passed some
2269 values. Ikarus has no way of getting around this system limitation
2270 and thus may leak some memory for some calls to \texttt{setenv}.
2271 Use sparingly.}
2272
2273
2274 \newpage
2275 \section{\label{sec:subprocess}Subprocess communication}
2276
2277 This section describes the facilities that Ikarus provides for
2278 starting subprocesses and sending and receiving data through the
2279 subprocesses' standard input, output, and error ports.
2280
2281 \defun{system}{procedure}
2282 \texttt{(system string)}
2283
2284 The \texttt{system} procedure takes a string represeting an external
2285 shell command and arguments and invokes the shell (typically
2286 \texttt{sh} on Unix systems) on this command. The returned value
2287 from \texttt{system} is the exit status of the external command.
2288
2289 Ikarus's \texttt{system} procedure is a thin wrapper around the
2290 \texttt{system} procedure in the Standard C Library \texttt{libc}.
2291
2292 \begin{verbatim}
2293 > (system "ls M*")
2294 Makefile Makefile.am Makefile.in
2295 0
2296 \end{verbatim}
2297
2298 \defun{process}{procedure}
2299 \texttt{(process program-name args ...)}
2300
2301 The \texttt{process} procedure takes as input a string representing
2302 the path to an external program and a set of strings that are the
2303 arguments to the external program. It invokes the program with the
2304 given arguments, and returns four values: (1) a process identifier
2305 (\texttt{pid}),
2306 (2) an output port which pipes to the process's \texttt{stdin}, (3)
2307 an input port wired to the process's \texttt{stdout}, and (4) an
2308 input port wired to the process's \texttt{stderr}. All three ports
2309 are blocking: reading and writing to any one of them blocks Ikarus
2310 until the some bytes are available for reading or writing.
2311 Attempting to read from the process's \texttt{stdout} port may block
2312 indefinitely if the external program does not write anything
2313 (e.g.,~if it attempts to read from \texttt{stdin} instead).
2314 Communicating with an external process must therefore be done
2315 according to the protocol in which the external process
2316 communicates.
2317
2318 \defun{process-nonblocking}{procedure}
2319 \texttt{(process-nonblocking program-name args ...)}
2320
2321 The procedure \texttt{process-nonblocking} is similar to the
2322 \texttt{process} procedure except that the three returned ports are
2323 put in nonblocking mode. Attempting to perform a read or write
2324 operation on a nonblocking port in which bytes are not available for
2325 reading or writing causes Ikarus to enqueue the port with the
2326 continuation in which the read/write operation occurs and attempt to
2327 dispatch previously enqueued ports on which some bytes are ready for
2328 read or write. See Section~\ref{sec:sockets} for more details on
2329 blocking and nonblocking operations.
2330
2331
2332
2333
2334 \defun{waitpid}{procedure}
2335 \texttt{(waitpid)}\\
2336 \texttt{(waitpid pid)}\\
2337 \texttt{(waitpid pid block?)}\\
2338 \texttt{(waitpid pid block? want-error?)}
2339
2340 The \texttt{waitpid} procedure waits for the process with the given
2341 \texttt{pid} to terminate and, if successful, returns a
2342 \texttt{wstatus} object encapsulating the wait status of the
2343 process. Without arguments, \texttt{waitpid} defaults the
2344 \texttt{pid} to \texttt{-1} which allows one to wait for any child
2345 process to exit. If the \texttt{block?} argument is true (the
2346 default), \texttt{waitpid} blocks indefinitely waiting for a child
2347 process to exit. When \texttt{block?} is false, \texttt{waitpid}
2348 returns immediately regardless of whether or not a child process has
2349 exited. The \texttt{want-error?} controls what happens if
2350 \texttt{block?} was specified to be \texttt{\#f} and no child had
2351 exited. If \texttt{want-error?} is true (the default), an error is
2352 signaled. Otherwise, \texttt{waitpid} returns \texttt{\#f} if no
2353 process has exited. Operations on the wait status result are listed
2354 below.
2355
2356 \defun{wstatus-pid}{procedure}
2357 \texttt{(wstatus-pid wstatus)}
2358
2359 The \texttt{wstatus-pid} returns the \texttt{pid} of the process
2360 whose status is recorded in the \texttt{wstatus} object. This
2361 \texttt{pid} is most useful when the default \texttt{pid} of
2362 \texttt{-1} is given to \texttt{waitpid} and thus the pid of the
2363 exiting process is not known beforehand.
2364
2365
2366 \defun{wstatus-exit-status}{procedure}
2367 \texttt{(wstatus-exit-status wstatus)}
2368
2369 The procedure \texttt{wstatus-exit-status} returns the exit status
2370 of the child process. It is typically \texttt{0} if the child
2371 exited normally and has other numeric values if the child process
2372 encountered an error.
2373
2374 \defun{wstatus-received-signal}{procedure}
2375 \texttt{(wstatus-received-signal wstatus)}
2376
2377 The procedure \texttt{wstatus-received-signal} returns the
2378 name of the signal (or the number of the signal if the name is not
2379 known) that caused the child process to exit.
2380
2381 The signal name is one of the following symbols:
2382 \begin{verbatim}
2383 SIGABRT SIGALRM SIGBUS SIGCHLD SIGCONT SIGFPE SIGHUP
2384 SIGILL SIGINT SIGKILL SIGPIPE SIGQUIT SIGSEGV SIGSTOP
2385 SIGTERM SIGTSTP SIGTTIN SIGTTOU SIGUSR1 SIGUSR2 SIGPOLL
2386 SIGPROF SIGSYS SIGTRAP SIGURG SIGVTALRM SIGXCPU SIGXFSZ
2387 \end{verbatim}
2388
2389 \defun{kill}{procedure}
2390 \texttt{(kill pid signal-name)}
2391
2392 The \texttt{kill} procedure takes a \texttt{pid} and a signal name
2393 (a symbol from the list above) and asks the operating system to send
2394 the signal to the given process.
2395
2396
2397
2398
2399 \newpage
2400 \section{\label{sec:sockets}TCP and UDP sockets}
2401
2402 Ikarus supports synchronous (blocking) and asynchronous
2403 (multiplexing) communication facilities over both TCP/IP and UDP/IP
2404 channels. It facilitates writing client and server applications
2405 that serve a variety of purposes, e.g., web servers,
2406 char clients, mail, news, et cetera.
2407
2408 The synchronous model is simple and is ideal for noninteractive
2409 command-line applications that communicate with a single host at a
2410 time. FTP clients, HTTP spiders, and off-line netnews caching
2411 programs typically use synchronous communication. The basic
2412 operations start with connecting (via \texttt{tcp-connect}) to an
2413 internet service (identified by a port number or a service name)
2414 located on some host (identified by its host name or IP number). By
2415 connecting to a server, we obtain an input port and an output port
2416 forming bidirectional channel of communication. Depending on the
2417 service protocol, the client exchanges information with the server
2418 by reading and writing to the designated ports. Read and write
2419 operations in this model may block indefinitely until appropriate
2420 number of bytes are read/written, or until the operation times out.
2421 Communication ends when the client closes both ports.
2422
2423 The asynchronous model allows for communicating with many hosts
2424 simultaneously. Ikarus maintains a queue of pending ports, the
2425 blocking operation performed on these ports, and their respective
2426 continuations. Whenever the operating system indicates that a
2427 read/write operation may block, Ikarus schedules the port and a
2428 restarting continuation into the queue and then dispatches one of
2429 the \emph{ready} operations. This is reminiscent of how
2430 multitasking operating systems schedule I/O-bound threads, except
2431 that in Ikarus, threads are lightweight, represented by ordinary
2432 continuations. Thus, reading or writing to a nonblocking port
2433 causes Ikarus to transparently capture a continuation, enlist it in
2434 the queue, and dispatch another continuation captured earlier.
2435 Multiple read and write operations from multiple connections are
2436 fulfilled concurrently, dispatching whichever one is ready and
2437 without one operation blocking the rest.
2438
2439 Because asynchronous scheduling and dispatching involves switching
2440 continuations, winders that maintain the dynamic environment
2441 (e.g.,~those established by \texttt{dynamic-wind},
2442 \texttt{parameterize}, \texttt{with-output-to-file},
2443 \texttt{with-exception-handler}, etc.) are properly invoked when
2444 leaving a dynamic context and entering another. Care must be taken
2445 when using winders that perform externally-visible side effects upon
2446 entering/leaving a dynamic context.
2447
2448
2449 \defun{tcp-connect}{procedure}
2450 \texttt{(tcp-connect host service)}
2451
2452 The procedure \texttt{tcp-connect} attempts to connect to the
2453 \texttt{service} located on the remote \texttt{host} through the
2454 TCP/IP protocol. The \texttt{host} argument is a string
2455 representing either the IP address (e.g., \texttt{"127.0.0.1"}) or a
2456 fully-qualified domain name (e.g., \texttt{"www.example.com"}), in
2457 which case name to address resolution is performed automatically.
2458 The \texttt{service} argument is also a string which can be either a
2459 port number (e.g., \texttt{"80"}) or a service name (e.g.,
2460 \texttt{"http"}) in which case the service name is mapped to the
2461 canonical port number for the service.
2462
2463 Upon success, \texttt{tcp-connect} returns two values: a binary
2464 \emph{input} port and a binary \emph{output} port. Writing and
2465 reading from the obtained ports may block indefinitely until an
2466 appropriate number of bytes is read/written. Closing both ports
2467 closes the communication channel and frees the underlying
2468 operating-system resources.
2469
2470
2471 \defun{tcp-connect-nonblocking}{procedure}
2472 \texttt{(tcp-connect-nonblocking host service)}
2473
2474 The procedure \texttt{tcp-connect-nonblocking} is similar to
2475 \texttt{tcp-connect} except that the two returned ports are put in
2476 \emph{nonblocking} mode. If an attempt to perform a read (write)
2477 operation on the input (output) port may block, a restart
2478 continuation is captured and scheduled in the I/O queue and a
2479 perviously blocked operation may be restarted (when its blocking
2480 operation can progress).
2481
2482 \defun{udp-connect}{procedure}
2483 \texttt{(udp-connect host service)}
2484
2485 The procedure \texttt{udp-connect} is similar to
2486 \texttt{tcp-connect} except that it connects to the remote server
2487 through the UDP protocol (as implied by the name).
2488
2489 \defun{udp-connect-nonblocking}{procedure}
2490 \texttt{(udp-connect-nonblocking host-name service-name)}
2491
2492 The procedure \texttt{udp-connect-nonblocking} is similar to
2493 \texttt{tcp-connect-nonblocking} except that it connects to the
2494 remote server through the UDP protocol.
2495
2496
2497 \defun{tcp-server-socket}{procedure}
2498 \texttt{(tcp-server-socket port-number)}
2499
2500 The procedure \texttt{tcp-server-socket} attempts to \emph{listen}
2501 on the given port number for incoming connections. On success,
2502 \texttt{tcp-server-socket} returns an abstract \emph{tcp-server}
2503 object encapsulating the underlying operating-system server socket.
2504 The server socket is placed in \emph{blocking} mode: an attempt to
2505 accept a connection on such server blocks indefinitely
2506 until a remote client attempts to establish a connection.
2507
2508 \defun{tcp-server-socket-nonblocking}{procedure}
2509 \texttt{(tcp-server-socket-nonblocking port-number)}
2510
2511 This procedure is similar to \texttt{tcp-server-socket} except that
2512 the returned server socket is placed in \emph{nonblocking} mode. An
2513 attempt to accept a connection from a nonblocking server socket does
2514 not block the entire process, instead, a restarting continuation is
2515 scheduled and is invoked when an incoming connection is available
2516 (and another I/O-bound operation blocks).
2517
2518
2519 \defun{accept-connection}{procedure}
2520 \texttt{(accept-connection tcp-server)}
2521
2522 The procedure \texttt{accept-connection} takes a tcp-server socket
2523 (e.g., one obtained from \texttt{tcp-server-socket}) and returns two
2524 values: a binary \emph{input} port and a binary \emph{output} port
2525 through which the server communicates with the connecting client.
2526 If the \texttt{tcp-server} object is in blocking mode,
2527 \texttt{accept-connection} may block the entire process until an
2528 incoming connection is obtained. If the server is in nonblocking
2529 mode, an (otherwise) blocking operation would be rescheduled and
2530 invoked later when a connection occurs.
2531
2532 The input and output ports that \texttt{accept-connection} returns
2533 are put in blocking mode. .
2534
2535 \newpage
2536
2537 \defun{accept-connection-nonblocking}{procedure}
2538 \texttt{(accept-connection-nonblocking tcp-server)}
2539
2540 The procedure \texttt{accept-connection-nonblocking} is similar to
2541 \texttt{accept-connection} except that the two returned ports are
2542 put in nonblocking mode.
2543
2544 \defun{close-tcp-server-socket}{procedure}
2545 \texttt{(close-tcp-server-socket tcp-server)}
2546
2547 This procedure closing the server socket (so that no more incoming
2548 connections can be accepted) and frees the underlying
2549 operating-system resources associated with the socket.
2550
2551
2552 \defun{register-callback}{procedure}
2553 \texttt{(register-callback input-port thunk)}\\
2554 \texttt{(register-callback output-port thunk)}\\
2555 \texttt{(register-callback tcp-server thunk)}
2556
2557
2558 The procedure \texttt{register-callback} takes a nonblocking port or
2559 server socket and a callback procedure. It enqueues the port/socket
2560 and the thunk into the event queue. The given procedure is called
2561 when another I/O operation blocks and data is ready to be read (for
2562 an input port argument), written (for an output port argument), or
2563 an incoming connection is available (for a tcp-server argument).
2564 The \texttt{register-callback} procedure returns immediately. It
2565 does not block and does not attempt to perform any read, write, or
2566 accept operation on the given argument.
2567
2568
2569
2570
2571 \chapter{\label{chapter:foreign}The \texttt{(ikarus foreign)} library}
2572
2573
2574 This chapter describes the facilities through which Ikarus
2575 interfaces with the host operating system and other external
2576 libraries. The facilities of the \texttt{(ikarus~foreign)}
2577 library give the Scheme program unrestricted access to the computer
2578 memory, allowing one to allocate, access, modify, and free memory as
2579 needed. The facilities also allow the Scheme program to \emph{call
2580 out} to system procedures as well as allow the native procedures to
2581 \emph{call back} into Scheme.
2582
2583 This chapter is organized as follows: Section~\ref{sec:ffi-overview}
2584 gives an overview of the basic concepts such as shared libraries,
2585 external symbols, foreign data types, pointers, and procedures.
2586 Section~\ref{sec:ffi-memory} describes the primitives that
2587 \texttt{(ikarus~foreign)} provides for direct manipulation of
2588 memory. Section~\ref{sec:ffi-procedures} deals with loading
2589 external libraries and calling out to native library procedures and
2590 calling back into Scheme. To demonstrate the usefulness of the
2591 foreign facilities, Ikarus ships with two libraries that also serve
2592 as extended examples for using the system.
2593 Section~\ref{sec:ffi-opengl} describes The OpenGL library
2594 \texttt{(ikarus~opengl)} which allows the programmer to produce 2D
2595 and 3D computer graphics. Section~\ref{sec:ffi-objc} describes the
2596 \texttt{(ikarus~objc)} which allows the programmer to access
2597 libraries and frameworks written in the Objective-C programming
2598 language and thus provides full access to the Mac OS X system
2599 (e.g.,~making graphical user interfaces with Cocoa and drawing
2600 graphics with Quartz all from Scheme).
2601
2602 Ikarus version \texttt{0.0.4} is the first version of Ikarus to
2603 support the described foreign interfaces.
2604 \newpage
2605
2606 \section{\label{sec:ffi-overview}Overview}
2607
2608 In order to make full use of the computer, it is important for a
2609 programming environment (e.g., Ikarus Scheme) to facilitate access
2610 to the underlying architecture on which it runs. The underlying
2611 architecture includes the API provided by the host operating system
2612 kernel (e.g., Linux), the system libraries (e.g., \texttt{libc}),
2613 and other site-installed libraries (e.g., \texttt{sqlite3}).
2614 Providing direct access to such API from within Scheme allows the
2615 programmer to write Scheme libraries that have few or no
2616 dependencies on external programs (such as \texttt{C} development
2617 toolchain). When dealing with system libraries, the programmer
2618 must have a thorough understanding of many aspects of the targetted
2619 system. This section attempts to provide answers to many questions
2620 that are frequently encountered when interfacing to external
2621 libraries.
2622
2623
2624 \section{Memory management}
2625
2626 Ikarus Scheme is a managed environment. Like in many programming
2627 environments, Ikarus manages its own memory. Scheme objects are
2628 allocated in a special memory region (the Scheme heap) and have
2629 type-specific object layout that allows the run time system to
2630 distinguish object types and allows the garbage collector to locate
2631 all potentially live objects and reclaim the memory of dead objects.
2632 Scheme objects are also \emph{opaque} in the sense that the data
2633 structures used to represent Scheme objects (e.g., pairs) are not
2634 exposed to the programmer, who can only interact with objects
2635 through an interface (e.g., \texttt{car}, \texttt{cdr}).
2636
2637 Unmanaged environments, such as the operating system on which Ikarus
2638 runs, require that the programmer manages the allocation and
2639 deallocation of system resources herself. Memory regions, file
2640 handles, external devices, the screen, etc., are all examples of
2641 resources whose management must be coordinated among the different
2642 parts of the system, and this becomes the responsibility of the
2643 programmer who is wiring the different subsystems together.
2644
2645 Memory, from a system's point of view, is \emph{transparent}. A
2646 pointer is an integer denoting an address of memory. This memory
2647 address may contain a value that requires interpretation. At the
2648 lowest-level, each byte of memory contains eight bits, each of which
2649 may be toggled on or off. A level higher, contiguous sequences of
2650 bytes are grouped together and are interpreted as integers, floating
2651 point numbers, or pointers to other memory addresses. These are the
2652 basic data types that are often interpreted atomically. Yet a level
2653 higher, groups of basic types form data structures such as arrays,
2654 linked lists, trees, and so on. Objects, as found in
2655 object-oriented programming languages, are at an even higher level
2656 of abstraction since they are treated as opaque references that
2657 retain state and know how to respond to messages.
2658
2659 The procedures in the \texttt{(ikarus~foreign)} library are meant to
2660 provide a way to interface with the low level memory operations such
2661 as setting and getting bytes from specific locations in memory.
2662 Although they do not provide high-level operations, the basic
2663 procdures make implementing high-level operations (such as the
2664 Objective-C system presented in Chapter~\ref{chapter:objc})
2665 possible. Programmers are encouraged to define their own
2666 abstractions that are most suitable for the specific target library
2667 rather than using the low-level operations directly. This results
2668 in writing more robust and more easily maintainable libraries. To
2669 put it more boldly: \textbf{Do not sprinkle your code with low-level
2670 memory operations}.
2671
2672
2673 \section{\label{sec:ffi-memory}Memory operations}
2674
2675 \defun{malloc}{procedure}
2676 \texttt{(malloc n)}
2677
2678 The \texttt{malloc} procedure allocates \texttt{n} bytes of memory
2679 and returns a pointer to the allocated memory. The \texttt{malloc}
2680 Scheme procedure is implemented using the host-provided
2681 \texttt{malloc} system procedure (often found in \texttt{libc}).
2682 The number of bytes, \texttt{n}, must be a positive exact integer.
2683
2684 \begin{verbatim}
2685 > (malloc 10)
2686 #<pointer #x00300320>
2687 > (malloc 10000)
2688 #<pointer #x01800400>
2689 \end{verbatim}
2690
2691 \newpage
2692 \defun{free}{procedure}
2693 \texttt{(free p)}
2694
2695 The \texttt{free} procedure takes a pointer and frees the memory
2696 region at the given address. The memory region must be allocated
2697 with \texttt{malloc}, \texttt{calloc}, or a similar system
2698 procedure. Once freed, memory operations on the given address are
2699 invalid and may cause the system to crash at unpredictable times.
2700 Ikarus cannot check for such errors since the memory may be freed by
2701 procedures that are external to Ikarus.
2702
2703
2704
2705 \defun{pointer->integer}{procedure}
2706 \texttt{(pointer->integer p)}
2707
2708 The procedure \texttt{pointer->integer} converts the value of the
2709 pointer \texttt{p} to an exact integer value. The result may be a
2710 fixnum or a bignum depending on the pointer.
2711
2712 \defun{integer->pointer}{procedure}
2713 \texttt{(integer->pointer n)}
2714
2715 The procedure \texttt{integer->pointer} converts the exact integer
2716 \texttt{n} to a pointer value. The lower 32 bits (or 64 bits on
2717 64-bit systems) of the value of \texttt{n} are significant in
2718 computing the pointer value. It is guaranteed that
2719 \texttt{(integer->pointer (pointer->integer p))} points to the same
2720 address as \texttt{p}.
2721
2722 \defun{pointer?}{procedure}
2723 \texttt{(pointer? x)}
2724
2725 The predicate \texttt{pointer?} returns \texttt{\#t} if the value
2726 of \texttt{x} is a pointer, and returns \texttt{\#f} otherwise.
2727
2728 \BoxedText{Note:}{The result of calling the procedures
2729 \texttt{eq?}, \texttt{eqv?} and \texttt{equal?} on pointer values is
2730 unspecified.}
2731
2732
2733 \newpage
2734
2735 \defun{pointer-set-c-char!}{procedure}
2736 \texttt{(pointer-set-c-char! p i n)}
2737
2738 The procedure \texttt{pointer-set-c-char!} sets a single byte of memory
2739 located at offset \texttt{i} from the pointer \texttt{p} to the
2740 value of \texttt{n}. The pointer \texttt{p} must be a valid
2741 pointer. The index \texttt{i} must be an exact integer. The value
2742 of \texttt{n} must be an exact integer. Only the 8 lowermost
2743 bits of \texttt{n} are used in the operation and the remaining bits
2744 are ignored.
2745
2746 \defun{pointer-set-c-short!}{procedure}
2747 \texttt{(pointer-set-c-short! p i n)}
2748
2749 The procedure \texttt{pointer-set-c-char!!} sets two bytes located at
2750 offset \texttt{i} and \texttt{(+ i 1)} to the 16 lowermost bits of
2751 the exact integer \texttt{n}. Note that the offset \texttt{i} is a
2752 byte offset; \texttt{pointer-set-c-short!} does not perform any pointer
2753 arithmetic such as scaling the offset by the size of the memory
2754 location.
2755
2756
2757 \defun{pointer-set-c-int!}{procedure}
2758 \texttt{(pointer-set-c-int! p i n)}
2759
2760 The procedure \texttt{pointer-set-c-int!} sets four bytes located at
2761 offset \texttt{i} to \texttt{(+ i 3)} to the 32 lowermost bits of
2762 the exact integer \texttt{n}. Like \texttt{pointer-set-c-short!},
2763 \texttt{pointer-set-c-int!} does not scale the offset \texttt{i}.
2764
2765
2766 \defun{pointer-set-c-long!}{procedure}
2767 \texttt{(pointer-set-c-long! p i n)}
2768
2769 On 64-bit systems, the procedure \texttt{pointer-set-c-long!} sets
2770 eight bytes located at offset \texttt{i} to \texttt{(+ i 7)} to the
2771 64 lowermost bits of the exact integer \texttt{n}. Like the
2772 previous procedures, \texttt{pointer-set-c-long!} does not scale the
2773 offset \texttt{i}. On 32-bit systems, \texttt{pointer-set-c-long!}
2774 performs the same task as \texttt{pointer-set-c-int!}.
2775
2776
2777 \defun{pointer-set-c-float!}{procedure}
2778 \texttt{(pointer-set-c-float! p i fl)}
2779
2780 The procedure \texttt{pointer-set-c-float!} converts the Scheme
2781 floating point number \texttt{fl} (represented in Ikarus as an
2782 IEEE-754 double precision floating point number) to a float (an
2783 IEEE-754 single precision floating point number) and stores the
2784 result in the four bytes at offset \texttt{i} of the pointer
2785 \texttt{p}.
2786
2787 \defun{pointer-set-c-double!}{procedure}
2788 \texttt{(pointer-set-c-double! p i fl)}
2789
2790 The procedure \texttt{pointer-set-c-double!} stores the double
2791 precision IEEE-754 floating point value of the Scheme flonum
2792 \texttt{fl} in the eight bytes at offset \texttt{i} of the pointer
2793 \texttt{p}.
2794
2795 \defun{pointer-set-c-pointer!}{procedure}
2796 \texttt{(pointer-set-c-pointer! p i pv)}
2797
2798 On 64-bit systems, the procedure \texttt{pointer-set-c-pointer!} sets
2799 eight bytes located at offset \texttt{i} to \texttt{(+ i 7)} to the
2800 64-bit pointer value of \texttt{pv}. On 32-bit systems, the
2801 procedure \texttt{pointer-set-c-pointer!} sets four bytes located at
2802 offset \texttt{i} to \texttt{(+ i 3)} to the 32-bit pointer value of
2803 \texttt{pv}. Like the previous procedures,
2804 \texttt{pointer-set-c-pointer!} does not scale the offset \texttt{i}.
2805
2806
2807
2808 \defun{pointer-ref-c-signed-char}{procedure}
2809 \texttt{(pointer-ref-c-signed-char p i)}
2810
2811 The procedure \texttt{pointer-ref-c-signed-char} loads a single byte located
2812 at offset \texttt{i} from the pointer \texttt{p} and returns an
2813 exact integer representing the sign-extended integer value of that
2814 byte. The resulting value is in the range of $[-128, 127]$ inclusive.
2815
2816 \defun{pointer-ref-c-unsigned-char}{procedure}
2817 \texttt{(pointer-ref-c-unsigned-char p i)}
2818
2819 The procedure \texttt{pointer-ref-c-unsigned-char} loads a single byte
2820 located at offset \texttt{i} from the pointer \texttt{p} and returns
2821 an exact integer representing the unsigned integer value of that
2822 byte. The resulting value is in the range $[0, 255]$ inclusive.
2823
2824
2825 The following example shows the difference between
2826 \texttt{pointer-ref-c-signed-char} and
2827 \texttt{pointer-ref-c-unsigned-char}.
2828
2829
2830 \begin{verbatim}
2831 > (let ([p (malloc 3)])
2832 (pointer-set-c-char! p 0 #b01111111)
2833 (pointer-set-c-char! p 1 #b10000000)
2834 (pointer-set-c-char! p 2 #b11111111)
2835 (let ([result
2836 (list (pointer-ref-c-signed-char p 0)
2837 (pointer-ref-c-signed-char p 1)
2838 (pointer-ref-c-signed-char p 2)
2839 (pointer-ref-c-unsigned-char p 0)
2840 (pointer-ref-c-unsigned-char p 1)
2841 (pointer-ref-c-unsigned-char p 2))])
2842 (free p)
2843 result))
2844 (127 -128 -1 127 128 255)
2845 \end{verbatim}
2846
2847 \defun{pointer-ref-c-signed-short}{procedure}
2848 \texttt{(pointer-ref-c-signed-short p i)}
2849
2850 The procedure \texttt{pointer-ref-c-signed-short} loads two bytes
2851 located at offsets \texttt{i} and \texttt{(+ i 1)} from the pointer
2852 \texttt{p} and returns an exact integer representing the
2853 sign-extended
2854 integer value of the sequence. The resulting value is in the range
2855 $[-32768, 32767]$ inclusive.
2856
2857 \defun{pointer-ref-c-unsigned-short}{procedure}
2858 \texttt{(pointer-ref-c-unsigned-short p i)}
2859
2860 The procedure \texttt{pointer-ref-c-unsigned-short} loads two bytes
2861 located at offsets \texttt{i} and \texttt{(+ i 1)} from the pointer
2862 \texttt{p} and returns an exact integer representing the unsigned
2863 integer value of the sequence. The resulting value is in the range
2864 $[0, 65535]$ inclusive.
2865
2866 \newpage
2867 \defun{pointer-ref-c-signed-int}{procedure}
2868 \texttt{(pointer-ref-c-signed-int p i)}
2869
2870 The procedure \texttt{pointer-ref-c-signed-int} loads four bytes
2871 starting at offset \texttt{i} of pointer \texttt{p} and returns an
2872 exact integer in the range of $[-2^{31},2^{31}-1]$ inclusive.
2873
2874
2875 \defun{pointer-ref-c-unsigned-int}{procedure}
2876 \texttt{(pointer-ref-c-unsigned-int p i)}
2877
2878 The procedure \texttt{pointer-ref-c-unsigned-int} loads four bytes
2879 starting at offset \texttt{i} of pointer \texttt{p} and returns an
2880 exact integer in the range of $[0,2^{32}-1]$ inclusive.
2881
2882
2883 \defun{pointer-ref-c-signed-long}{procedure}
2884 \texttt{(pointer-ref-c-signed-long p i)}
2885
2886 On 64-bit systems, the procedure \texttt{pointer-ref-c-signed-long}
2887 loads eight bytes starting at offset \texttt{i} of pointer
2888 \texttt{p} and returns an integer in the range of
2889 $[-2^{63},2^{63}-1]$ inclusive. On 32-bit systems, the procedure
2890 \texttt{pointer-ref-c-signed-long} performs the same task as
2891 \texttt{pointer-ref-c-signed-int}.
2892
2893
2894 \defun{pointer-ref-c-unsigned-long}{procedure}
2895 \texttt{(pointer-ref-c-unsigned-long p i)}
2896
2897 On 64-bit systems, the procedure \texttt{pointer-ref-c-unsigned-long}
2898 loads eight bytes starting at offset \texttt{i} of pointer
2899 \texttt{p} and returns an integer in the range of
2900 $[0,2^{64}-1]$ inclusive. On 32-bit systems, the procedure
2901 \texttt{pointer-ref-c-unsigned-long} performs the same task as
2902 \texttt{pointer-ref-c-unsigned-int}.
2903
2904
2905 \defun{pointer-ref-c-float}{procedure}
2906 \texttt{(pointer-ref-c-float p i)}
2907
2908 The procedure \texttt{pointer-ref-c-float} returns the four-byte
2909 float (represented as IEEE-754 single precision floating point
2910 number) stored at offset \texttt{i} of the pointer \texttt{p}.
2911 The value is extended to an IEEE-754 double precision floating
2912 point number that Ikarus uses to represent inexact numbers.
2913
2914 \defun{pointer-ref-c-double}{procedure}
2915 \texttt{(pointer-ref-c-double p i)}
2916
2917 The procedure \texttt{pointer-ref-c-double} returns the eight-byte
2918 float (represented as IEEE-754 double precision floating point
2919 number) stored at offset \texttt{i} of the pointer \texttt{p}.
2920
2921
2922 \defun{pointer-ref-c-pointer}{procedure}
2923 \texttt{(pointer-ref-c-pointer p i)}
2924
2925 The procedure \texttt{pointer-ref-c-pointer} returns the pointer
2926 stored at offset \texttt{i} from the pointer \texttt{p}. The size
2927 of the pointer (also the number of bytes loaded) depends on the
2928 architecture: it is 4 bytes on 32-bit systems and 8 bytes on 64-bit
2929 systems.
2930
2931 \section{\label{sec:foreign-objects}Accessing foreign objects from
2932 Scheme}
2933
2934
2935 \defun{dlopen}{procedure}
2936 \texttt{(dlopen)}\\
2937 \texttt{(dlopen library-name)}\\
2938 \texttt{(dlopen library-name lazy? global?)}
2939
2940 The procedure \texttt{dlopen} takes a string \texttt{library-name}
2941 represented a system library and calls the system procedure
2942 \texttt{dlopen} which dynamically loads the given library into the
2943 running process. The name of the library is system-dependent and
2944 must include the appropriate suffix (e.g., \texttt{*.so} on Linux,
2945 \texttt{*.dylib} on Darwin and \texttt{*.dll} on Cygwin). The
2946 \texttt{library-name} may include a full path which identifies the
2947 location of the library, or may be just the name of the library in
2948 which case the system will lookup the library name using the
2949 \texttt{LD\_LIBRARY\_PATH} environment variable.
2950
2951 The argument \texttt{lazy?} specifies how library dependencies are
2952 loaded. If true, \texttt{dlopen} delays the resolution and loading
2953 of dependent libraries until they are actually used. If false, all
2954 library dependencies are loaded before the call to \texttt{dlopen}
2955 returns.
2956
2957 The argument \texttt{global?} specifies how the scope of the symbols
2958 exported from the loaded library. If true, all exported symbols
2959 become part of the running image, and subsequent \texttt{dlsym}
2960 calls may not need to specify the library from which the symbol is
2961 loaded. If false, the exported symbols are not global and the
2962 library pointer needs to be specified for \texttt{dlsym}.
2963
2964 Calling \texttt{(dlopen library-name)} is equivalent to
2965 \texttt{(dlopen library-name \#f \#f)}. Calling \texttt{(dlopen)}
2966 without arguments returns a pointer to the current process.
2967
2968 If succesful, \texttt{dlopen} returns a pointer to the external
2969 library which can be used subsequently by \texttt{dlsym} and
2970 \texttt{dlclose}. If the library cannot be loaded, \texttt{dlopen}
2971 returns \texttt{\#f} and the procedure \texttt{dlerror} can be used
2972 to obtain the cause of the failure.
2973
2974 Consult the \texttt{dlopen(3)} page in your system manual for
2975 further details.
2976
2977 \defun{dlclose}{procedure}
2978 \texttt{(dlclose library-pointer)}
2979
2980 The procedure \texttt{dlclose} is a wrapped around the system
2981 procedure with the same name. It receives a library pointer
2982 (e.g.,~one obtained from \texttt{dlopen}) and releases the resources
2983 loaded from that library. Closing a library renders all symbols and
2984 static data structures that the library exports invalid and the
2985 program may crash or corrupt its memory if such symbols are used
2986 after a library is closed.
2987
2988 Most system implementations of dynamic loading employ reference
2989 counting for \texttt{dlopen} and \texttt{dlclose} in that library
2990 resources are not freed until the number of calls to
2991 \texttt{dlclose} matches the number of calls to \texttt{dlopen}.
2992
2993 The procedure \texttt{dlclose} returns a boolean value indicating
2994 whether the success status of the operation. If \texttt{dlclose}
2995 returns \texttt{\#f}, the procedure \texttt{dlerror} can be used to
2996 obtain the cause of the error.
2997
2998 Consult the \texttt{dlclose(3)} page in your system manual for
2999 further details.
3000
3001 \defun{dlerror}{procedure}
3002 \texttt{(dlerror)}
3003
3004 If any of the dynamic loading operations (i.e., \texttt{dlopen},
3005 \texttt{dlclose}, \texttt{dlsym}) fails, the cause of the error can
3006 be obtained by calling \texttt{dlerror} which returns a string
3007 describing the error. The procedure \texttt{dlerror} returns
3008 \texttt{\#f} if there was no dynamic loading error.
3009
3010 Consult the \texttt{dlerror(3)} page in your system manual for
3011 further details.
3012
3013 \defun{dlsym}{procedure}
3014 \texttt{(dlsym library-pointer string)}
3015
3016 The procedure \texttt{dlsym} takes a library pointer (e.g., one
3017 obtained by a call to \texttt{dlopen}) and a string representing the
3018 name of a symbol that the library exports and returns a pointer to
3019 the location of that symbol in memory. If \texttt{dlsym} fails, it
3020 returns \texttt{\#f} and the cause of the error can be obtained
3021 using the procedure \texttt{dlerror}.
3022
3023 Consult the \texttt{dlsym(3)} page in your system manual for
3024 further details.
3025
3026
3027 \section{\label{sec:callout}Calling out to foreign procedures}
3028
3029 Ikarus provides the means to call out from Scheme to foreign
3030 procedures. This allows the programmers to extend Ikarus to access
3031 system-specific facilities that is available on the host machine.
3032
3033 In order to call out to a foreign procedure, one must provide two
3034 pieces of information: the signature of the foreign procedure (e.g.,
3035 its type declaration if it is a \texttt{C} procedure) and the
3036 address of the procedure in memory. The address of the procedure
3037 can be easily obtained using \texttt{dlsym} if the name of the
3038 procedure and its exporting library are known. The signature of the
3039 procedure cannot, in general, be obtained dynamically, and therefore
3040 must be hard coded into the program.
3041
3042 The signature of the foreign procedure is required for proper
3043 linkeage between the Scheme system and the foreign system. Using
3044 the signature, Ikarus determines how Scheme values are converted
3045 into native values, and where (e.g., in which registers and stack
3046 slots) to put these arguments. The signature also determines where
3047 the returned values are placed and how they are converted from the
3048 system data types to the corresponding Scheme data types.
3049
3050 A procedure's signature is composed of two parts: the return type
3051 and the parameter types. The return type is a symbol that can be
3052 any one of the type specifiers listed in
3053 Figure~\ref{fig:foreign-types}, page~\pageref{fig:foreign-types}.
3054 The parameter types is a list of type specifier symbols. The symbol
3055 \texttt{void} can appear as a return type but cannot appear as a
3056 parameter type.
3057
3058
3059
3060 \defun{make-c-callout}{procedure}
3061 \texttt{((make-c-callout return-type parameter-types) native-pointer)}
3062
3063 The procedure \texttt{make-c-callout} is the primary facility for
3064 making foreign procedures callable from Scheme. It works as
3065 follows. First, \texttt{make-c-callout} receives two arguments
3066 denoting the signature of the procedure to be called. It prepares a
3067 bridge that converts from Scheme's calling conventions and data
3068 structures to their foreign counterparts. It returns a procedure
3069 $p_1$. Second, the procedure $p_1$ accepts a pointer to a foreign
3070 procedure (e.g., one obtained from \texttt{dlsym}) and returns a
3071 Scheme procedure $p_2$ that encapsulates the foreign procedure. The
3072 final procedure $p_2$ can be called with as many arguments as the
3073 ones specified in the \texttt{parameter-types}. The parameters
3074 supplies to $p_2$ must match the types supplied as the
3075 \texttt{parameter-types} according to the ``Valid Scheme types''
3076 column in the table in Figure~\ref{fig:foreign-types}. The
3077 procedure $p_2$ converts the parameters from Scheme types to native
3078 types, calls the foreign procedure, obtains the result, and converts
3079 it to the appropriate Scheme value (depending on the
3080 \texttt{return-type}).
3081
3082 The interface of \texttt{make-c-callout} is broken down into three
3083 stages in order to accomodate common usage patterns. Often types, a
3084 function signature can be used by many foreign procedures and
3085 therefore, \texttt{make-c-callout} can be called once per signature
3086 and each signature can be used multiple times. Similarly,
3087 separating the foreign procedure preparation from parameter passing
3088 allows for preparing the foreign procedure once and calling it many
3089 times.
3090
3091 The types listed in Figure~\ref{fig:foreign-types} are restricted to
3092 basic types and provide no automatic conversion from composite
3093 Scheme data structures (such as strings, symbols, vectors, and
3094 lists) to native types. The restriction is intentional in order for
3095 Ikarus to avoid making invalid assumptions about the memory
3096 management of the targeted library. For example, while Ikarus
3097 \emph{can} convert a Scheme string to a native byte array (e.g.,
3098 using \texttt{string->bytevector} to decode the string, then using
3099 \texttt{malloc} to allocate a temporary buffer, and copying the
3100 bytes from the bytevector to the allocated memory), it cannot decide
3101 when this allocated byte array is no longer needed and should be
3102 freed. This knowledge is library-dependent and is often
3103 procedure-dependent. Therefore, Ikarus leaves it to the programmer
3104 to manage all memory related issues.
3105
3106 Outgoing parameters to foreign procedures are checked against the
3107 declared types. For example, if a callback is prepared to expect a
3108 parameter of type \texttt{signed-int}, only exact integers are
3109 allowed to be passed out. For integer types, only a fixed number of
3110 bits is used and the remaining bits are ignored. For floating point
3111 types, the argument is checked to be a Scheme flonum. No implicit
3112 conversion between exact and inexact numbers is performed.
3113 {
3114 \begin{figure}[b!]
3115 \begin{center}
3116 \begin{tabular}{@{}llll@{}}
3117 \hline
3118 Type specifier & Size & Valid Scheme types & Corresponding \texttt{C} types\\
3119 \hline
3120 \texttt{signed-char} & 1 byte & exact integer & \texttt{char}\\
3121 \texttt{unsigned-char} & 1 byte & exact integer & \texttt{unsigned char}\\
3122 \texttt{signed-short} & 2 bytes & exact integer & \texttt{short}\\
3123 \texttt{unsigned-short} & 2 bytes & exact integer & \texttt{unsigned short}\\
3124 \texttt{signed-int} & 4 bytes & exact integer & \texttt{int}\\
3125 \texttt{unsigned-int} & 4 bytes & exact integer & \texttt{unsigned int}\\
3126 \texttt{signed-long} & 4/8 bytes & exact integer & \texttt{long}\\
3127 \texttt{unsigned-long} & 4/8 bytes & exact integer & \texttt{unsigned long}\\
3128 \texttt{float} & 4 bytes & flonum & \texttt{float}\\
3129 \texttt{double} & 8 bytes & flonum & \texttt{double}\\
3130 \texttt{pointer} & 4/8 bytes & pointer &
3131 \texttt{void*}, \texttt{char*}, \texttt{int*}, \texttt{int**}, \\
3132 &&& \texttt{int(*)(int,int,int)}, etc. \\
3133 \texttt{void} & -- & -- & \texttt{void}\\
3134 \hline
3135 \end{tabular}
3136 \end{center}
3137 \caption{\label{fig:foreign-types}The above table lists valid type
3138 specifiers that can be used in callout and callback signatures.
3139 Specifiers with ``4/8 bytes'' have size that depends on the system:
3140 it is 4 bytes on 32-bit systems and 8 bytes on 64-bit systems. The
3141 \texttt{void} specifier can only be used as a return value
3142 specifier to mean ``no useful value is returned''.}
3143 \end{figure}
3144 }
3145
3146
3147 The following example illustrates the use of the
3148 \texttt{make-c-callout} procedure in combination with \texttt{dlopen}
3149 and \texttt{dlsym}. The session was run on a 32-bit Ikarus running
3150 under Mac OS X 10.4. First, the \texttt{libc.dylib} foreign library
3151 is loaded and is bound to the variable \texttt{libc}. Next, we
3152 obtain a pointer to the \texttt{atan} foreign procedure that is
3153 defined in \texttt{libc}. The native procedure \texttt{atan} takes
3154 a \texttt{double} as an argument and returns a \texttt{double} and
3155 that's the signature that we use for \texttt{make-c-callout}.
3156 Finally, we call the foreign procedure interface with one argument,
3157 \texttt{1.0}, which is a flonum and thus matches the required
3158 parameter type. The native procedure returns a \texttt{double}
3159 value which is converted to the Scheme flonum with value
3160 \texttt{0.7853981633974483}.
3161
3162 \begin{verbatim}
3163 > (import (ikarus foreign))
3164 > (define libc (dlopen "libc.dylib"))
3165 > libc
3166 #<pointer #x00100770>
3167 > (define libc-atan-ptr (dlsym libc "atan"))
3168 > libc-atan-ptr
3169 #<pointer #x9006CB1F>
3170 > (define libc-atan
3171 ((make-c-callout 'double '(double)) libc-atan-ptr))
3172 > libc-atan
3173 #<procedure>
3174 > (libc-atan 1.0)
3175 0.7853981633974483
3176 > (libc-atan 1)
3177 Unhandled exception
3178 Condition components:
3179 1. &assertion
3180 2. &who: callout-procedure
3181 3. &message: "argument does not match type double"
3182 4. &irritants: (1)
3183 \end{verbatim}
3184
3185
3186 \section{\label{sec:callback}Calling back to Scheme}
3187
3188 In order to provide full interoperability with native procedures,
3189 Ikarus allows native procedures to call back into Scheme just as it
3190 allows Scheme to call out to native procedures. This is important
3191 for many system libraries that provide graphical user interfaces
3192 with event handling (e.g., Cocoa, GTK+, GLUT, etc.), database
3193 engines (e.g., libsqlite, libmysql, etc.), among others.
3194
3195 The native calling site for the call back is compiled with a
3196 specific callback signature encoding the expected parameter types
3197 and return type. Therefore, a Scheme procedure used for a call back
3198 must be wrapped with a proper adapter that converts the incoming
3199 parameters from native format to Scheme values as well as convert
3200 the value that the Scheme procedure returns back to native format.
3201 The signature format is similar to the one used for call outs (see
3202 Figure~\ref{fig:foreign-types} on page~\pageref{fig:foreign-types} for
3203 details).
3204
3205
3206 \defun{make-c-callback}{procedure}
3207 \texttt{((make-c-callback return-type parameter-types) scheme-procedure)}
3208
3209 The procedure \texttt{make-c-callback} is similar to the procedure
3210 \texttt{make-c-callout} except that it provides a bridge from native
3211 procedures back into Scheme. While the procedure
3212 \texttt{make-c-callout} takes a native pointer and returns a Scheme
3213 procedure, \texttt{make-c-callback} takes a Scheme procedure and
3214 returns a native pointer. The native pointer can be called by
3215 foreign procedures. The native parameters are converted to Scheme
3216 data (according to \texttt{parameter-types}), the Scheme procedure
3217 is called with these parameters, and the returned value is converted
3218 back into native format (according to \texttt{return-type}) before
3219 control returns to the native call site.
3220
3221
3222 Note that the native procedure pointer obtained from
3223 \texttt{make-c-callback} is indistinguishable from other native
3224 procedures that are obtained using \texttt{dlsym} or similar means.
3225 In particular, such native pointers can be passed to
3226 \texttt{make-c-callout} resulting in a Scheme procedure that calls out
3227 to the native procedure that in turn calls back into Scheme. The
3228 following segment illustrates a very inefficient way of extracting
3229 the lowermost 32 bits from an exact integer.
3230
3231 \begin{verbatim}
3232 > (format "~x"
3233 (((make-c-callout 'unsigned-int '(unsigned-int))
3234 ((make-c-callback 'unsigned-int '(unsigned-int))
3235 values))
3236 #xfedcba09876543210fedcba09876543210))
3237 "76543210"
3238 \end{verbatim}
3239
3240 \BoxedText{Caveat emptor:}{Preparing each call out and call back
3241 procedure leaks a small amount of memory. This is because the
3242 system cannot track such pointers that go into native code
3243 (which may retain such pointers indefinitely). Use judiciously.}
3244
3245
3246 \nocite{ghuloum-implicit}
3247 \nocite{ghuloum-generation}
3248
3249
3250
3251
3252 \appendix
3253 \chapter{Missing Features}
3254
3255 Ikarus does not fully conform to \rnrs{6} yet. Although it
3256 implements most of \rnrs{6}'s macros and procedures, some are still
3257 missing. This section summarizes the set of missing features and
3258 procedures.
3259
3260
3261 \begin{itemize}
3262 \item \texttt{number->string} does not accept the third argument
3263 (precision). Similarly, \texttt{string->number} and the reader do
3264 not recognize the \texttt{|p} notation.
3265
3266
3267 \item The following procedures are missing from \texttt{(rnrs arithmetic
3268 bitwise)}:
3269 \begin{Verbatim}
3270 bitwise-reverse-bit-field bitwise-rotate-bit-field
3271 \end{Verbatim}
3272
3273 \item The following procedures are missing from \texttt{(rnrs arithmetic
3274 fixnum)}:
3275 \begin{Verbatim}
3276 fxreverse-bit-field fxrotate-bit-field
3277 \end{Verbatim}
3278
3279
3280 \item The following procedures are missing from \texttt{(rnrs hashtables)}:
3281 \begin{Verbatim}
3282 equal-hash
3283 \end{Verbatim}
3284
3285 \item The following procedures are missing from \texttt{(rnrs io ports)}:
3286 \begin{Verbatim}
3287 make-custom-binary-input/output-port
3288 make-custom-textual-input/output-port
3289 open-file-input/output-port
3290 \end{Verbatim}
3291
3292 \end{itemize}
3293
3294 \newpage
3295
3296 \backmatter
3297 %\appendix
3298 \phantomsection
3299 %\addcontentsline{toc}{chapter}{Bibliogaraphy}
3300 \addcontentsline{toc}{chapter}{\bibname}
3301 \bibliographystyle{plain}
3302 \bibliography{ikarus-scheme-users-guide}
3303 \newpage
3304 \phantomsection
3305 \addcontentsline{toc}{chapter}{Index}
3306 \printindex
3307 \end{document}
3308
3309
3310
3311
3312
3313