4 @setfilename data-rep.info
5 @settitle Data Representation in Guile
10 @dircategory Scheme Programming
12 * data-rep: (data-rep). Data Representation in Guile --- how to use
13 Guile objects in your C code.
16 @setchapternewpage off
19 Data Representation in Guile
21 Copyright (C) 1998 Free Software Foundation
23 Permission is granted to make and distribute verbatim copies of
24 this manual provided the copyright notice and this permission notice
25 are preserved on all copies.
28 Permission is granted to process this file through TeX and print the
29 results, provided the printed document carries copying permission
30 notice identical to this one except for the removal of this paragraph
31 (this paragraph not being relevant to the printed manual).
34 Permission is granted to copy and distribute modified versions of this
35 manual under the conditions for verbatim copying, provided that the entire
36 resulting derived work is distributed under the terms of a permission
37 notice identical to this one.
39 Permission is granted to copy and distribute translations of this manual
40 into another language, under the above conditions for modified versions,
41 except that this permission notice may be stated in a translation approved
42 by the Free Software Foundation.
47 @comment The title is printed in a large font.
48 @title Data Representation in Guile
49 @subtitle $Id: data-rep.texi,v 1.1 1998-10-07 07:37:16 jimb Exp $
50 @subtitle For use with Guile @value{VERSION}
52 @author Free Software Foundation
53 @author @email{jimb@@red-bean.com}
54 @c The following two commands start the copyright page.
56 @vskip 0pt plus 1filll
57 @vskip 0pt plus 1filll
58 Copyright @copyright{} 1998 Free Software Foundation
60 Permission is granted to make and distribute verbatim copies of
61 this manual provided the copyright notice and this permission notice
62 are preserved on all copies.
64 Permission is granted to copy and distribute modified versions of this
65 manual under the conditions for verbatim copying, provided that the entire
66 resulting derived work is distributed under the terms of a permission
67 notice identical to this one.
69 Permission is granted to copy and distribute translations of this manual
70 into another language, under the above conditions for modified versions,
71 except that this permission notice may be stated in a translation approved
72 by Free Software Foundation.
80 @node Top, Data Representation in Scheme, (dir), (dir)
81 @top Data Representation in Guile
84 This essay is meant to provide the background necessary to read and
85 write C code that manipulates Scheme values in a way that conforms to
86 libguile's interface. If you would like to write or maintain a
87 Guile-based application, this is the first information you need.
89 In order to make sense of Guile's SCM_ functions, or read libguile's
90 source code, it's essential to have a good grasp of how Guile actually
91 represents Scheme values. Otherwise, a lot of the code, and the
92 conventions it follows, won't make very much sense.
94 We assume you know both C and Scheme, but we do not assume you are
95 familiar with Guile's C interface.
99 * Data Representation in Scheme:: Why things aren't just totally
100 straightforward, in general terms.
101 * How Guile does it:: How to write C code that manipulates
102 Guile values, with an explanation
103 of Guile's garbage collector.
104 * Defining New Types (Smobs):: How to extend Guile with your own
105 application-specific datatypes.
108 @node Data Representation in Scheme, How Guile does it, Top, Top
109 @section Data Representation in Scheme
111 Scheme is a latently-typed language; this means that the system cannot,
112 in general, determine the type of a given expression at compile time.
113 Types only become apparent at run time. Variables do not have fixed
114 types; a variable may hold a pair at one point, an integer at the next,
115 and a thousand-element vector later. Instead, values have fixed types.
117 In order to implement standard Scheme functions like @code{pair?} and
118 @code{string?} and provide garbage collection, the representation of
119 every value must contain enough information to accurately determine its
120 type at run time. Often, Scheme systems also use this information to
121 determine whether a program has attempted to apply an operation to an
122 inappropriately typed value (such as taking the @code{car} of a string).
124 Because variables, pairs, and vectors may hold values of any type,
125 Scheme implementations use a uniform representation for values --- a
126 single type large enough to hold either a complete value or a pointer
127 to a complete value, along with the necessary typing information.
129 The following sections will present a simple typing system, and then
130 make some refinements to correct its major weaknesses. However, this is
131 not a description of the system Guile actually uses. It is only an
132 illustration of the issues Guile's system must address. We provide all
133 the information one needs to work with Guile's data in @ref{How Guile
138 * A Simple Representation::
144 @node A Simple Representation, Faster Integers, Data Representation in Scheme, Data Representation in Scheme
145 @subsection A Simple Representation
147 The simplest way to meet the above requirements in C would be to
148 represent each value as a pointer to a structure containing a type
149 indicator, followed by a union carrying the real value. Assuming that
150 @code{SCM} is the name of our universal type, we can write:
153 enum type @{ integer, pair, string, vector, ... @};
155 typedef struct value *SCM;
161 struct @{ SCM car, cdr; @} pair;
162 struct @{ int length; char *elts; @} string;
163 struct @{ int length; SCM *elts; @} vector;
168 with the ellipses replaced with code for the remaining Scheme types.
170 This representation is sufficient to implement all of Scheme's
171 semantics. If @var{x} is an @code{SCM} value:
174 To test if @var{x} is an integer, we can write @code{@var{x}->type == integer}.
176 To find its value, we can write @code{@var{x}->value.integer}.
178 To test if @var{x} is a vector, we can write @code{@var{x}->type == vector}.
180 If we know @var{x} is a vector, we can write
181 @code{@var{x}->value.vector.elts[0]} to refer to its first element.
183 If we know @var{x} is a pair, we can write
184 @code{@var{x}->value.pair.car} to extract its car.
188 @node Faster Integers, Cheaper Pairs, A Simple Representation, Data Representation in Scheme
189 @subsection Faster Integers
191 Unfortunately, the above representation has a serious disadvantage. In
192 order to return an integer, an expression must allocate a @code{struct
193 value}, initialize it to represent that integer, and return a pointer to
194 it. Furthermore, fetching an integer's value requires a memory
195 reference, which is much slower than a register reference on most
196 processors. Since integers are extremely common, this representation is
197 too costly, in both time and space. Integers should be very cheap to
198 create and manipulate.
200 One possible solution comes from the observation that, on many
201 architectures, structures must be aligned on a four-byte boundary.
202 (Whether or not the machine actually requires it, we can write our own
203 allocator for @code{struct value} objects that assures this is true.)
204 In this case, the lower two bits of the structure's address are known to
207 This gives us the room we need to provide an improved representation
208 for integers. We make the following rules:
211 If the lower two bits of an @code{SCM} value are zero, then the SCM
212 value is a pointer to a @code{struct value}, and everything proceeds as
215 Otherwise, the @code{SCM} value represents an integer, whose value
216 appears in its upper bits.
219 Here is C code implementing this convention:
221 enum type @{ pair, string, vector, ... @};
223 typedef struct value *SCM;
228 struct @{ SCM car, cdr; @} pair;
229 struct @{ int length; char *elts; @} string;
230 struct @{ int length; SCM *elts; @} vector;
235 #define POINTER_P(x) (((int) (x) & 3) == 0)
236 #define INTEGER_P(x) (! POINTER_P (x))
238 #define GET_INTEGER(x) ((int) (x) >> 2)
239 #define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1))
242 Notice that @code{integer} no longer appears as an element of @code{enum
243 type}, and the union has lost its @code{integer} member. Instead, we
244 use the @code{POINTER_P} and @code{INTEGER_P} macros to make a coarse
245 classification of values into integers and non-integers, and do further
246 type testing as before.
248 Here's how we would answer the questions posed above (again, assume
249 @var{x} is an @code{SCM} value):
252 To test if @var{x} is an integer, we can write @code{INTEGER_P (@var{x})}.
254 To find its value, we can write @code{GET_INTEGER (@var{x})}.
256 To test if @var{x} is a vector, we can write:
258 @code{POINTER_P (@var{x}) && @var{x}->type == vector}
260 Given the new representation, we must make sure @var{x} is truly a
261 pointer before we dereference it to determine its complete type.
263 If we know @var{x} is a vector, we can write
264 @code{@var{x}->value.vector.elts[0]} to refer to its first element, as
267 If we know @var{x} is a pair, we can write
268 @code{@var{x}->value.pair.car} to extract its car, just as before.
271 This representation allows us to operate more efficiently on integers
272 than the first. For example, if @var{x} and @var{y} are known to be
273 integers, we can compute their sum as follows:
275 MAKE_INTEGER (GET_INTEGER (@var{x}) + GET_INTEGER (@var{y}))
277 Now, integer math requires no allocation or memory references. Most
278 real Scheme systems actually use an even more efficient representation,
279 but this essay isn't about bit-twiddling. (Hint: what if pointers had
280 @code{01} in their least significant bits, and integers had @code{00}?)
283 @node Cheaper Pairs, Guile Is Hairier, Faster Integers, Data Representation in Scheme
284 @subsection Cheaper Pairs
286 However, there is yet another issue to confront. Most Scheme heaps
287 contain more pairs than any other type of object; Jonathan Rees says
288 that pairs occupy 45% of the heap in his Scheme implementation, Scheme
289 48. However, our representation above spends three @code{SCM}-sized
290 words per pair --- one for the type, and two for the @sc{car} and
291 @sc{cdr}. Is there any way to represent pairs using only two words?
293 Let us refine the convention we established earlier. Let us assert
297 If the bottom two bits of an @code{SCM} value are @code{#b00}, then
298 it is a pointer, as before.
300 If the bottom two bits are @code{#b01}, then the upper bits are an
301 integer. This is a bit more restrictive than before.
303 If the bottom two bits are @code{#b10}, then the value, with the bottom
304 two bits masked out, is the address of a pair.
307 Here is the new C code:
309 enum type @{ string, vector, ... @};
311 typedef struct value *SCM;
316 struct @{ int length; char *elts; @} string;
317 struct @{ int length; SCM *elts; @} vector;
326 #define POINTER_P(x) (((int) (x) & 3) == 0)
328 #define INTEGER_P(x) (((int) (x) & 3) == 1)
329 #define GET_INTEGER(x) ((int) (x) >> 2)
330 #define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1))
332 #define PAIR_P(x) (((int) (x) & 3) == 2)
333 #define GET_PAIR(x) ((struct pair *) ((int) (x) & ~3))
336 Notice that @code{enum type} and @code{struct value} now only contain
337 provisions for vectors and strings; both integers and pairs have become
338 special cases. The code above also assumes that an @code{int} is large
339 enough to hold a pointer, which isn't generally true.
342 Our list of examples is now as follows:
345 To test if @var{x} is an integer, we can write @code{INTEGER_P
346 (@var{x})}; this is as before.
348 To find its value, we can write @code{GET_INTEGER (@var{x})}, as
351 To test if @var{x} is a vector, we can write:
353 @code{POINTER_P (@var{x}) && @var{x}->type == vector}
355 We must still make sure that @var{x} is a pointer to a @code{struct
356 value} before dereferencing it to find its type.
358 If we know @var{x} is a vector, we can write
359 @code{@var{x}->value.vector.elts[0]} to refer to its first element, as
362 We can write @code{PAIR_P (@var{x})} to determine if @var{x} is a
363 pair, and then write @code{GET_PAIR (@var{x})->car} to refer to its
367 This change in representation reduces our heap size by 15%. It also
368 makes it cheaper to decide if a value is a pair, because no memory
369 references are necessary; it suffices to check the bottom two bits of
370 the @code{SCM} value. This may be significant when traversing lists, a
371 common activity in a Scheme system.
373 Again, most real Scheme systems use a slighty different implementation;
374 for example, if GET_PAIR subtracts off the low bits of @code{x}, instead
375 of masking them off, the optimizer will often be able to combine that
376 subtraction with the addition of the offset of the structure member we
377 are referencing, making a modified pointer as fast to use as an
381 @node Guile Is Hairier, , Cheaper Pairs, Data Representation in Scheme
382 @subsection Guile Is Hairier
384 We originally started with a very simple typing system --- each object
385 has a field that indicates its type. Then, for the sake of efficiency
386 in both time and space, we moved some of the typing information directly
387 into the @code{SCM} value, and left the rest in the @code{struct value}.
388 Guile itself employs a more complex hierarchy, storing finer and finer
389 gradations of type information in different places, depending on the
390 object's coarser type.
392 In the author's opinion, Guile could be simplified greatly without
393 significant loss of efficiency, but the simplified system would still be
394 more complex than what we've presented above.
397 @node How Guile does it, Defining New Types (Smobs), Data Representation in Scheme, Top
398 @section How Guile does it
400 Here we present the specifics of how Guile represents its data. We
401 don't go into complete detail; an exhaustive description of Guile's
402 system would be boring, and we do not wish to encourage people to write
403 code which depends on its details anyway. We do, however, present
404 everything one need know to use Guile's data.
409 * Garbage Collection::
410 * Immediates vs. Non-immediates::
411 * Immediate Datatypes::
412 * Non-immediate Datatypes::
413 * Signalling Type Errors::
416 @node General Rules, Garbage Collection, How Guile does it, How Guile does it
417 @subsection General Rules
419 Any code which operates on Guile datatypes must @code{#include} the
420 header file @code{<libguile.h>}. This file contains a definition for
421 the @code{SCM} typedef (Guile's universal type, as in the examples
422 above), and definitions and declarations for a host of macros and
423 functions that operate on @code{SCM} values.
425 All identifiers declared by @code{<libguile.h>} begin with @code{scm_}
428 @c [[I wish this were true, but I don't think it is at the moment. -JimB]]
429 @c Macros do not evaluate their arguments more than once, unless documented
432 The functions described here generally check the types of their
433 @code{SCM} arguments, and signal an error if their arguments are of an
434 inappropriate type. Macros generally do not, unless that is their
435 specified purpose. You must verify their argument types beforehand, as
438 Macros and functions that return a boolean value have names ending in
439 @code{P} or @code{_p} (for ``predicate''). Those that return a negated
440 boolean value have names starting with @code{SCM_N}. For example,
441 @code{SCM_IMP (@var{x})} is a predicate which returns non-zero iff
442 @var{x} is an immediate value (an @code{IM}). @code{SCM_NCONSP
443 (@var{x})} is a predicate which returns non-zero iff @var{x} is
444 @emph{not} a pair object (a @code{CONS}).
447 @node Garbage Collection, Immediates vs. Non-immediates, General Rules, How Guile does it
448 @subsection Garbage Collection
450 Aside from the latent typing, the major source of constraints on a
451 Scheme implementation's data representation is the garbage collector.
452 The collector must be able to traverse every live object in the heap, to
453 determine which objects are not live.
455 There are many ways to implement this, but Guile uses an algorithm
456 called @dfn{mark and sweep}. The collector scans the system's global
457 variables and the local variables on the stack to determine which
458 objects are immediately accessible by the C code. It then scans those
459 objects to find the objects they point to, @i{et cetera}. The collector
460 sets a @dfn{mark bit} on each object it finds, so each object is
461 traversed only once. This process is called @dfn{tracing}.
463 When the collector can find no unmarked objects pointed to by marked
464 objects, it assumes that any objects that are still unmarked will never
465 be used by the program (since there is no path of dereferences from any
466 global or local variable that reaches them) and deallocates them.
468 In the above paragraphs, we did not specify how the garbage collector
469 finds the global and local variables; as usual, there are many different
470 approaches. Frequently, the programmer must maintain a list of pointers
471 to all global variables that refer to the heap, and another list
472 (adjusted upon entry to and exit from each function) of local variables,
473 for the collector's benefit.
475 The list of global variables is usually not too difficult to maintain,
476 since global variables are relatively rare. However, an explicitly
477 maintained list of local variables (in the author's personal experience)
478 is a nightmare to maintain. Thus, Guile uses a technique called
479 @dfn{conservative garbage collection}, to make the local variable list
482 The trick to conservative collection is to treat the stack as an
483 ordinary range of memory, and assume that @emph{every} word on the stack
484 is a pointer into the heap. Thus, the collector marks all objects whose
485 addresses appear anywhere in the stack, without knowing for sure how
486 that word is meant to be interpreted.
488 Obviously, such a system will occasionally retain objects that are
489 actually garbage, and should be freed. In practice, this is not a
490 problem. The alternative, an explicitly maintained list of local
491 variable addresses, is effectively much less reliable, due to programmer
494 To accomodate this technique, data must be represented so that the
495 collector can accurately determine whether a given stack word is a
496 pointer or not. Guile does this as follows:
500 Every heap object has a two-word header, called a @dfn{cell}. Some
501 objects, like pairs, fit entirely in a cell's two words; others may
502 store pointers to additional memory in either of the words. For
503 example, strings and vectors store their length in the first word, and a
504 pointer to their elements in the second.
507 Guile allocates whole arrays of cells at a time, called @dfn{heap
508 segments}. These segments are always allocated so that the cells they
509 contain fall on eight-byte boundaries, or whatever is appropriate for
510 the machine's word size. Guile keeps all cells in a heap segment
511 initialized, whether or not they are currently in use.
514 Guile maintains a sorted table of heap segments.
518 Thus, given any random word @var{w} fetched from the stack, Guile's
519 garbage collector can consult the table to see if @var{w} falls within a
520 known heap segment, and check @var{w}'s alignment. If both tests pass,
521 the collector knows that @var{w} is a valid pointer to a cell,
522 intentional or not, and proceeds to trace the cell.
524 Note that heap segments do not contain all the data Guile uses; cells
525 for objects like vectors and strings contain pointers to other memory
526 areas. However, since those pointers are internal, and not shared among
527 many pieces of code, it is enough for the collector to find the cell,
528 and then use the cell's type to find more pointers to trace.
531 @node Immediates vs. Non-immediates, Immediate Datatypes, Garbage Collection, How Guile does it
532 @subsection Immediates vs. Non-immediates
534 Guile classifies Scheme objects into two kinds: those that fit entirely
535 within an @code{SCM}, and those that require heap storage.
537 The former class are called @dfn{immediates}. The class of immediates
538 includes small integers, characters, boolean values, the empty list, the
539 mysterious end-of-file object, and some others.
541 The remaining types are called, not suprisingly, @dfn{non-immediates}.
542 They include pairs, procedures, strings, vectors, and all other data
545 @deftypefn Macro int SCM_IMP (SCM @var{x})
546 Return non-zero iff @var{x} is an immediate object.
549 @deftypefn Macro int SCM_NIMP (SCM @var{x})
550 Return non-zero iff @var{x} is a non-immediate object. This is the
551 exact complement of @code{SCM_IMP}, above.
553 You must use this macro before calling a finer-grained predicate to
554 determine @var{x}'s type. For example, to see if @var{x} is a pair, you
557 SCM_NIMP (@var{x}) && SCM_CONSP (@var{x})
559 This is because Guile stores typing information for non-immediate values
560 in their cells, rather than in the @code{SCM} value itself; thus, you
561 must determine whether @var{x} refers to a cell before looking inside
564 This is somewhat of a pity, because it means that the programmer needs
565 to know which types Guile implements as immediates vs. non-immediates.
566 There are (possibly better) representations in which @code{SCM_CONSP}
567 can be self-sufficient. The immediate type predicates do not suffer
572 @node Immediate Datatypes, Non-immediate Datatypes, Immediates vs. Non-immediates, How Guile does it
573 @subsection Immediate Datatypes
575 The following datatypes are immediate values; that is, they fit entirely
576 within an @code{SCM} value. The @code{SCM_IMP} and @code{SCM_NIMP}
577 macros will distinguish these from non-immediates; see @ref{Immediates
578 vs. Non-immediates} for an explanation of the distinction.
580 Note that the type predicates for immediate values work correctly on any
581 @code{SCM} value; you do not need to call @code{SCM_IMP} first, to
582 establish that a value is immediate. This differs from the
583 non-immediate type predicates, which work correctly only on
584 non-immediate values; you must be sure the value is @code{SCM_NIMP}
585 before applying them.
595 @node Integers, Characters, Immediate Datatypes, Immediate Datatypes
596 @subsubsection Integers
598 Here are functions for operating on small integers, that fit within an
599 @code{SCM}. Such integers are called @dfn{immediate numbers}, or
600 @dfn{INUMs}. In general, INUMs occupy all but two bits of an
603 Bignums and floating-point numbers are non-immediate objects, and have
604 their own, separate accessors. The functions here will not work on
605 them. This is not as much of a problem as you might think, however,
606 because the system never constructs bignums that could fit in an INUM,
607 and never uses floating point values for exact integers.
609 @deftypefn Macro int SCM_INUMP (SCM @var{x})
610 Return non-zero iff @var{x} is a small integer value.
613 @deftypefn Macro int SCM_NINUMP (SCM @var{x})
614 The complement of SCM_INUMP.
617 @deftypefn Macro int SCM_INUM (SCM @var{x})
618 Return the value of @var{x} as an ordinary, C integer. If @var{x}
619 is not an INUM, the result is undefined.
622 @deftypefn Macro SCM SCM_MAKINUM (int @var{i})
623 Given a C integer @var{i}, return its representation as an @code{SCM}.
624 This function does not check for overflow.
628 @node Characters, Booleans, Integers, Immediate Datatypes
629 @subsubsection Characters
631 Here are functions for operating on characters.
633 @deftypefn Macro int SCM_ICHRP (SCM @var{x})
634 Return non-zero iff @var{x} is a character value.
637 @deftypefn Macro {unsigned int} SCM_ICHR (SCM @var{x})
638 Return the value of @code{x} as a C character. If @var{x} is not a
639 Scheme character, the result is undefined.
642 @deftypefn Macro SCM SCM_MAKICHR (SCM @var{c})
643 Given a C character @var{c}, return its representation as a Scheme
648 @node Booleans, Unique Values, Characters, Immediate Datatypes
649 @subsubsection Booleans
651 Here are functions and macros for operating on booleans.
653 @deftypefn Macro SCM SCM_BOOL_T
654 @deftypefnx Macro SCM SCM_BOOL_F
655 The Scheme true and false values.
658 @deftypefn Macro int SCM_NFALSEP (@var{x})
659 Convert the Scheme boolean value to a C boolean. Since every object in
660 Scheme except @code{#f} is true, this amounts to comparing @var{x} to
661 @code{#f}; hence the name.
662 @c Noel feels a chill here.
665 @deftypefn Macro SCM SCM_BOOL_NOT (@var{x})
666 Return the boolean inverse of @var{x}. If @var{x} is not a
667 Scheme boolean, the result is undefined.
671 @node Unique Values, , Booleans, Immediate Datatypes
672 @subsubsection Unique Values
674 The immediate values that are neither small integers, characters, nor
675 booleans are all unique values --- that is, datatypes with only one
678 @deftypefn Macro SCM SCM_EOL
679 The Scheme empty list object, or ``End Of List'' object, usually written
680 in Scheme as @code{'()}.
683 @deftypefn Macro SCM SCM_EOF_VAL
684 The Scheme end-of-file value. It has no standard written
685 representation, for obvious reasons.
688 @deftypefn Macro SCM SCM_UNSPECIFIED
689 The value returned by expressions which the Scheme standard says return
690 an ``unspecified'' value.
692 This is sort of a weirdly literal way to take things, but the standard
693 read-eval-print loop prints nothing when the expression returns this
694 value, so it's not a bad idea to return this when you can't think of
695 anything else helpful.
698 @deftypefn Macro SCM SCM_UNDEFINED
699 The ``undefined'' value. Its most important property is that is not
700 equal to any valid Scheme value. This is put to various internal uses
701 by C code interacting with Guile.
703 For example, when you write a C function that is callable from Scheme
704 and which takes optional arguments, the interpreter passes
705 @code{SCM_UNDEFINED} for any arguments you did not receive.
707 We also use this to mark unbound variables.
710 @deftypefn Macro int SCM_UNBNDP (SCM @var{x})
711 Return true if @var{x} is @code{SCM_UNDEFINED}. Apply this to a
712 symbol's value to see if it has a binding as a global variable.
716 @node Non-immediate Datatypes, Signalling Type Errors, Immediate Datatypes, How Guile does it
717 @subsection Non-immediate Datatypes
719 A non-immediate datatype is one which lives in the heap, either because
720 it cannot fit entirely within a @code{SCM} word, or because it denotes a
721 specific storage location (in the nomenclature of the Revised^4 Report
724 The @code{SCM_IMP} and @code{SCM_NIMP} macros will distinguish these
725 from immediates; see @ref{Immediates vs. Non-immediates}.
727 Given a cell, Guile distinguishes between pairs and other non-immediate
728 types by storing special @dfn{tag} values in a non-pair cell's car, that
729 cannot appear in normal pairs. A cell with a non-tag value in its car
730 is an ordinary pair. The type of a cell with a tag in its car depends
731 on the tag; the non-immediate type predicates test this value. If a tag
732 value appears elsewhere (in a vector, for example), the heap may become
737 * Non-immediate Type Predicates:: Special rules for using the type
738 predicates described here.
747 @node Non-immediate Type Predicates, Pairs, Non-immediate Datatypes, Non-immediate Datatypes
748 @subsubsection Non-immediate Type Predicates
750 As mentioned in @ref{Garbage Collection}, all non-immediate objects
751 start with a @dfn{cell}, or a pair of words. Furthermore, all type
752 information that distinguishes one kind of non-immediate from another is
753 stored in the cell. The type information in the @code{SCM} value
754 indicates only that the object is a non-immediate; all finer
755 distinctions require one to examine the cell itself, usually with the
756 appropriate type predicate macro.
758 The type predicates for non-immediate objects generally assume that
759 their argument is a non-immediate value. Thus, you must be sure that a
760 value is @code{SCM_NIMP} first before passing it to a non-immediate type
761 predicate. Thus, the idiom for testing whether a value is a cell or not
764 SCM_NIMP (@var{x}) && SCM_CONSP (@var{x})
768 @node Pairs, Vectors, Non-immediate Type Predicates, Non-immediate Datatypes
771 Pairs are the essential building block of list structure in Scheme. A
772 pair object has two fields, called the @dfn{car} and the @dfn{cdr}.
774 It is conventional for a pair's @sc{car} to contain an element of a
775 list, and the @sc{cdr} to point to the next pair in the list, or to
776 contain @code{SCM_EOL}, indicating the end of the list. Thus, a set of
777 pairs chained through their @sc{cdr}s constitutes a singly-linked list.
778 Scheme and libguile define many functions which operate on lists
779 constructed in this fashion, so although lists chained through the
780 @sc{car}s of pairs will work fine too, they may be less convenient to
781 manipulate, and receive less support from the community.
783 Guile implements pairs by mapping the @sc{car} and @sc{cdr} of a pair
784 directly into the two words of the cell.
787 @deftypefn Macro int SCM_CONSP (SCM @var{x})
788 Return non-zero iff @var{x} is a Scheme pair object.
789 The results are undefined if @var{x} is an immediate value.
792 @deftypefn Macro int SCM_NCONSP (SCM @var{x})
793 The complement of SCM_CONSP.
796 @deftypefn Macro void SCM_NEWCELL (SCM @var{into})
797 Allocate a new cell, and set @var{into} to point to it. This macro
798 expands to a statement, not an expression, and @var{into} must be an
801 This is the most primitive way to allocate a cell; it is quite fast.
803 The @sc{car} of the cell initially tags it as a ``free cell''. If the
804 caller intends to use it as an ordinary cons, she must store ordinary
805 SCM values in its @sc{car} and @sc{cdr}.
807 If the caller intends to use it as a header for some other type, she
808 must store an appropriate magic value in the cell's @sc{car}, to mark
809 it as a member of that type, and store whatever value in the @sc{cdr}
810 that type expects. You should generally not do this, unless you are
811 implementing a new datatype, and thoroughly understand the code in
812 @code{<libguile/tags.h>}.
815 @deftypefun SCM scm_cons (SCM @var{car}, SCM @var{cdr})
816 Allocate (``CONStruct'') a new pair, with @var{car} and @var{cdr} as its
821 The macros below perform no typechecking. The results are undefined if
822 @var{cell} is an immediate. However, since all non-immediate Guile
823 objects are constructed from cells, and these macros simply return the
824 first element of a cell, they actually can be useful on datatypes other
825 than pairs. (Of course, it is not very modular to use them outside of
826 the code which implements that datatype.)
828 @deftypefn Macro SCM SCM_CAR (SCM @var{cell})
829 Return the @sc{car}, or first field, of @var{cell}.
832 @deftypefn Macro SCM SCM_CDR (SCM @var{cell})
833 Return the @sc{cdr}, or second field, of @var{cell}.
836 @deftypefn Macro void SCM_SETCAR (SCM @var{cell}, SCM @var{x})
837 Set the @sc{car} of @var{cell} to @var{x}.
840 @deftypefn Macro void SCM_SETCDR (SCM @var{cell}, SCM @var{x})
841 Set the @sc{cdr} of @var{cell} to @var{x}.
844 @deftypefn Macro SCM SCM_CAAR (SCM @var{cell})
845 @deftypefnx Macro SCM SCM_CADR (SCM @var{cell})
846 @deftypefnx Macro SCM SCM_CDAR (SCM @var{cell}) @dots{}
847 @deftypefnx Macro SCM SCM_CDDDDR (SCM @var{cell})
848 Return the @sc{car} of the @sc{car} of @var{cell}, the @sc{car} of the
849 @sc{cdr} of @var{cell}, @i{et cetera}.
853 @node Vectors, Procedures, Pairs, Non-immediate Datatypes
854 @subsubsection Vectors, Strings, and Symbols
856 Vectors, strings, and symbols have some properties in common. They all
857 have a length, and they all have an array of elements. In the case of a
858 vector, the elements are @code{SCM} values; in the case of a string or
859 symbol, the elements are characters.
861 All these types store their length (along with some tagging bits) in the
862 @sc{car} of their header cell, and store a pointer to the elements in
863 their @sc{cdr}. Thus, the @code{SCM_CAR} and @code{SCM_CDR} macros
864 are (somewhat) meaningful when applied to these datatypes.
866 @deftypefn Macro int SCM_VECTORP (SCM @var{x})
867 Return non-zero iff @var{x} is a vector.
868 The results are undefined if @var{x} is an immediate value.
871 @deftypefn Macro int SCM_STRINGP (SCM @var{x})
872 Return non-zero iff @var{x} is a string.
873 The results are undefined if @var{x} is an immediate value.
876 @deftypefn Macro int SCM_SYMBOLP (SCM @var{x})
877 Return non-zero iff @var{x} is a symbol.
878 The results are undefined if @var{x} is an immediate value.
881 @deftypefn Macro int SCM_LENGTH (SCM @var{x})
882 Return the length of the object @var{x}.
883 The results are undefined if @var{x} is not a vector, string, or symbol.
886 @deftypefn Macro {SCM *} SCM_VELTS (SCM @var{x})
887 Return a pointer to the array of elements of the vector @var{x}.
888 The results are undefined if @var{x} is not a vector.
891 @deftypefn Macro {char *} SCM_CHARS (SCM @var{x})
892 Return a pointer to the characters of @var{x}.
893 The results are undefined if @var{x} is not a symbol or a string.
896 There are also a few magic values stuffed into memory before a symbol's
897 characters, but you don't want to know about those. What cruft!
900 @node Procedures, Closures, Vectors, Non-immediate Datatypes
901 @subsubsection Procedures
903 Guile provides two kinds of procedures: @dfn{closures}, which are the
904 result of evaluating a @code{lambda} expression, and @dfn{subrs}, which
905 are C functions packaged up as Scheme objects, to make them available to
908 (There are actually other sorts of procedures: compiled closures, and
909 continuations; see the source code for details about them.)
911 @deftypefun SCM scm_procedure_p (SCM @var{x})
912 Return @code{SCM_BOOL_T} iff @var{x} is a Scheme procedure object, of
913 any sort. Otherwise, return @code{SCM_BOOL_F}.
917 @node Closures, Subrs, Procedures, Non-immediate Datatypes
918 @subsubsection Closures
920 [FIXME: this needs to be further subbed, but texinfo has no subsubsub]
922 A closure is a procedure object, generated as the value of a
923 @code{lambda} expression in Scheme. The representation of a closure is
924 straightforward --- it contains a pointer to the code of the lambda
925 expression from which it was created, and a pointer to the environment
928 In Guile, each closure also has a property list, allowing the system to
929 store information about the closure. I'm not sure what this is used for
930 at the moment --- the debugger, maybe?
932 @deftypefn Macro int SCM_CLOSUREP (SCM @var{x})
933 Return non-zero iff @var{x} is a closure. The results are
934 undefined if @var{x} is an immediate value.
937 @deftypefn Macro SCM SCM_PROCPROPS (SCM @var{x})
938 Return the property list of the closure @var{x}. The results are
939 undefined if @var{x} is not a closure.
942 @deftypefn Macro void SCM_SETPROCPROPS (SCM @var{x}, SCM @var{p})
943 Set the property list of the closure @var{x} to @var{p}. The results
944 are undefined if @var{x} is not a closure.
947 @deftypefn Macro SCM SCM_CODE (SCM @var{x})
948 Return the code of the closure @var{x}. The results are undefined if
949 @var{x} is not a closure.
951 This function should probably only be used internally by the
952 interpreter, since the representation of the code is intimately
953 connected with the interpreter's implementation.
956 @deftypefn Macro SCM SCM_ENV (SCM @var{x})
957 Return the environment enclosed by @var{x}.
958 The results are undefined if @var{x} is not a closure.
960 This function should probably only be used internally by the
961 interpreter, since the representation of the environment is intimately
962 connected with the interpreter's implementation.
966 @node Subrs, Ports, Closures, Non-immediate Datatypes
969 [FIXME: this needs to be further subbed, but texinfo has no subsubsub]
971 A subr is a pointer to a C function, packaged up as a Scheme object to
972 make it callable by Scheme code. In addition to the function pointer,
973 the subr also contains a pointer to the name of the function, and
974 information about the number of arguments accepted by the C fuction, for
975 the sake of error checking.
977 There is no single type predicate macro that recognizes subrs, as
978 distinct from other kinds of procedures. The closest thing is
979 @code{scm_procedure_p}; see @ref{Procedures}.
981 @deftypefn Macro {char *} SCM_SNAME (@var{x})
982 Return the name of the subr @var{x}. The results are undefined if
983 @var{x} is not a subr.
986 @deftypefun SCM scm_make_gsubr (char *@var{name}, int @var{req}, int @var{opt}, int @var{rest}, SCM (*@var{function})())
987 Create a new subr object named @var{name}, based on the C function
988 @var{function}, make it visible to Scheme the value of as a global
989 variable named @var{name}, and return the subr object.
991 The subr object accepts @var{req} required arguments, @var{opt} optional
992 arguments, and a @var{rest} argument iff @var{rest} is non-zero. The C
993 function @var{function} should accept @code{@var{req} + @var{opt}}
994 arguments, or @code{@var{req} + @var{opt} + 1} arguments if @code{rest}
997 When a subr object is applied, it must be applied to at least @var{req}
998 arguments, or else Guile signals an error. @var{function} receives the
999 subr's first @var{req} arguments as its first @var{req} arguments. If
1000 there are fewer than @var{opt} arguments remaining, then @var{function}
1001 receives the value @code{SCM_UNDEFINED} for any missing optional
1002 arguments. If @var{rst} is non-zero, then any arguments after the first
1003 @code{@var{req} + @var{opt}} are packaged up as a list as passed as
1004 @var{function}'s last argument.
1006 Note that subrs can actually only accept a predefined set of
1007 combinations of required, optional, and rest arguments. For example, a
1008 subr can take one required argument, or one required and one optional
1009 argument, but a subr can't take one required and two optional arguments.
1010 It's bizarre, but that's the way the interpreter was written. If the
1011 arguments to @code{scm_make_gsubr} do not fit one of the predefined
1012 patterns, then @code{scm_make_gsubr} will return a compiled closure
1013 object instead of a subr object.
1017 @node Ports, , Subrs, Non-immediate Datatypes
1018 @subsubsection Ports
1020 Haven't written this yet, 'cos I don't understand ports yet.
1023 @node Signalling Type Errors, , Non-immediate Datatypes, How Guile does it
1024 @subsection Signalling Type Errors
1026 Every function visible at the Scheme level should aggressively check the
1027 types of its arguments, to avoid misinterpreting a value, and perhaps
1028 causing a segmentation fault. Guile provides some macros to make this
1031 @deftypefn Macro void SCM_ASSERT (int @var{test}, SCM @var{obj}, int @var{position}, char *@var{subr})
1032 If @var{test} is zero, signal an error, attributed to the subroutine
1033 named @var{subr}, operating on the value @var{obj}. The @var{position}
1034 value determines exactly what sort of error to signal.
1036 If @var{position} is a string, @code{SCM_ASSERT} raises a
1037 ``miscellaneous'' error whose message is that string.
1039 Otherwise, @var{position} should be one of the values defined below.
1042 @deftypefn Macro int SCM_ARG1
1043 @deftypefnx Macro int SCM_ARG2
1044 @deftypefnx Macro int SCM_ARG3
1045 @deftypefnx Macro int SCM_ARG4
1046 @deftypefnx Macro int SCM_ARG5
1047 Signal a ``wrong type argument'' error. When used as the @var{position}
1048 argument of @code{SCM_ASSERT}, @code{SCM_ARG@var{n}} claims that
1049 @var{obj} has the wrong type for the @var{n}'th argument of @var{subr}.
1051 The only way to complain about the type of an argument after the fifth
1052 is to use @code{SCM_ARGn}, defined below, which doesn't specify which
1053 argument is wrong. You could pass your own error message to
1054 @code{SCM_ASSERT} as the @var{position}, but then the error signalled is
1055 a ``miscellaneous'' error, not a ``wrong type argument'' error. This
1057 @comment Any function with more than two arguments is wrong --- Perlis
1058 @comment Despite Perlis, I agree. Why not have two Macros, one with
1059 @comment a string error message, and the other with an integer position
1060 @comment that only claims a type error in an argument?
1061 @comment --- Keith Wright
1064 @deftypefn Macro int SCM_ARGn
1065 As above, but does not specify which argument's type is incorrect.
1068 @deftypefn Macro int SCM_WNA
1069 Signal an error complaining that the function received the wrong number
1072 Interestingly, the message is attributed to the function named by
1073 @var{obj}, not @var{subr}, so @var{obj} must be a Scheme string object
1074 naming the function. Usually, Guile catches these errors before ever
1075 invoking the subr, so we don't run into these problems.
1078 @deftypefn Macro int SCM_OUTOFRANGE
1079 Signal an error complaining that @var{obj} is ``out of range'' for
1084 @node Defining New Types (Smobs), , How Guile does it, Top
1085 @section Defining New Types (Smobs)
1087 @dfn{Smobs} are Guile's mechanism for adding new non-immediate types to
1088 the system.@footnote{The term ``smob'' was coined by Aubrey Jaffer, who
1089 says it comes from ``small object'', referring to the fact that only the
1090 @sc{cdr} and part of the @sc{car} of a smob's cell are available for
1091 use.} To define a new smob type, the programmer provides Guile with
1092 some essential information about the type --- how to print it, how to
1093 garbage collect it, @i{et cetera} --- and Guile returns a fresh type tag for
1094 use in the @sc{car} of new cells. The programmer can then use
1095 @code{scm_make_gsubr} to publish a set of C functions to the Scheme
1096 world that create and operate on these objects.
1100 * Describing a New Type::
1101 * Creating Instances::
1103 * Garbage Collecting Smobs::
1104 * Garbage Collecting Simple Smobs::
1105 * A Complete Example::
1108 @node Describing a New Type, Creating Instances, Defining New Types (Smobs), Defining New Types (Smobs)
1109 @subsection Describing a New Type
1111 To define a new type, the programmer must fill in an @code{scm_smobfuns}
1112 structure with functions to manage instances of the type. Here is the
1113 definition of the structure:
1116 typedef struct scm_smobfuns
1118 SCM (*mark) (SCM @var{obj});
1119 scm_sizet (*free) (SCM @var{obj});
1120 int (*print) (SCM @var{obj},
1122 scm_print_state *@var{pstate});
1123 SCM (*equalp) (SCM @var{a}, SCM @var{b});
1129 Guile will apply this function to each instance of the new type it
1130 encounters during garbage collection. This function is responsible for
1131 telling the collector about any other non-immediate objects the object
1132 refers to. @xref{Garbage Collecting Smobs}, for more details.
1135 Guile will apply this function to each instance of the new type it could
1136 not find any live pointers to. The function should release all
1137 resources held by the object and return.
1138 @xref{Garbage Collecting Smobs}, for more details.
1141 Guile will apply this function to each instance of the new type to print
1142 the value, as for @code{display} or @code{write}. The function should
1143 write a printed representation of @var{exp} on @var{port}, in accordance
1144 with the parameters in @var{pstate}. (For more information on print
1145 states, see @ref{Ports}.)
1148 If Scheme code asks the @code{equal?} function to compare two instances
1149 of the same smob type, Guile calls this function. It should return
1150 @code{SCM_BOOL_T} if @var{a} and @var{b} should be considered
1151 @code{equal?}, or @code{SCM_BOOL_F} otherwise. If @code{equalp} is
1152 zero, @code{equal?} will assume that two instances of this type are
1153 never @code{equal?} unless they are @code{eq?}.
1157 Once you have built a @code{scm_smobfuns} structure, you can call the
1158 @code{scm_newsmob} function to add the type to the system.
1160 @deftypefun long scm_newsmob (scm_smobfuns *@var{funs})
1161 This function adds the type described by @var{funs} to the system. The
1162 return value is a tag, used in creating instances of the type.
1165 For example, here is how one might declare and register a new type
1166 representing eight-bit grayscale images:
1168 #include <libguile.h>
1170 scm_smobfuns image_funs = @{
1171 mark_image, free_image, print_image, 0
1179 image_tag = scm_newsmob (&image_funs);
1184 @node Creating Instances, Typechecking, Describing a New Type, Defining New Types (Smobs)
1185 @subsection Creating Instances
1187 Like other non-immediate types, smobs start with a cell whose @sc{car}
1188 contains typing information, and whose @code{cdr} is free for any use.
1189 To create an instance of a smob type, you must allocate a fresh cell, by
1190 calling @code{SCM_NEWCELL}, and store the tag returned by
1191 @code{scm_smobfuns} in its car.
1193 Guile provides the following functions for managing memory, which are
1194 often helpful when implementing smobs:
1196 @deftypefun {char *} scm_must_malloc (long @var{len}, char *@var{what})
1197 Allocate @var{len} bytes of memory, using @code{malloc}, and return a
1200 If there is not enough memory available, invoke the garbage collector,
1201 and try once more. If there is still not enough, signal an error,
1202 reporting that we could not allocate @var{what}.
1204 This function also helps maintain statistics about the size of the heap.
1207 @deftypefun {char *} scm_must_realloc (char *@var{addr}, long @var{olen}, long @var{len}, char *@var{what})
1208 Resize (and possibly relocate) the block of memory at @var{addr}, to
1209 have a size of @var{len} bytes, by calling @code{realloc}. Return a
1210 pointer to the new block.
1212 If there is not enough memory available, invoke the garbage collector,
1213 and try once more. If there is still not enough, signal an error,
1214 reporting that we could not allocate @var{what}.
1216 The value @var{olen} should be the old size of the block of memory at
1217 @var{addr}; it is only used for keeping statistics on the size of the
1221 @deftypefun void scm_must_free (char *@var{addr})
1222 Free the block of memory at @var{addr}, using @code{free}. If
1223 @var{addr} is zero, signal an error, complaining of an attempt to free
1224 something that is already free.
1226 This does no record-keeping; instead, the smob's @code{free} function
1227 must take care of that.
1229 This function isn't usually sufficiently different from the usual
1230 @code{free} function to be worth using.
1234 Continuing the above example, if the global variable @code{image_tag}
1235 contains a tag returned by @code{scm_newsmob}, here is how we could
1236 construct a smob whose @sc{cdr} contains a pointer to a freshly
1237 allocated @code{struct image}:
1244 /* The name of this image */
1247 /* A function to call when this image is
1248 modified, e.g., to update the screen,
1249 or SCM_BOOL_F if no action necessary */
1254 create_image (SCM name, int width, int height)
1256 struct image *image;
1259 image = (struct image *) scm_must_malloc (sizeof (*image), "image");
1260 image->width = width;
1261 image->height = height;
1262 image->pixels = scm_must_malloc (width * height, "image pixels");
1264 image->update_func = SCM_BOOL_F;
1266 SCM_NEWCELL (image_smob);
1267 SCM_SETCAR (image_smob, image_tag);
1268 SCM_SETCDR (image_smob, image);
1275 @node Typechecking, Garbage Collecting Smobs, Creating Instances, Defining New Types (Smobs)
1276 @subsection Typechecking
1278 Functions that operate on smobs should aggressively check the types of
1279 their arguments, to avoid misinterpreting some other datatype as a smob,
1280 and perhaps causing a segmentation fault. Fortunately, this is pretty
1281 simple to do. The function need only verify that its argument is a
1282 non-immediate, whose @sc{car} is the type tag returned by
1285 For example, here is a simple function that operates on an image smob,
1286 and checks the type of its argument. We also present an expanded
1287 version of the @code{init_image_type} function, to make clear_image
1288 available to the Scheme level.
1291 clear_image (SCM image_smob)
1294 struct image *image;
1296 SCM_ASSERT ((SCM_NIMP (image_smob)
1297 && SCM_CAR (image_smob) == image_tag),
1298 image_smob, SCM_ARG1, "clear-image");
1300 image = (struct image *) SCM_CDR (image_smob);
1301 area = image->width * image->height;
1302 memset (image->pixels, 0, area);
1304 /* Invoke the image's update function. */
1305 if (image->update_func != SCM_BOOL_F)
1306 scm_apply (image->update_func, SCM_EOL, SCM_EOL);
1308 return SCM_UNSPECIFIED;
1315 image_tag = scm_newsmob (&image_funs);
1316 scm_make_gsubr ("clear-image", 1, 0, 0, clear_image);
1320 Note that checking types is a little more complicated during garbage
1321 collection; see the description of @code{SCM_GCTYP16} in @ref{Garbage
1325 @node Garbage Collecting Smobs, Garbage Collecting Simple Smobs, Typechecking, Defining New Types (Smobs)
1326 @subsection Garbage Collecting Smobs
1328 Once a smob has been released to the tender mercies of the Scheme
1329 system, it must be prepared to survive garbage collection. Guile calls
1330 the @code{mark} and @code{free} functions of the @code{scm_smobfuns}
1331 structure to manage this.
1333 As described before (@pxref{Garbage Collection}), every object in the
1334 Scheme system has a @dfn{mark bit}, which the garbage collector uses to
1335 tell live objects from dead ones. When collection starts, every
1336 object's mark bit is clear. The collector traces pointers through the
1337 heap, starting from objects known to be live, and sets the mark bit on
1338 each object it encounters. When it can find no more unmarked objects,
1339 the collector walks all objects, live and dead, frees those whose mark
1340 bits are still clear, and clears the mark bit on the others.
1342 The two main portions of the collection are called the @dfn{mark phase},
1343 during which the collector marks live objects, and the @dfn{sweep
1344 phase}, during which the collector frees all unmarked objects.
1346 The mark bit of a smob lives in its @sc{car}, along with the smob's type
1347 tag. When the collector encounters a smob, it sets the smob's mark bit,
1348 and uses the smob's type tag to find the appropriate @code{mark}
1349 function for that smob: the one listed in that smob's
1350 @code{scm_smobfuns} structure. It then calls the @code{mark} function,
1351 passing it the smob as its only argument.
1353 The @code{mark} function's is responsible for marking any other Scheme
1354 objects the smob refers to. If it does not do so, the objects' mark
1355 bits will still be clear when the collector begins to sweep, and the
1356 collector will free them. If this occurs, it will probably break, or at
1357 least confuse, any code operating on the smob; the smob's @code{SCM}
1358 values will have become dangling references.
1360 To mark an arbitrary Scheme object, the @code{mark} function may call
1363 @deftypefun void scm_gc_mark (SCM @var{x})
1364 Mark the object @var{x}, and recurse on any objects @var{x} refers to.
1365 If @var{x}'s mark bit is already set, return immediately.
1368 Thus, here is how we might write the @code{mark} function for the image
1369 smob type discussed above:
1373 mark_image (SCM image_smob)
1375 /* Mark the image's name and update function. */
1376 struct image *image = (struct image *) SCM_CDR (image_smob);
1378 scm_gc_mark (image->name);
1379 scm_gc_mark (image->update_func);
1386 Note that, even though the image's @code{update_func} could be an
1387 arbitrarily complex structure (representing a procedure and any values
1388 enclosed in its environment), @code{scm_gc_mark} will recurse as
1389 necessary to mark all its components. Because @code{scm_gc_mark} sets
1390 an object's mark bit before it recurses, it is not confused by
1391 circular structures.
1393 As an optimization, the collector will mark whatever value is returned
1394 by the @code{mark} function; this helps limit depth of recursion during
1395 the mark phase. Thus, the code above could also be written as:
1399 mark_image (SCM image_smob)
1401 /* Mark the image's name and update function. */
1402 struct image *image = (struct image *) SCM_CDR (image_smob);
1404 scm_gc_mark (image->name);
1405 return image->update_func;
1411 Finally, when the collector encounters an unmarked smob during the sweep
1412 phase, it uses the smob's tag to find the appropriate @code{free}
1413 function for the smob. It then calls the function, passing it the smob
1414 as its only argument.
1416 The @code{free} function must release any resources used by the smob.
1417 However, it need not free objects managed by the collector; the
1418 collector will take care of them. The return type of the @code{free}
1419 function should be @code{scm_sizet}, an unsigned integral type; the
1420 @code{free} function should return the number of bytes released, to help
1421 the collector maintain statistics on the size of the heap.
1423 Here is how we might write the @code{free} function for the image smob
1427 free_image (SCM image_smob)
1429 struct image *image = (struct image *) SCM_CDR (image_smob);
1430 scm_sizet size = image->width * image->height + sizeof (*image);
1432 free (image->pixels);
1439 During the sweep phase, the garbage collector will clear the mark bits
1440 on all live objects. The code which implements a smob need not do this
1443 There is no way for smob code to be notified when collection is
1446 Note that, since a smob's mark bit lives in its @sc{car}, along with the
1447 smob's type tag, the technique for checking the type of a smob described
1448 in @ref{Typechecking} will not necessarily work during GC. If you need
1449 to find out whether a given object is a particular smob type during GC,
1450 use the following macro:
1452 @deftypefn Macro void SCM_GCTYP16 (SCM @var{x})
1453 Return the type bits of the smob @var{x}, with the mark bit clear.
1455 Use this macro instead of @code{SCM_CAR} to check the type of a smob
1456 during GC. Usually, only code called by the smob's @code{mark} function
1457 need worry about this.
1460 It is usually a good idea to minimize the amount of processing done
1461 during garbage collection; keep @code{mark} and @code{free} functions
1462 very simple. Since collections occur at unpredictable times, it is easy
1463 for any unusual activity to interfere with normal code.
1466 @node Garbage Collecting Simple Smobs, A Complete Example, Garbage Collecting Smobs, Defining New Types (Smobs)
1467 @subsection Garbage Collecting Simple Smobs
1469 It is often useful to define very simple smob types --- smobs which have
1470 no data to mark, other than the cell itself, or smobs whose @sc{cdr} is
1471 simply an ordinary Scheme object, to be marked recursively. Guile
1472 provides some functions to handle these common cases.
1474 If the smob refers to no other Scheme objects, then no action is
1475 necessary; the garbage collector has already marked the smob cell
1476 itself. In that case, you can use zero as your mark function.
1478 @deftypefun SCM scm_markcdr (SCM @var{x})
1479 Mark the references in the smob @var{x}, assuming that @var{x}'s
1480 @sc{cdr} contains an ordinary Scheme object, and @var{x} refers to no
1481 other objects. This function simply returns @var{x}'s @sc{cdr}.
1484 @deftypefun scm_sizet scm_free0 (SCM @var{x})
1485 Do nothing; return zero. This function is appropriate for smobs that
1486 use either zero or @code{scm_markcdr} as their marking functions, and
1487 refer to no heap storage, including memory managed by @code{malloc},
1488 other than the smob's header cell.
1492 @node A Complete Example, , Garbage Collecting Simple Smobs, Defining New Types (Smobs)
1493 @subsection A Complete Example
1495 Here is the complete text of the implementation of the image datatype,
1496 as presented in the sections above. We also provide a definition for
1497 the smob's @code{print} function.
1501 #include <libguile.h>
1509 /* The name of this image */
1512 /* A function to call when this image is
1513 modified, e.g., to update the screen,
1514 or SCM_BOOL_F if no action necessary */
1520 create_image (SCM name, int width, int height)
1522 struct image *image;
1525 image = (struct image *) scm_must_malloc (sizeof (*image), "image");
1526 image->width = width;
1527 image->height = height;
1528 image->pixels = scm_must_malloc (width * height, "image pixels");
1530 image->update_func = SCM_BOOL_F;
1532 SCM_NEWCELL (image_smob);
1533 SCM_SETCDR (image_smob, image);
1534 SCM_SETCAR (image_smob, image_tag);
1541 clear_image (SCM image_smob)
1544 struct image *image;
1546 SCM_ASSERT ((SCM_NIMP (image_smob)
1547 && SCM_CAR (image_smob) == image_tag),
1548 image_smob, SCM_ARG1, "clear-image");
1550 image = (struct image *) SCM_CDR (image_smob);
1551 area = image->width * image->height;
1552 memset (image->pixels, 0, area);
1554 /* Invoke the image's update function. */
1555 if (image->update_func != SCM_BOOL_F)
1556 scm_apply (image->update_func, SCM_EOL, SCM_EOL);
1558 return SCM_UNSPECIFIED;
1563 mark_image (SCM image_smob)
1565 struct image *image = (struct image *) SCM_CDR (image_smob);
1567 scm_gc_mark (image->name);
1568 return image->update_func;
1573 free_image (SCM image_smob)
1575 struct image *image = (struct image *) SCM_CDR (image_smob);
1576 scm_sizet size = image->width * image->height + sizeof (*image);
1578 free (image->pixels);
1586 print_image (SCM obj, SCM port, scm_print_state *pstate)
1588 struct image *image = (struct image *) SCM_CDR (image_smob);
1590 scm_gen_puts (scm_regular_string, "#<image ", port);
1591 scm_display (image->name, port);
1592 scm_gen_puts (scm_regular_string, ">", port);
1594 /* non-zero means success */
1598 scm_smobfuns image_funs = @{
1599 mark_image, free_image, print_image, 0
1606 image_tag = scm_newsmob (&image_funs);
1607 scm_make_gsubr ("clear-image", 1, 0, 0, clear_image);