2001-04-09 Martin Grabmueller <mgrabmue@cs.tu-berlin.de>
[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
abaec75d 49@c essay @subtitle $Id: data-rep.texi,v 1.18 2001-04-02 21:53:20 ossau Exp $
38a93523
NJ
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::
abaec75d 436* Immediates vs Non-immediates::
38a93523
NJ
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
abaec75d
NJ
557@node Immediates vs Non-immediates
558@subsection Immediates vs Non-immediates
38a93523
NJ
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.
38a93523
NJ
578@end deftypefn
579
abaec75d
NJ
580Note that, as of Guile 1.4, it is no longer necessary to use the
581@code{SCM_NIMP} macro before calling a finer-grained predicate to
582determine @var{x}'s type, such as @code{SCM_CONSP} or
583@code{SCM_VECTORP}. The definitions of all Guile type predicates
584now include a call to @code{SCM_NIMP} where necessary.
585
38a93523
NJ
586
587@node Immediate Datatypes
588@subsection Immediate Datatypes
589
590The following datatypes are immediate values; that is, they fit entirely
591within an @code{SCM} value. The @code{SCM_IMP} and @code{SCM_NIMP}
592macros will distinguish these from non-immediates; see @ref{Immediates
abaec75d 593vs Non-immediates} for an explanation of the distinction.
38a93523
NJ
594
595Note that the type predicates for immediate values work correctly on any
596@code{SCM} value; you do not need to call @code{SCM_IMP} first, to
597establish that a value is immediate. This differs from the
598non-immediate type predicates, which work correctly only on
599non-immediate values; you must be sure the value is @code{SCM_NIMP}
600before applying them.
601
602
603@menu
604* Integer Data::
605* Character Data::
606* Boolean Data::
607* Unique Values::
608@end menu
609
610@node Integer Data
611@subsubsection Integers
612
613Here are functions for operating on small integers, that fit within an
614@code{SCM}. Such integers are called @dfn{immediate numbers}, or
615@dfn{INUMs}. In general, INUMs occupy all but two bits of an
616@code{SCM}.
617
618Bignums and floating-point numbers are non-immediate objects, and have
619their own, separate accessors. The functions here will not work on
620them. This is not as much of a problem as you might think, however,
621because the system never constructs bignums that could fit in an INUM,
622and never uses floating point values for exact integers.
623
624@deftypefn Macro int SCM_INUMP (SCM @var{x})
625Return non-zero iff @var{x} is a small integer value.
626@end deftypefn
627
628@deftypefn Macro int SCM_NINUMP (SCM @var{x})
629The complement of SCM_INUMP.
630@end deftypefn
631
632@deftypefn Macro int SCM_INUM (SCM @var{x})
633Return the value of @var{x} as an ordinary, C integer. If @var{x}
634is not an INUM, the result is undefined.
635@end deftypefn
636
637@deftypefn Macro SCM SCM_MAKINUM (int @var{i})
638Given a C integer @var{i}, return its representation as an @code{SCM}.
639This function does not check for overflow.
640@end deftypefn
641
642
643@node Character Data
644@subsubsection Characters
645
646Here are functions for operating on characters.
647
648@deftypefn Macro int SCM_CHARP (SCM @var{x})
649Return non-zero iff @var{x} is a character value.
650@end deftypefn
651
652@deftypefn Macro {unsigned int} SCM_CHAR (SCM @var{x})
653Return the value of @code{x} as a C character. If @var{x} is not a
654Scheme character, the result is undefined.
655@end deftypefn
656
657@deftypefn Macro SCM SCM_MAKE_CHAR (int @var{c})
658Given a C character @var{c}, return its representation as a Scheme
659character value.
660@end deftypefn
661
662
663@node Boolean Data
664@subsubsection Booleans
665
666Here are functions and macros for operating on booleans.
667
668@deftypefn Macro SCM SCM_BOOL_T
669@deftypefnx Macro SCM SCM_BOOL_F
670The Scheme true and false values.
671@end deftypefn
672
673@deftypefn Macro int SCM_NFALSEP (@var{x})
674Convert the Scheme boolean value to a C boolean. Since every object in
675Scheme except @code{#f} is true, this amounts to comparing @var{x} to
676@code{#f}; hence the name.
677@c Noel feels a chill here.
678@end deftypefn
679
680@deftypefn Macro SCM SCM_BOOL_NOT (@var{x})
681Return the boolean inverse of @var{x}. If @var{x} is not a
682Scheme boolean, the result is undefined.
683@end deftypefn
684
685
686@node Unique Values
687@subsubsection Unique Values
688
689The immediate values that are neither small integers, characters, nor
690booleans are all unique values --- that is, datatypes with only one
691instance.
692
693@deftypefn Macro SCM SCM_EOL
694The Scheme empty list object, or ``End Of List'' object, usually written
695in Scheme as @code{'()}.
696@end deftypefn
697
698@deftypefn Macro SCM SCM_EOF_VAL
699The Scheme end-of-file value. It has no standard written
700representation, for obvious reasons.
701@end deftypefn
702
703@deftypefn Macro SCM SCM_UNSPECIFIED
704The value returned by expressions which the Scheme standard says return
705an ``unspecified'' value.
706
707This is sort of a weirdly literal way to take things, but the standard
708read-eval-print loop prints nothing when the expression returns this
709value, so it's not a bad idea to return this when you can't think of
710anything else helpful.
711@end deftypefn
712
713@deftypefn Macro SCM SCM_UNDEFINED
714The ``undefined'' value. Its most important property is that is not
715equal to any valid Scheme value. This is put to various internal uses
716by C code interacting with Guile.
717
718For example, when you write a C function that is callable from Scheme
719and which takes optional arguments, the interpreter passes
720@code{SCM_UNDEFINED} for any arguments you did not receive.
721
722We also use this to mark unbound variables.
723@end deftypefn
724
725@deftypefn Macro int SCM_UNBNDP (SCM @var{x})
726Return true if @var{x} is @code{SCM_UNDEFINED}. Apply this to a
727symbol's value to see if it has a binding as a global variable.
728@end deftypefn
729
730
731@node Non-immediate Datatypes
732@subsection Non-immediate Datatypes
733
734A non-immediate datatype is one which lives in the heap, either because
735it cannot fit entirely within a @code{SCM} word, or because it denotes a
736specific storage location (in the nomenclature of the Revised^4 Report
737on Scheme).
738
739The @code{SCM_IMP} and @code{SCM_NIMP} macros will distinguish these
abaec75d 740from immediates; see @ref{Immediates vs Non-immediates}.
38a93523
NJ
741
742Given a cell, Guile distinguishes between pairs and other non-immediate
743types by storing special @dfn{tag} values in a non-pair cell's car, that
744cannot appear in normal pairs. A cell with a non-tag value in its car
745is an ordinary pair. The type of a cell with a tag in its car depends
746on the tag; the non-immediate type predicates test this value. If a tag
747value appears elsewhere (in a vector, for example), the heap may become
748corrupted.
749
750
751@menu
752* Non-immediate Type Predicates:: Special rules for using the type
753 predicates described here.
754* Pair Data::
755* Vector Data::
756* Procedures::
757* Closures::
758* Subrs::
759* Port Data::
760@end menu
761
762@node Non-immediate Type Predicates
763@subsubsection Non-immediate Type Predicates
764
765As mentioned in @ref{Conservative GC}, all non-immediate objects
766start with a @dfn{cell}, or a pair of words. Furthermore, all type
767information that distinguishes one kind of non-immediate from another is
768stored in the cell. The type information in the @code{SCM} value
769indicates only that the object is a non-immediate; all finer
770distinctions require one to examine the cell itself, usually with the
771appropriate type predicate macro.
772
773The type predicates for non-immediate objects generally assume that
774their argument is a non-immediate value. Thus, you must be sure that a
775value is @code{SCM_NIMP} first before passing it to a non-immediate type
776predicate. Thus, the idiom for testing whether a value is a cell or not
777is:
778@example
779SCM_NIMP (@var{x}) && SCM_CONSP (@var{x})
780@end example
781
782
783@node Pair Data
784@subsubsection Pairs
785
786Pairs are the essential building block of list structure in Scheme. A
787pair object has two fields, called the @dfn{car} and the @dfn{cdr}.
788
789It is conventional for a pair's @sc{car} to contain an element of a
790list, and the @sc{cdr} to point to the next pair in the list, or to
791contain @code{SCM_EOL}, indicating the end of the list. Thus, a set of
792pairs chained through their @sc{cdr}s constitutes a singly-linked list.
793Scheme and libguile define many functions which operate on lists
794constructed in this fashion, so although lists chained through the
795@sc{car}s of pairs will work fine too, they may be less convenient to
796manipulate, and receive less support from the community.
797
798Guile implements pairs by mapping the @sc{car} and @sc{cdr} of a pair
799directly into the two words of the cell.
800
801
802@deftypefn Macro int SCM_CONSP (SCM @var{x})
803Return non-zero iff @var{x} is a Scheme pair object.
804The results are undefined if @var{x} is an immediate value.
805@end deftypefn
806
807@deftypefn Macro int SCM_NCONSP (SCM @var{x})
808The complement of SCM_CONSP.
809@end deftypefn
810
811@deftypefn Macro void SCM_NEWCELL (SCM @var{into})
812Allocate a new cell, and set @var{into} to point to it. This macro
813expands to a statement, not an expression, and @var{into} must be an
814lvalue of type SCM.
815
816This is the most primitive way to allocate a cell; it is quite fast.
817
818The @sc{car} of the cell initially tags it as a ``free cell''. If the
819caller intends to use it as an ordinary cons, she must store ordinary
820SCM values in its @sc{car} and @sc{cdr}.
821
822If the caller intends to use it as a header for some other type, she
823must store an appropriate magic value in the cell's @sc{car}, to mark
824it as a member of that type, and store whatever value in the @sc{cdr}
825that type expects. You should generally not do this, unless you are
826implementing a new datatype, and thoroughly understand the code in
827@code{<libguile/tags.h>}.
828@end deftypefn
829
830@deftypefun SCM scm_cons (SCM @var{car}, SCM @var{cdr})
831Allocate (``CONStruct'') a new pair, with @var{car} and @var{cdr} as its
832contents.
833@end deftypefun
834
835
836The macros below perform no typechecking. The results are undefined if
837@var{cell} is an immediate. However, since all non-immediate Guile
838objects are constructed from cells, and these macros simply return the
839first element of a cell, they actually can be useful on datatypes other
840than pairs. (Of course, it is not very modular to use them outside of
841the code which implements that datatype.)
842
843@deftypefn Macro SCM SCM_CAR (SCM @var{cell})
844Return the @sc{car}, or first field, of @var{cell}.
845@end deftypefn
846
847@deftypefn Macro SCM SCM_CDR (SCM @var{cell})
848Return the @sc{cdr}, or second field, of @var{cell}.
849@end deftypefn
850
851@deftypefn Macro void SCM_SETCAR (SCM @var{cell}, SCM @var{x})
852Set the @sc{car} of @var{cell} to @var{x}.
853@end deftypefn
854
855@deftypefn Macro void SCM_SETCDR (SCM @var{cell}, SCM @var{x})
856Set the @sc{cdr} of @var{cell} to @var{x}.
857@end deftypefn
858
859@deftypefn Macro SCM SCM_CAAR (SCM @var{cell})
860@deftypefnx Macro SCM SCM_CADR (SCM @var{cell})
861@deftypefnx Macro SCM SCM_CDAR (SCM @var{cell}) @dots{}
862@deftypefnx Macro SCM SCM_CDDDDR (SCM @var{cell})
863Return the @sc{car} of the @sc{car} of @var{cell}, the @sc{car} of the
864@sc{cdr} of @var{cell}, @i{et cetera}.
865@end deftypefn
866
867
868@node Vector Data
869@subsubsection Vectors, Strings, and Symbols
870
871Vectors, strings, and symbols have some properties in common. They all
872have a length, and they all have an array of elements. In the case of a
873vector, the elements are @code{SCM} values; in the case of a string or
874symbol, the elements are characters.
875
876All these types store their length (along with some tagging bits) in the
877@sc{car} of their header cell, and store a pointer to the elements in
878their @sc{cdr}. Thus, the @code{SCM_CAR} and @code{SCM_CDR} macros
879are (somewhat) meaningful when applied to these datatypes.
880
881@deftypefn Macro int SCM_VECTORP (SCM @var{x})
882Return non-zero iff @var{x} is a vector.
883The results are undefined if @var{x} is an immediate value.
884@end deftypefn
885
886@deftypefn Macro int SCM_STRINGP (SCM @var{x})
887Return non-zero iff @var{x} is a string.
888The results are undefined if @var{x} is an immediate value.
889@end deftypefn
890
891@deftypefn Macro int SCM_SYMBOLP (SCM @var{x})
892Return non-zero iff @var{x} is a symbol.
893The results are undefined if @var{x} is an immediate value.
894@end deftypefn
895
896@deftypefn Macro int SCM_LENGTH (SCM @var{x})
897Return the length of the object @var{x}.
898The results are undefined if @var{x} is not a vector, string, or symbol.
899@end deftypefn
900
901@deftypefn Macro {SCM *} SCM_VELTS (SCM @var{x})
902Return a pointer to the array of elements of the vector @var{x}.
903The results are undefined if @var{x} is not a vector.
904@end deftypefn
905
906@deftypefn Macro {char *} SCM_CHARS (SCM @var{x})
907Return a pointer to the characters of @var{x}.
908The results are undefined if @var{x} is not a symbol or a string.
909@end deftypefn
910
911There are also a few magic values stuffed into memory before a symbol's
912characters, but you don't want to know about those. What cruft!
913
914
915@node Procedures
916@subsubsection Procedures
917
918Guile provides two kinds of procedures: @dfn{closures}, which are the
919result of evaluating a @code{lambda} expression, and @dfn{subrs}, which
920are C functions packaged up as Scheme objects, to make them available to
921Scheme programmers.
922
923(There are actually other sorts of procedures: compiled closures, and
924continuations; see the source code for details about them.)
925
926@deftypefun SCM scm_procedure_p (SCM @var{x})
927Return @code{SCM_BOOL_T} iff @var{x} is a Scheme procedure object, of
928any sort. Otherwise, return @code{SCM_BOOL_F}.
929@end deftypefun
930
931
932@node Closures
933@subsubsection Closures
934
935[FIXME: this needs to be further subbed, but texinfo has no subsubsub]
936
937A closure is a procedure object, generated as the value of a
938@code{lambda} expression in Scheme. The representation of a closure is
939straightforward --- it contains a pointer to the code of the lambda
940expression from which it was created, and a pointer to the environment
941it closes over.
942
943In Guile, each closure also has a property list, allowing the system to
944store information about the closure. I'm not sure what this is used for
945at the moment --- the debugger, maybe?
946
947@deftypefn Macro int SCM_CLOSUREP (SCM @var{x})
948Return non-zero iff @var{x} is a closure. The results are
949undefined if @var{x} is an immediate value.
950@end deftypefn
951
952@deftypefn Macro SCM SCM_PROCPROPS (SCM @var{x})
953Return the property list of the closure @var{x}. The results are
954undefined if @var{x} is not a closure.
955@end deftypefn
956
957@deftypefn Macro void SCM_SETPROCPROPS (SCM @var{x}, SCM @var{p})
958Set the property list of the closure @var{x} to @var{p}. The results
959are undefined if @var{x} is not a closure.
960@end deftypefn
961
962@deftypefn Macro SCM SCM_CODE (SCM @var{x})
963Return the code of the closure @var{x}. The results are undefined if
964@var{x} is not a closure.
965
966This function should probably only be used internally by the
967interpreter, since the representation of the code is intimately
968connected with the interpreter's implementation.
969@end deftypefn
970
971@deftypefn Macro SCM SCM_ENV (SCM @var{x})
972Return the environment enclosed by @var{x}.
973The results are undefined if @var{x} is not a closure.
974
975This function should probably only be used internally by the
976interpreter, since the representation of the environment is intimately
977connected with the interpreter's implementation.
978@end deftypefn
979
980
981@node Subrs
982@subsubsection Subrs
983
984[FIXME: this needs to be further subbed, but texinfo has no subsubsub]
985
986A subr is a pointer to a C function, packaged up as a Scheme object to
987make it callable by Scheme code. In addition to the function pointer,
988the subr also contains a pointer to the name of the function, and
989information about the number of arguments accepted by the C fuction, for
990the sake of error checking.
991
992There is no single type predicate macro that recognizes subrs, as
993distinct from other kinds of procedures. The closest thing is
994@code{scm_procedure_p}; see @ref{Procedures}.
995
996@deftypefn Macro {char *} SCM_SNAME (@var{x})
997Return the name of the subr @var{x}. The results are undefined if
998@var{x} is not a subr.
999@end deftypefn
1000
1001@deftypefun SCM scm_make_gsubr (char *@var{name}, int @var{req}, int @var{opt}, int @var{rest}, SCM (*@var{function})())
1002Create a new subr object named @var{name}, based on the C function
1003@var{function}, make it visible to Scheme the value of as a global
1004variable named @var{name}, and return the subr object.
1005
1006The subr object accepts @var{req} required arguments, @var{opt} optional
1007arguments, and a @var{rest} argument iff @var{rest} is non-zero. The C
1008function @var{function} should accept @code{@var{req} + @var{opt}}
1009arguments, or @code{@var{req} + @var{opt} + 1} arguments if @code{rest}
1010is non-zero.
1011
1012When a subr object is applied, it must be applied to at least @var{req}
1013arguments, or else Guile signals an error. @var{function} receives the
1014subr's first @var{req} arguments as its first @var{req} arguments. If
1015there are fewer than @var{opt} arguments remaining, then @var{function}
1016receives the value @code{SCM_UNDEFINED} for any missing optional
1017arguments. If @var{rst} is non-zero, then any arguments after the first
1018@code{@var{req} + @var{opt}} are packaged up as a list as passed as
1019@var{function}'s last argument.
1020
1021Note that subrs can actually only accept a predefined set of
1022combinations of required, optional, and rest arguments. For example, a
1023subr can take one required argument, or one required and one optional
1024argument, but a subr can't take one required and two optional arguments.
1025It's bizarre, but that's the way the interpreter was written. If the
1026arguments to @code{scm_make_gsubr} do not fit one of the predefined
1027patterns, then @code{scm_make_gsubr} will return a compiled closure
1028object instead of a subr object.
1029@end deftypefun
1030
1031
1032@node Port Data
1033@subsubsection Ports
1034
1035Haven't written this yet, 'cos I don't understand ports yet.
1036
1037
1038@node Signalling Type Errors
1039@subsection Signalling Type Errors
1040
1041Every function visible at the Scheme level should aggressively check the
1042types of its arguments, to avoid misinterpreting a value, and perhaps
1043causing a segmentation fault. Guile provides some macros to make this
1044easier.
1045
1046@deftypefn Macro void SCM_ASSERT (int @var{test}, SCM @var{obj}, int @var{position}, char *@var{subr})
1047If @var{test} is zero, signal an error, attributed to the subroutine
1048named @var{subr}, operating on the value @var{obj}. The @var{position}
1049value determines exactly what sort of error to signal.
1050
1051If @var{position} is a string, @code{SCM_ASSERT} raises a
1052``miscellaneous'' error whose message is that string.
1053
1054Otherwise, @var{position} should be one of the values defined below.
1055@end deftypefn
1056
1057@deftypefn Macro int SCM_ARG1
1058@deftypefnx Macro int SCM_ARG2
1059@deftypefnx Macro int SCM_ARG3
1060@deftypefnx Macro int SCM_ARG4
1061@deftypefnx Macro int SCM_ARG5
1062Signal a ``wrong type argument'' error. When used as the @var{position}
1063argument of @code{SCM_ASSERT}, @code{SCM_ARG@var{n}} claims that
1064@var{obj} has the wrong type for the @var{n}'th argument of @var{subr}.
1065
1066The only way to complain about the type of an argument after the fifth
1067is to use @code{SCM_ARGn}, defined below, which doesn't specify which
1068argument is wrong. You could pass your own error message to
1069@code{SCM_ASSERT} as the @var{position}, but then the error signalled is
1070a ``miscellaneous'' error, not a ``wrong type argument'' error. This
1071seems kludgy to me.
1072@comment Any function with more than two arguments is wrong --- Perlis
1073@comment Despite Perlis, I agree. Why not have two Macros, one with
1074@comment a string error message, and the other with an integer position
1075@comment that only claims a type error in an argument?
1076@comment --- Keith Wright
1077@end deftypefn
1078
1079@deftypefn Macro int SCM_ARGn
1080As above, but does not specify which argument's type is incorrect.
1081@end deftypefn
1082
1083@deftypefn Macro int SCM_WNA
1084Signal an error complaining that the function received the wrong number
1085of arguments.
1086
1087Interestingly, the message is attributed to the function named by
1088@var{obj}, not @var{subr}, so @var{obj} must be a Scheme string object
1089naming the function. Usually, Guile catches these errors before ever
1090invoking the subr, so we don't run into these problems.
1091@end deftypefn
1092
1093
1094@node Defining New Types (Smobs)
1095@section Defining New Types (Smobs)
1096
1097@dfn{Smobs} are Guile's mechanism for adding new non-immediate types to
1098the system.@footnote{The term ``smob'' was coined by Aubrey Jaffer, who
1099says it comes from ``small object'', referring to the fact that only the
1100@sc{cdr} and part of the @sc{car} of a smob's cell are available for
1101use.} To define a new smob type, the programmer provides Guile with
1102some essential information about the type --- how to print it, how to
1103garbage collect it, and so on --- and Guile returns a fresh type tag for
1104use in the @sc{car} of new cells. The programmer can then use
1105@code{scm_make_gsubr} to make a set of C functions that create and
1106operate on these objects visible to Scheme code.
1107
1108(You can find a complete version of the example code used in this
1109section in the Guile distribution, in @file{doc/example-smob}. That
1110directory includes a makefile and a suitable @code{main} function, so
1111you can build a complete interactive Guile shell, extended with the
1112datatypes described here.)
1113
1114@menu
1115* Describing a New Type::
1116* Creating Instances::
1117* Typechecking::
1118* Garbage Collecting Smobs::
1119* A Common Mistake In Allocating Smobs::
1120* Garbage Collecting Simple Smobs::
1121* A Complete Example::
1122@end menu
1123
1124@node Describing a New Type
1125@subsection Describing a New Type
1126
1127To define a new type, the programmer must write four functions to
1128manage instances of the type:
1129
1130@table @code
1131@item mark
1132Guile will apply this function to each instance of the new type it
1133encounters during garbage collection. This function is responsible for
1134telling the collector about any other non-immediate objects the object
1135refers to. The default smob mark function is to not mark any data.
1136@xref{Garbage Collecting Smobs}, for more details.
1137
1138@item free
1139Guile will apply this function to each instance of the new type it could
1140not find any live pointers to. The function should release all
1141resources held by the object and return the number of bytes released.
1142This is analagous to the Java finalization method-- it is invoked at
1143an unspecified time (when garbage collection occurs) after the object
1144is dead.
1145The default free function frees the smob data (if the size of the struct
1146passed to @code{scm_make_smob_type} or @code{scm_make_smob_type_mfpe} is
1147non-zero) using @code{scm_must_free} and returns the size of that
1148struct. @xref{Garbage Collecting Smobs}, for more details.
1149
1150@item print
1151@c GJB:FIXME:: @var{exp} and @var{port} need to refer to a prototype of
1152@c the print function.... where is that, or where should it go?
1153Guile will apply this function to each instance of the new type to print
1154the value, as for @code{display} or @code{write}. The function should
1155write a printed representation of @var{exp} on @var{port}, in accordance
1156with the parameters in @var{pstate}. (For more information on print
1157states, see @ref{Port Data}.) The default print function prints @code{#<NAME ADDRESS>}
1158where @code{NAME} is the first argument passed to @code{scm_make_smob_type} or
1159@code{scm_make_smob_type_mfpe}.
1160
1161@item equalp
1162If Scheme code asks the @code{equal?} function to compare two instances
1163of the same smob type, Guile calls this function. It should return
1164@code{SCM_BOOL_T} if @var{a} and @var{b} should be considered
1165@code{equal?}, or @code{SCM_BOOL_F} otherwise. If @code{equalp} is
1166@code{NULL}, @code{equal?} will assume that two instances of this type are
1167never @code{equal?} unless they are @code{eq?}.
1168
1169@end table
1170
1171To actually register the new smob type, call @code{scm_make_smob_type}:
1172
1173@deftypefun long scm_make_smob_type (const char *name, scm_sizet size)
1174This function implements the standard way of adding a new smob type,
1175named @var{name}, with instance size @var{size}, to the system. The
1176return value is a tag that is used in creating instances of the type.
1177If @var{size} is 0, then no memory will be allocated when instances of
1178the smob are created, and nothing will be freed by the default free
1179function. Default values are provided for mark, free, print, and,
1180equalp, as described above. If you want to customize any of these
1181functions, the call to @code{scm_make_smob_type} should be immediately
1182followed by calls to one or several of @code{scm_set_smob_mark},
1183@code{scm_set_smob_free}, @code{scm_set_smob_print}, and/or
1184@code{scm_set_smob_equalp}.
1185@end deftypefun
1186
1187Each of the below @code{scm_set_smob_XXX} functions registers a smob
1188special function for a given type. Each function is intended to be used
1189only zero or one time per type, and the call should be placed
1190immediately following the call to @code{scm_make_smob_type}.
1191
1192@deftypefun void scm_set_smob_mark (long tc, SCM (*mark) (SCM))
1193This function sets the smob marking procedure for the smob type specified by
1194the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.
1195@end deftypefun
1196
1197@deftypefun void scm_set_smob_free (long tc, scm_sizet (*free) (SCM))
1198This function sets the smob freeing procedure for the smob type specified by
1199the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.
1200@end deftypefun
1201
1202@deftypefun void scm_set_smob_print (long tc, int (*print) (SCM,SCM,scm_print_state*))
1203This function sets the smob printing procedure for the smob type specified by
1204the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.
1205@end deftypefun
1206
1207@deftypefun void scm_set_smob_equalp (long tc, SCM (*equalp) (SCM,SCM))
1208This function sets the smob equality-testing predicate for the smob type specified by
1209the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.
1210@end deftypefun
1211
1212Instead of using @code{scm_make_smob_type} and calling each of the
1213individual @code{scm_set_smob_XXX} functions to register each special
1214function independently, you can use @code{scm_make_smob_type_mfpe} to
1215register all of the special functions at once as you create the smob
1216type@footnote{Warning: There is an ongoing discussion among the developers which
1217may result in deprecating @code{scm_make_smob_type_mfpe} in next release
1218of Guile.}:
1219
1220@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))
1221This function invokes @code{scm_make_smob_type} on its first two arguments
1222to add a new smob type named @var{name}, with instance size @var{size} to the system.
1223It also registers the @var{mark}, @var{free}, @var{print}, @var{equalp} smob
1224special functions for that new type. Any of these parameters can be @code{NULL}
1225to have that special function use the default behaviour for guile.
1226The return value is a tag that is used in creating instances of the type. If @var{size}
1227is 0, then no memory will be allocated when instances of the smob are created, and
1228nothing will be freed by the default free function.
1229@end deftypefun
1230
1231For example, here is how one might declare and register a new type
1232representing eight-bit grayscale images:
1233@example
1234#include <libguile.h>
1235
1236long image_tag;
1237
1238void
1239init_image_type ()
1240@{
1241 image_tag = scm_make_smob_type_mfpe ("image",sizeof(struct image),
1242 mark_image, free_image, print_image, NULL);
1243@}
1244@end example
1245
1246
1247@node Creating Instances
1248@subsection Creating Instances
1249
1250Like other non-immediate types, smobs start with a cell whose @sc{car}
1251contains typing information, and whose @code{cdr} is free for any use. For smobs,
1252the @code{cdr} stores a pointer to the internal C structure holding the
1253smob-specific data.
1254To create an instance of a smob type following these standards, you should
1255use @code{SCM_NEWSMOB}:
1256
1257@deftypefn Macro void SCM_NEWSMOB(SCM value,long tag,void *data)
1258Make @var{value} contain a smob instance of the type with tag @var{tag}
1259and smob data @var{data}. @var{value} must be previously declared
1260as C type @code{SCM}.
1261@end deftypefn
1262
1263Since it is often the case (e.g., in smob constructors) that you will
1264create a smob instance and return it, there is also a slightly specialized
1265macro for this situation:
1266
1267@deftypefn Macro fn_returns SCM_RETURN_NEWSMOB(long tab, void *data)
1268This macro expands to a block of code that creates a smob instance of
1269the type with tag @var{tag} and smob data @var{data}, and returns
1270that @code{SCM} value. It should be the last piece of code in
1271a block.
1272@end deftypefn
1273
1274Guile provides the following functions for managing memory, which are
1275often helpful when implementing smobs:
1276
1277@deftypefun {char *} scm_must_malloc (long @var{len}, char *@var{what})
1278Allocate @var{len} bytes of memory, using @code{malloc}, and return a
1279pointer to them.
1280
1281If there is not enough memory available, invoke the garbage collector,
1282and try once more. If there is still not enough, signal an error,
1283reporting that we could not allocate @var{what}.
1284
1285This function also helps maintain statistics about the size of the heap.
1286@end deftypefun
1287
1288@deftypefun {char *} scm_must_realloc (char *@var{addr}, long @var{olen}, long @var{len}, char *@var{what})
1289Resize (and possibly relocate) the block of memory at @var{addr}, to
1290have a size of @var{len} bytes, by calling @code{realloc}. Return a
1291pointer to the new block.
1292
1293If there is not enough memory available, invoke the garbage collector,
1294and try once more. If there is still not enough, signal an error,
1295reporting that we could not allocate @var{what}.
1296
1297The value @var{olen} should be the old size of the block of memory at
1298@var{addr}; it is only used for keeping statistics on the size of the
1299heap.
1300@end deftypefun
1301
1302@deftypefun void scm_must_free (char *@var{addr})
1303Free the block of memory at @var{addr}, using @code{free}. If
1304@var{addr} is zero, signal an error, complaining of an attempt to free
1305something that is already free.
1306
1307This does no record-keeping; instead, the smob's @code{free} function
1308must take care of that.
1309
1310This function isn't usually sufficiently different from the usual
1311@code{free} function to be worth using.
1312@end deftypefun
1313
1314
1315Continuing the above example, if the global variable @code{image_tag}
1316contains a tag returned by @code{scm_newsmob}, here is how we could
1317construct a smob whose @sc{cdr} contains a pointer to a freshly
1318allocated @code{struct image}:
1319
1320@example
1321struct image @{
1322 int width, height;
1323 char *pixels;
1324
1325 /* The name of this image */
1326 SCM name;
1327
1328 /* A function to call when this image is
1329 modified, e.g., to update the screen,
1330 or SCM_BOOL_F if no action necessary */
1331 SCM update_func;
1332@};
1333
1334SCM
1335make_image (SCM name, SCM s_width, SCM s_height)
1336@{
1337 struct image *image;
1338 int width, height;
1339
1340 SCM_ASSERT (SCM_NIMP (name) && SCM_STRINGP (name), name,
1341 SCM_ARG1, "make-image");
1342 SCM_ASSERT (SCM_INUMP (s_width), s_width, SCM_ARG2, "make-image");
1343 SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");
1344
1345 width = SCM_INUM (s_width);
1346 height = SCM_INUM (s_height);
1347
1348 image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
1349 image->width = width;
1350 image->height = height;
1351 image->pixels = scm_must_malloc (width * height, "image pixels");
1352 image->name = name;
1353 image->update_func = SCM_BOOL_F;
1354
1355 SCM_RETURN_NEWSMOB (image_tag, image);
1356@}
1357@end example
1358
1359
1360@node Typechecking
1361@subsection Typechecking
1362
1363Functions that operate on smobs should aggressively check the types of
1364their arguments, to avoid misinterpreting some other datatype as a smob,
1365and perhaps causing a segmentation fault. Fortunately, this is pretty
1366simple to do. The function need only verify that its argument is a
1367non-immediate, whose @sc{car} is the type tag returned by
1368@code{scm_newsmob}.
1369
1370For example, here is a simple function that operates on an image smob,
1371and checks the type of its argument. We also present an expanded
1372version of the @code{init_image_type} function, to make
1373@code{clear_image} and the image constructor function @code{make_image}
1374visible to Scheme code.
1375@example
1376SCM
1377clear_image (SCM image_smob)
1378@{
1379 int area;
1380 struct image *image;
1381
1382 SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob),
1383 image_smob, SCM_ARG1, "clear-image");
1384
1385 image = (struct image *) SCM_SMOB_DATA (image_smob);
1386 area = image->width * image->height;
1387 memset (image->pixels, 0, area);
1388
1389 /* Invoke the image's update function. */
1390 if (image->update_func != SCM_BOOL_F)
1391 scm_apply (image->update_func, SCM_EOL, SCM_EOL);
1392
1393 return SCM_UNSPECIFIED;
1394@}
1395
1396
1397void
1398init_image_type ()
1399@{
1400 image_tag = scm_newsmob (&image_funs);
1401
1402 scm_make_gsubr ("make-image", 3, 0, 0, make_image);
1403 scm_make_gsubr ("clear-image", 1, 0, 0, clear_image);
1404@}
1405@end example
1406
1407Note that checking types is a little more complicated during garbage
1408collection; see the description of @code{SCM_GCTYP16} in @ref{Garbage
1409Collecting Smobs}.
1410
1411@c GJB:FIXME:: should talk about guile-snarf somewhere!
1412
1413@node Garbage Collecting Smobs
1414@subsection Garbage Collecting Smobs
1415
1416Once a smob has been released to the tender mercies of the Scheme
1417system, it must be prepared to survive garbage collection. Guile calls
1418the @code{mark} and @code{free} functions of the @code{scm_smobfuns}
1419structure to manage this.
1420
1421As described before (@pxref{Conservative GC}), every object in the
1422Scheme system has a @dfn{mark bit}, which the garbage collector uses to
1423tell live objects from dead ones. When collection starts, every
1424object's mark bit is clear. The collector traces pointers through the
1425heap, starting from objects known to be live, and sets the mark bit on
1426each object it encounters. When it can find no more unmarked objects,
1427the collector walks all objects, live and dead, frees those whose mark
1428bits are still clear, and clears the mark bit on the others.
1429
1430The two main portions of the collection are called the @dfn{mark phase},
1431during which the collector marks live objects, and the @dfn{sweep
1432phase}, during which the collector frees all unmarked objects.
1433
1434The mark bit of a smob lives in its @sc{car}, along with the smob's type
1435tag. When the collector encounters a smob, it sets the smob's mark bit,
1436and uses the smob's type tag to find the appropriate @code{mark}
1437function for that smob: the one listed in that smob's
1438@code{scm_smobfuns} structure. It then calls the @code{mark} function,
1439passing it the smob as its only argument.
1440
1441The @code{mark} function is responsible for marking any other Scheme
1442objects the smob refers to. If it does not do so, the objects' mark
1443bits will still be clear when the collector begins to sweep, and the
1444collector will free them. If this occurs, it will probably break, or at
1445least confuse, any code operating on the smob; the smob's @code{SCM}
1446values will have become dangling references.
1447
1448To mark an arbitrary Scheme object, the @code{mark} function may call
1449this function:
1450
1451@deftypefun void scm_gc_mark (SCM @var{x})
1452Mark the object @var{x}, and recurse on any objects @var{x} refers to.
1453If @var{x}'s mark bit is already set, return immediately.
1454@end deftypefun
1455
1456Thus, here is how we might write the @code{mark} function for the image
1457smob type discussed above:
1458@example
1459@group
1460SCM
1461mark_image (SCM image_smob)
1462@{
1463 /* Mark the image's name and update function. */
1464 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1465
1466 scm_gc_mark (image->name);
1467 scm_gc_mark (image->update_func);
1468
1469 return SCM_BOOL_F;
1470@}
1471@end group
1472@end example
1473
1474Note that, even though the image's @code{update_func} could be an
1475arbitrarily complex structure (representing a procedure and any values
1476enclosed in its environment), @code{scm_gc_mark} will recurse as
1477necessary to mark all its components. Because @code{scm_gc_mark} sets
1478an object's mark bit before it recurses, it is not confused by
1479circular structures.
1480
1481As an optimization, the collector will mark whatever value is returned
1482by the @code{mark} function; this helps limit depth of recursion during
1483the mark phase. Thus, the code above could also be written as:
1484@example
1485@group
1486SCM
1487mark_image (SCM image_smob)
1488@{
1489 /* Mark the image's name and update function. */
1490 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1491
1492 scm_gc_mark (image->name);
1493 return image->update_func;
1494@}
1495@end group
1496@end example
1497
1498
1499Finally, when the collector encounters an unmarked smob during the sweep
1500phase, it uses the smob's tag to find the appropriate @code{free}
1501function for the smob. It then calls the function, passing it the smob
1502as its only argument.
1503
1504The @code{free} function must release any resources used by the smob.
1505However, it need not free objects managed by the collector; the
1506collector will take care of them. The return type of the @code{free}
1507function should be @code{scm_sizet}, an unsigned integral type; the
1508@code{free} function should return the number of bytes released, to help
1509the collector maintain statistics on the size of the heap.
1510
1511Here is how we might write the @code{free} function for the image smob
1512type:
1513@example
1514scm_sizet
1515free_image (SCM image_smob)
1516@{
1517 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1518 scm_sizet size = image->width * image->height + sizeof (*image);
1519
1520 free (image->pixels);
1521 free (image);
1522
1523 return size;
1524@}
1525@end example
1526
1527During the sweep phase, the garbage collector will clear the mark bits
1528on all live objects. The code which implements a smob need not do this
1529itself.
1530
1531There is no way for smob code to be notified when collection is
1532complete.
1533
1534Note that, since a smob's mark bit lives in its @sc{car}, along with the
1535smob's type tag, the technique for checking the type of a smob described
1536in @ref{Typechecking} will not necessarily work during GC. If you need
1537to find out whether a given object is a particular smob type during GC,
1538use the following macro:
1539
1540@deftypefn Macro void SCM_GCTYP16 (SCM @var{x})
1541Return the type bits of the smob @var{x}, with the mark bit clear.
1542
1543Use this macro instead of @code{SCM_CAR} to check the type of a smob
1544during GC. Usually, only code called by the smob's @code{mark} function
1545need worry about this.
1546@end deftypefn
1547
1548It is usually a good idea to minimize the amount of processing done
1549during garbage collection; keep @code{mark} and @code{free} functions
1550very simple. Since collections occur at unpredictable times, it is easy
1551for any unusual activity to interfere with normal code.
1552
1553
1554@node A Common Mistake In Allocating Smobs, Garbage Collecting Simple Smobs, Garbage Collecting Smobs, Defining New Types (Smobs)
1555@subsection A Common Mistake In Allocating Smobs
1556
1557When constructing new objects, you must be careful that the garbage
1558collector can always find any new objects you allocate. For example,
1559suppose we wrote the @code{make_image} function this way:
1560
1561@example
1562SCM
1563make_image (SCM name, SCM s_width, SCM s_height)
1564@{
1565 struct image *image;
1566 SCM image_smob;
1567 int width, height;
1568
1569 SCM_ASSERT (SCM_NIMP (name) && SCM_STRINGP (name), name,
1570 SCM_ARG1, "make-image");
1571 SCM_ASSERT (SCM_INUMP (s_width), s_width, SCM_ARG2, "make-image");
1572 SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");
1573
1574 width = SCM_INUM (s_width);
1575 height = SCM_INUM (s_height);
1576
1577 image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
1578 image->width = width;
1579 image->height = height;
1580 image->pixels = scm_must_malloc (width * height, "image pixels");
1581
1582 /* THESE TWO LINES HAVE CHANGED: */
1583 image->name = scm_string_copy (name);
1584 image->update_func = scm_make_gsubr (@dots{});
1585
1586 SCM_NEWCELL (image_smob);
1587 SCM_SETCDR (image_smob, image);
1588 SCM_SETCAR (image_smob, image_tag);
1589
1590 return image_smob;
1591@}
1592@end example
1593
1594This code is incorrect. The calls to @code{scm_string_copy} and
1595@code{scm_make_gsubr} allocate fresh objects. Allocating any new object
1596may cause the garbage collector to run. If @code{scm_make_gsubr}
1597invokes a collection, the garbage collector has no way to discover that
1598@code{image->name} points to the new string object; the @code{image}
1599structure is not yet part of any Scheme object, so the garbage collector
1600will not traverse it. Since the garbage collector cannot find any
1601references to the new string object, it will free it, leaving
1602@code{image} pointing to a dead object.
1603
1604A correct implementation might say, instead:
1605@example
1606 image->name = SCM_BOOL_F;
1607 image->update_func = SCM_BOOL_F;
1608
1609 SCM_NEWCELL (image_smob);
1610 SCM_SETCDR (image_smob, image);
1611 SCM_SETCAR (image_smob, image_tag);
1612
1613 image->name = scm_string_copy (name);
1614 image->update_func = scm_make_gsubr (@dots{});
1615
1616 return image_smob;
1617@end example
1618
1619Now, by the time we allocate the new string and function objects,
1620@code{image_smob} points to @code{image}. If the garbage collector
1621scans the stack, it will find a reference to @code{image_smob} and
1622traverse @code{image}, so any objects @code{image} points to will be
1623preserved.
1624
1625
1626@node Garbage Collecting Simple Smobs, A Complete Example, A Common Mistake In Allocating Smobs, Defining New Types (Smobs)
1627@subsection Garbage Collecting Simple Smobs
1628
1629It is often useful to define very simple smob types --- smobs which have
1630no data to mark, other than the cell itself, or smobs whose @sc{cdr} is
1631simply an ordinary Scheme object, to be marked recursively. Guile
1632provides some functions to handle these common cases; you can use these
1633functions as your smob type's @code{mark} function, if your smob's
1634structure is simple enough.
1635
1636If the smob refers to no other Scheme objects, then no action is
1637necessary; the garbage collector has already marked the smob cell
1638itself. In that case, you can use zero as your mark function.
1639
1640@deftypefun SCM scm_markcdr (SCM @var{x})
1641Mark the references in the smob @var{x}, assuming that @var{x}'s
1642@sc{cdr} contains an ordinary Scheme object, and @var{x} refers to no
1643other objects. This function simply returns @var{x}'s @sc{cdr}.
1644@end deftypefun
1645
1646@deftypefun scm_sizet scm_free0 (SCM @var{x})
1647Do nothing; return zero. This function is appropriate for smobs that
1648use either zero or @code{scm_markcdr} as their marking functions, and
1649refer to no heap storage, including memory managed by @code{malloc},
1650other than the smob's header cell.
1651@end deftypefun
1652
1653
1654@node A Complete Example
1655@subsection A Complete Example
1656
1657Here is the complete text of the implementation of the image datatype,
1658as presented in the sections above. We also provide a definition for
1659the smob's @code{print} function, and make some objects and functions
1660static, to clarify exactly what the surrounding code is using.
1661
1662As mentioned above, you can find this code in the Guile distribution, in
1663@file{doc/example-smob}. That directory includes a makefile and a
1664suitable @code{main} function, so you can build a complete interactive
1665Guile shell, extended with the datatypes described here.)
1666
1667@example
1668/* file "image-type.c" */
1669
1670#include <stdlib.h>
1671#include <libguile.h>
1672
1673static long image_tag;
1674
1675struct image @{
1676 int width, height;
1677 char *pixels;
1678
1679 /* The name of this image */
1680 SCM name;
1681
1682 /* A function to call when this image is
1683 modified, e.g., to update the screen,
1684 or SCM_BOOL_F if no action necessary */
1685 SCM update_func;
1686@};
1687
1688static SCM
1689make_image (SCM name, SCM s_width, SCM s_height)
1690@{
1691 struct image *image;
1692 SCM image_smob;
1693 int width, height;
1694
1695 SCM_ASSERT (SCM_NIMP (name) && SCM_STRINGP (name), name,
1696 SCM_ARG1, "make-image");
1697 SCM_ASSERT (SCM_INUMP (s_width), s_width, SCM_ARG2, "make-image");
1698 SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");
1699
1700 width = SCM_INUM (s_width);
1701 height = SCM_INUM (s_height);
1702
1703 image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
1704 image->width = width;
1705 image->height = height;
1706 image->pixels = scm_must_malloc (width * height, "image pixels");
1707 image->name = name;
1708 image->update_func = SCM_BOOL_F;
1709
1710 SCM_NEWSMOB (image_smob, image_tag, image);
1711
1712 return image_smob;
1713@}
1714
1715static SCM
1716clear_image (SCM image_smob)
1717@{
1718 int area;
1719 struct image *image;
1720
1721 SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob),
1722 image_smob, SCM_ARG1, "clear-image");
1723
1724 image = (struct image *) SCM_SMOB_DATA (image_smob);
1725 area = image->width * image->height;
1726 memset (image->pixels, 0, area);
1727
1728 /* Invoke the image's update function. */
1729 if (image->update_func != SCM_BOOL_F)
1730 scm_apply (image->update_func, SCM_EOL, SCM_EOL);
1731
1732 return SCM_UNSPECIFIED;
1733@}
1734
1735static SCM
1736mark_image (SCM image_smob)
1737@{
1738 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1739
1740 scm_gc_mark (image->name);
1741 return image->update_func;
1742@}
1743
1744static scm_sizet
1745free_image (SCM image_smob)
1746@{
1747 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1748 scm_sizet size = image->width * image->height + sizeof (struct image);
1749
1750 free (image->pixels);
1751 free (image);
1752
1753 return size;
1754@}
1755
1756static int
1757print_image (SCM image_smob, SCM port, scm_print_state *pstate)
1758@{
1759 struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
1760
1761 scm_puts ("#<image ", port);
1762 scm_display (image->name, port);
1763 scm_puts (">", port);
1764
1765 /* non-zero means success */
1766 return 1;
1767@}
1768
1769static scm_smobfuns image_funs = @{
1770 mark_image, free_image, print_image, 0
1771@};
1772
1773void
1774init_image_type ()
1775@{
1776 image_tag = scm_newsmob (&image_funs);
1777
1778 scm_make_gsubr ("clear-image", 1, 0, 0, clear_image);
1779 scm_make_gsubr ("make-image", 3, 0, 0, make_image);
1780@}
1781@end example
1782
1783Here is a sample build and interaction with the code from the
1784@file{example-smob} directory, on the author's machine:
1785
1786@example
1787zwingli:example-smob$ make CC=gcc
1788gcc `guile-config compile` -c image-type.c -o image-type.o
1789gcc `guile-config compile` -c myguile.c -o myguile.o
1790gcc image-type.o myguile.o `guile-config link` -o myguile
1791zwingli:example-smob$ ./myguile
1792guile> make-image
1793#<primitive-procedure make-image>
1794guile> (define i (make-image "Whistler's Mother" 100 100))
1795guile> i
1796#<image Whistler's Mother>
1797guile> (clear-image i)
1798guile> (clear-image 4)
1799ERROR: In procedure clear-image in expression (clear-image 4):
1800ERROR: Wrong type argument in position 1: 4
1801ABORT: (wrong-type-arg)
1802
1803Type "(backtrace)" to get more information.
1804guile>
1805@end example
1806
1807@c essay @bye