Debian Codegraph @

src/doc/old-manual/ecldev.xmlf

raw
1 <?xml version="1.0" encoding="utf-8"?>
2 <!DOCTYPE book [
3 <!ENTITY % eclent SYSTEM "ecl.ent">
4 %eclent;
5 ]>
6 <book xmlns="http://docbook.org/ns/docbook" version="5.0" xml:lang="en">
7 <chapter xml:id="Internals">
8 <title>Internals</title>
9 <para>&ECL; is an implementation of the Common-Lisp language that is based on a kernel
10 written in C plus a set of libraries written in Common-Lisp. The kernel includes a
11 bytecodes compiler, an interpreter, and enough functions to create and
12 manipulate all lisp objects. The lisp libraries provide higher level constructs
13 such as macro definitions, LOOPs, an implementation of CLOS, and a translator
14 from Lisp to C.</para>
15 <para>As a result of this design, which dates back to the Kyoto CL and was later
16 improved in Giuseppe Attardi's ECoLisp, &ECL; can be used as</para>
17 <itemizedlist mark="bullet">
18 <listitem>
19 <para>As a standalone implementation of the Common-Lisp language</para>
20 </listitem>
21 <listitem>
22 <para>As an embedded interpreter subject to the control of a larger C program.</para>
23 </listitem>
24 <listitem>
25 <para>As a Common-Lisp environment with C/C++ extensions.</para>
26 </listitem>
27 </itemizedlist>
28 <para role="continues">This manual describes the facility of &ECL; to interface the C language and
29 &ECL;. With this facility, the user can arrange his or her C-language
30 programs so that they can be invoked from &ECL;. In addition, the user can
31 write Lisp function definitions in the C language to increase runtime
32 efficiency.</para>
33
34 <section xml:id="Building-programs">
35 <title>Building programs</title>
36 <para>In this section we describe how you can use &ECL; to build programs and
37 loadable extensions that you can later on distribute to other people.</para>
38
39 <sect1 label="2.1" xml:id="What-can-ECL-do-">
40 <title>What can &ECL; do?</title>
41 <para>Some day for some reasons you will be in the need to distribute code that
42 has been developed using &ECL;. In the following sections we will describe
43 the means that &ECL; offers you to do so. Basically, these are the
44 alternatives</para>
45 <variablelist>
46 <varlistentry>
47 <term>Source code</term>
48 <listitem>
49 <para>You distribute your programs in source code form. This is the easiest and most
50 portable way, but not the fastest one.</para>
51 </listitem>
52 </varlistentry>
53 <varlistentry>
54 <term>Standalone programs</term>
55 <listitem>
56 <para>You translate all your lisp code to C using the &ECL; compiler. The final
57 object files can be linked against other C/C++ libraries to obtain a standalone
58 executable.</para>
59 </listitem>
60 </varlistentry>
61 <varlistentry>
62 <term>You can build statically and dynamically linked libraries.</term>
63 <listitem>
64 <para>You translate all your lisp code to C and combine the resulting object files
65 into a single library with <filename>.a</filename> extension. You can distribute this library
66 to other people and the final users can utilize these libraries to build
67 standalone programs.</para>
68 </listitem>
69 </varlistentry>
70 <varlistentry>
71 <term>You can build dynamically loadable files.</term>
72 <listitem>
73 <para>This is the most flexible way. You translate all lisp code to C and link it
74 against possibly other C/C++ libraries to obtain a dynamically loadable library
75 (file type <filename>.so</filename> under unix). This library can be loaded a startup time to
76 add new functionality to the &ECL; environment.</para>
77 </listitem>
78 </varlistentry>
79 </variablelist>
80 <para>In several of these options, we have mentioned the possibility to include C/C++
81 code. Even if this is possible, you cannot use ordinary C/C++ compilers and
82 makefiles to build &ECL; extensions, let it be programs or
83 libraries. Briefly, you have to organize your code as follows</para>
84 <orderedlist numeration="arabic">
85 <listitem>
86 <para>Organize the C code as a library, let it be static or dynamic.</para>
87 </listitem>
88 <listitem>
89 <para>Build a function, say <literal>mymain()</literal>, in which the initialization phase
90 for your library is performed.</para>
91 </listitem>
92 <listitem>
93 <para>Group the code that interfaces to Lisp in separate C files, all of which
94 should include <literal>#include &lt;ecl/ecl.h&gt;</literal> at the beginning.</para>
95 </listitem>
96 <listitem>
97 <para>Compile your lisp source files.</para>
98 </listitem>
99 <listitem>
100 <para>Let &ECL; build the final executable or library.</para>
101 </listitem>
102 </orderedlist>
103 <para role="continues">In the final step there are ways to instruct &ECL; to call your
104 initialization function (<literal>mymain()</literal> in the example above). These means
105 are explained in the following sections.</para>
106 <!-- -->
107 </sect1>
108
109 <sect1 label="2.2" xml:id="Compiling-files">
110 <title>Compiling files</title>
111 <para>&ECL; supports two types of compilation. One is bytecodes compilation. This
112 process is performed on-the-fly, as you load source files with lisp code. This
113 leads to a series of bytes for each instruction, the so called
114 "bytecodes". These bytecodes are interpreted in a virtual machine, which is
115 written in C and which is reasonably fast.</para>
116 <para>The other type of compilation is the so-called "native" compilation. This
117 process consists on translating the lisp source file to C language. The
118 intermediate file is later compiled using a C compiler. The result is an object
119 file which may have different purposes.</para>
120 <variablelist>
121 <varlistentry>
122 <term>Dynamically loadable files or FASL (FASt Loadable) files</term>
123 <listitem>
124 <para>These are produced in a &ECL; built with support for dynamically loadable
125 libraries (Feature <replaceable>:DLOPEN</replaceable> is in <replaceable>*features*</replaceable>), when no extra
126 arguments are passed to <literal>compile-file</literal>. These object files typically have
127 the <filename>.fas</filename> extension, and can be loaded with <literal>load</literal>. They cannot be used
128 to build libraries nor standalone executable programs.</para>
129 </listitem>
130 </varlistentry>
131 <varlistentry>
132 <term>linkable object files</term>
133 <listitem>
134 <para>These are produced when invoking <literal>compile-file</literal> with the keyword argument
135 <replaceable>:system-p</replaceable> set to true. The object file typically has the <filename>.o</filename>
136 extension. It cannot be loaded with <literal>load</literal>, but it can be used to build
137 libraries, standalone executable programs, or larger FASL files.</para>
138 </listitem>
139 </varlistentry>
140 </variablelist>
141 <!-- -->
142 </sect1>
143
144 <sect1 label="2.3" xml:id="Building-standalone-executables">
145 <title>Building standalone executables</title>
146 <para>To build an executable you need a working &ECL; image with the
147 compiler. The function to build customized images is
148 <replaceable>c::build-program</replaceable>. The description of this function is as
149 follows. Care should be taken that <replaceable>image-name</replaceable> differs from any
150 filename in <replaceable>lisp-files</replaceable>.</para>
151 <blockquote>
152 <screen><indexterm role="fn"><primary>c:build-program</primary></indexterm>&#151; Function: <function>c:build-program</function> <varname>{</varname><varname>image-name</varname> <varname>&amp;key</varname> <varname>lisp-files</varname> <varname>ld-flags</varname> <varname>prologue-code</varname> <varname>epilogue-code</varname><varname>}</varname></screen>
153 <para>This function builds a lisp image up from the core lisp library, plus all
154 components listed in <replaceable>lisp-files</replaceable>. Each component is either:</para>
155 <itemizedlist mark="bullet">
156 <listitem>
157 <para>A symbol: Names a statically linked library built from lisp code.</para>
158 </listitem>
159 <listitem>
160 <para>A string: Denotes an object file built from lisp code.</para>
161 </listitem>
162 </itemizedlist>
163 <para role="continues"><replaceable>ld-flags</replaceable> is a list of strings with additional parameters to be passed
164 to the linker. You can include here your favorite C/C++ libraries.</para>
165 <para><replaceable>prologue-code</replaceable> and <replaceable>epilogue-code</replaceable> are used to customize the
166 initialization process of the lisp image. In order to build the executable,
167 <replaceable>c:build-program</replaceable> first writes down a piece of C code which initializes the
168 lisp environment. You can customize the initialization process by suppling code
169 to be executed before (<replaceable>prologue-code</replaceable>) or after (<replaceable>epilogue-code</replaceable>)
170 setting up the lisp environment. Typically <replaceable>prologue-code</replaceable> defaults to an
171 empty string, while <replaceable>epilogue-code</replaceable> invokes the classical lisp
172 <replaceable>top-level</replaceable>. Additionally, as a convenience, <replaceable>epilogue-code</replaceable> can
173 be either a string with C code or also a list with a lisp form, which
174 will be interpreted at run time.</para>
175 </blockquote>
176 <!-- -->
177 </sect1>
178
179 <sect1 label="2.4" xml:id="Building-libraries">
180 <title>Building libraries</title>
181 <para>To build a library you proceed more or less the same way as with standalone
182 executables. There are two different functions depending on whether you need
183 to build static or shared libraries.</para>
184 <blockquote>
185 <screen><indexterm role="fn"><primary>c:build-static-library</primary></indexterm>&#151; Function: <function>c:build-static-library</function> <varname>{</varname><varname>library-name</varname> <varname>&amp;key</varname> <varname>lisp-files</varname> <varname>prologue-code</varname> <varname>epilogue-code</varname> <varname>init-name</varname><varname>}</varname></screen>
186 <screen><indexterm role="fn"><primary>c:build-shared-library</primary></indexterm>&#151; Function: <function>c:build-shared-library</function> <varname>{</varname><varname>library-name</varname> <varname>&amp;key</varname> <varname>lisp-files</varname> <varname>prologue-code</varname> <varname>epilogue-code</varname> <varname>ld-flags</varname> <varname>init-name</varname><varname>}</varname></screen>
187 <para>This function builds a library file up from the object files listed in
188 <replaceable>lisp-files</replaceable>. Each of the arguments to <replaceable>lisp-file</replaceable> must name a single
189 object file produced with <literal>compile-file</literal>.</para>
190 <para><replaceable>library-name</replaceable> is the physical pathname corresponding to the library. The
191 value of <replaceable>library-name</replaceable> must follow some system-specific conventions. To
192 make your program portable, <replaceable>library-name</replaceable> should be built using the
193 output of <literal>compile-file-pathname</literal>.</para>
194 <para><replaceable>prologue-code</replaceable> and <replaceable>epilogue-code</replaceable> are strings with C code to be
195 executed before and after initializing the library, respectively. For
196 dynamically linked libraries you can also provide a list of strings in
197 <replaceable>ld-flags</replaceable>. These strings are additional parameters for the linker and
198 their purpose is to link C/C++ extensions into the library.</para>
199 <para><replaceable>init-name</replaceable> gives the initialization function of the library a
200 user-specified name. Thus a the generated library may be used and/or
201 linked to a C application.</para>
202 </blockquote>
203 <!-- -->
204 </sect1>
205
206 <sect1 label="2.5" xml:id="File-names">
207 <title>File names</title>
208 <blockquote>
209 <screen><indexterm role="fn"><primary>compile-file-pathname</primary></indexterm>&#151; Function: <function>compile-file-pathname</function> <varname>{</varname><varname>filename-base</varname> <varname>&amp;key</varname> <varname>output-file</varname> <varname>type</varname><varname>}</varname></screen>
210 <para>When compiling lisp files, creating libraries, etc, a number of files are
211 produced which are of interest for the user or programmer. However, the name
212 of these files will change from system to system. The purpose of the function
213 <literal>compile-file-pathname</literal> is to query the compiler about the name of the
214 different files that it can produce. Possible values of the <replaceable>type</replaceable>
215 argument include:</para>
216 <variablelist>
217 <varlistentry>
218 <term>:fas (default)</term>
219 <listitem>
220 <para>Standard compiled files that can be loaded with <literal>load</literal>.</para>
221 </listitem>
222 </varlistentry>
223 <varlistentry>
224 <term>:c, :data, :h</term>
225 <listitem>
226 <para>Intermediate files produced by the Lisp-to-C translator.</para>
227 </listitem>
228 </varlistentry>
229 <varlistentry>
230 <term>:o</term>
231 <listitem>
232 <para>Linkable object files.</para>
233 </listitem>
234 </varlistentry>
235 <varlistentry>
236 <term>:lib, :static-library</term>
237 <listitem>
238 <para>A normal library produced with <literal>c:build-static-library</literal>.</para>
239 </listitem>
240 </varlistentry>
241 <varlistentry>
242 <term>:dll, :shared-library</term>
243 <listitem>
244 <para>A dynamically linked library produced with <literal>c:build-shared-library</literal>.</para>
245 </listitem>
246 </varlistentry>
247 <varlistentry>
248 <term>:program</term>
249 <listitem>
250 <para>An executable produced with <literal>c:build-program</literal>.</para>
251 </listitem>
252 </varlistentry>
253 </variablelist>
254 <para>The output of this function is system specific. For example, under FreeBSD<screen>
255 &gt; (compile-file-pathname "/this/path/mylib" :type :lib)
256 #P"/this/path/libmylib.a"
257 &gt; (compile-file-pathname "/this/path/mylib" :type :dll)
258 #P"/this/path/libmylib.so"
259 &gt; (compile-file-pathname "/this/path/mycode")
260 #P"/this/path/mycode.fas"
261 </screen></para>
262 </blockquote>
263 <!-- -->
264 </sect1>
265
266 <sect1 label="2.6" xml:id="Compiler-examples">
267 <title>Compiler examples</title>
268 <sect2 label="2.6.1">
269 <title>The <filename>hello.lisp</filename> file</title>
270 <para>In the following examples we will use the same lisp program. You have to
271 create a file called <filename>hello.lisp</filename> which contains the following lines</para>
272 <programlisting>
273 (princ "Hello world!")
274 (terpri)
275 (quit)
276 </programlisting>
277 <para role="continues">If you start &ECL; and load this file in the Common-Lisp environment you
278 will see the <literal>"Hello world!"</literal> message and the interpreter will be closed.<screen>
279 ECL (Embeddable Common-Lisp) 0.9d
280 Copyright (C) 1984 Taiichi Yuasa and Masami Hagiya
281 Copyright (C) 1993 Giuseppe Attardi
282 Copyright (C) 2000 Juan J. Garcia-Ripoll
283 ECL is free software, and you are welcome to redistribute it
284 under certain conditions; see file 'Copyright' for details.
285 Type :h for Help. Top level.
286 &gt; <lineannotation>(load "hello.lisp")</lineannotation>
287 ;;; Loading "hello.lisp"
288 Hello World!
289 </screen></para>
290 </sect2>
291
292 <sect2 label="2.6.2">
293 <title>Example of loadable object file</title>
294 <para>You can only perform the example in this section if your &ECL; image supports
295 dynamically loading of object files. This is true if you find the keyword
296 <replaceable>:dlopen</replaceable> in the <replaceable>*features*</replaceable> variable. This is true, for instance,
297 in a typical FreeBSD or Linux box,<screen>
298 Type :h for Help. Top level.
299 &gt; <lineannotation>*features*</lineannotation>
300 (:IEEE-FLOATING-POINT :IBM-PC :I386 :BSD :UNIX :DLOPEN :ANSI-CL :CLOS
301 :BOEHM-GC :ECL :COMMON)
302 </screen></para>
303 <para>In this example we build a loadable extension which prints the <literal>"Hello
304 world!"</literal> message. First you need to create a the <filename>hello.lisp</filename> file. Next
305 you have to enter the &ECL; environment and type <literal>(compile-file
306 "hello.lisp")</literal>. This produces a loadable object file.</para>
307 <para><screen>
308 Type :h for Help. Top level.
309 &gt; <lineannotation>(compile-file "hello.lisp")</lineannotation>
310 ;;; Loading #P"/usr/lib/ecl/cmp.fas"
311 ;;; Loading #P"/usr/lib/ecl/sysfun.lsp"
312 ;;; Compiling hello.lisp.
313 ;;; End of Pass 1.
314 ;;; Calling the C compiler...
315 ;;; Invoking external command: gcc -O2 -march=i686 -pipe -fomit-frame-pointer -fPIC -fstrict-aliasing -Dlinux -O "-I/usr/lib/ecl/" -w -c "hello.c" -o "hello.o"
316 ;;; Invoking external command: gcc -o "hello.fas" -L"/usr/lib/ecl/" "hello.o" -Wl,&#x2013;rpath,/usr/lib/ecl/ -shared -lecl -lgmp -lgc -ldl -lm
317 ;;; OPTIMIZE levels: Safety=2, Space=0, Speed=3
318 ;;; Finished compiling hello.lisp.
319 #P"hello.fas"
320 Top level.
321 &gt; <lineannotation>(load "hello")</lineannotation>
322 ;;; Loading #P"hello.fas"
323 Hello World!
324 </screen></para>
325 </sect2>
326
327 <sect2 label="2.6.3">
328 <title>Example of standalone program</title>
329 <para>In this example we build a standalone program which prints the <literal>"Hello
330 world!"</literal> message and does nothing else. First you must create the
331 <filename>hello.lisp</filename> file shown above. Next you have to enter the &ECL;
332 environment and type <literal>(compile-file "hello.lisp" :system-p t)</literal>. This
333 produces an object file that can be linked against the &ECL; core image.</para>
334 <para><screen>
335 Type :h for Help. Top level.
336 &gt; <lineannotation>(compile-file "hello.lisp" :system-p t)</lineannotation>
337 ;;; Loading #P"/usr/lib/ecl/cmp.fas"
338 ;;; Loading #P"/usr/lib/ecl/sysfun.lsp"
339 ;;; Compiling hello.lisp.
340 ;;; End of Pass 1.
341 ;;; Calling the C compiler...
342 ;;; Invoking external command: gcc -O2 -march=i686 -pipe -fomit-frame-pointer -fPIC -fstrict-aliasing -Dlinux -O "-I/usr/lib/ecl/" -w -c "hello.c" -o "hello.o"
343 ;;; OPTIMIZE levels: Safety=2, Space=0, Speed=3
344 ;;; Finished compiling hello.lisp.
345 #P"hello.o"
346 </screen></para>
347 <para role="continues">The final step is to build the executable using the <literal>c:build-program</literal>
348 instruction.<screen>
349 &gt; <lineannotation>(c:build-program "myecl" :lisp-files '("hello.o"))</lineannotation>
350 ;;; Invoking external command: gcc -O2 -march=i686 -pipe -fomit-frame-pointer -fPIC -fstrict-aliasing -Dlinux -O "-I/usr/lib/ecl/" -w -c "myecl.c" -o "myecl.o"
351 ;;; Invoking external command: gcc -o "myecl" -L"/usr/lib/ecl/" "myecl.o" "hello.o" -Wl,&#x2013;rpath,/usr/lib/ecl/ -lecl -lgmp -lgc -ldl -lm
352 #P"myecl"
353 Top level.
354 </screen>Now you can execute this program from your favorite shell.</para>
355 <para role="continues"><screen>
356 % <lineannotation>./myecl</lineannotation>
357 Hello world!
358 </screen></para>
359 </sect2>
360
361 <sect2 label="2.6.4">
362 <title>Combining files into a larger FASL</title>
363 <para>You can only perform the example in this section if your &ECL; image supports
364 dynamically loading of object files. In this example we build a loadable
365 library which prints the <literal>"Hello world!"</literal> message and does nothing
366 else. First you must create the <filename>hello.lisp</filename> file shown above. Next you
367 have to enter the &ECL; environment and type <literal>(compile-file "hello.lisp"
368 :system-p t)</literal>. This produces an object file that can be linked to form a loadable
369 library.</para>
370 <para><screen>
371 Type :h for Help. Top level.
372 &gt; (compile-file "hello.lisp" :system-p t)
373 ;;; Loading #P"/usr/lib/ecl/cmp.fas"
374 ;;; Loading #P"/usr/lib/ecl/sysfun.lsp"
375 ;;; Compiling hello.lisp.
376 ;;; End of Pass 1.
377 ;;; Calling the C compiler...
378 ;;; Invoking external command: gcc -O2 -march=i686 -pipe -fomit-frame-pointer -fPIC -fstrict-aliasing -Dlinux -O "-I/usr/lib/ecl/" -w -c "hello.c" -o "hello.o"
379 ;;; OPTIMIZE levels: Safety=2, Space=0, Speed=3
380 ;;; Finished compiling hello.lisp.
381 #P"hello.o"
382 </screen></para>
383 <para role="continues">The final step is to build the library using the <literal>c:build-fasl</literal>
384 instruction.<screen>
385 &gt; (c:build-fasl "myecl" :lisp-files '("hello.o"))
386 ;;; Invoking external command: gcc -O2 -march=i686 -pipe -fomit-frame-pointer -fPIC -fstrict-aliasing -Dlinux -O "-I/usr/lib/ecl/" -w -c "myecl.c" -o "myecl.o"
387 ;;; Invoking external command: gcc -o "libmyecl.so" -L"/usr/lib/ecl/" "myecl.o" "hello.o" -Wl,&#x2013;rpath,/usr/lib/ecl/ -shared -lecl -lgmp -lgc -ldl -lm
388 #P"libmyecl.so"
389 </screen>Now you can load this extension from any &ECL; image, even those you produce
390 with <literal>c:build-program</literal>.</para>
391 <para role="continues"><screen>
392 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; THIS EXAMPLE IS WRONG?! &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;
393 &gt; (load "myecl")
394 ;;; Loading myecl.fas
395 Hello world!
396 Bye.
397 </screen></para>
398 <!-- -->
399 </sect2>
400 </sect1>
401 </section>
402
403 <section xml:id="Lisp-objects">
404 <title>Manipulating Lisp objects</title>
405 <para>If you want to extend, fix or simply customize &ECL; for your own needs,
406 you should understand how the implementation works.</para>
407
408 <sect1 label="3.1" xml:id="Objects-representation">
409 <title>Objects representation</title>
410 <para>In &ECL; a lisp object is represented by a type called <literal>cl_object</literal>. This
411 type is a word which is long enough to host both an integer and a pointer. The
412 least significant bits of this word, also called the tag bits, determine
413 whether it is a pointer to a C structure representing a complex object, or
414 whether it is an immediate data, such as a fixnum or a character.</para>
415 <screen><![CDATA[
416 |-------------------|--|
417 | Fixnum value |01|
418 |-------------------|--|
419
420 |------------|------|--|
421 | Unused bits| char |10|
422 |------------|------|--|
423
424 |----------------------| |--------|--------|-----|--------|
425 | Pointer to cell |---->| word-1 | word-2 | ... | word-n |
426 |----------------------| |--------|--------|-----|--------|
427 | ...................00| | actual data of the object |
428 |----------------------| |--------------------------------|
429 ]]></screen>
430 <para>The fixnums and characters are called immediate datatypes, because they require
431 no more than the <literal>cl_object</literal> datatype to store all information. All other
432 &ECL; objects are non-immediate and they are represented by a pointer to a
433 cell that is allocated on the heap. Each cell consists of several words of
434 memory and contains all the information related to that object. By storing data
435 in multiples of a word size, we make sure that the least significant bits of a
436 pointer are zero, which distinguishes pointers from immediate data.</para>
437 <para>In an immediate datatype, the tag bits determine the type of the object. In
438 non-immediate datatypes, the first byte in the cell contains the secondary type
439 indicator, and distinguishes between different types of non immediate data. The
440 use of the remaining bytes differs for each type of object. For instance, a
441 cons cell consists of three words:</para>
442 <screen><![CDATA[
443 |---------|----------|
444 |CONS| | |
445 |---------|----------|
446 | car-pointer |
447 |--------------------|
448 | cdr-pointer |
449 |--------------------|
450 ]]></screen>
451 <para>There is one important function which tells the type of an object, plus several
452 macros which group several tests.</para>
453 <blockquote>
454 <screen><indexterm role="tp"><primary>cl_object</primary></indexterm>&#151; C type: <structname>cl_object</structname></screen>
455 <para>This is the type of a lisp object. For your C/C++ program, a <literal>cl_object</literal>
456 can be either a fixnum, a character, or a pointer to a union of structures (See
457 the header <filename>object.h</filename>). The actual interpretation of that object can be
458 guessed with the macro <literal>ecl_t_of</literal>.</para>
459 <para>For example, if <replaceable>x</replaceable> is of type <literal>cl_object</literal>, and it is of type fixnum,
460 we may retrieve its value</para>
461 <screen>
462 if (ecl_t_of(x) == t_fixnum)
463 printf("Integer value: %d\n", fix(x));
464 </screen>
465 <para role="continues">If <replaceable>x</replaceable> is of type <literal>cl_object</literal> and it does not contain an immediate
466 datatype, you may inspect the cell associated to the lisp object using <replaceable>x</replaceable>
467 as a pointer. For example,</para>
468 <screen>
469 if (ecl_t_of(x) == t_cons)
470 printf("CAR = %x, CDR = %x\n", x-&gt;cons.car, x-&gt;cons.cdr);
471 else if (ecl_t_of(x) == t_string)
472 printf("String: %s\n", x-&gt;string.self);
473 </screen>
474 <para role="continues">You should see the following sections and the header <filename>object.h</filename> to learn
475 how to use the different fields of a <literal>cl_object</literal> pointer.</para>
476 </blockquote>
477 <blockquote>
478 <screen><indexterm role="tp"><primary>cl_type</primary></indexterm>&#151; C type: <structname>cl_type</structname></screen>
479 <para>Enumeration type which distinguishes the different types of lisp objects. The
480 most important values are t_cons, t_fixnum, t_character, t_bignum, t_ratio,
481 t_singlefloat, t_doublefloat, t_complex, t_symbol, t_package, t_hashtable,
482 t_array, t_vector, t_string, t_bitvector, t_stream, t_random, t_readtable,
483 t_pathname, t_bytecodes, t_cfun, t_cclosure, t_gfun, t_instance, t_foreign and
484 t_thread.</para>
485 </blockquote>
486 <blockquote>
487 <screen><indexterm role="fn"><primary>ecl_t_of</primary></indexterm>&#151; Function: <returnvalue>cl_type</returnvalue> <function>ecl_t_of</function> (<type>cl_object</type> <varname>O</varname>)</screen>
488 <para>If <replaceable>O</replaceable> is a valid lisp object, <literal>ecl_t_of(<replaceable>O</replaceable>)</literal> returns an integer
489 denoting the type that lisp object. That integer is one of the values of the
490 enumeration type <literal>cl_type</literal>.</para>
491 </blockquote>
492 <blockquote>
493 <screen><indexterm role="fn"><primary>FIXNUMP</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>FIXNUMP</function> (<type>cl_object</type> <varname>o</varname>)</screen>
494 <screen><indexterm role="fn"><primary>CHARACTERP</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>CHARACTERP</function> (<type>cl_object</type> <varname>o</varname>)</screen>
495 <screen><indexterm role="fn"><primary>CONSP</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>CONSP</function> (<type>cl_object</type> <varname>o</varname>)</screen>
496 <screen><indexterm role="fn"><primary>LISTP</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>LISTP</function> (<type>cl_object</type> <varname>o</varname>)</screen>
497 <screen><indexterm role="fn"><primary>ATOM</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>ATOM</function> (<type>cl_object</type> <varname>o</varname>)</screen>
498 <screen><indexterm role="fn"><primary>ARRAYP</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>ARRAYP</function> (<type>cl_object</type> <varname>o</varname>)</screen>
499 <screen><indexterm role="fn"><primary>VECTORP</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>VECTORP</function> (<type>cl_object</type> <varname>o</varname>)</screen>
500 <screen><indexterm role="fn"><primary>STRINGP</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>STRINGP</function> (<type>cl_object</type> <varname>o</varname>)</screen>
501 <para>Different macros that check whether <replaceable>o</replaceable> belongs to the specified type.
502 These checks have been optimized, and are preferred over several calls to
503 <literal>ecl_t_of</literal>.</para>
504 </blockquote>
505 <blockquote>
506 <screen><indexterm role="fn"><primary>IMMEDIATE</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>IMMEDIATE</function> (<type>cl_object</type> <varname>o</varname>)</screen>
507 <para>Tells whether <replaceable>o</replaceable> is an immediate datatype.</para>
508 </blockquote>
509 <!-- -->
510 </sect1>
511
512 <sect1 label="3.2" xml:id="Constructing-objects">
513 <title>Constructing objects</title>
514 <para>On each of the following sections we will document the standard interface for
515 building objects of different types. For some objects, though, it is too
516 difficult to make a C interface that resembles all of the functionality in the
517 lisp environment. In those cases you need to</para>
518 <orderedlist numeration="arabic">
519 <listitem>
520 <para>build the objects from their textual representation, or</para>
521 </listitem>
522 <listitem>
523 <para>use the evaluator to build these objects.</para>
524 </listitem>
525 </orderedlist>
526 <para role="continues">The first way makes use of a C or Lisp string to construct an object. The two
527 functions you need to know are the following ones.</para>
528 <blockquote>
529 <screen><indexterm role="fn"><primary>c_string_to_object</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>c_string_to_object</function> (<type>const</type> <varname>char</varname> <type>*</type><varname>s</varname>)</screen>
530 <screen><indexterm role="fn"><primary>string_to_object</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>string_to_object</function> (<type>cl_object</type> <varname>o</varname>)</screen>
531 <para><literal>c_string_to_object</literal> builds a lisp object from a C string which contains a
532 suitable representation of a lisp object. <literal>string_to_object</literal> performs the
533 same task, but uses a lisp string, and therefore it is less useful. Two
534 examples of their use</para>
535 <screen>
536 /* Using a C string */
537 cl_object array1 = c_string_to_object("#(1 2 3 4)");
538
539 /* Using a Lisp string */
540 cl_object string = make_simple_string("#(1 2 3 4)");
541 cl_object array2 = string_to_object(string);
542 </screen>
543 </blockquote>
544 <!-- -->
545 </sect1>
546
547 <sect1 label="3.3" xml:id="Integers">
548 <title>Integers</title>
549 <para>Common-Lisp distinguishes two types of integer types: bignums and fixnums. A
550 fixnum is a small integer, which ideally occupies only a word of memory and
551 which is between the values <replaceable>MOST-NEGATIVE-FIXNUM</replaceable> and
552 <replaceable>MOST-POSITIVE-FIXNUM</replaceable>. A bignum is any integer which is not a fixnum and
553 it is only constrained by the amount of memory available to represent it.</para>
554 <para>In &ECL; a fixnum is an integer that, together with the tag bits, fits in a
555 word of memory. The size of a word, and thus the size of a fixnum, varies from
556 one architecture to another, and you should refer to the types and constants in
557 the <filename>ecl.h</filename> header to make sure that your C extensions are portable.
558 All other integers are stored as bignums, they are not immediate objects, they
559 take up a variable amount of memory and the GNU Multiprecision Library is
560 required to create, manipulate and calculate with them.</para>
561 <blockquote>
562 <screen><indexterm role="tp"><primary>cl_fixnum</primary></indexterm>&#151; C type: <structname>cl_fixnum</structname></screen>
563 <para>This is a C signed integer type capable of holding a whole fixnum without any
564 loss of precision. The opposite is not true, and you may create a
565 <literal>cl_fixnum</literal> which exceeds the limits of a fixnum and should be stored as a
566 bignum.</para>
567 </blockquote>
568 <blockquote>
569 <screen><indexterm role="tp"><primary>cl_index</primary></indexterm>&#151; C type: <structname>cl_index</structname></screen>
570 <para>This is a C unsigned integer type capable of holding a nonnegative fixnum without
571 loss of precision. Typically, a <literal>cl_index</literal> is used as an index into an array,
572 or into a proper list, etc.</para>
573 </blockquote>
574 <blockquote>
575 <screen><indexterm role="vr"><primary>MOST_NEGATIVE_FIXNUM</primary></indexterm>&#151; Constant: <varname>MOST_NEGATIVE_FIXNUM</varname></screen>
576 <screen><indexterm role="vr"><primary>MOST_POSITIVE_FIXNUM</primary></indexterm>&#151; Constant: <varname>MOST_POSITIVE_FIXNUM</varname></screen>
577 <para>These constants mark the limits of a fixnum.</para>
578 </blockquote>
579 <blockquote>
580 <screen><indexterm role="fn"><primary>FIXNUM_MINUSP</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>FIXNUM_MINUSP</function> (<type>cl_object</type> <varname>o</varname>)</screen>
581 <screen><indexterm role="fn"><primary>FIXNUM_PLUSP</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>FIXNUM_PLUSP</function> (<type>cl_object</type> <varname>o</varname>)</screen>
582 <para>These functions perform the checks (<replaceable>o</replaceable> &lt; 0) and (0 &lt;= <replaceable>o</replaceable>),
583 respectively.</para>
584 </blockquote>
585 <blockquote>
586 <screen><indexterm role="fn"><primary>MAKE_FIXNUM</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>MAKE_FIXNUM</function> (<type>cl_fixnum</type> <varname>n</varname>)</screen>
587 <screen><indexterm role="fn"><primary>fix</primary></indexterm>&#151; Function: <returnvalue>cl_fixnum</returnvalue> <function>fix</function> (<type>cl_object</type> <varname>o</varname>)</screen>
588 <para><literal>MAKE_FIXNUM</literal> and <literal>fix</literal> convert from an integer to a lisp object
589 of fixnum type and vice versa. These functions no not check their arguments.</para>
590 </blockquote>
591 <blockquote>
592 <screen><indexterm role="fn"><primary>fixint</primary></indexterm>&#151; Function: <returnvalue>cl_fixnum</returnvalue> <function>fixint</function> (<type>cl_object</type> <varname>o</varname>)</screen>
593 <para>Converts a lisp fixnum to a C integer of the appropriate size. Signals an error
594 if <replaceable>o</replaceable> is not of fixnum type.</para>
595 </blockquote>
596 <blockquote>
597 <screen><indexterm role="fn"><primary>fixnnint</primary></indexterm>&#151; Function: <returnvalue>cl_index</returnvalue> <function>fixnnint</function> (<type>cl_object</type> <varname>o</varname>)</screen>
598 <para>Similar to <literal>fixint</literal> but also ensures that <replaceable>o</replaceable> is not negative.</para>
599 </blockquote>
600 <!-- -->
601 </sect1>
602
603 <sect1 label="3.4" xml:id="Characters">
604 <title>Characters</title>
605 <para>&ECL; has only one type of characters, which fits in the C type <literal>char</literal>.
606 The following constants and functions operate on characters.</para>
607 <blockquote>
608 <screen><indexterm role="vr"><primary>CHAR_CODE_LIMIT</primary></indexterm>&#151; Constant: <varname>CHAR_CODE_LIMIT</varname></screen>
609 <para>Each character is assigned an integer code which ranges from 0 to
610 (<replaceable>CHAR_CODE_LIMIT</replaceable>-1).</para>
611 </blockquote>
612 <blockquote>
613 <screen><indexterm role="fn"><primary>CHAR_CODE</primary></indexterm>&#151; Function: <returnvalue>cl_fixnum</returnvalue> <function>CHAR_CODE</function> (<type>cl_object</type> <varname>o</varname>)</screen>
614 <screen><indexterm role="fn"><primary>char_code</primary></indexterm>&#151; Function: <returnvalue>cl_fixnum</returnvalue> <function>char_code</function> (<type>cl_object</type> <varname>o</varname>)</screen>
615 <para>Returns the integer code associated to a lisp character. Only <literal>char_code</literal>
616 checks its arguments.</para>
617 </blockquote>
618 <blockquote>
619 <screen><indexterm role="fn"><primary>CODE_CHAR</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>CODE_CHAR</function> (<type>cl_fixnum</type> <varname>o</varname>)</screen>
620 <para>Returns the lisp character associated to an integer code. It does not check
621 its arguments.</para>
622 </blockquote>
623 <blockquote>
624 <screen><indexterm role="fn"><primary>coerce_to_character</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>coerce_to_character</function> (<type>cl_object</type> <varname>o</varname>)</screen>
625 <para>Coerces a lisp object to type character. Valid arguments are a character,
626 or a string designator of length 1. In all other cases an error is signaled.</para>
627 </blockquote>
628 <blockquote>
629 <screen><indexterm role="fn"><primary>char_eq</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>char_eq</function> (<type>cl_object</type> <varname>x</varname>, <type>cl_object</type> <varname>y</varname>)</screen>
630 <screen><indexterm role="fn"><primary>char_equal</primary></indexterm>&#151; Function: <returnvalue>bool</returnvalue> <function>char_equal</function> (<type>cl_object</type> <varname>x</varname>, <type>cl_object</type> <varname>y</varname>)</screen>
631 <para>Compare two characters for equality. <literal>char_eq</literal> take case into account and
632 <literal>char_equal</literal> ignores it.</para>
633 </blockquote>
634 <blockquote>
635 <screen><indexterm role="fn"><primary>char_cmp</primary></indexterm>&#151; Function: <returnvalue>int</returnvalue> <function>char_cmp</function> (<type>cl_object</type> <varname>x</varname>, <type>cl_object</type> <varname>y</varname>)</screen>
636 <screen><indexterm role="fn"><primary>char_compare</primary></indexterm>&#151; Function: <returnvalue>int</returnvalue> <function>char_compare</function> (<type>cl_object</type> <varname>x</varname>, <type>cl_object</type> <varname>y</varname>)</screen>
637 <para>Compare the relative order of two characters. <literal>char_cmp</literal> takes care of
638 case and <literal>char_compare</literal> converts all characters to uppercase before
639 comparing them.</para>
640 </blockquote>
641 <!-- -->
642 </sect1>
643
644 <sect1 label="3.5" xml:id="Arrays">
645 <title>Arrays</title>
646 <para>An array is an aggregate of data of a common type, which can be accessed with
647 one or more nonnegative indices. &ECL; stores arrays as a C structure with a
648 pointer to the region of memory which contains the actual data. The cell
649 of an array datatype varies depending on whether it is a vector, a bytevector,
650 a multidimensional array or a string.</para>
651 <para>If <replaceable>x</replaceable> contains a vector, you can access the following fields:</para>
652 <variablelist>
653 <varlistentry>
654 <term><literal>x-&gt;vector.elttype</literal></term>
655 <listitem>
656 <para>The type of the elements of the vector.</para>
657 </listitem>
658 </varlistentry>
659 <varlistentry>
660 <term><literal>x-&gt;vector.dim</literal></term>
661 <listitem>
662 <para>The maximum number of elements.</para>
663 </listitem>
664 </varlistentry>
665 <varlistentry>
666 <term><literal>x-&gt;vector.fillp</literal></term>
667 <listitem>
668 <para>Actual number of elements in the vector or "fill pointer".</para>
669 </listitem>
670 </varlistentry>
671 <varlistentry>
672 <term><literal>x-&gt;vector.self</literal></term>
673 <listitem>
674 <para>Union of pointers of different types. You should choose the right pointer
675 depending on <literal>x-&gt;vector.elltype</literal></para>
676 </listitem>
677 </varlistentry>
678 <varlistentry>
679 <term><literal>x-&gt;vector.hasfillp</literal></term>
680 <listitem>
681 <para>Whether <literal>x-&gt;vector.fillp</literal> can be smaller than <literal>x-&gt;vector.dim</literal>.</para>
682 </listitem>
683 </varlistentry>
684 </variablelist>
685 <para>If <replaceable>x</replaceable> contains a multidimensional array, the cell elements become</para>
686 <variablelist>
687 <varlistentry>
688 <term><literal>x-&gt;array.elttype</literal></term>
689 <listitem>
690 <para>The type of the elements of the array.</para>
691 </listitem>
692 </varlistentry>
693 <varlistentry>
694 <term><literal>x-&gt;array.dim</literal></term>
695 <listitem>
696 <para>Number of elements in the array.</para>
697 </listitem>
698 </varlistentry>
699 <varlistentry>
700 <term><literal>x-&gt;array.rank</literal></term>
701 <listitem>
702 <para>Number of dimensions of the array.</para>
703 </listitem>
704 </varlistentry>
705 <varlistentry>
706 <term><literal>x-&gt;array.dims[]</literal></term>
707 <listitem>
708 <para>Array with the dimensions of the array. The elements range from
709 <literal>x-&gt;array.dim[0]</literal> to <literal>x-&gt;array.dim[x-&gt;array.rank-1]</literal>.</para>
710 </listitem>
711 </varlistentry>
712 <varlistentry>
713 <term><literal>x-&gt;array.self</literal></term>
714 <listitem>
715 <para>Union of pointers to the actual data. You should choose the right pointer
716 depending on <literal>x-&gt;array.elltype</literal>.</para>
717 </listitem>
718 </varlistentry>
719 <varlistentry>
720 <term><literal>x-&gt;array.rank</literal></term>
721 <listitem>
722 <para>Whether <literal>x-&gt;vector.fillp</literal> can be smaller than <literal>x-&gt;vector.dim</literal>.</para>
723 </listitem>
724 </varlistentry>
725 </variablelist>
726 <para role="continues">Bitvectors and strings are treated separately.</para>
727 <para>Each array is of an specialized type which is the type of the elements of the
728 array. &ECL; has arrays only a few following specialized types, and for each
729 of these types there is a C integer which is the corresponding value of
730 <literal>x-&gt;array.elttype</literal> or <literal>x-&gt;vector.elttype</literal>. We list those types
731 together with the C constant that denotes that type:</para>
732 <variablelist>
733 <varlistentry>
734 <term><replaceable>T</replaceable></term>
735 <listitem>
736 <para><literal>aet_object</literal></para>
737 </listitem>
738 </varlistentry>
739 <varlistentry>
740 <term><replaceable>CHARACTER</replaceable></term>
741 <listitem>
742 <para><literal>aet_ch</literal></para>
743 </listitem>
744 </varlistentry>
745 <varlistentry>
746 <term><replaceable>FIXNUM</replaceable></term>
747 <listitem>
748 <para><literal>aet_fix</literal></para>
749 </listitem>
750 </varlistentry>
751 <varlistentry>
752 <term><replaceable>BIT</replaceable></term>
753 <listitem>
754 <para><literal>aet_bit</literal></para>
755 </listitem>
756 </varlistentry>
757 <varlistentry>
758 <term><replaceable>SINGLE-FLOAT</replaceable></term>
759 <listitem>
760 <para><literal>aet_sf</literal></para>
761 </listitem>
762 </varlistentry>
763 <varlistentry>
764 <term><replaceable>DOUBLE-FLOAT</replaceable></term>
765 <listitem>
766 <para><literal>aet_df</literal></para>
767 </listitem>
768 </varlistentry>
769 </variablelist>
770 <blockquote>
771 <screen><indexterm role="fn"><primary>array_elttype</primary></indexterm>&#151; Function: <returnvalue>cl_elttype</returnvalue> <function>array_elttype</function> (<type>cl_object</type> <varname>o</varname>)</screen>
772 <para>Returns the element type of the array <replaceable>o</replaceable>, which can be a string, a
773 bitvector, vector, or a multidimensional array. For example, the code
774 <literal>array_elttype(c_string_to_object("\"AAA\""))</literal> returns <literal>aet_ch</literal>,
775 while the <literal>array_elttype(c_string_to_object("#(A B C)"))</literal> returns
776 <literal>aet_object</literal>.</para>
777 </blockquote>
778 <blockquote>
779 <screen><indexterm role="fn"><primary>aref</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>aref</function> (<type>cl_object</type> <varname>array</varname>, <type>cl_index</type> <varname>index</varname>)</screen>
780 <screen><indexterm role="fn"><primary>aset</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>aset</function> (<type>cl_object</type> <varname>array</varname>, <type>cl_index</type> <varname>index</varname>, <type>cl_object</type> <varname>value</varname>)</screen>
781 <para>These functions are used to retrieve and set the elements of an array. The
782 elements are accessed with one index, <replaceable>index</replaceable>, as in the lisp function
783 <literal>ROW-MAJOR-AREF</literal>. For example</para>
784 <screen>
785 cl_object array = c_string_to_object("#2A((1 2) (3 4))");
786 cl_object x = aref(array, 3);
787 cl_print(1, x); /* Outputs 4 */
788 aset(array, 3, MAKE_FIXNUM(5));
789 cl_print(1, array); /* Outputs #2A((1 2) (3 5)) */
790 </screen>
791 </blockquote>
792 <blockquote>
793 <screen><indexterm role="fn"><primary>aref1</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>aref1</function> (<type>cl_object</type> <varname>vector</varname>, <type>cl_index</type> <varname>index</varname>)</screen>
794 <screen><indexterm role="fn"><primary>aset1</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>aset1</function> (<type>cl_object</type> <varname>vector</varname>, <type>cl_index</type> <varname>index</varname>, <type>cl_object</type> <varname>value</varname>)</screen>
795 <para>These functions are similar to <literal>aref</literal> and <literal>aset</literal>, but they operate on
796 vectors.</para>
797 <screen>
798 cl_object array = c_string_to_object("#(1 2 3 4)");
799 cl_object x = aref1(array, 3);
800 cl_print(1, x); /* Outputs 4 */
801 aset1(array, 3, MAKE_FIXNUM(5));
802 cl_print(1, array); /* Outputs #(1 2 3 5) */
803 </screen>
804 </blockquote>
805 <!-- -->
806 </sect1>
807
808 <sect1 label="3.6" xml:id="Strings">
809 <title>Strings</title>
810 <para>A string, both in Common-Lisp and in &ECL; is nothing but a vector of
811 characters. Therefore, almost everything mentioned in the section of arrays
812 remains valid here. The only important difference is that &ECL; stores
813 strings as a lisp object with a pointer to a zero terminated C string. Thus, if
814 a string has <replaceable>n</replaceable> characters, &ECL; will reserve <replaceable>n</replaceable>+1 bytes for the
815 string. This allows us to pass the string <literal>self</literal> pointer to any C
816 routine.</para>
817 <para>If <replaceable>x</replaceable> is a lisp object of type string, we can access the following fields:</para>
818 <variablelist>
819 <varlistentry>
820 <term><literal>x-&gt;string.dim</literal></term>
821 <listitem>
822 <para>Maximum number of characters that it can contain.</para>
823 </listitem>
824 </varlistentry>
825 <varlistentry>
826 <term><literal>x-&gt;string.fillp</literal></term>
827 <listitem>
828 <para>Actual number of characters in the string.</para>
829 </listitem>
830 </varlistentry>
831 <varlistentry>
832 <term><literal>x-&gt;string.self</literal></term>
833 <listitem>
834 <para>Pointer to the characters.</para>
835 </listitem>
836 </varlistentry>
837 <varlistentry>
838 <term><literal>x-&gt;string.hasfillp</literal></term>
839 <listitem>
840 <para>True if <literal>x-&gt;string.fillp</literal> can be smaller than <literal>x-&gt;string.dim</literal>.</para>
841 </listitem>
842 </varlistentry>
843 </variablelist>
844 <blockquote>
845 <screen><indexterm role="fn"><primary>make_simple_string</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>make_simple_string</function> (<type>char</type> <varname>*</varname><varname>s</varname>)</screen>
846 <screen><indexterm role="fn"><primary>make_string_copy</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>make_string_copy</function> (<type>char</type> <varname>*</varname><varname>s</varname>)</screen>
847 <para>Both routines build a lisp string from a C string. <literal>make_string_copy</literal>
848 allocates new space and copies the content of the string to
849 it. <literal>make_simple_string</literal> simply uses the memory pointed by <replaceable>s</replaceable>, which
850 should not be deallocated. Both routines use <literal>strlen</literal> to calculate the
851 length of the string.</para>
852 </blockquote>
853 </sect1>
854
855 <sect1 label="3.7" xml:id="Bitvectors">
856 <title>Bitvectors</title>
857 </sect1>
858
859 <sect1 label="3.8" xml:id="Streams">
860 <title>Streams</title>
861 </sect1>
862
863 <sect1 label="3.9" xml:id="Structures">
864 <title>Structures</title>
865 </sect1>
866
867 <sect1 label="3.10" xml:id="Instances">
868 <title>Instances</title>
869 <!-- -->
870 </sect1>
871
872 <sect1 label="3.11" xml:id="Bytecodes">
873 <title>Bytecodes</title>
874 <para>A bytecodes object is a lisp object with a piece of code that can be
875 interpreted. The objects of type <literal>t_bytecode</literal> are implicitly constructed
876 by a call to <literal>eval</literal>, but can also be explicitly constructed with the
877 <literal>make_lambda</literal> function.</para>
878 <blockquote>
879 <screen><indexterm role="fn"><primary>cl_safe_eval</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>cl_safe_eval</function> (<type>cl_object</type> <varname>form</varname>, <type>cl_object</type> <varname>env</varname>, <type>cl_object</type> <varname>err_value</varname></screen>
880 <screen><indexterm role="fn"><primary>cl_eval</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>cl_eval</function> (<type>cl_object</type> <varname>form</varname>)</screen>
881 <para><literal>cl_safe_eval</literal> evaluates <replaceable>form</replaceable> in the lexical environment <replaceable>env</replaceable>,
882 which can be <replaceable>nil</replaceable>. Before evaluating it, the expression <replaceable>form</replaceable> must
883 be bytecompiled. <literal>cl_eval</literal> is the equivalent of <literal>cl_safe_eval</literal> but
884 without environment and with <replaceable>err_value</replaceable> set to <replaceable>nil</replaceable>. It exists only
885 for compatibility with previous versions.</para>
886 <screen>
887 cl_object form = c_string_to_object("(print 1)");
888 cl_safe_eval(form,Cnil);
889 cl_safe_eval(form, Cnil);
890 </screen>
891 </blockquote>
892 <blockquote>
893 <screen><indexterm role="fn"><primary>si_make_lambda</primary></indexterm>&#151; Function: <returnvalue>cl_object</returnvalue> <function>si_make_lambda</function> (<type>cl_object</type> <varname>name</varname>, <type>cl_object</type> <varname>def</varname>)</screen>
894 <para>Builds an interpreted lisp function with name given by the symbol <replaceable>name</replaceable>
895 and body given by <replaceable>def</replaceable>. For instance, we would achieve the equivalent of</para>
896 <programlisting>
897 (funcall #'(lambda (x y) (block foo (+ x y)))
898 1 2)
899 </programlisting>
900 <para role="continues">with the following code</para>
901 <screen>
902 cl_object def = c_string_to_object("((x y) (+ x y))");
903 cl_object name = _intern("foo")
904 cl_object fun = si_make_lambda(name, def);
905 return funcall(fun, MAKE_FIXNUM(1), MAKE_FIXNUM(2));
906 </screen>
907 <para role="continues">Notice that <literal>si_safe_lambda</literal> performs a bytecodes compilation
908 of the definition and thus it may signal some errors. Such errors are not
909 handled by the routine itself you might consider using <literal>cl_safe_eval</literal>
910 or <literal>cl_eval</literal> instead:</para>
911 <screen>
912 cl_object def = c_string_to_object("#'(lambda-block foo (x y) (+ x y))");
913 cl_object fun = cl_eval(def);
914 return funcall(fun, MAKE_FIXNUM(1), MAKE_FIXNUM(2));
915 </screen>
916 </blockquote>
917 <!-- -->
918 </sect1>
919 </section>
920
921 <section xml:id="The-interpreter">
922 <title>The interpreter</title>
923 <sect1 label="4.1" xml:id="ECL-stacks">
924 <title>&ECL; stacks</title>
925 <para>&ECL; uses the following stacks:</para>
926 <variablelist>
927 <varlistentry>
928 <term>Frame Stack</term>
929 <listitem>
930 <para>consisting of catch, block, tagbody frames</para>
931 </listitem>
932 </varlistentry>
933 <varlistentry>
934 <term>Bind Stack</term>
935 <listitem>
936 <para>for shallow binding of dynamic variables</para>
937 </listitem>
938 </varlistentry>
939 <varlistentry>
940 <term>Interpreter Stack</term>
941 <listitem>
942 <para>acts as a Forth data stack, keeping intermediate arguments to
943 interpreted functions, plus a history of called functions.</para>
944 </listitem>
945 </varlistentry>
946 <varlistentry>
947 <term>C Control Stack</term>
948 <listitem>
949 <para>used for arguments/values passing, typed lexical variables,
950 temporary values, and function invocation.</para>
951 </listitem>
952 </varlistentry>
953 </variablelist>
954 </sect1>
955
956 <sect1 label="4.2" xml:id="Procedure-Call-Conventions">
957 <title>Procedure Call Conventions</title>
958 <para>&ECL; employs standard C calling conventions to achieve efficiency and
959 interoperability with other languages.
960 Each Lisp function is implemented as a C function which takes as many
961 argument as the Lisp original plus one additional integer argument
962 which holds the number of actual arguments. The function sets <literal>NValues</literal>
963 to the number of Lisp values produced, it returns the first one and the
964 remaining ones are kept in a global (per thread) array (<literal>VALUES</literal>).</para>
965 <para>To show the argument/value passing mechanism, here we list the actual
966 code for the Common-Lisp function <literal>cons</literal>.</para>
967 <screen>
968 cl_cons(int narg, object car, object cdr)
969 { object x;
970 check_arg(2);
971 x = alloc_object(t_cons);
972 CAR(x) = car;
973 CDR(x) = cdr;
974 NValues = 1;
975 return x;
976 }
977 </screen>
978 <para>&ECL; adopts the convention that the name of a function that implements a
979 Common-Lisp function begins with a short package name (<literal>cl</literal> for COMMON-LISP,
980 <literal>si</literal> for SYSTEM, etc), followed by <literal>L</literal>, and followed by the name of
981 the Common-Lisp function. (Strictly speaking, `<literal>-</literal>' and `<literal>*</literal>' in the
982 Common-Lisp function name are replaced by `<literal>_</literal>' and `<literal>A</literal>', respectively,
983 to obey the syntax of C.)</para>
984 <para><literal>check_arg(2)</literal> in the code of <literal>cl_cons</literal> checks that exactly two
985 arguments are supplied to <literal>cons</literal>. That is, it checks that <literal>narg</literal> is
986 2, and otherwise, it causes an error. <literal>allocate_object(t_cons)</literal> allocates
987 a cons cell in the heap and returns the pointer to the cell. After the
988 <literal>CAR</literal> and the <literal>CDR</literal> fields of the cell are set, the cell pointer is
989 returned directly. The number assigned to NValues set by the function (1 in
990 this case) represents the number of values of the function.</para>
991 <para>In general, if one is to play with the C kernel of &ECL; there is no need to
992 know about all these conventions. There is a preprocessor that takes care of
993 the details, by using a lisp representation of the statements that output
994 values, and of the function definitions. For instance, the actual source code
995 for <literal>cl_cons</literal> in <filename>src/c/lists.d</filename></para>
996 <screen>
997 @(defun cons (car cdr)
998 @
999 @(return CONS(car, cdr))
1000 @)
1001 </screen>
1002 </sect1>
1003
1004 <sect1 label="4.3" xml:id="The-lexical-environment">
1005 <title>The lexical environment</title>
1006 <para>The &ECL; interpreter uses two A-lists (Association lists) to
1007 represent lexical environments.</para>
1008 <itemizedlist mark="bullet">
1009 <listitem>
1010 <para>One for variable bindings</para>
1011 </listitem>
1012 <listitem>
1013 <para>One for local function/macro/tag/block bindings</para>
1014 </listitem>
1015 </itemizedlist>
1016 <para>When a function closure is created, the current two A-lists are
1017 saved in the closure along with the lambda expression. Later, when the
1018 closure is invoked, the saved A-lists are
1019 used to recover the lexical environment.</para>
1020 </sect1>
1021
1022 <sect1 label="4.4" xml:id="The-interpreter-stack">
1023 <title>The interpreter stack</title>
1024 <para>The bytecodes interpreter uses a stack of its own to save and restore values
1025 from intermediate calculations. This Forth-like data stack is also used in
1026 other parts of the C kernel for various purposes, such as saving compiled code,
1027 keeping arguments to FORMAT, etc.</para>
1028 <para>However, one of the most important roles of the Interpreter Stack is to keep a
1029 log of the functions which are called during the execution of bytecodes. For
1030 each function invoked, the interpreter keeps three lisp objects on the stack:</para>
1031 <screen><![CDATA[
1032 +----------+------------------------------------------------+
1033 | function | lexical environment | index to previous record |
1034 +----------+---------------------+--------------------------+
1035 ]]></screen>
1036 <para>The first item is the object which is funcalled. It can be a bytecodes object,
1037 a compiled function or a generic function. In the last two cases the lexical
1038 environment is just NIL. In the first case, the second item on the stack is
1039 the lexical environment on which the code is executed. Each of these records
1040 are popped out of the stack after function invocation.</para>
1041 <para>Let us see how these invocation records are used for debugging.<screen>
1042 &gt;(defun fact (x) ;;; Wrong definition of the
1043 (if (= x 0) ;;; factorial function.
1044 one ;;; one should be 1.
1045 (* x (fact (1- x)))))
1046 FACT
1047
1048 &gt;(fact 3) ;;; Tries 3!
1049 Error: The variable ONE is unbound.
1050 Error signalled by IF.
1051 Broken at IF.
1052 &gt;&gt;:b ;;; Backtrace.
1053 Backtrace: eval &gt; fact &gt; if &gt; fact &gt; if &gt; fact &gt; if &gt; fact &gt; IF
1054 ;;; Currently at the last IF.
1055 &gt;&gt;:h ;;; Help.
1056
1057 Break commands:
1058 :q(uit) Return to some previous break level.
1059 :pop Pop to previous break level.
1060 :c(ontinue) Continue execution.
1061 :b(acktrace) Print backtrace.
1062 :f(unction) Show current function.
1063 :p(revious) Go to previous function.
1064 :n(ext) Go to next function.
1065 :g(o) Go to next function.
1066 :fs Search forward for function.
1067 :bs Search backward for function.
1068 :v(ariables) Show local variables, functions, blocks, and tags.
1069 :l(ocal) Return the nth local value on the stack.
1070 :hide Hide function.
1071 :unhide Unhide function.
1072 :hp Hide package.
1073 :unhp Unhide package.
1074 :unhide-all Unhide all variables and packages.
1075 :bds Show binding stack.
1076 :m(essage) Show error message.
1077 :hs Help stack.
1078 Top level commands:
1079 :cf Compile file.
1080 :exit or ^D Exit Lisp.
1081 :ld Load file.
1082 :step Single step form.
1083 :tr(ace) Trace function.
1084 :untr(ace) Untrace function.
1085
1086 Help commands:
1087 :apropos Apropos.
1088 :doc(ument) Document.
1089 :h(elp) or ? Help. Type ":help help" for more information.
1090
1091 &gt;&gt;:p ;;; Move to the last call of FACT.
1092 Broken at IF.
1093
1094 &gt;&gt;:b
1095 Backtrace: eval &gt; fact &gt; if &gt; fact &gt; if &gt; fact &gt; if &gt; FACT &gt; if
1096 ;;; Now at the last FACT.
1097 &gt;&gt;:v ;;; The environment at the last call
1098 Local variables: ;;; to FACT is recovered.
1099 X: 0 ;;; X is the only bound variable.
1100 Block names: FACT. ;;; The block FACT is established.
1101
1102 &gt;&gt;x
1103 0 ;;; The value of x is 0.
1104
1105 &gt;&gt;(return-from fact 1) ;;; Return from the last call of
1106 6 ;;; FACT with the value of 0.
1107 ;;; The execution is resumed and
1108 &gt; ;;; the value 6 is returned.
1109 ;;; Again at the top-level loop.
1110 </screen></para>
1111 <!-- -->
1112 </sect1>
1113 </section>
1114
1115 <section xml:id="The-compiler">
1116 <title>The compiler</title>
1117 <sect1 label="5.1" xml:id="The-compiler-translates-to-C">
1118 <title>The compiler translates to C</title>
1119 <para>The &ECL; compiler is essentially a translator from Common-Lisp to C. Given
1120 a Lisp source file, the compiler first generates three intermediate
1121 files:</para>
1122 <itemizedlist mark="bullet">
1123 <listitem>
1124 <para>a C-file which consists of the C version of the Lisp program</para>
1125 </listitem>
1126 <listitem>
1127 <para>an H-file which consists of declarations referenced in the C-file</para>
1128 </listitem>
1129 <listitem>
1130 <para>a Data-file which consists of Lisp data to be used at load time</para>
1131 </listitem>
1132 </itemizedlist>
1133 <para>The &ECL; compiler then invokes the C compiler to compile the
1134 C-file into an object file. Finally, the contents of the Data-file is
1135 appended to the object file to make a <emphasis>Fasl-file</emphasis>. The generated
1136 Fasl-file can be loaded into the &ECL; system by the Common-Lisp
1137 function <literal>load</literal>. By default, the three intermediate files are
1138 deleted after the compilation, but, if asked, the compiler leaves
1139 them.</para>
1140 <para>The merits of the use of C as the intermediate language are:</para>
1141 <itemizedlist mark="-">
1142 <listitem>
1143 <para>The &ECL; compiler is highly portable.</para>
1144 </listitem>
1145 <listitem>
1146 <para>Cross compilation is possible, because the contents of the
1147 intermediate files are common to all versions of &ECL;. For example,
1148 one can compile his or her Lisp program by the &ECL; compiler on
1149 a Sun, bring the intermediate files to DOS, compile the C-file with
1150 the gcc compiler under DOS, and then append the Data-file to the object
1151 file. This procedure generates the Fasl-file for the &ECL; system on
1152 DOS. This kind of cross compilation makes it easier to port &ECL;.</para>
1153 </listitem>
1154 <listitem>
1155 <para>Hardware-dependent optimizations such as register allocations
1156 are done by the C compiler.</para>
1157 </listitem>
1158 </itemizedlist>
1159 <para>The demerits are:</para>
1160 <itemizedlist mark="-">
1161 <listitem>
1162 <para>At those sites where no C compiler is available,
1163 the users cannot compile their Lisp programs.</para>
1164 </listitem>
1165 <listitem>
1166 <para>The compilation time is long. 70% to 80% of the
1167 compilation time is used by the C compiler. The &ECL; compiler is
1168 therefore slower than compiler generating machine code directly.</para>
1169 </listitem>
1170 </itemizedlist>
1171 </sect1>
1172
1173 <sect1 label="5.2" xml:id="The-compiler-mimics-human-C-programmer">
1174 <title>The compiler mimics human C programmer</title>
1175 <para>The format of the intermediate C code generated by the &ECL; compiler is the
1176 same as the hand-coded C code of the &ECL; source programs. For example,
1177 supposing that the Lisp source file contains the
1178 following function definition:</para>
1179 <programlisting>
1180 (defvar *delta* 2)
1181 (defun add1 (x) (+ *delta* x))
1182 </programlisting>
1183 <para role="continues">The compiler generates the following intermediate C code.</para>
1184 <screen>
1185 /* function definition for ADD1 */
1186 static cl_object L1(cl_object V1)
1187 { VT2 VLEX2 CLSR2
1188 cl_object value0;
1189 value0=number_plus(symbol_value(VV[0]),V1); NVALUES=1;
1190 return value0;
1191 }
1192 /* initialization of this module */
1193 void init_CODE(cl_object flag)
1194 { VT1 CLSR1
1195 cl_object value0;
1196 if (!FIXNUMP(flag)){
1197 Cblock=flag;
1198 #ifndef ECL_DYNAMIC_VV
1199 flag-&gt;cblock.data = VV;
1200 #endif
1201 flag-&gt;cblock.self_destruct=0;
1202 flag-&gt;cblock.data_size = VM;
1203 flag-&gt;cblock.data_text = compiler_data_text;
1204 flag-&gt;cblock.data_text_size = compiler_data_text_size;
1205 return;}
1206 #ifdef ECL_DYNAMIC_VV
1207 VV = Cblock-&gt;cblock.data;
1208 #endif
1209 T0= MAKE_FIXNUM(2);
1210 si_Xmake_special(VV[0])
1211 if(SYM_VAL(T0)!=OBJNULL) cl_setq(VV[0],T0);
1212 cl_def_c_function(VV[1],(void*)L1,1);
1213 }
1214 </screen>
1215 <para>The C function <literal>L1</literal> implements the Lisp function <literal>add1</literal>.
1216 This relation is established by <literal>cl_def_c_function</literal> in the
1217 initialization function <literal>init_CODE</literal>, which is invoked at load
1218 time. There, the vector <literal>VV</literal> consists of Lisp objects;
1219 <literal>VV[0]</literal> and <literal>VV[1]</literal> in this example hold the Lisp symbols
1220 <literal>*delta*</literal> and <literal>add1</literal>. <literal>VM</literal> in the definition of
1221 <literal>L1</literal> is a C macro declared in the corresponding H-file. The
1222 actual value of <literal>VM</literal> is the number of value stack locations used
1223 by this module, i.e., 2 in this example. Thus the following macro
1224 definition is found in the H-file.</para>
1225 <screen>
1226 #define VM 2
1227 </screen>
1228 </sect1>
1229
1230 <sect1 label="5.3" xml:id="Implementation-of-Compiled-Closures">
1231 <title>Implementation of Compiled Closures</title>
1232 <para>The &ECL; compiler takes two passes before it invokes the C
1233 compiler. The major role of the first pass is to detect function
1234 closures and to detect, for each function closure, those lexical
1235 objects (i.e., lexical variable, local function definitions, tags, and
1236 block-names) to be enclosed within the closure. This check must be
1237 done before the C code generation in the second pass, because lexical
1238 objects to be enclosed in function closures are treated in a different
1239 way from those not enclosed.</para>
1240 <para>Ordinarily, lexical variables in a compiled function <emphasis>f</emphasis>
1241 are allocated on the C stack. However, if a lexical variable is
1242 to be enclosed in function closures, it is allocated on a list, called
1243 the &ldquo;environment list&rdquo;, which is local to <emphasis>f</emphasis>. In addition, a
1244 local variable is created which points to the lexical
1245 variable's location (within the environment list), so that
1246 the variable may be accessed through an indirection rather than by list
1247 traversal.</para>
1248 <para>The environment list is a pushdown list: It is empty when <emphasis>f</emphasis> is called.
1249 An element is pushed on the environment list when a variable to be enclosed in
1250 closures is bound, and is popped when the binding is no more in effect. That
1251 is, at any moment during execution of <emphasis>f</emphasis>, the environment list contains
1252 those lexical variables whose binding is still in effect and which should be
1253 enclosed in closures. When a compiled closure is created during execution of
1254 <emphasis>f</emphasis>, the compiled code for the closure is coupled with the environment
1255 list at that moment to form the compiled closure.</para>
1256 <para>Later, when the compiled closure is invoked, a pointer is set up to each
1257 lexical variable in the environment list, so that each object may be referenced
1258 through a memory indirection.</para>
1259 <para>Let us see an example. Suppose the following function has been compiled.</para>
1260 <programlisting>
1261 (defun foo (x)
1262 (let ((a #'(lambda () (incf x)))
1263 (y x))
1264 (values a #'(lambda () (incf x y)))))
1265 </programlisting>
1266 <para><literal>foo</literal> returns two compiled closures. The first closure increments <replaceable>x</replaceable>
1267 by one, whereas the second closure increments <replaceable>x</replaceable> by the initial value of
1268 <replaceable>x</replaceable>. Both closures return the incremented value of <replaceable>x</replaceable>.</para>
1269 <para><screen>
1270 &gt;(multiple-value-setq (f g) (foo 10))
1271 #&lt;compiled-closure nil&gt;
1272
1273 &gt;(funcall f)
1274 11
1275
1276 &gt;(funcall g)
1277 21
1278
1279 &gt;
1280 </screen></para>
1281 <para>After this, the two compiled closures look like:</para>
1282 <screen><![CDATA[
1283 second closure y: x:
1284 |-------|------| |-------|------| |------|------|
1285 | ** | --|----->| 10 | --|------>| 21 | nil |
1286 |-------|------| |-------|------| |------|------|
1287 ^
1288 first closure |
1289 |-------|------| |
1290 | * | --|----------|
1291 |-------|------|
1292
1293 * : address of the compiled code for #'(lambda () (incf x))
1294 ** : address of the compiled code for #'(lambda () (incf x y))
1295 ]]></screen>
1296 </sect1>
1297
1298 <sect1 label="5.4" xml:id="Use-of-Declarations-to-Improve-Efficiency">
1299 <title>Use of Declarations to Improve Efficiency</title>
1300 <para>Declarations, especially type and function declarations,
1301 increase the efficiency of the compiled code. For example, for the
1302 following Lisp source file, with two Common-Lisp declarations added,</para>
1303 <programlisting>
1304 (eval-when (compile)
1305 (proclaim '(function tak (fixnum fixnum fixnum) fixnum))
1306
1307 (defun tak (x y z)
1308 (declare (fixnum x y z))
1309 (if (not (&lt; y x))
1310 z
1311 (tak (tak (1- x) y z)
1312 (tak (1- y) z x)
1313 (tak (1- z) x y))))
1314 </programlisting>
1315 <para>The compiler generates the following C code:</para>
1316 <screen>
1317 /* local entry for function TAK */
1318 static int LI1(register int V1,register int V2,register int V3)
1319 { VT3 VLEX3 CLSR3
1320 TTL:
1321 if (V2 &lt; V1) {
1322 goto L2;}
1323 return(V3);
1324 L2:
1325 { int V5;
1326 V5 = LI1((V1)-1,V2,V3);
1327 { int V6;
1328 V6 = LI1((V2)-1,V3,V1);
1329 V3 = LI1((V3)-1,V1,V2);
1330 V2 = V6;
1331 V1 = V5;}}
1332 goto TTL;
1333 ;;; Note: Tail-recursive call of TAK was replaced by iteration.
1334 }
1335 </screen>
1336 </sect1>
1337
1338 <sect1 label="5.5" xml:id="Inspecting-generated-C-code">
1339 <title>Inspecting generated C code</title>
1340 <para>Common-Lisp defines a function disassemble, which is
1341 supposed to disassemble a compiled function and to display the
1342 assembler code. According to <emphasis>Common-Lisp: The Language</emphasis>,</para>
1343
1344 <para><emphasis>This is primary useful for debugging the compiler</emphasis>, ..\\</para>
1345 <!-- FIXME: Actually disassemble shows bytecode -->
1346 <para>This is, however, <emphasis>useless</emphasis> in our case, because we are
1347 not concerned with assembly language. Rather, we are interested in
1348 the C code generated by the &ECL; compiler. Thus the disassemble
1349 function in &ECL; accepts not-yet-compiled functions only and displays
1350 the translated C code.</para>
1351 <para><screen>
1352 &gt; (defun add1 (x) (1+ x))
1353 ADD1
1354 &gt; (disassemble *)
1355 ;;; Compiling (DEFUN ADD1 ...).
1356 ;;; Emitting code for ADD1.
1357
1358 /* function definition for ADD1 */
1359 static L1(int narg, object V1)
1360 { VT3 VLEX3 CLSR3
1361 TTL:
1362 VALUES(0) = one_plus((V1));
1363 RETURN(1);
1364 }
1365 </screen></para>
1366 </sect1>
1367
1368 <sect1 label="5.6" xml:id="Embedding-C-code">
1369 <title>Embedding C code in lisp source</title>
1370 <para>There are several mechanism to integrate C code within &ECL;, but
1371 everything is built around two functions that allow the user to embed
1372 arbitrary C/C++ code into Lisp source code.</para>
1373 <para>The two mechanisms are the <literal>Clines</literal> and the <literal>c-inline</literal> special
1374 forms. The first one permits to insert code in the intermediate C/C++ file
1375 generated by the &ECL; compiler. Such a form outputs no value and takes
1376 no arguments, except a series of strings which are inserted literally,
1377 such as <literal>#include</literal> or <literal>#define</literal> statements, function definitions, etc.</para>
1378 <blockquote>
1379 <screen><indexterm role="fn"><primary>Clines</primary></indexterm>&#151; Macro: <function>Clines</function> <varname>{</varname><varname>{</varname><varname>string</varname><varname>}</varname><varname>*</varname><varname>}</varname></screen>
1380 <para>When the &ECL; compiler encounters a macro form <literal>(Clines <replaceable>string1
1381 ... stringn</replaceable>)</literal>, it simply outputs the <replaceable>strings</replaceable> into the c-file. The
1382 arguments are not evaluated and each argument must be a string. Each
1383 <replaceable>string</replaceable> may consist of any number of lines, and separate lines in the
1384 <replaceable>string</replaceable> are placed in separate lines in the c-file. In addition, each
1385 <replaceable>string</replaceable> opens a fresh line in the c-file, i.e., the first character in the
1386 <replaceable>string</replaceable> is placed at the first column of a line. Therefore, C-language
1387 preprocessor commands such as <literal>#define</literal> and <literal>#include</literal> will be
1388 recognized as such by the C compiler, if the ' # ' sign appears as the first
1389 character of the <replaceable>string</replaceable> or as the first character of a line within the
1390 <replaceable>string</replaceable>.</para>
1391 <para>When interpreted, a <literal>Clines</literal> macro form expands to ().</para>
1392 </blockquote>
1393 <programlisting>(use-package "FFI")
1394
1395 (Clines
1396 " int tak(x, y, z) "
1397 " int x, y, z; "
1398 " { if (y &gt;= x) return(z); "
1399 " else return(tak(tak(x-1, y, z), "
1400 " tak(y-1, z, x), "
1401 " tak(z-1, x, y))); "
1402 " } "
1403 )
1404
1405 (defun tak (x y z)
1406 (c-inline (x y z) (:int :int :int) :int
1407 "tak(#0,#1,#2)" :one-liner t))
1408 </programlisting>
1409 <para>The second mechanism, which you already appreciate in the example above, is the
1410 <literal>c-inline</literal> special form. This powerful method allows the user to insert C
1411 code which is evaluated, and which can accept values and return values from and
1412 to the Lisp world, with an automatic convertion taking place in both directions.</para>
1413 <blockquote>
1414 <screen><indexterm role="fn"><primary>c-inline</primary></indexterm>&#151; Macro: <function>c-inline</function> <varname>{</varname><varname>args-list</varname> <varname>arg-C-types</varname> <varname>output-C-type</varname> <varname>C-expr</varname> <varname>&amp;key</varname> (<varname>side-effects</varname> <varname><literal>T</literal></varname>) (<varname>one-liner</varname> <varname><literal>T</literal></varname>)<varname>}</varname></screen>
1415 <para><literal>c-inline</literal> is a special form that can only be used in compiled
1416 code. For all purposes it behaves as a Lisp form, which takes the
1417 arguments given in <replaceable>args-list</replaceable> and produces a single value. Behind
1418 the curtains, the arguments of <replaceable>args-list</replaceable> (which can be any valid
1419 Lisp form) are coerced to the the C types given in <replaceable>arg-C-types</replaceable>,
1420 passed to the C expression <replaceable>C-expr</replaceable>, and coerced back to Lisp
1421 using the C type <replaceable>output-C-type</replaceable> as a guide. Multiple return
1422 values can be returned by setting <replaceable>output-C-type</replaceable> to <literal>(values
1423 type-1 type-2 ...)</literal>.</para>
1424 <para><replaceable>C-expr</replaceable> is a string containing C code and maybe some special
1425 escape codes. First, the arguments of the form may be retrieved as
1426 <literal>#0</literal>, <literal>#1</literal>, etc. Second, if the <literal>c-inline</literal> form is a
1427 one-line C expression (That is, <replaceable>one-liner</replaceable> is true), then the
1428 whole expression is interpreted as the output value. But if the code,
1429 on the other hand, is a multiline expression (<replaceable>one-liner</replaceable> is
1430 false), the form has to be output using <literal>@(return)
1431 =...</literal>. Multiple values are returned as <literal>@(return 0)=... ;
1432 @(return 1)=...;</literal>. Finally, Lisp constants may be used in the C code
1433 making use of the prefix <literal>@</literal>.</para>
1434 <programlisting>
1435 (use-package "FFI")
1436
1437 (Clines "
1438 #include &lt;math.h&gt;
1439
1440 double foo (double x, double y) {
1441 return sinh(x) * y;
1442 }")
1443
1444 (defvar *a*
1445 (c-inline (1.23) (:double) :double
1446 "foo(#0,1.44)"
1447 :side-effects nil
1448 :one-liner t))
1449
1450 (defvar *b*
1451 (c-inline (1.23) (:double) :double
1452 "{cl_object x = symbol_value(@*a*);
1453 @(return) = foo(#0,object_to_float(x));}"
1454 :side-effects nil
1455 :one-liner nil))
1456 </programlisting>
1457 </blockquote>
1458 </sect1>
1459
1460 <sect1 label="5.7" xml:id="The-C-language-interface">
1461 <title>The C language interface</title>
1462 <para>Using these special forms <literal>clines</literal> and <literal>c-inline</literal>, plus the ability to
1463 handle pointers to foreign data, we have built a rather complete FFI for
1464 interfacing with the C world. This interface is compatible with the UFFI
1465 specification, which can be found in the web. We recommend you to grab the
1466 documentation from this package and read it carefully. All examples should
1467 run unmodified under &ECL; (Of course, you do not need to download UFFI
1468 itself, as everything is already implemented in &ECL;.</para>
1469 <para>However, because &ECL; provides some additional functionality which escapes the
1470 UFFI, and also for compatibility with older versions of the &ECL; environment,
1471 we provide additional toplevel forms, which are listed in the next section.</para>
1472 </sect1>
1473
1474 <sect1 label="5.8" xml:id="The-old-C-language-interface">
1475 <title>The old C language interface</title>
1476 <para>In this section we list several macros and toplevel forms which are provided
1477 either for convenience or for compatibility with older versions of &ECL;.
1478 You should avoid using them when the UFFI-compatible interface provides
1479 similar functionality.</para>
1480 <para>We define some terminology here which is used throughout this Section. A
1481 <emphasis>C-id</emphasis> is either a Lisp string consisting of a valid C-language
1482 identifier, or a Lisp symbol whose print-name, with all its alphabetic
1483 characters turned into lower case, is a valid C identifier. Thus the symbol
1484 <literal>foo</literal> is equivalent to the string <literal>"foo"</literal> when used as a C-id.
1485 Similarly, a <emphasis>C-expr</emphasis> is a string that may be regarded as a
1486 C-language expression. A <emphasis>C-type</emphasis> is one of the Lisp symbols
1487 <literal>:int, :char, :float, :double,...</literal> and <literal>:object</literal>.
1488 Each corresponds to a data type in the C language; <literal>:object</literal> is
1489 the type of Lisp object and other C-types are primitive data types in C.</para>
1490 <blockquote>
1491 <screen><indexterm role="fn"><primary>defentry</primary></indexterm>&#151; Macro: <function>defentry</function> <varname>{</varname><varname>function</varname> <varname>parameter-list</varname> <varname>C-function</varname><varname>}</varname></screen>
1492 <para><literal>defentry</literal> defines a Lisp function whose body consists of the calling
1493 sequence to a C-language function. <replaceable>function</replaceable> is the name of the Lisp
1494 function to be defined, and <replaceable>C-function</replaceable> specifies the C function to be
1495 invoked. <replaceable>C-function</replaceable> must be either a list <literal>(<replaceable>type C-id</replaceable>)</literal> or
1496 <replaceable>C-id</replaceable>, where <replaceable>type</replaceable> and <replaceable>C-id</replaceable> are the type and the name of the C
1497 function. <replaceable>type</replaceable> must be a C-type or the symbol <literal>void</literal> which means
1498 that the C function returns no value. <literal>(object <replaceable>C-id</replaceable>)</literal> may be
1499 abbreviated as <replaceable>C-id</replaceable>. <replaceable>parameter-list</replaceable> is a list of C-types for the
1500 parameters of the C function. For example, the following <literal>defentry</literal> form
1501 defines a Lisp function <literal>tak</literal> from which the C function <literal>tak</literal> above
1502 is called.</para>
1503 </blockquote>
1504 <programlisting>(defentry tak (:int :int :int) (:int tak))
1505 </programlisting>
1506 <para>The Lisp function <literal>tak</literal> defined by this <literal>defentry</literal> form requires
1507 three arguments. The arguments are converted to <literal>int</literal> values before they
1508 are passed to the C function. On return from the C function, the returned
1509 <literal>int</literal> value is converted to a Lisp integer (actually a fixnum) and this
1510 fixnum will be returned as the value of the Lisp function. See below for type
1511 conversion between Lisp and the C language.</para>
1512 <para>A <literal>defentry</literal> form is treated in the above way only when it appears as a
1513 top-level form of a Lisp source file. Otherwise, a <literal>defentry</literal> form
1514 expands to ().</para>
1515 <blockquote>
1516 <screen><indexterm role="fn"><primary>defla</primary></indexterm>&#151; Macro: <function>defla</function> <varname>{</varname><varname>name</varname> <varname>lambda-list</varname> <varname>{</varname><varname>declaration</varname> <varname>|</varname> <varname>doc-string</varname><varname>}</varname><varname>*</varname><varname>}</varname></screen>
1517 <para>When interpreted, <literal>defla</literal> is exactly the same as <literal>defun</literal>. That is,
1518 <literal>(defla <replaceable>name lambda-list . body</replaceable>)</literal> expands to <literal>(defun <replaceable>name
1519 lambda-list . body</replaceable>)</literal>. However, <literal>defla</literal> forms are completely ignored by
1520 the compiler; no C-language code will be generated for <literal>defla</literal> forms. The
1521 primary use of <literal>defla</literal> is to define a Lisp function in two ways within a
1522 single Lisp source file; one in the C language and the other in Lisp.
1523 <literal>defla</literal> is short for <emphasis>DEF</emphasis>ine <emphasis>L</emphasis>isp <emphasis>A</emphasis>lternative.</para>
1524 </blockquote>
1525 <para>Suppose you have a Lisp source file whose contents are:</para>
1526 <programlisting>(use-package "FFI")
1527
1528 ;;; C version of TAK.
1529 (Clines "
1530
1531 int tak(x, y, z)
1532 int x, y, z;
1533 { if (y &gt;= x) return(z);
1534 else return(tak(tak(x-1, y, z),
1535 tak(y-1, z, x),
1536 tak(z-1, x, y)));
1537 }
1538 "
1539 )
1540
1541 ;;; TAK calls the C function tak defined above.
1542 (defentry tak (:int :int :int) (:int tak))
1543 ;;; The alternative Lisp definition of TAK.
1544 (defla tak (x y z)
1545 (if (&gt;= y x)
1546 z
1547 (tak (tak (1- x) y z)
1548 (tak (1- y) z x)
1549 (tak (1- z) x y))))
1550 </programlisting>
1551 <para>When this file is loaded into &ECL;, the interpreter uses the Lisp version of
1552 the <literal>tak</literal> definition. Once this file has been compiled, and when the
1553 generated fasl file is loaded into &ECL;, a function call to <literal>tak</literal> is
1554 actually the call to the C version of <literal>tak</literal>.</para>
1555 <blockquote>
1556 <screen><indexterm role="fn"><primary>defCbody</primary></indexterm>&#151; Function: <function>defCbody</function> <varname>name args-types result-type C-expr</varname></screen>
1557 <para>The &ECL; compiler produces a function named <replaceable>name</replaceable> with as many
1558 arguments as <replaceable>arg-types</replaceable>. The <replaceable>C-expr</replaceable> is an arbitrary C expression
1559 where the arguments to the function are denoted by <literal>#</para>
1560 <replaceable>i</replaceable></literal>
1561 <para>, where
1562 <literal></para>
1563 <replaceable>i</replaceable></literal>
1564 <para>is the integer corresponding to the argument position. The
1565 <replaceable>args-types</replaceable> is the list of Common-Lisp types of the arguments to the function,
1566 while <replaceable>result-type</replaceable> is the Common-Lisp type of the result. The actual arguments
1567 are coerced to the required types before executing the <replaceable>C-expr</replaceable> and the
1568 result is converted into a Lisp object. <literal>defCbody</literal> is ignored by the
1569 interpreter.</para>
1570 </blockquote>
1571 <para>For example, the logical AND of two integers could be defined as:</para>
1572 <programlisting>(defCbody logand (fixnum fixnum) fixnum "(#0) &amp; (#1)")
1573 </programlisting>
1574 <blockquote>
1575 <screen><indexterm role="fn"><primary>definline</primary></indexterm>&#151; Function: <function>definline</function> <varname>{</varname><varname>name</varname> <varname>args-types</varname> <varname>result-type</varname> <varname>C-expr</varname><varname>}</varname></screen>
1576 <para><literal>definline</literal> behaves exactly as <literal>defCbody</literal>. Moreover, after a
1577 <literal>definline</literal> definition has been supplied, the &ECL; compiler will expand
1578 inline any call to function <replaceable>name</replaceable> into code corresponding to the C
1579 language expression <replaceable>C-expr</replaceable>, provided that the actual arguments are of the
1580 specified type. If the actual arguments cannot be coerced to those types, the
1581 inline expansion is not performed. <literal>definline</literal> is ignored by the
1582 interpreter.</para>
1583 </blockquote>
1584 <para>For example, a function to access the n-th byte of a string and return it as an
1585 integer can be defined as follows:</para>
1586 <programlisting>(definline aref-byte (string fixnum) fixnum
1587 "(#0)-&gt;ust.ust_self[#1]")
1588 </programlisting>
1589 <para>The definitions of the C data structures used to represent \clisp objects can
1590 be found in file <literal>ecl.h</literal> in the directory <literal>"src/h"</literal> of the source
1591 distribution.</para>
1592 <para>&ECL; converts a Lisp object into a C-language data by using the Common-Lisp
1593 function <literal>coerce</literal>: For the C-type <literal>int</literal> (or <literal>char</literal>), the object
1594 is first coerced to a Lisp integer and the least significant 32-bit (or 8-bit)
1595 field is used as the C <literal>int</literal> (or <literal>char</literal>). For the C-type
1596 <literal>float</literal> (or <literal>double</literal>), the object is coerced to a single-float (or a
1597 double-float) and this value is used as the <literal>C float</literal> (or <literal>double</literal>).
1598 Conversion from a C data into a Lisp object is obvious: <literal>C char, int,
1599 float,</literal> and <literal>double</literal> become the equivalent Lisp <literal>character</literal>,
1600 <literal>fixnum</literal>, <literal>single-float</literal>, and <literal>double-float</literal>, respectively.</para>
1601 <para>Here we list the complete syntax of <literal>Clines</literal>, <literal>defentry</literal>,
1602 <literal>definline</literal> and <literal>defCbody</literal> macro forms.</para>
1603 <screen><![CDATA[
1604 Clines-form:
1605 (Clines @{string@}*)
1606
1607 defentry-form:
1608 (defentry symbol (@{C-type@}*)
1609 @{C-function-name | (@{C-type | void@} C-function-name)@})
1610
1611 defCbody-form:
1612 (defCbody symbol (@{type@}*) type C-expr)
1613
1614 definline-form:
1615 (defCbody symbol (@{type@}*) type C-expr)
1616
1617 C-function-name:
1618 @{ string | symbol @}
1619 C-expr:
1620 string
1621 C-type:
1622 @{ object | int | char | float | double @}
1623 ]]></screen>
1624 <!-- -->
1625 </sect1>
1626 </section>
1627
1628 <section xml:id="The-Garbage-Collector">
1629 <title>The Garbage Collector</title>
1630 <para>Using &ECL; in existing application sometimes involves keeping Lisp
1631 objects where the garbage collector normally cannot see them.</para>
1632 <!-- FIXME: Complete this... -->
1633 <!-- -->
1634 </section>
1635
1636 <section xml:id="Porting-ECL">
1637 <title>Porting &ECL;</title>
1638 <para>To port &ECL; to a new architecture, the following steps are required:</para>
1639 <orderedlist numeration="arabic">
1640 <listitem>
1641 <para>Ensure that the GNU Multiprecision library supports this machine.</para>
1642 </listitem>
1643 <listitem>
1644 <para>Ensure that the Boehm-Weiser garbage collector is supported by that
1645 architecture. Alternatively, port ECL's own garbage collector
1646 <filename>src/c/alloc.d</filename> and <filename>src/c/gbc.d</filename> to that platform.</para>
1647 </listitem>
1648 <listitem>
1649 <para>Fix <filename>src/aclocal.in</filename>, <filename>src/h/ecl.h</filename> and <filename>src/h/ecl-cmp.h</filename>
1650 so that they supply flags for the new host machine.</para>
1651 </listitem>
1652 <listitem>
1653 <para>Fix the machine dependent code in <filename>src/c/</filename>. The most critical
1654 parts are in the <filename>unix*</filename> and <filename>thread*</filename> files.</para>
1655 </listitem>
1656 <listitem>
1657 <para>Compile as in any other platform.</para>
1658 </listitem>
1659 <listitem>
1660 <para>Run the tests and compare to the results of other platforms.</para>
1661 </listitem>
1662 </orderedlist>
1663 </section>
1664 </chapter>
1665 <!-- Keep this comment at the end of the file
1666 Local variables:
1667 sgml-parent-document: "ecl.xml"
1668 sgml-indent-step: 1
1669 nxml-child-indent: 1
1670 nxml-outline-child-indent: 1
1671 fill-column: 79
1672 End:
1673 -->
1674 </book>