Move doc files into guile-core distribution (1)
[bpt/guile.git] / doc / data-rep.texi
CommitLineData
38a93523
NJ
1@c essay \input texinfo
2@c essay @c -*-texinfo-*-
3@c essay @c %**start of header
4@c essay @setfilename data-rep.info
5@c essay @settitle Data Representation in Guile
6@c essay @c %**end of header
7
8@c essay @include version.texi
9
10@c essay @dircategory The Algorithmic Language Scheme
11@c essay @direntry
12@c essay * data-rep: (data-rep). Data Representation in Guile --- how to use
13 Guile objects in your C code.
14@c essay @end direntry
15
16@c essay @setchapternewpage off
17
18@c essay @ifinfo
19@c essay Data Representation in Guile
20
21@c essay Copyright (C) 1998, 1999, 2000 Free Software Foundation
22
23@c essay Permission is granted to make and distribute verbatim copies of
24@c essay this manual provided the copyright notice and this permission notice
25@c essay are preserved on all copies.
26
27@c essay @ignore
28@c essay Permission is granted to process this file through TeX and print the
29@c essay results, provided the printed document carries copying permission
30@c essay notice identical to this one except for the removal of this paragraph
31@c essay (this paragraph not being relevant to the printed manual).
32@c essay @end ignore
33
34@c essay Permission is granted to copy and distribute modified versions of this
35@c essay manual under the conditions for verbatim copying, provided that the entire
36@c essay resulting derived work is distributed under the terms of a permission
37@c essay notice identical to this one.
38
39@c essay Permission is granted to copy and distribute translations of this manual
40@c essay into another language, under the above conditions for modified versions,
41@c essay except that this permission notice may be stated in a translation approved
42@c essay by the Free Software Foundation.
43@c essay @end ifinfo
44
45@c essay @titlepage
46@c essay @sp 10
47@c essay @comment The title is printed in a large font.
48@c essay @title Data Representation in Guile
49@c essay @subtitle $Id: data-rep.texi,v 1.17 2001-03-09 08:21:59 ossau Exp $
50@c essay @subtitle For use with Guile @value{VERSION}
51@c essay @author Jim Blandy
52@c essay @author Free Software Foundation
53@c essay @author @email{jimb@@red-bean.com}
54@c essay @c The following two commands start the copyright page.
55@c essay @page
56@c essay @vskip 0pt plus 1filll
57@c essay @vskip 0pt plus 1filll
58@c essay Copyright @copyright{} 1998 Free Software Foundation
59
60@c essay Permission is granted to make and distribute verbatim copies of
61@c essay this manual provided the copyright notice and this permission notice
62@c essay are preserved on all copies.
63
64@c essay Permission is granted to copy and distribute modified versions of this
65@c essay manual under the conditions for verbatim copying, provided that the entire
66@c essay resulting derived work is distributed under the terms of a permission
67@c essay notice identical to this one.
68
69@c essay Permission is granted to copy and distribute translations of this manual
70@c essay into another language, under the above conditions for modified versions,
71@c essay except that this permission notice may be stated in a translation approved
72@c essay by Free Software Foundation.
73@c essay @end titlepage
74
75@c essay @c @smallbook
76@c essay @c @finalout
77@c essay @headings double
78
79
80@c essay @node Top, Data Representation in Scheme, (dir), (dir)
81@c essay @top Data Representation in Guile
82
83@c essay @ifinfo
84@c essay This essay is meant to provide the background necessary to read and
85@c essay write C code that manipulates Scheme values in a way that conforms to
86@c essay libguile's interface. If you would like to write or maintain a
87@c essay Guile-based application in C or C++, this is the first information you
88@c essay need.
89
90@c essay In order to make sense of Guile's @code{SCM_} functions, or read
91@c essay libguile's source code, it's essential to have a good grasp of how Guile
92@c essay actually represents Scheme values. Otherwise, a lot of the code, and
93@c essay the conventions it follows, won't make very much sense.
94
95@c essay We assume you know both C and Scheme, but we do not assume you are
96@c essay familiar with Guile's C interface.
97@c essay @end ifinfo
98
99
100@page
101@node Data Representation
102@chapter Data Representation in Guile
103
104@strong{by Jim Blandy}
105
106[Due to the rather non-orthogonal and performance-oriented nature of the
107SCM interface, you need to understand SCM internals *before* you can use
108the SCM API. That's why this chapter comes first.]
109
110[NOTE: this is Jim Blandy's essay almost entirely unmodified. It has to
111be adapted to fit this manual smoothly.]
112
113In order to make sense of Guile's SCM_ functions, or read libguile's
114source code, it's essential to have a good grasp of how Guile actually
115represents Scheme values. Otherwise, a lot of the code, and the
116conventions it follows, won't make very much sense. This essay is meant
117to provide the background necessary to read and write C code that
118manipulates Scheme values in a way that is compatible with libguile.
119
120We assume you know both C and Scheme, but we do not assume you are
121familiar with Guile's implementation.
122
123@menu
124* Data Representation in Scheme:: Why things aren't just totally
125 straightforward, in general terms.
126* How Guile does it:: How to write C code that manipulates
127 Guile values, with an explanation
128 of Guile's garbage collector.
129* Defining New Types (Smobs):: How to extend Guile with your own
130 application-specific datatypes.
131@end menu
132
133@node Data Representation in Scheme
134@section Data Representation in Scheme
135
136Scheme is a latently-typed language; this means that the system cannot,
137in general, determine the type of a given expression at compile time.
138Types only become apparent at run time. Variables do not have fixed
139types; a variable may hold a pair at one point, an integer at the next,
140and a thousand-element vector later. Instead, values, not variables,
141have fixed types.
142
143In order to implement standard Scheme functions like @code{pair?} and
144@code{string?} and provide garbage collection, the representation of
145every value must contain enough information to accurately determine its
146type at run time. Often, Scheme systems also use this information to
147determine whether a program has attempted to apply an operation to an
148inappropriately typed value (such as taking the @code{car} of a string).
149
150Because variables, pairs, and vectors may hold values of any type,
151Scheme implementations use a uniform representation for values --- a
152single type large enough to hold either a complete value or a pointer
153to a complete value, along with the necessary typing information.
154
155The following sections will present a simple typing system, and then
156make some refinements to correct its major weaknesses. However, this is
157not a description of the system Guile actually uses. It is only an
158illustration of the issues Guile's system must address. We provide all
159the information one needs to work with Guile's data in @ref{How Guile
160does it}.
161
162
163@menu
164* A Simple Representation::
165* Faster Integers::
166* Cheaper Pairs::
167* Guile Is Hairier::
168@end menu
169
170@node A Simple Representation
171@subsection A Simple Representation
172
173The simplest way to meet the above requirements in C would be to
174represent each value as a pointer to a structure containing a type
175indicator, followed by a union carrying the real value. Assuming that
176@code{SCM} is the name of our universal type, we can write:
177
178@example
179enum type @{ integer, pair, string, vector, ... @};
180
181typedef struct value *SCM;
182
183struct value @{
184 enum type type;
185 union @{
186 int integer;
187 struct @{ SCM car, cdr; @} pair;
188 struct @{ int length; char *elts; @} string;
189 struct @{ int length; SCM *elts; @} vector;
190 ...
191 @} value;
192@};
193@end example
194with the ellipses replaced with code for the remaining Scheme types.
195
196This representation is sufficient to implement all of Scheme's
197semantics. If @var{x} is an @code{SCM} value:
198@itemize @bullet
199@item
200 To test if @var{x} is an integer, we can write @code{@var{x}->type == integer}.
201@item
202 To find its value, we can write @code{@var{x}->value.integer}.
203@item
204 To test if @var{x} is a vector, we can write @code{@var{x}->type == vector}.
205@item
206 If we know @var{x} is a vector, we can write
207 @code{@var{x}->value.vector.elts[0]} to refer to its first element.
208@item
209 If we know @var{x} is a pair, we can write
210 @code{@var{x}->value.pair.car} to extract its car.
211@end itemize
212
213
214@node Faster Integers
215@subsection Faster Integers
216
217Unfortunately, the above representation has a serious disadvantage. In
218order to return an integer, an expression must allocate a @code{struct
219value}, initialize it to represent that integer, and return a pointer to
220it. Furthermore, fetching an integer's value requires a memory
221reference, which is much slower than a register reference on most
222processors. Since integers are extremely common, this representation is
223too costly, in both time and space. Integers should be very cheap to
224create and manipulate.
225
226One possible solution comes from the observation that, on many
227architectures, structures must be aligned on a four-byte boundary.
228(Whether or not the machine actually requires it, we can write our own
229allocator for @code{struct value} objects that assures this is true.)
230In this case, the lower two bits of the structure's address are known to
231be zero.
232
233This gives us the room we need to provide an improved representation
234for integers. We make the following rules:
235@itemize @bullet
236@item
237If the lower two bits of an @code{SCM} value are zero, then the SCM
238value is a pointer to a @code{struct value}, and everything proceeds as
239before.
240@item
241Otherwise, the @code{SCM} value represents an integer, whose value
242appears in its upper bits.
243@end itemize
244
245Here is C code implementing this convention:
246@example
247enum type @{ pair, string, vector, ... @};
248
249typedef struct value *SCM;
250
251struct value @{
252 enum type type;
253 union @{
254 struct @{ SCM car, cdr; @} pair;
255 struct @{ int length; char *elts; @} string;
256 struct @{ int length; SCM *elts; @} vector;
257 ...
258 @} value;
259@};
260
261#define POINTER_P(x) (((int) (x) & 3) == 0)
262#define INTEGER_P(x) (! POINTER_P (x))
263
264#define GET_INTEGER(x) ((int) (x) >> 2)
265#define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1))
266@end example
267
268Notice that @code{integer} no longer appears as an element of @code{enum
269type}, and the union has lost its @code{integer} member. Instead, we
270use the @code{POINTER_P} and @code{INTEGER_P} macros to make a coarse
271classification of values into integers and non-integers, and do further
272type testing as before.
273
274Here's how we would answer the questions posed above (again, assume
275@var{x} is an @code{SCM} value):
276@itemize @bullet
277@item
278 To test if @var{x} is an integer, we can write @code{INTEGER_P (@var{x})}.
279@item
280 To find its value, we can write @code{GET_INTEGER (@var{x})}.
281@item
282 To test if @var{x} is a vector, we can write:
283@example
284 @code{POINTER_P (@var{x}) && @var{x}->type == vector}
285@end example
286 Given the new representation, we must make sure @var{x} is truly a
287 pointer before we dereference it to determine its complete type.
288@item
289 If we know @var{x} is a vector, we can write
290 @code{@var{x}->value.vector.elts[0]} to refer to its first element, as
291 before.
292@item
293 If we know @var{x} is a pair, we can write
294 @code{@var{x}->value.pair.car} to extract its car, just as before.
295@end itemize
296
297This representation allows us to operate more efficiently on integers
298than the first. For example, if @var{x} and @var{y} are known to be
299integers, we can compute their sum as follows:
300@example
301MAKE_INTEGER (GET_INTEGER (@var{x}) + GET_INTEGER (@var{y}))
302@end example
303Now, integer math requires no allocation or memory references. Most
304real Scheme systems actually use an even more efficient representation,
305but this essay isn't about bit-twiddling. (Hint: what if pointers had
306@code{01} in their least significant bits, and integers had @code{00}?)
307
308
309@node Cheaper Pairs
310@subsection Cheaper Pairs
311
312However, there is yet another issue to confront. Most Scheme heaps
313contain more pairs than any other type of object; Jonathan Rees says
314that pairs occupy 45% of the heap in his Scheme implementation, Scheme
31548. However, our representation above spends three @code{SCM}-sized
316words per pair --- one for the type, and two for the @sc{car} and
317@sc{cdr}. Is there any way to represent pairs using only two words?
318
319Let us refine the convention we established earlier. Let us assert
320that:
321@itemize @bullet
322@item
323 If the bottom two bits of an @code{SCM} value are @code{#b00}, then
324 it is a pointer, as before.
325@item
326 If the bottom two bits are @code{#b01}, then the upper bits are an
327 integer. This is a bit more restrictive than before.
328@item
329 If the bottom two bits are @code{#b10}, then the value, with the bottom
330 two bits masked out, is the address of a pair.
331@end itemize
332
333Here is the new C code:
334@example
335enum type @{ string, vector, ... @};
336
337typedef struct value *SCM;
338
339struct value @{
340 enum type type;
341 union @{
342 struct @{ int length; char *elts; @} string;
343 struct @{ int length; SCM *elts; @} vector;
344 ...
345 @} value;
346@};
347
348struct pair @{
349 SCM car, cdr;
350@};
351
352#define POINTER_P(x) (((int) (x) & 3) == 0)
353
354#define INTEGER_P(x) (((int) (x) & 3) == 1)
355#define GET_INTEGER(x) ((int) (x) >> 2)
356#define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1))
357
358#define PAIR_P(x) (((int) (x) & 3) == 2)
359#define GET_PAIR(x) ((struct pair *) ((int) (x) & ~3))
360@end example
361
362Notice that @code{enum type} and @code{struct value} now only contain
363provisions for vectors and strings; both integers and pairs have become
364special cases. The code above also assumes that an @code{int} is large
365enough to hold a pointer, which isn't generally true.
366
367
368Our list of examples is now as follows:
369@itemize @bullet
370@item
371 To test if @var{x} is an integer, we can write @code{INTEGER_P
372 (@var{x})}; this is as before.
373@item
374 To find its value, we can write @code{GET_INTEGER (@var{x})}, as
375 before.
376@item
377 To test if @var{x} is a vector, we can write:
378@example
379 @code{POINTER_P (@var{x}) && @var{x}->type == vector}
380@end example
381 We must still make sure that @var{x} is a pointer to a @code{struct
382 value} before dereferencing it to find its type.
383@item
384 If we know @var{x} is a vector, we can write
385 @code{@var{x}->value.vector.elts[0]} to refer to its first element, as
386 before.
387@item
388 We can write @code{PAIR_P (@var{x})} to determine if @var{x} is a
389 pair, and then write @code{GET_PAIR (@var{x})->car} to refer to its
390 car.
391@end itemize
392
393This change in representation reduces our heap size by 15%. It also
394makes it cheaper to decide if a value is a pair, because no memory
395references are necessary; it suffices to check the bottom two bits of
396the @code{SCM} value. This may be significant when traversing lists, a
397common activity in a Scheme system.
398
399Again, most real Scheme systems use a slighty different implementation;
400for example, if GET_PAIR subtracts off the low bits of @code{x}, instead
401of masking them off, the optimizer will often be able to combine that
402subtraction with the addition of the offset of the structure member we
403are referencing, making a modified pointer as fast to use as an
404unmodified pointer.
405
406
407@node Guile Is Hairier
408@subsection Guile Is Hairier
409
410We originally started with a very simple typing system --- each object
411has a field that indicates its type. Then, for the sake of efficiency
412in both time and space, we moved some of the typing information directly
413into the @code{SCM} value, and left the rest in the @code{struct value}.
414Guile itself employs a more complex hierarchy, storing finer and finer
415gradations of type information in different places, depending on the
416object's coarser type.
417
418In the author's opinion, Guile could be simplified greatly without
419significant loss of efficiency, but the simplified system would still be
420more complex than what we've presented above.
421
422
423@node How Guile does it
424@section How Guile does it
425
426Here we present the specifics of how Guile represents its data. We
427don't go into complete detail; an exhaustive description of Guile's
428system would be boring, and we do not wish to encourage people to write
429code which depends on its details anyway. We do, however, present
430everything one need know to use Guile's data.
431
432
433@menu
434* General Rules::
435* Conservative GC::
436* Immediates vs. Non-immediates::
437* Immediate Datatypes::
438* Non-immediate Datatypes::
439* Signalling Type Errors::
440@end menu
441
442@node General Rules
443@subsection General Rules
444
445Any code which operates on Guile datatypes must @code{#include} the
446header file @code{<libguile.h>}. This file contains a definition for
447the @code{SCM} typedef (Guile's universal type, as in the examples
448above), and definitions and declarations for a host of macros and
449functions that operate on @code{SCM} values.
450
451All identifiers declared by @code{<libguile.h>} begin with @code{scm_}
452or @code{SCM_}.
453
454@c [[I wish this were true, but I don't think it is at the moment. -JimB]]
455@c Macros do not evaluate their arguments more than once, unless documented
456@c to do so.
457
458The functions described here generally check the types of their
459@code{SCM} arguments, and signal an error if their arguments are of an
460inappropriate type. Macros generally do not, unless that is their
461specified purpose. You must verify their argument types beforehand, as
462necessary.
463
464Macros and functions that return a boolean value have names ending in
465@code{P} or @code{_p} (for ``predicate''). Those that return a negated
466boolean value have names starting with @code{SCM_N}. For example,
467@code{SCM_IMP (@var{x})} is a predicate which returns non-zero iff
468@var{x} is an immediate value (an @code{IM}). @code{SCM_NCONSP
469(@var{x})} is a predicate which returns non-zero iff @var{x} is
470@emph{not} a pair object (a @code{CONS}).
471
472
473@node Conservative GC
474@subsection Conservative Garbage Collection
475
476Aside from the latent typing, the major source of constraints on a
477Scheme implementation's data representation is the garbage collector.
478The collector must be able to traverse every live object in the heap, to
479determine which objects are not live.
480
481There are many ways to implement this, but Guile uses an algorithm
482called @dfn{mark and sweep}. The collector scans the system's global
483variables and the local variables on the stack to determine which
484objects are immediately accessible by the C code. It then scans those
485objects to find the objects they point to, @i{et cetera}. The collector
486sets a @dfn{mark bit} on each object it finds, so each object is
487traversed only once. This process is called @dfn{tracing}.
488
489When the collector can find no unmarked objects pointed to by marked
490objects, it assumes that any objects that are still unmarked will never
491be used by the program (since there is no path of dereferences from any
492global or local variable that reaches them) and deallocates them.
493
494In the above paragraphs, we did not specify how the garbage collector
495finds the global and local variables; as usual, there are many different
496approaches. Frequently, the programmer must maintain a list of pointers
497to all global variables that refer to the heap, and another list
498(adjusted upon entry to and exit from each function) of local variables,
499for the collector's benefit.
500
501The list of global variables is usually not too difficult to maintain,
502since global variables are relatively rare. However, an explicitly
503maintained list of local variables (in the author's personal experience)
504is a nightmare to maintain. Thus, Guile uses a technique called
505@dfn{conservative garbage collection}, to make the local variable list
506unnecessary.
507
508The trick to conservative collection is to treat the stack as an
509ordinary range of memory, and assume that @emph{every} word on the stack
510is a pointer into the heap. Thus, the collector marks all objects whose
511addresses appear anywhere in the stack, without knowing for sure how
512that word is meant to be interpreted.
513
514Obviously, such a system will occasionally retain objects that are
515actually garbage, and should be freed. In practice, this is not a
516problem. The alternative, an explicitly maintained list of local
517variable addresses, is effectively much less reliable, due to programmer
518error.
519
520To accommodate this technique, data must be represented so that the
521collector can accurately determine whether a given stack word is a
522pointer or not. Guile does this as follows:
523@itemize @bullet
524
525@item
526Every heap object has a two-word header, called a @dfn{cell}. Some
527objects, like pairs, fit entirely in a cell's two words; others may
528store pointers to additional memory in either of the words. For
529example, strings and vectors store their length in the first word, and a
530pointer to their elements in the second.
531
532@item
533Guile allocates whole arrays of cells at a time, called @dfn{heap
534segments}. These segments are always allocated so that the cells they
535contain fall on eight-byte boundaries, or whatever is appropriate for
536the machine's word size. Guile keeps all cells in a heap segment
537initialized, whether or not they are currently in use.
538
539@item
540Guile maintains a sorted table of heap segments.
541
542@end itemize
543
544Thus, given any random word @var{w} fetched from the stack, Guile's
545garbage collector can consult the table to see if @var{w} falls within a
546known heap segment, and check @var{w}'s alignment. If both tests pass,
547the collector knows that @var{w} is a valid pointer to a cell,
548intentional or not, and proceeds to trace the cell.
549
550Note that heap segments do not contain all the data Guile uses; cells
551for objects like vectors and strings contain pointers to other memory
552areas. However, since those pointers are internal, and not shared among
553many pieces of code, it is enough for the collector to find the cell,
554and then use the cell's type to find more pointers to trace.
555
556
557@node Immediates vs. Non-immediates
558@subsection Immediates vs. Non-immediates
559
560Guile classifies Scheme objects into two kinds: those that fit entirely
561within an @code{SCM}, and those that require heap storage.
562
563The former class are called @dfn{immediates}. The class of immediates
564includes small integers, characters, boolean values, the empty list, the
565mysterious end-of-file object, and some others.
566
567The remaining types are called, not suprisingly, @dfn{non-immediates}.
568They include pairs, procedures, strings, vectors, and all other data
569types in Guile.
570
571@deftypefn Macro int SCM_IMP (SCM @var{x})
572Return non-zero iff @var{x} is an immediate object.
573@end deftypefn
574
575@deftypefn Macro int SCM_NIMP (SCM @var{x})
576Return non-zero iff @var{x} is a non-immediate object. This is the
577exact complement of @code{SCM_IMP}, above.
578
579You must use this macro before calling a finer-grained predicate to
580determine @var{x}'s type. For example, to see if @var{x} is a pair, you
581must write:
582@example
583SCM_NIMP (@var{x}) && SCM_CONSP (@var{x})
584@end example
585This is because Guile stores typing information for non-immediate values
586in their cells, rather than in the @code{SCM} value itself; thus, you
587must determine whether @var{x} refers to a cell before looking inside
588it.
589
590This is somewhat of a pity, because it means that the programmer needs
591to know which types Guile implements as immediates vs. non-immediates.
592There are (possibly better) representations in which @code{SCM_CONSP}
593can be self-sufficient. The immediate type predicates do not suffer
594from this weakness.
595@end deftypefn
596
597
598@node Immediate Datatypes
599@subsection Immediate Datatypes
600
601The following datatypes are immediate values; that is, they fit entirely
602within an @code{SCM} value. The @code{SCM_IMP} and @code{SCM_NIMP}
603macros will distinguish these from non-immediates; see @ref{Immediates
604vs. Non-immediates} for an explanation of the distinction.
605
606Note that the type predicates for immediate values work correctly on any
607@code{SCM} value; you do not need to call @code{SCM_IMP} first, to
608establish that a value is immediate. This differs from the
609non-immediate type predicates, which work correctly only on
610non-immediate values; you must be sure the value is @code{SCM_NIMP}
611before applying them.
612
613
614@menu
615* Integer Data::
616* Character Data::
617* Boolean Data::
618* Unique Values::
619@end menu
620
621@node Integer Data
622@subsubsection Integers
623
624Here are functions for operating on small integers, that fit within an
625@code{SCM}. Such integers are called @dfn{immediate numbers}, or
626@dfn{INUMs}. In general, INUMs occupy all but two bits of an
627@code{SCM}.
628
629Bignums and floating-point numbers are non-immediate objects, and have
630their own, separate accessors. The functions here will not work on
631them. This is not as much of a problem as you might think, however,
632because the system never constructs bignums that could fit in an INUM,
633and never uses floating point values for exact integers.
634
635@deftypefn Macro int SCM_INUMP (SCM @var{x})
636Return non-zero iff @var{x} is a small integer value.
637@end deftypefn
638
639@deftypefn Macro int SCM_NINUMP (SCM @var{x})
640The complement of SCM_INUMP.
641@end deftypefn
642
643@deftypefn Macro int SCM_INUM (SCM @var{x})
644Return the value of @var{x} as an ordinary, C integer. If @var{x}
645is not an INUM, the result is undefined.
646@end deftypefn
647
648@deftypefn Macro SCM SCM_MAKINUM (int @var{i})
649Given a C integer @var{i}, return its representation as an @code{SCM}.
650This function does not check for overflow.
651@end deftypefn
652
653
654@node Character Data
655@subsubsection Characters
656
657Here are functions for operating on characters.
658
659@deftypefn Macro int SCM_CHARP (SCM @var{x})
660Return non-zero iff @var{x} is a character value.
661@end deftypefn
662
663@deftypefn Macro {unsigned int} SCM_CHAR (SCM @var{x})
664Return the value of @code{x} as a C character. If @var{x} is not a
665Scheme character, the result is undefined.
666@end deftypefn
667
668@deftypefn Macro SCM SCM_MAKE_CHAR (int @var{c})
669Given a C character @var{c}, return its representation as a Scheme
670character value.
671@end deftypefn
672
673
674@node Boolean Data
675@subsubsection Booleans
676
677Here are functions and macros for operating on booleans.
678
679@deftypefn Macro SCM SCM_BOOL_T
680@deftypefnx Macro SCM SCM_BOOL_F
681The Scheme true and false values.
682@end deftypefn
683
684@deftypefn Macro int SCM_NFALSEP (@var{x})
685Convert the Scheme boolean value to a C boolean. Since every object in
686Scheme except @code{#f} is true, this amounts to comparing @var{x} to
687@code{#f}; hence the name.
688@c Noel feels a chill here.
689@end deftypefn
690
691@deftypefn Macro SCM SCM_BOOL_NOT (@var{x})
692Return the boolean inverse of @var{x}. If @var{x} is not a
693Scheme boolean, the result is undefined.
694@end deftypefn
695
696
697@node Unique Values
698@subsubsection Unique Values
699
700The immediate values that are neither small integers, characters, nor
701booleans are all unique values --- that is, datatypes with only one
702instance.
703
704@deftypefn Macro SCM SCM_EOL
705The Scheme empty list object, or ``End Of List'' object, usually written
706in Scheme as @code{'()}.
707@end deftypefn
708
709@deftypefn Macro SCM SCM_EOF_VAL
710The Scheme end-of-file value. It has no standard written
711representation, for obvious reasons.
712@end deftypefn
713
714@deftypefn Macro SCM SCM_UNSPECIFIED
715The value returned by expressions which the Scheme standard says return
716an ``unspecified'' value.
717
718This is sort of a weirdly literal way to take things, but the standard
719read-eval-print loop prints nothing when the expression returns this
720value, so it's not a bad idea to return this when you can't think of
721anything else helpful.
722@end deftypefn
723
724@deftypefn Macro SCM SCM_UNDEFINED
725The ``undefined'' value. Its most important property is that is not
726equal to any valid Scheme value. This is put to various internal uses
727by C code interacting with Guile.
728
729For example, when you write a C function that is callable from Scheme
730and which takes optional arguments, the interpreter passes
731@code{SCM_UNDEFINED} for any arguments you did not receive.
732
733We also use this to mark unbound variables.
734@end deftypefn
735
736@deftypefn Macro int SCM_UNBNDP (SCM @var{x})
737Return true if @var{x} is @code{SCM_UNDEFINED}. Apply this to a
738symbol's value to see if it has a binding as a global variable.
739@end deftypefn
740
741
742@node Non-immediate Datatypes
743@subsection Non-immediate Datatypes
744
745A non-immediate datatype is one which lives in the heap, either because
746it cannot fit entirely within a @code{SCM} word, or because it denotes a
747specific storage location (in the nomenclature of the Revised^4 Report
748on Scheme).
749
750The @code{SCM_IMP} and @code{SCM_NIMP} macros will distinguish these
751from immediates; see @ref{Immediates vs. Non-immediates}.
752
753Given a cell, Guile distinguishes between pairs and other non-immediate
754types by storing special @dfn{tag} values in a non-pair cell's car, that
755cannot appear in normal pairs. A cell with a non-tag value in its car
756is an ordinary pair. The type of a cell with a tag in its car depends
757on the tag; the non-immediate type predicates test this value. If a tag
758value appears elsewhere (in a vector, for example), the heap may become
759corrupted.
760
761
762@menu
763* Non-immediate Type Predicates:: Special rules for using the type
764 predicates described here.
765* Pair Data::
766* Vector Data::
767* Procedures::
768* Closures::
769* Subrs::
770* Port Data::
771@end menu
772
773@node Non-immediate Type Predicates
774@subsubsection Non-immediate Type Predicates
775
776As mentioned in @ref{Conservative GC}, all non-immediate objects
777start with a @dfn{cell}, or a pair of words. Furthermore, all type
778information that distinguishes one kind of non-immediate from another is
779stored in the cell. The type information in the @code{SCM} value
780indicates only that the object is a non-immediate; all finer
781distinctions require one to examine the cell itself, usually with the
782appropriate type predicate macro.
783
784The type predicates for non-immediate objects generally assume that
785their argument is a non-immediate value. Thus, you must be sure that a
786value is @code{SCM_NIMP} first before passing it to a non-immediate type
787predicate. Thus, the idiom for testing whether a value is a cell or not
788is:
789@example
790SCM_NIMP (@var{x}) && SCM_CONSP (@var{x})
791@end example
792
793
794@node Pair Data
795@subsubsection Pairs
796
797Pairs are the essential building block of list structure in Scheme. A
798pair object has two fields, called the @dfn{car} and the @dfn{cdr}.
799
800It is conventional for a pair's @sc{car} to contain an element of a
801list, and the @sc{cdr} to point to the next pair in the list, or to
802contain @code{SCM_EOL}, indicating the end of the list. Thus, a set of
803pairs chained through their @sc{cdr}s constitutes a singly-linked list.
804Scheme and libguile define many functions which operate on lists
805constructed in this fashion, so although lists chained through the
806@sc{car}s of pairs will work fine too, they may be less convenient to
807manipulate, and receive less support from the community.
808
809Guile implements pairs by mapping the @sc{car} and @sc{cdr} of a pair
810directly into the two words of the cell.
811
812
813@deftypefn Macro int SCM_CONSP (SCM @var{x})
814Return non-zero iff @var{x} is a Scheme pair object.
815The results are undefined if @var{x} is an immediate value.
816@end deftypefn
817
818@deftypefn Macro int SCM_NCONSP (SCM @var{x})
819The complement of SCM_CONSP.
820@end deftypefn
821
822@deftypefn Macro void SCM_NEWCELL (SCM @var{into})
823Allocate a new cell, and set @var{into} to point to it. This macro
824expands to a statement, not an expression, and @var{into} must be an
825lvalue of type SCM.
826
827This is the most primitive way to allocate a cell; it is quite fast.
828
829The @sc{car} of the cell initially tags it as a ``free cell''. If the
830caller intends to use it as an ordinary cons, she must store ordinary
831SCM values in its @sc{car} and @sc{cdr}.
832
833If the caller intends to use it as a header for some other type, she
834must store an appropriate magic value in the cell's @sc{car}, to mark
835it as a member of that type, and store whatever value in the @sc{cdr}
836that type expects. You should generally not do this, unless you are
837implementing a new datatype, and thoroughly understand the code in
838@code{<libguile/tags.h>}.
839@end deftypefn
840
841@deftypefun SCM scm_cons (SCM @var{car}, SCM @var{cdr})
842Allocate (``CONStruct'') a new pair, with @var{car} and @var{cdr} as its
843contents.
844@end deftypefun
845
846
847The macros below perform no typechecking. The results are undefined if
848@var{cell} is an immediate. However, since all non-immediate Guile
849objects are constructed from cells, and these macros simply return the
850first element of a cell, they actually can be useful on datatypes other
851than pairs. (Of course, it is not very modular to use them outside of
852the code which implements that datatype.)
853
854@deftypefn Macro SCM SCM_CAR (SCM @var{cell})
855Return the @sc{car}, or first field, of @var{cell}.
856@end deftypefn
857
858@deftypefn Macro SCM SCM_CDR (SCM @var{cell})
859Return the @sc{cdr}, or second field, of @var{cell}.
860@end deftypefn
861
862@deftypefn Macro void SCM_SETCAR (SCM @var{cell}, SCM @var{x})
863Set the @sc{car} of @var{cell} to @var{x}.
864@end deftypefn
865
866@deftypefn Macro void SCM_SETCDR (SCM @var{cell}, SCM @var{x})
867Set the @sc{cdr} of @var{cell} to @var{x}.
868@end deftypefn
869
870@deftypefn Macro SCM SCM_CAAR (SCM @var{cell})
871@deftypefnx Macro SCM SCM_CADR (SCM @var{cell})
872@deftypefnx Macro SCM SCM_CDAR (SCM @var{cell}) @dots{}
873@deftypefnx Macro SCM SCM_CDDDDR (SCM @var{cell})
874Return the @sc{car} of the @sc{car} of @var{cell}, the @sc{car} of the
875@sc{cdr} of @var{cell}, @i{et cetera}.
876@end deftypefn
877
878
879@node Vector Data
880@subsubsection Vectors, Strings, and Symbols
881
882Vectors, strings, and symbols have some properties in common. They all
883have a length, and they all have an array of elements. In the case of a
884vector, the elements are @code{SCM} values; in the case of a string or
885symbol, the elements are characters.
886
887All these types store their length (along with some tagging bits) in the
888@sc{car} of their header cell, and store a pointer to the elements in
889their @sc{cdr}. Thus, the @code{SCM_CAR} and @code{SCM_CDR} macros
890are (somewhat) meaningful when applied to these datatypes.
891
892@deftypefn Macro int SCM_VECTORP (SCM @var{x})
893Return non-zero iff @var{x} is a vector.
894The results are undefined if @var{x} is an immediate value.
895@end deftypefn
896
897@deftypefn Macro int SCM_STRINGP (SCM @var{x})
898Return non-zero iff @var{x} is a string.
899The results are undefined if @var{x} is an immediate value.
900@end deftypefn
901
902@deftypefn Macro int SCM_SYMBOLP (SCM @var{x})
903Return non-zero iff @var{x} is a symbol.
904The results are undefined if @var{x} is an immediate value.
905@end deftypefn
906
907@deftypefn Macro int SCM_LENGTH (SCM @var{x})
908Return the length of the object @var{x}.
909The results are undefined if @var{x} is not a vector, string, or symbol.
910@end deftypefn
911
912@deftypefn Macro {SCM *} SCM_VELTS (SCM @var{x})
913Return a pointer to the array of elements of the vector @var{x}.
914The results are undefined if @var{x} is not a vector.
915@end deftypefn
916
917@deftypefn Macro {char *} SCM_CHARS (SCM @var{x})
918Return a pointer to the characters of @var{x}.
919The results are undefined if @var{x} is not a symbol or a string.
920@end deftypefn
921
922There are also a few magic values stuffed into memory before a symbol's
923characters, but you don't want to know about those. What cruft!
924
925
926@node Procedures
927@subsubsection Procedures
928
929Guile provides two kinds of procedures: @dfn{closures}, which are the
930result of evaluating a @code{lambda} expression, and @dfn{subrs}, which
931are C functions packaged up as Scheme objects, to make them available to
932Scheme programmers.
933
934(There are actually other sorts of procedures: compiled closures, and
935continuations; see the source code for details about them.)
936
937@deftypefun SCM scm_procedure_p (SCM @var{x})
938Return @code{SCM_BOOL_T} iff @var{x} is a Scheme procedure object, of
939any sort. Otherwise, return @code{SCM_BOOL_F}.
940@end deftypefun
941
942
943@node Closures
944@subsubsection Closures
945
946[FIXME: this needs to be further subbed, but texinfo has no subsubsub]
947
948A closure is a procedure object, generated as the value of a
949@code{lambda} expression in Scheme. The representation of a closure is
950straightforward --- it contains a pointer to the code of the lambda
951expression from which it was created, and a pointer to the environment
952it closes over.
953
954In Guile, each closure also has a property list, allowing the system to
955store information about the closure. I'm not sure what this is used for
956at the moment --- the debugger, maybe?
957
958@deftypefn Macro int SCM_CLOSUREP (SCM @var{x})
959Return non-zero iff @var{x} is a closure. The results are
960undefined if @var{x} is an immediate value.
961@end deftypefn
962
963@deftypefn Macro SCM SCM_PROCPROPS (SCM @var{x})
964Return the property list of the closure @var{x}. The results are
965undefined if @var{x} is not a closure.
966@end deftypefn
967
968@deftypefn Macro void SCM_SETPROCPROPS (SCM @var{x}, SCM @var{p})
969Set the property list of the closure @var{x} to @var{p}. The results
970are undefined if @var{x} is not a closure.
971@end deftypefn
972
973@deftypefn Macro SCM SCM_CODE (SCM @var{x})
974Return the code of the closure @var{x}. The results are undefined if
975@var{x} is not a closure.
976
977This function should probably only be used internally by the
978interpreter, since the representation of the code is intimately
979connected with the interpreter's implementation.
980@end deftypefn
981
982@deftypefn Macro SCM SCM_ENV (SCM @var{x})
983Return the environment enclosed by @var{x}.
984The results are undefined if @var{x} is not a closure.
985
986This function should probably only be used internally by the
987interpreter, since the representation of the environment is intimately
988connected with the interpreter's implementation.
989@end deftypefn
990
991
992@node Subrs
993@subsubsection Subrs
994
995[FIXME: this needs to be further subbed, but texinfo has no subsubsub]
996
997A subr is a pointer to a C function, packaged up as a Scheme object to
998make it callable by Scheme code. In addition to the function pointer,
999the subr also contains a pointer to the name of the function, and
1000information about the number of arguments accepted by the C fuction, for
1001the sake of error checking.
1002
1003There is no single type predicate macro that recognizes subrs, as
1004distinct from other kinds of procedures. The closest thing is
1005@code{scm_procedure_p}; see @ref{Procedures}.
1006
1007@deftypefn Macro {char *} SCM_SNAME (@var{x})
1008Return the name of the subr @var{x}. The results are undefined if
1009@var{x} is not a subr.
1010@end deftypefn
1011
1012@deftypefun SCM scm_make_gsubr (char *@var{name}, int @var{req}, int @var{opt}, int @var{rest}, SCM (*@var{function})())
1013Create a new subr object named @var{name}, based on the C function
1014@var{function}, make it visible to Scheme the value of as a global
1015variable named @var{name}, and return the subr object.
1016
1017The subr object accepts @var{req} required arguments, @var{opt} optional
1018arguments, and a @var{rest} argument iff @var{rest} is non-zero. The C
1019function @var{function} should accept @code{@var{req} + @var{opt}}
1020arguments, or @code{@var{req} + @var{opt} + 1} arguments if @code{rest}
1021is non-zero.
1022
1023When a subr object is applied, it must be applied to at least @var{req}
1024arguments, or else Guile signals an error. @var{function} receives the
1025subr's first @var{req} arguments as its first @var{req} arguments. If
1026there are fewer than @var{opt} arguments remaining, then @var{function}
1027receives the value @code{SCM_UNDEFINED} for any missing optional
1028arguments. If @var{rst} is non-zero, then any arguments after the first
1029@code{@var{req} + @var{opt}} are packaged up as a list as passed as
1030@var{function}'s last argument.
1031
1032Note that subrs can actually only accept a predefined set of
1033combinations of required, optional, and rest arguments. For example, a
1034subr can take one required argument, or one required and one optional
1035argument, but a subr can't take one required and two optional arguments.
1036It's bizarre, but that's the way the interpreter was written. If the
1037arguments to @code{scm_make_gsubr} do not fit one of the predefined
1038patterns, then @code{scm_make_gsubr} will return a compiled closure
1039object instead of a subr object.
1040@end deftypefun
1041
1042
1043@node Port Data
1044@subsubsection Ports
1045
1046Haven't written this yet, 'cos I don't understand ports yet.
1047
1048
1049@node Signalling Type Errors
1050@subsection Signalling Type Errors
1051
1052Every function visible at the Scheme level should aggressively check the
1053types of its arguments, to avoid misinterpreting a value, and perhaps
1054causing a segmentation fault. Guile provides some macros to make this
1055easier.
1056
1057@deftypefn Macro void SCM_ASSERT (int @var{test}, SCM @var{obj}, int @var{position}, char *@var{subr})
1058If @var{test} is zero, signal an error, attributed to the subroutine
1059named @var{subr}, operating on the value @var{obj}. The @var{position}
1060value determines exactly what sort of error to signal.
1061
1062If @var{position} is a string, @code{SCM_ASSERT} raises a
1063``miscellaneous'' error whose message is that string.
1064
1065Otherwise, @var{position} should be one of the values defined below.
1066@end deftypefn
1067
1068@deftypefn Macro int SCM_ARG1
1069@deftypefnx Macro int SCM_ARG2
1070@deftypefnx Macro int SCM_ARG3
1071@deftypefnx Macro int SCM_ARG4
1072@deftypefnx Macro int SCM_ARG5
1073Signal a ``wrong type argument'' error. When used as the @var{position}
1074argument of @code{SCM_ASSERT}, @code{SCM_ARG@var{n}} claims that
1075@var{obj} has the wrong type for the @var{n}'th argument of @var{subr}.
1076
1077The only way to complain about the type of an argument after the fifth
1078is to use @code{SCM_ARGn}, defined below, which doesn't specify which
1079argument is wrong. You could pass your own error message to
1080@code{SCM_ASSERT} as the @var{position}, but then the error signalled is
1081a ``miscellaneous'' error, not a ``wrong type argument'' error. This
1082seems kludgy to me.
1083@comment Any function with more than two arguments is wrong --- Perlis
1084@comment Despite Perlis, I agree. Why not have two Macros, one with
1085@comment a string error message, and the other with an integer position
1086@comment that only claims a type error in an argument?
1087@comment --- Keith Wright
1088@end deftypefn
1089
1090@deftypefn Macro int SCM_ARGn
1091As above, but does not specify which argument's type is incorrect.
1092@end deftypefn
1093
1094@deftypefn Macro int SCM_WNA
1095Signal an error complaining that the function received the wrong number
1096of arguments.
1097
1098Interestingly, the message is attributed to the function named by
1099@var{obj}, not @var{subr}, so @var{obj} must be a Scheme string object
1100naming the function. Usually, Guile catches these errors before ever
1101invoking the subr, so we don't run into these problems.
1102@end deftypefn
1103
1104
1105@node Defining New Types (Smobs)
1106@section Defining New Types (Smobs)
1107
1108@dfn{Smobs} are Guile's mechanism for adding new non-immediate types to
1109the system.@footnote{The term ``smob'' was coined by Aubrey Jaffer, who
1110says it comes from ``small object'', referring to the fact that only the
1111@sc{cdr} and part of the @sc{car} of a smob's cell are available for
1112use.} To define a new smob type, the programmer provides Guile with
1113some essential information about the type --- how to print it, how to
1114garbage collect it, and so on --- and Guile returns a fresh type tag for
1115use in the @sc{car} of new cells. The programmer can then use
1116@code{scm_make_gsubr} to make a set of C functions that create and
1117operate on these objects visible to Scheme code.
1118
1119(You can find a complete version of the example code used in this
1120section in the Guile distribution, in @file{doc/example-smob}. That
1121directory includes a makefile and a suitable @code{main} function, so
1122you can build a complete interactive Guile shell, extended with the
1123datatypes described here.)
1124
1125@menu
1126* Describing a New Type::
1127* Creating Instances::
1128* Typechecking::
1129* Garbage Collecting Smobs::
1130* A Common Mistake In Allocating Smobs::
1131* Garbage Collecting Simple Smobs::
1132* A Complete Example::
1133@end menu
1134
1135@node Describing a New Type
1136@subsection Describing a New Type
1137
1138To define a new type, the programmer must write four functions to
1139manage instances of the type:
1140
1141@table @code
1142@item mark
1143Guile will apply this function to each instance of the new type it
1144encounters during garbage collection. This function is responsible for
1145telling the collector about any other non-immediate objects the object
1146refers to. The default smob mark function is to not mark any data.
1147@xref{Garbage Collecting Smobs}, for more details.
1148
1149@item free
1150Guile will apply this function to each instance of the new type it could
1151not find any live pointers to. The function should release all
1152resources held by the object and return the number of bytes released.
1153This is analagous to the Java finalization method-- it is invoked at
1154an unspecified time (when garbage collection occurs) after the object
1155is dead.
1156The default free function frees the smob data (if the size of the struct
1157passed to @code{scm_make_smob_type} or @code{scm_make_smob_type_mfpe} is
1158non-zero) using @code{scm_must_free} and returns the size of that
1159struct. @xref{Garbage Collecting Smobs}, for more details.
1160
1161@item print
1162@c GJB:FIXME:: @var{exp} and @var{port} need to refer to a prototype of
1163@c the print function.... where is that, or where should it go?
1164Guile will apply this function to each instance of the new type to print
1165the value, as for @code{display} or @code{write}. The function should
1166write a printed representation of @var{exp} on @var{port}, in accordance
1167with the parameters in @var{pstate}. (For more information on print
1168states, see @ref{Port Data}.) The default print function prints @code{#<NAME ADDRESS>}
1169where @code{NAME} is the first argument passed to @code{scm_make_smob_type} or
1170@code{scm_make_smob_type_mfpe}.
1171
1172@item equalp
1173If Scheme code asks the @code{equal?} function to compare two instances
1174of the same smob type, Guile calls this function. It should return
1175@code{SCM_BOOL_T} if @var{a} and @var{b} should be considered
1176@code{equal?}, or @code{SCM_BOOL_F} otherwise. If @code{equalp} is
1177@code{NULL}, @code{equal?} will assume that two instances of this type are
1178never @code{equal?} unless they are @code{eq?}.
1179
1180@end table
1181
1182To actually register the new smob type, call @code{scm_make_smob_type}:
1183
1184@deftypefun long scm_make_smob_type (const char *name, scm_sizet size)
1185This function implements the standard way of adding a new smob type,
1186named @var{name}, with instance size @var{size}, to the system. The
1187return value is a tag that is used in creating instances of the type.
1188If @var{size} is 0, then no memory will be allocated when instances of
1189the smob are created, and nothing will be freed by the default free
1190function. Default values are provided for mark, free, print, and,
1191equalp, as described above. If you want to customize any of these
1192functions, the call to @code{scm_make_smob_type} should be immediately
1193followed by calls to one or several of @code{scm_set_smob_mark},
1194@code{scm_set_smob_free}, @code{scm_set_smob_print}, and/or
1195@code{scm_set_smob_equalp}.
1196@end deftypefun
1197
1198Each of the below @code{scm_set_smob_XXX} functions registers a smob
1199special function for a given type. Each function is intended to be used
1200only zero or one time per type, and the call should be placed
1201immediately following the call to @code{scm_make_smob_type}.
1202
1203@deftypefun void scm_set_smob_mark (long tc, SCM (*mark) (SCM))
1204This function sets the smob marking procedure for the smob type specified by
1205the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.
1206@end deftypefun
1207
1208@deftypefun void scm_set_smob_free (long tc, scm_sizet (*free) (SCM))
1209This function sets the smob freeing procedure for the smob type specified by
1210the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.
1211@end deftypefun
1212
1213@deftypefun void scm_set_smob_print (long tc, int (*print) (SCM,SCM,scm_print_state*))
1214This function sets the smob printing procedure for the smob type specified by
1215the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.
1216@end deftypefun
1217
1218@deftypefun void scm_set_smob_equalp (long tc, SCM (*equalp) (SCM,SCM))
1219This function sets the smob equality-testing predicate for the smob type specified by
1220the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.
1221@end deftypefun
1222
1223Instead of using @code{scm_make_smob_type} and calling each of the
1224individual @code{scm_set_smob_XXX} functions to register each special
1225function independently, you can use @code{scm_make_smob_type_mfpe} to
1226register all of the special functions at once as you create the smob
1227type@footnote{Warning: There is an ongoing discussion among the developers which
1228may result in deprecating @code{scm_make_smob_type_mfpe} in next release
1229of Guile.}:
1230
1231@deftypefun long scm_make_smob_type_mfpe(const char *name, scm_sizet size, SCM (*mark) (SCM), scm_sizet (*free) (SCM), int (*print) (SCM, SCM, scm_print_state*), SCM (*equalp) (SCM, SCM))
1232This function invokes @code{scm_make_smob_type} on its first two arguments
1233to add a new smob type named @var{name}, with instance size @var{size} to the system.
1234It also registers the @var{mark}, @var{free}, @var{print}, @var{equalp} smob
1235special functions for that new type. Any of these parameters can be @code{NULL}
1236to have that special function use the default behaviour for guile.
1237The return value is a tag that is used in creating instances of the type. If @var{size}
1238is 0, then no memory will be allocated when instances of the smob are created, and
1239nothing will be freed by the default free function.
1240@end deftypefun
1241
1242For example, here is how one might declare and register a new type
1243representing eight-bit grayscale images:
1244@example
1245#include <libguile.h>
1246
1247long image_tag;
1248
1249void
1250init_image_type ()
1251@{
1252 image_tag = scm_make_smob_type_mfpe ("image",sizeof(struct image),
1253 mark_image, free_image, print_image, NULL);
1254@}
1255@end example
1256
1257
1258@node Creating Instances
1259@subsection Creating Instances
1260
1261Like other non-immediate types, smobs start with a cell whose @sc{car}
1262contains typing information, and whose @code{cdr} is free for any use. For smobs,
1263the @code{cdr} stores a pointer to the internal C structure holding the
1264smob-specific data.
1265To create an instance of a smob type following these standards, you should
1266use @code{SCM_NEWSMOB}:
1267
1268@deftypefn Macro void SCM_NEWSMOB(SCM value,long tag,void *data)
1269Make @var{value} contain a smob instance of the type with tag @var{tag}
1270and smob data @var{data}. @var{value} must be previously declared
1271as C type @code{SCM}.
1272@end deftypefn
1273
1274Since it is often the case (e.g., in smob constructors) that you will
1275create a smob instance and return it, there is also a slightly specialized
1276macro for this situation:
1277
1278@deftypefn Macro fn_returns SCM_RETURN_NEWSMOB(long tab, void *data)
1279This macro expands to a block of code that creates a smob instance of
1280the type with tag @var{tag} and smob data @var{data}, and returns
1281that @code{SCM} value. It should be the last piece of code in
1282a block.
1283@end deftypefn
1284
1285Guile provides the following functions for managing memory, which are
1286often helpful when implementing smobs:
1287
1288@deftypefun {char *} scm_must_malloc (long @var{len}, char *@var{what})
1289Allocate @var{len} bytes of memory, using @code{malloc}, and return a
1290pointer to them.
1291
1292If there is not enough memory available, invoke the garbage collector,
1293and try once more. If there is still not enough, signal an error,
1294reporting that we could not allocate @var{what}.
1295
1296This function also helps maintain statistics about the size of the heap.
1297@end deftypefun
1298
1299@deftypefun {char *} scm_must_realloc (char *@var{addr}, long @var{olen}, long @var{len}, char *@var{what})
1300Resize (and possibly relocate) the block of memory at @var{addr}, to
1301have a size of @var{len} bytes, by calling @code{realloc}. Return a
1302pointer to the new block.
1303
1304If there is not enough memory available, invoke the garbage collector,
1305and try once more. If there is still not enough, signal an error,
1306reporting that we could not allocate @var{what}.
1307
1308The value @var{olen} should be the old size of the block of memory at
1309@var{addr}; it is only used for keeping statistics on the size of the
1310heap.
1311@end deftypefun
1312
1313@deftypefun void scm_must_free (char *@var{addr})
1314Free the block of memory at @var{addr}, using @code{free}. If
1315@var{addr} is zero, signal an error, complaining of an attempt to free
1316something that is already free.
1317
1318This does no record-keeping; instead, the smob's @code{free} function
1319must take care of that.
1320
1321This function isn't usually sufficiently different from the usual
1322@code{free} function to be worth using.
1323@end deftypefun
1324
1325
1326Continuing the above example, if the global variable @code{image_tag}
1327contains a tag returned by @code{scm_newsmob}, here is how we could
1328construct a smob whose @sc{cdr} contains a pointer to a freshly
1329allocated @code{struct image}:
1330
1331@example
1332struct image @{
1333 int width, height;
1334 char *pixels;
1335
1336 /* The name of this image */
1337 SCM name;
1338
1339 /* A function to call when this image is
1340 modified, e.g., to update the screen,
1341 or SCM_BOOL_F if no action necessary */
1342 SCM update_func;
1343@};
1344
1345SCM
1346make_image (SCM name, SCM s_width, SCM s_height)
1347@{
1348 struct image *image;
1349 int width, height;
1350
1351 SCM_ASSERT (SCM_NIMP (name) && SCM_STRINGP (name), name,
1352 SCM_ARG1, "make-image");
1353 SCM_ASSERT (SCM_INUMP (s_width), s_width, SCM_ARG2, "make-image");
1354 SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");
1355
1356 width = SCM_INUM (s_width);
1357 height = SCM_INUM (s_height);
1358
1359 image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
1360 image->width = width;
1361 image->height = height;
1362 image->pixels = scm_must_malloc (width * height, "image pixels");
1363 image->name = name;
1364 image->update_func = SCM_BOOL_F;
1365
1366 SCM_RETURN_NEWSMOB (image_tag, image);
1367@}
1368@end example
1369
1370
1371@node Typechecking
1372@subsection Typechecking
1373
1374Functions that operate on smobs should aggressively check the types of
1375their arguments, to avoid misinterpreting some other datatype as a smob,
1376and perhaps causing a segmentation fault. Fortunately, this is pretty
1377simple to do. The function need only verify that its argument is a
1378non-immediate, whose @sc{car} is the type tag returned by
1379@code{scm_newsmob}.
1380
1381For example, here is a simple function that operates on an image smob,
1382and checks the type of its argument. We also present an expanded
1383version of the @code{init_image_type} function, to make
1384@code{clear_image} and the image constructor function @code{make_image}
1385visible to Scheme code.
1386@example
1387SCM
1388clear_image (SCM image_smob)
1389@{
1390 int area;
1391 struct image *image;
1392
1393 SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob),
1394 image_smob, SCM_ARG1, "clear-image");
1395
1396 image = (struct image *) SCM_SMOB_DATA (image_smob);
1397 area = image->width * image->height;
1398 memset (image->pixels, 0, area);
1399
1400 /* Invoke the image's update function. */
1401 if (image->update_func != SCM_BOOL_F)
1402 scm_apply (image->update_func, SCM_EOL, SCM_EOL);
1403
1404 return SCM_UNSPECIFIED;
1405@}
1406
1407
1408void
1409init_image_type ()
1410@{
1411 image_tag = scm_newsmob (&image_funs);
1412
1413 scm_make_gsubr ("make-image", 3, 0, 0, make_image);
1414 scm_make_gsubr ("clear-image", 1, 0, 0, clear_image);
1415@}
1416@end example
1417
1418Note that checking types is a little more complicated during garbage
1419collection; see the description of @code{SCM_GCTYP16} in @ref{Garbage
1420Collecting Smobs}.
1421
1422@c GJB:FIXME:: should talk about guile-snarf somewhere!
1423
1424@node Garbage Collecting Smobs
1425@subsection Garbage Collecting Smobs
1426
1427Once a smob has been released to the tender mercies of the Scheme
1428system, it must be prepared to survive garbage collection. Guile calls
1429the @code{mark} and @code{free} functions of the @code{scm_smobfuns}
1430structure to manage this.
1431
1432As described before (@pxref{Conservative GC}), every object in the
1433Scheme system has a @dfn{mark bit}, which the garbage collector uses to
1434tell live objects from dead ones. When collection starts, every
1435object's mark bit is clear. The collector traces pointers through the
1436heap, starting from objects known to be live, and sets the mark bit on
1437each object it encounters. When it can find no more unmarked objects,
1438the collector walks all objects, live and dead, frees those whose mark
1439bits are still clear, and clears the mark bit on the others.
1440
1441The two main portions of the collection are called the @dfn{mark phase},
1442during which the collector marks live objects, and the @dfn{sweep
1443phase}, during which the collector frees all unmarked objects.
1444
1445The mark bit of a smob lives in its @sc{car}, along with the smob's type
1446tag. When the collector encounters a smob, it sets the smob's mark bit,
1447and uses the smob's type tag to find the appropriate @code{mark}
1448function for that smob: the one listed in that smob's
1449@code{scm_smobfuns} structure. It then calls the @code{mark} function,
1450passing it the smob as its only argument.
1451
1452The @code{mark} function is responsible for marking any other Scheme
1453objects the smob refers to. If it does not do so, the objects' mark
1454bits will still be clear when the collector begins to sweep, and the
1455collector will free them. If this occurs, it will probably break, or at
1456least confuse, any code operating on the smob; the smob's @code{SCM}
1457values will have become dangling references.
1458
1459To mark an arbitrary Scheme object, the @code{mark} function may call
1460this function:
1461
1462@deftypefun void scm_gc_mark (SCM @var{x})
1463Mark the object @var{x}, and recurse on any objects @var{x} refers to.
1464If @var{x}'s mark bit is already set, return immediately.
1465@end deftypefun
1466
1467Thus, here is how we might write the @code{mark} function for the image
1468smob type discussed above:
1469@example
1470@group
1471SCM
1472mark_image (SCM image_smob)
1473@{
1474 /* Mark the image's name and update function. */
1475 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1476
1477 scm_gc_mark (image->name);
1478 scm_gc_mark (image->update_func);
1479
1480 return SCM_BOOL_F;
1481@}
1482@end group
1483@end example
1484
1485Note that, even though the image's @code{update_func} could be an
1486arbitrarily complex structure (representing a procedure and any values
1487enclosed in its environment), @code{scm_gc_mark} will recurse as
1488necessary to mark all its components. Because @code{scm_gc_mark} sets
1489an object's mark bit before it recurses, it is not confused by
1490circular structures.
1491
1492As an optimization, the collector will mark whatever value is returned
1493by the @code{mark} function; this helps limit depth of recursion during
1494the mark phase. Thus, the code above could also be written as:
1495@example
1496@group
1497SCM
1498mark_image (SCM image_smob)
1499@{
1500 /* Mark the image's name and update function. */
1501 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1502
1503 scm_gc_mark (image->name);
1504 return image->update_func;
1505@}
1506@end group
1507@end example
1508
1509
1510Finally, when the collector encounters an unmarked smob during the sweep
1511phase, it uses the smob's tag to find the appropriate @code{free}
1512function for the smob. It then calls the function, passing it the smob
1513as its only argument.
1514
1515The @code{free} function must release any resources used by the smob.
1516However, it need not free objects managed by the collector; the
1517collector will take care of them. The return type of the @code{free}
1518function should be @code{scm_sizet}, an unsigned integral type; the
1519@code{free} function should return the number of bytes released, to help
1520the collector maintain statistics on the size of the heap.
1521
1522Here is how we might write the @code{free} function for the image smob
1523type:
1524@example
1525scm_sizet
1526free_image (SCM image_smob)
1527@{
1528 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1529 scm_sizet size = image->width * image->height + sizeof (*image);
1530
1531 free (image->pixels);
1532 free (image);
1533
1534 return size;
1535@}
1536@end example
1537
1538During the sweep phase, the garbage collector will clear the mark bits
1539on all live objects. The code which implements a smob need not do this
1540itself.
1541
1542There is no way for smob code to be notified when collection is
1543complete.
1544
1545Note that, since a smob's mark bit lives in its @sc{car}, along with the
1546smob's type tag, the technique for checking the type of a smob described
1547in @ref{Typechecking} will not necessarily work during GC. If you need
1548to find out whether a given object is a particular smob type during GC,
1549use the following macro:
1550
1551@deftypefn Macro void SCM_GCTYP16 (SCM @var{x})
1552Return the type bits of the smob @var{x}, with the mark bit clear.
1553
1554Use this macro instead of @code{SCM_CAR} to check the type of a smob
1555during GC. Usually, only code called by the smob's @code{mark} function
1556need worry about this.
1557@end deftypefn
1558
1559It is usually a good idea to minimize the amount of processing done
1560during garbage collection; keep @code{mark} and @code{free} functions
1561very simple. Since collections occur at unpredictable times, it is easy
1562for any unusual activity to interfere with normal code.
1563
1564
1565@node A Common Mistake In Allocating Smobs, Garbage Collecting Simple Smobs, Garbage Collecting Smobs, Defining New Types (Smobs)
1566@subsection A Common Mistake In Allocating Smobs
1567
1568When constructing new objects, you must be careful that the garbage
1569collector can always find any new objects you allocate. For example,
1570suppose we wrote the @code{make_image} function this way:
1571
1572@example
1573SCM
1574make_image (SCM name, SCM s_width, SCM s_height)
1575@{
1576 struct image *image;
1577 SCM image_smob;
1578 int width, height;
1579
1580 SCM_ASSERT (SCM_NIMP (name) && SCM_STRINGP (name), name,
1581 SCM_ARG1, "make-image");
1582 SCM_ASSERT (SCM_INUMP (s_width), s_width, SCM_ARG2, "make-image");
1583 SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");
1584
1585 width = SCM_INUM (s_width);
1586 height = SCM_INUM (s_height);
1587
1588 image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
1589 image->width = width;
1590 image->height = height;
1591 image->pixels = scm_must_malloc (width * height, "image pixels");
1592
1593 /* THESE TWO LINES HAVE CHANGED: */
1594 image->name = scm_string_copy (name);
1595 image->update_func = scm_make_gsubr (@dots{});
1596
1597 SCM_NEWCELL (image_smob);
1598 SCM_SETCDR (image_smob, image);
1599 SCM_SETCAR (image_smob, image_tag);
1600
1601 return image_smob;
1602@}
1603@end example
1604
1605This code is incorrect. The calls to @code{scm_string_copy} and
1606@code{scm_make_gsubr} allocate fresh objects. Allocating any new object
1607may cause the garbage collector to run. If @code{scm_make_gsubr}
1608invokes a collection, the garbage collector has no way to discover that
1609@code{image->name} points to the new string object; the @code{image}
1610structure is not yet part of any Scheme object, so the garbage collector
1611will not traverse it. Since the garbage collector cannot find any
1612references to the new string object, it will free it, leaving
1613@code{image} pointing to a dead object.
1614
1615A correct implementation might say, instead:
1616@example
1617 image->name = SCM_BOOL_F;
1618 image->update_func = SCM_BOOL_F;
1619
1620 SCM_NEWCELL (image_smob);
1621 SCM_SETCDR (image_smob, image);
1622 SCM_SETCAR (image_smob, image_tag);
1623
1624 image->name = scm_string_copy (name);
1625 image->update_func = scm_make_gsubr (@dots{});
1626
1627 return image_smob;
1628@end example
1629
1630Now, by the time we allocate the new string and function objects,
1631@code{image_smob} points to @code{image}. If the garbage collector
1632scans the stack, it will find a reference to @code{image_smob} and
1633traverse @code{image}, so any objects @code{image} points to will be
1634preserved.
1635
1636
1637@node Garbage Collecting Simple Smobs, A Complete Example, A Common Mistake In Allocating Smobs, Defining New Types (Smobs)
1638@subsection Garbage Collecting Simple Smobs
1639
1640It is often useful to define very simple smob types --- smobs which have
1641no data to mark, other than the cell itself, or smobs whose @sc{cdr} is
1642simply an ordinary Scheme object, to be marked recursively. Guile
1643provides some functions to handle these common cases; you can use these
1644functions as your smob type's @code{mark} function, if your smob's
1645structure is simple enough.
1646
1647If the smob refers to no other Scheme objects, then no action is
1648necessary; the garbage collector has already marked the smob cell
1649itself. In that case, you can use zero as your mark function.
1650
1651@deftypefun SCM scm_markcdr (SCM @var{x})
1652Mark the references in the smob @var{x}, assuming that @var{x}'s
1653@sc{cdr} contains an ordinary Scheme object, and @var{x} refers to no
1654other objects. This function simply returns @var{x}'s @sc{cdr}.
1655@end deftypefun
1656
1657@deftypefun scm_sizet scm_free0 (SCM @var{x})
1658Do nothing; return zero. This function is appropriate for smobs that
1659use either zero or @code{scm_markcdr} as their marking functions, and
1660refer to no heap storage, including memory managed by @code{malloc},
1661other than the smob's header cell.
1662@end deftypefun
1663
1664
1665@node A Complete Example
1666@subsection A Complete Example
1667
1668Here is the complete text of the implementation of the image datatype,
1669as presented in the sections above. We also provide a definition for
1670the smob's @code{print} function, and make some objects and functions
1671static, to clarify exactly what the surrounding code is using.
1672
1673As mentioned above, you can find this code in the Guile distribution, in
1674@file{doc/example-smob}. That directory includes a makefile and a
1675suitable @code{main} function, so you can build a complete interactive
1676Guile shell, extended with the datatypes described here.)
1677
1678@example
1679/* file "image-type.c" */
1680
1681#include <stdlib.h>
1682#include <libguile.h>
1683
1684static long image_tag;
1685
1686struct image @{
1687 int width, height;
1688 char *pixels;
1689
1690 /* The name of this image */
1691 SCM name;
1692
1693 /* A function to call when this image is
1694 modified, e.g., to update the screen,
1695 or SCM_BOOL_F if no action necessary */
1696 SCM update_func;
1697@};
1698
1699static SCM
1700make_image (SCM name, SCM s_width, SCM s_height)
1701@{
1702 struct image *image;
1703 SCM image_smob;
1704 int width, height;
1705
1706 SCM_ASSERT (SCM_NIMP (name) && SCM_STRINGP (name), name,
1707 SCM_ARG1, "make-image");
1708 SCM_ASSERT (SCM_INUMP (s_width), s_width, SCM_ARG2, "make-image");
1709 SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");
1710
1711 width = SCM_INUM (s_width);
1712 height = SCM_INUM (s_height);
1713
1714 image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
1715 image->width = width;
1716 image->height = height;
1717 image->pixels = scm_must_malloc (width * height, "image pixels");
1718 image->name = name;
1719 image->update_func = SCM_BOOL_F;
1720
1721 SCM_NEWSMOB (image_smob, image_tag, image);
1722
1723 return image_smob;
1724@}
1725
1726static SCM
1727clear_image (SCM image_smob)
1728@{
1729 int area;
1730 struct image *image;
1731
1732 SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob),
1733 image_smob, SCM_ARG1, "clear-image");
1734
1735 image = (struct image *) SCM_SMOB_DATA (image_smob);
1736 area = image->width * image->height;
1737 memset (image->pixels, 0, area);
1738
1739 /* Invoke the image's update function. */
1740 if (image->update_func != SCM_BOOL_F)
1741 scm_apply (image->update_func, SCM_EOL, SCM_EOL);
1742
1743 return SCM_UNSPECIFIED;
1744@}
1745
1746static SCM
1747mark_image (SCM image_smob)
1748@{
1749 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1750
1751 scm_gc_mark (image->name);
1752 return image->update_func;
1753@}
1754
1755static scm_sizet
1756free_image (SCM image_smob)
1757@{
1758 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1759 scm_sizet size = image->width * image->height + sizeof (struct image);
1760
1761 free (image->pixels);
1762 free (image);
1763
1764 return size;
1765@}
1766
1767static int
1768print_image (SCM image_smob, SCM port, scm_print_state *pstate)
1769@{
1770 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1771
1772 scm_puts ("#<image ", port);
1773 scm_display (image->name, port);
1774 scm_puts (">", port);
1775
1776 /* non-zero means success */
1777 return 1;
1778@}
1779
1780static scm_smobfuns image_funs = @{
1781 mark_image, free_image, print_image, 0
1782@};
1783
1784void
1785init_image_type ()
1786@{
1787 image_tag = scm_newsmob (&image_funs);
1788
1789 scm_make_gsubr ("clear-image", 1, 0, 0, clear_image);
1790 scm_make_gsubr ("make-image", 3, 0, 0, make_image);
1791@}
1792@end example
1793
1794Here is a sample build and interaction with the code from the
1795@file{example-smob} directory, on the author's machine:
1796
1797@example
1798zwingli:example-smob$ make CC=gcc
1799gcc `guile-config compile` -c image-type.c -o image-type.o
1800gcc `guile-config compile` -c myguile.c -o myguile.o
1801gcc image-type.o myguile.o `guile-config link` -o myguile
1802zwingli:example-smob$ ./myguile
1803guile> make-image
1804#<primitive-procedure make-image>
1805guile> (define i (make-image "Whistler's Mother" 100 100))
1806guile> i
1807#<image Whistler's Mother>
1808guile> (clear-image i)
1809guile> (clear-image 4)
1810ERROR: In procedure clear-image in expression (clear-image 4):
1811ERROR: Wrong type argument in position 1: 4
1812ABORT: (wrong-type-arg)
1813
1814Type "(backtrace)" to get more information.
1815guile>
1816@end example
1817
1818@c essay @bye