*** empty log message ***
[bpt/guile.git] / doc / data-rep.texi
1 \input texinfo
2 @c -*-texinfo-*-
3 @c %**start of header
4 @setfilename data-rep.info
5 @settitle Data Representation in Guile
6 @c %**end of header
7
8 @include version.texi
9
10 @dircategory Scheme Programming
11 @direntry
12 * data-rep: (data-rep). Data Representation in Guile --- how to use
13 Guile objects in your C code.
14 @end direntry
15
16 @setchapternewpage off
17
18 @ifinfo
19 Data Representation in Guile
20
21 Copyright (C) 1998 Free Software Foundation
22
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.
26
27 @ignore
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).
32 @end ignore
33
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.
38
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.
43 @end ifinfo
44
45 @titlepage
46 @sp 10
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}
51 @author Jim Blandy
52 @author Free Software Foundation
53 @author @email{jimb@@red-bean.com}
54 @c The following two commands start the copyright page.
55 @page
56 @vskip 0pt plus 1filll
57 @vskip 0pt plus 1filll
58 Copyright @copyright{} 1998 Free Software Foundation
59
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.
63
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.
68
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.
73 @end titlepage
74
75 @c @smallbook
76 @c @finalout
77 @headings double
78
79
80 @node Top, Data Representation in Scheme, (dir), (dir)
81 @top Data Representation in Guile
82
83 @ifinfo
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.
88
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.
93
94 We assume you know both C and Scheme, but we do not assume you are
95 familiar with Guile's C interface.
96 @end ifinfo
97
98 @menu
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.
106 @end menu
107
108 @node Data Representation in Scheme, How Guile does it, Top, Top
109 @section Data Representation in Scheme
110
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.
116
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).
123
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.
128
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
134 does it}.
135
136
137 @menu
138 * A Simple Representation::
139 * Faster Integers::
140 * Cheaper Pairs::
141 * Guile Is Hairier::
142 @end menu
143
144 @node A Simple Representation, Faster Integers, Data Representation in Scheme, Data Representation in Scheme
145 @subsection A Simple Representation
146
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:
151
152 @example
153 enum type @{ integer, pair, string, vector, ... @};
154
155 typedef struct value *SCM;
156
157 struct value @{
158 enum type type;
159 union @{
160 int integer;
161 struct @{ SCM car, cdr; @} pair;
162 struct @{ int length; char *elts; @} string;
163 struct @{ int length; SCM *elts; @} vector;
164 ...
165 @} value;
166 @};
167 @end example
168 with the ellipses replaced with code for the remaining Scheme types.
169
170 This representation is sufficient to implement all of Scheme's
171 semantics. If @var{x} is an @code{SCM} value:
172 @itemize @bullet
173 @item
174 To test if @var{x} is an integer, we can write @code{@var{x}->type == integer}.
175 @item
176 To find its value, we can write @code{@var{x}->value.integer}.
177 @item
178 To test if @var{x} is a vector, we can write @code{@var{x}->type == vector}.
179 @item
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.
182 @item
183 If we know @var{x} is a pair, we can write
184 @code{@var{x}->value.pair.car} to extract its car.
185 @end itemize
186
187
188 @node Faster Integers, Cheaper Pairs, A Simple Representation, Data Representation in Scheme
189 @subsection Faster Integers
190
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.
199
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
205 be zero.
206
207 This gives us the room we need to provide an improved representation
208 for integers. We make the following rules:
209 @itemize @bullet
210 @item
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
213 before.
214 @item
215 Otherwise, the @code{SCM} value represents an integer, whose value
216 appears in its upper bits.
217 @end itemize
218
219 Here is C code implementing this convention:
220 @example
221 enum type @{ pair, string, vector, ... @};
222
223 typedef struct value *SCM;
224
225 struct value @{
226 enum type type;
227 union @{
228 struct @{ SCM car, cdr; @} pair;
229 struct @{ int length; char *elts; @} string;
230 struct @{ int length; SCM *elts; @} vector;
231 ...
232 @} value;
233 @};
234
235 #define POINTER_P(x) (((int) (x) & 3) == 0)
236 #define INTEGER_P(x) (! POINTER_P (x))
237
238 #define GET_INTEGER(x) ((int) (x) >> 2)
239 #define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1))
240 @end example
241
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.
247
248 Here's how we would answer the questions posed above (again, assume
249 @var{x} is an @code{SCM} value):
250 @itemize @bullet
251 @item
252 To test if @var{x} is an integer, we can write @code{INTEGER_P (@var{x})}.
253 @item
254 To find its value, we can write @code{GET_INTEGER (@var{x})}.
255 @item
256 To test if @var{x} is a vector, we can write:
257 @example
258 @code{POINTER_P (@var{x}) && @var{x}->type == vector}
259 @end example
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.
262 @item
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
265 before.
266 @item
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.
269 @end itemize
270
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:
274 @example
275 MAKE_INTEGER (GET_INTEGER (@var{x}) + GET_INTEGER (@var{y}))
276 @end example
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}?)
281
282
283 @node Cheaper Pairs, Guile Is Hairier, Faster Integers, Data Representation in Scheme
284 @subsection Cheaper Pairs
285
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?
292
293 Let us refine the convention we established earlier. Let us assert
294 that:
295 @itemize @bullet
296 @item
297 If the bottom two bits of an @code{SCM} value are @code{#b00}, then
298 it is a pointer, as before.
299 @item
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.
302 @item
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.
305 @end itemize
306
307 Here is the new C code:
308 @example
309 enum type @{ string, vector, ... @};
310
311 typedef struct value *SCM;
312
313 struct value @{
314 enum type type;
315 union @{
316 struct @{ int length; char *elts; @} string;
317 struct @{ int length; SCM *elts; @} vector;
318 ...
319 @} value;
320 @};
321
322 struct pair @{
323 SCM car, cdr;
324 @};
325
326 #define POINTER_P(x) (((int) (x) & 3) == 0)
327
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))
331
332 #define PAIR_P(x) (((int) (x) & 3) == 2)
333 #define GET_PAIR(x) ((struct pair *) ((int) (x) & ~3))
334 @end example
335
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.
340
341
342 Our list of examples is now as follows:
343 @itemize @bullet
344 @item
345 To test if @var{x} is an integer, we can write @code{INTEGER_P
346 (@var{x})}; this is as before.
347 @item
348 To find its value, we can write @code{GET_INTEGER (@var{x})}, as
349 before.
350 @item
351 To test if @var{x} is a vector, we can write:
352 @example
353 @code{POINTER_P (@var{x}) && @var{x}->type == vector}
354 @end example
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.
357 @item
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
360 before.
361 @item
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
364 car.
365 @end itemize
366
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.
372
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
378 unmodified pointer.
379
380
381 @node Guile Is Hairier, , Cheaper Pairs, Data Representation in Scheme
382 @subsection Guile Is Hairier
383
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.
391
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.
395
396
397 @node How Guile does it, Defining New Types (Smobs), Data Representation in Scheme, Top
398 @section How Guile does it
399
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.
405
406
407 @menu
408 * General Rules::
409 * Garbage Collection::
410 * Immediates vs. Non-immediates::
411 * Immediate Datatypes::
412 * Non-immediate Datatypes::
413 * Signalling Type Errors::
414 @end menu
415
416 @node General Rules, Garbage Collection, How Guile does it, How Guile does it
417 @subsection General Rules
418
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.
424
425 All identifiers declared by @code{<libguile.h>} begin with @code{scm_}
426 or @code{SCM_}.
427
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
430 @c to do so.
431
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
436 necessary.
437
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}).
445
446
447 @node Garbage Collection, Immediates vs. Non-immediates, General Rules, How Guile does it
448 @subsection Garbage Collection
449
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.
454
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}.
462
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.
467
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.
474
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
480 unnecessary.
481
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.
487
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
492 error.
493
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:
497 @itemize @bullet
498
499 @item
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.
505
506 @item
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.
512
513 @item
514 Guile maintains a sorted table of heap segments.
515
516 @end itemize
517
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.
523
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.
529
530
531 @node Immediates vs. Non-immediates, Immediate Datatypes, Garbage Collection, How Guile does it
532 @subsection Immediates vs. Non-immediates
533
534 Guile classifies Scheme objects into two kinds: those that fit entirely
535 within an @code{SCM}, and those that require heap storage.
536
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.
540
541 The remaining types are called, not suprisingly, @dfn{non-immediates}.
542 They include pairs, procedures, strings, vectors, and all other data
543 types in Guile.
544
545 @deftypefn Macro int SCM_IMP (SCM @var{x})
546 Return non-zero iff @var{x} is an immediate object.
547 @end deftypefn
548
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.
552
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
555 must write:
556 @example
557 SCM_NIMP (@var{x}) && SCM_CONSP (@var{x})
558 @end example
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
562 it.
563
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
568 from this weakness.
569 @end deftypefn
570
571
572 @node Immediate Datatypes, Non-immediate Datatypes, Immediates vs. Non-immediates, How Guile does it
573 @subsection Immediate Datatypes
574
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.
579
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.
586
587
588 @menu
589 * Integers::
590 * Characters::
591 * Booleans::
592 * Unique Values::
593 @end menu
594
595 @node Integers, Characters, Immediate Datatypes, Immediate Datatypes
596 @subsubsection Integers
597
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
601 @code{SCM}.
602
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.
608
609 @deftypefn Macro int SCM_INUMP (SCM @var{x})
610 Return non-zero iff @var{x} is a small integer value.
611 @end deftypefn
612
613 @deftypefn Macro int SCM_NINUMP (SCM @var{x})
614 The complement of SCM_INUMP.
615 @end deftypefn
616
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.
620 @end deftypefn
621
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.
625 @end deftypefn
626
627
628 @node Characters, Booleans, Integers, Immediate Datatypes
629 @subsubsection Characters
630
631 Here are functions for operating on characters.
632
633 @deftypefn Macro int SCM_ICHRP (SCM @var{x})
634 Return non-zero iff @var{x} is a character value.
635 @end deftypefn
636
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.
640 @end deftypefn
641
642 @deftypefn Macro SCM SCM_MAKICHR (SCM @var{c})
643 Given a C character @var{c}, return its representation as a Scheme
644 character value.
645 @end deftypefn
646
647
648 @node Booleans, Unique Values, Characters, Immediate Datatypes
649 @subsubsection Booleans
650
651 Here are functions and macros for operating on booleans.
652
653 @deftypefn Macro SCM SCM_BOOL_T
654 @deftypefnx Macro SCM SCM_BOOL_F
655 The Scheme true and false values.
656 @end deftypefn
657
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.
663 @end deftypefn
664
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.
668 @end deftypefn
669
670
671 @node Unique Values, , Booleans, Immediate Datatypes
672 @subsubsection Unique Values
673
674 The immediate values that are neither small integers, characters, nor
675 booleans are all unique values --- that is, datatypes with only one
676 instance.
677
678 @deftypefn Macro SCM SCM_EOL
679 The Scheme empty list object, or ``End Of List'' object, usually written
680 in Scheme as @code{'()}.
681 @end deftypefn
682
683 @deftypefn Macro SCM SCM_EOF_VAL
684 The Scheme end-of-file value. It has no standard written
685 representation, for obvious reasons.
686 @end deftypefn
687
688 @deftypefn Macro SCM SCM_UNSPECIFIED
689 The value returned by expressions which the Scheme standard says return
690 an ``unspecified'' value.
691
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.
696 @end deftypefn
697
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.
702
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.
706
707 We also use this to mark unbound variables.
708 @end deftypefn
709
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.
713 @end deftypefn
714
715
716 @node Non-immediate Datatypes, Signalling Type Errors, Immediate Datatypes, How Guile does it
717 @subsection Non-immediate Datatypes
718
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
722 on Scheme).
723
724 The @code{SCM_IMP} and @code{SCM_NIMP} macros will distinguish these
725 from immediates; see @ref{Immediates vs. Non-immediates}.
726
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
733 corrupted.
734
735
736 @menu
737 * Non-immediate Type Predicates:: Special rules for using the type
738 predicates described here.
739 * Pairs::
740 * Vectors::
741 * Procedures::
742 * Closures::
743 * Subrs::
744 * Ports::
745 @end menu
746
747 @node Non-immediate Type Predicates, Pairs, Non-immediate Datatypes, Non-immediate Datatypes
748 @subsubsection Non-immediate Type Predicates
749
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.
757
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
762 is:
763 @example
764 SCM_NIMP (@var{x}) && SCM_CONSP (@var{x})
765 @end example
766
767
768 @node Pairs, Vectors, Non-immediate Type Predicates, Non-immediate Datatypes
769 @subsubsection Pairs
770
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}.
773
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.
782
783 Guile implements pairs by mapping the @sc{car} and @sc{cdr} of a pair
784 directly into the two words of the cell.
785
786
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.
790 @end deftypefn
791
792 @deftypefn Macro int SCM_NCONSP (SCM @var{x})
793 The complement of SCM_CONSP.
794 @end deftypefn
795
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
799 lvalue of type SCM.
800
801 This is the most primitive way to allocate a cell; it is quite fast.
802
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}.
806
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>}.
813 @end deftypefn
814
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
817 contents.
818 @end deftypefun
819
820
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.)
827
828 @deftypefn Macro SCM SCM_CAR (SCM @var{cell})
829 Return the @sc{car}, or first field, of @var{cell}.
830 @end deftypefn
831
832 @deftypefn Macro SCM SCM_CDR (SCM @var{cell})
833 Return the @sc{cdr}, or second field, of @var{cell}.
834 @end deftypefn
835
836 @deftypefn Macro void SCM_SETCAR (SCM @var{cell}, SCM @var{x})
837 Set the @sc{car} of @var{cell} to @var{x}.
838 @end deftypefn
839
840 @deftypefn Macro void SCM_SETCDR (SCM @var{cell}, SCM @var{x})
841 Set the @sc{cdr} of @var{cell} to @var{x}.
842 @end deftypefn
843
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}.
850 @end deftypefn
851
852
853 @node Vectors, Procedures, Pairs, Non-immediate Datatypes
854 @subsubsection Vectors, Strings, and Symbols
855
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.
860
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.
865
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.
869 @end deftypefn
870
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.
874 @end deftypefn
875
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.
879 @end deftypefn
880
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.
884 @end deftypefn
885
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.
889 @end deftypefn
890
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.
894 @end deftypefn
895
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!
898
899
900 @node Procedures, Closures, Vectors, Non-immediate Datatypes
901 @subsubsection Procedures
902
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
906 Scheme programmers.
907
908 (There are actually other sorts of procedures: compiled closures, and
909 continuations; see the source code for details about them.)
910
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}.
914 @end deftypefun
915
916
917 @node Closures, Subrs, Procedures, Non-immediate Datatypes
918 @subsubsection Closures
919
920 [FIXME: this needs to be further subbed, but texinfo has no subsubsub]
921
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
926 it closes over.
927
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?
931
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.
935 @end deftypefn
936
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.
940 @end deftypefn
941
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.
945 @end deftypefn
946
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.
950
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.
954 @end deftypefn
955
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.
959
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.
963 @end deftypefn
964
965
966 @node Subrs, Ports, Closures, Non-immediate Datatypes
967 @subsubsection Subrs
968
969 [FIXME: this needs to be further subbed, but texinfo has no subsubsub]
970
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.
976
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}.
980
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.
984 @end deftypefn
985
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.
990
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}
995 is non-zero.
996
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.
1005
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.
1014 @end deftypefun
1015
1016
1017 @node Ports, , Subrs, Non-immediate Datatypes
1018 @subsubsection Ports
1019
1020 Haven't written this yet, 'cos I don't understand ports yet.
1021
1022
1023 @node Signalling Type Errors, , Non-immediate Datatypes, How Guile does it
1024 @subsection Signalling Type Errors
1025
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
1029 easier.
1030
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.
1035
1036 If @var{position} is a string, @code{SCM_ASSERT} raises a
1037 ``miscellaneous'' error whose message is that string.
1038
1039 Otherwise, @var{position} should be one of the values defined below.
1040 @end deftypefn
1041
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}.
1050
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
1056 seems kludgy to me.
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
1062 @end deftypefn
1063
1064 @deftypefn Macro int SCM_ARGn
1065 As above, but does not specify which argument's type is incorrect.
1066 @end deftypefn
1067
1068 @deftypefn Macro int SCM_WNA
1069 Signal an error complaining that the function received the wrong number
1070 of arguments.
1071
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.
1076 @end deftypefn
1077
1078 @deftypefn Macro int SCM_OUTOFRANGE
1079 Signal an error complaining that @var{obj} is ``out of range'' for
1080 @var{subr}.
1081 @end deftypefn
1082
1083
1084 @node Defining New Types (Smobs), , How Guile does it, Top
1085 @section Defining New Types (Smobs)
1086
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.
1097
1098
1099 @menu
1100 * Describing a New Type::
1101 * Creating Instances::
1102 * Typechecking::
1103 * Garbage Collecting Smobs::
1104 * Garbage Collecting Simple Smobs::
1105 * A Complete Example::
1106 @end menu
1107
1108 @node Describing a New Type, Creating Instances, Defining New Types (Smobs), Defining New Types (Smobs)
1109 @subsection Describing a New Type
1110
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:
1114
1115 @example
1116 typedef struct scm_smobfuns
1117 @{
1118 SCM (*mark) (SCM @var{obj});
1119 scm_sizet (*free) (SCM @var{obj});
1120 int (*print) (SCM @var{obj},
1121 SCM @var{port},
1122 scm_print_state *@var{pstate});
1123 SCM (*equalp) (SCM @var{a}, SCM @var{b});
1124 @} scm_smobfuns;
1125 @end example
1126
1127 @table @code
1128 @item mark
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.
1133
1134 @item free
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.
1139
1140 @item print
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}.)
1146
1147 @item equalp
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?}.
1154
1155 @end table
1156
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.
1159
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.
1163 @end deftypefun
1164
1165 For example, here is how one might declare and register a new type
1166 representing eight-bit grayscale images:
1167 @example
1168 #include <libguile.h>
1169
1170 scm_smobfuns image_funs = @{
1171 mark_image, free_image, print_image, 0
1172 @};
1173
1174 long image_tag;
1175
1176 void
1177 init_image_type ()
1178 @{
1179 image_tag = scm_newsmob (&image_funs);
1180 @}
1181 @end example
1182
1183
1184 @node Creating Instances, Typechecking, Describing a New Type, Defining New Types (Smobs)
1185 @subsection Creating Instances
1186
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.
1192
1193 Guile provides the following functions for managing memory, which are
1194 often helpful when implementing smobs:
1195
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
1198 pointer to them.
1199
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}.
1203
1204 This function also helps maintain statistics about the size of the heap.
1205 @end deftypefun
1206
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.
1211
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}.
1215
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
1218 heap.
1219 @end deftypefun
1220
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.
1225
1226 This does no record-keeping; instead, the smob's @code{free} function
1227 must take care of that.
1228
1229 This function isn't usually sufficiently different from the usual
1230 @code{free} function to be worth using.
1231 @end deftypefun
1232
1233
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}:
1238
1239 @example
1240 struct image @{
1241 int width, height;
1242 char *pixels;
1243
1244 /* The name of this image */
1245 SCM name;
1246
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 */
1250 SCM update_func;
1251 @};
1252
1253 SCM
1254 create_image (SCM name, int width, int height)
1255 @{
1256 struct image *image;
1257 SCM image_smob;
1258
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");
1263 image->name = name;
1264 image->update_func = SCM_BOOL_F;
1265
1266 SCM_NEWCELL (image_smob);
1267 SCM_SETCAR (image_smob, image_tag);
1268 SCM_SETCDR (image_smob, image);
1269
1270 return image_smob;
1271 @}
1272 @end example
1273
1274
1275 @node Typechecking, Garbage Collecting Smobs, Creating Instances, Defining New Types (Smobs)
1276 @subsection Typechecking
1277
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
1283 @code{scm_newsmob}.
1284
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.
1289 @example
1290 SCM
1291 clear_image (SCM image_smob)
1292 @{
1293 int area;
1294 struct image *image;
1295
1296 SCM_ASSERT ((SCM_NIMP (image_smob)
1297 && SCM_CAR (image_smob) == image_tag),
1298 image_smob, SCM_ARG1, "clear-image");
1299
1300 image = (struct image *) SCM_CDR (image_smob);
1301 area = image->width * image->height;
1302 memset (image->pixels, 0, area);
1303
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);
1307
1308 return SCM_UNSPECIFIED;
1309 @}
1310
1311
1312 void
1313 init_image_type ()
1314 @{
1315 image_tag = scm_newsmob (&image_funs);
1316 scm_make_gsubr ("clear-image", 1, 0, 0, clear_image);
1317 @}
1318 @end example
1319
1320 Note that checking types is a little more complicated during garbage
1321 collection; see the description of @code{SCM_GCTYP16} in @ref{Garbage
1322 Collecting Smobs}.
1323
1324
1325 @node Garbage Collecting Smobs, Garbage Collecting Simple Smobs, Typechecking, Defining New Types (Smobs)
1326 @subsection Garbage Collecting Smobs
1327
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.
1332
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.
1341
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.
1345
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.
1352
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.
1359
1360 To mark an arbitrary Scheme object, the @code{mark} function may call
1361 this function:
1362
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.
1366 @end deftypefun
1367
1368 Thus, here is how we might write the @code{mark} function for the image
1369 smob type discussed above:
1370 @example
1371 @group
1372 SCM
1373 mark_image (SCM image_smob)
1374 @{
1375 /* Mark the image's name and update function. */
1376 struct image *image = (struct image *) SCM_CDR (image_smob);
1377
1378 scm_gc_mark (image->name);
1379 scm_gc_mark (image->update_func);
1380
1381 return SCM_BOOL_F;
1382 @}
1383 @end group
1384 @end example
1385
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.
1392
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:
1396 @example
1397 @group
1398 SCM
1399 mark_image (SCM image_smob)
1400 @{
1401 /* Mark the image's name and update function. */
1402 struct image *image = (struct image *) SCM_CDR (image_smob);
1403
1404 scm_gc_mark (image->name);
1405 return image->update_func;
1406 @}
1407 @end group
1408 @end example
1409
1410
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.
1415
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.
1422
1423 Here is how we might write the @code{free} function for the image smob
1424 type:
1425 @example
1426 scm_sizet
1427 free_image (SCM image_smob)
1428 @{
1429 struct image *image = (struct image *) SCM_CDR (image_smob);
1430 scm_sizet size = image->width * image->height + sizeof (*image);
1431
1432 free (image->pixels);
1433 free (image);
1434
1435 return size;
1436 @}
1437 @end example
1438
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
1441 itself.
1442
1443 There is no way for smob code to be notified when collection is
1444 complete.
1445
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:
1451
1452 @deftypefn Macro void SCM_GCTYP16 (SCM @var{x})
1453 Return the type bits of the smob @var{x}, with the mark bit clear.
1454
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.
1458 @end deftypefn
1459
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.
1464
1465
1466 @node Garbage Collecting Simple Smobs, A Complete Example, Garbage Collecting Smobs, Defining New Types (Smobs)
1467 @subsection Garbage Collecting Simple Smobs
1468
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.
1473
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.
1477
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}.
1482 @end deftypefun
1483
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.
1489 @end deftypefun
1490
1491
1492 @node A Complete Example, , Garbage Collecting Simple Smobs, Defining New Types (Smobs)
1493 @subsection A Complete Example
1494
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.
1498
1499 @example
1500 #include <stdlib.h>
1501 #include <libguile.h>
1502
1503 long image_tag;
1504
1505 struct image @{
1506 int width, height;
1507 char *pixels;
1508
1509 /* The name of this image */
1510 SCM name;
1511
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 */
1515 SCM update_func;
1516 @};
1517
1518
1519 SCM
1520 create_image (SCM name, int width, int height)
1521 @{
1522 struct image *image;
1523 SCM image_smob;
1524
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");
1529 image->name = name;
1530 image->update_func = SCM_BOOL_F;
1531
1532 SCM_NEWCELL (image_smob);
1533 SCM_SETCDR (image_smob, image);
1534 SCM_SETCAR (image_smob, image_tag);
1535
1536 return image_smob;
1537 @}
1538
1539
1540 SCM
1541 clear_image (SCM image_smob)
1542 @{
1543 int area;
1544 struct image *image;
1545
1546 SCM_ASSERT ((SCM_NIMP (image_smob)
1547 && SCM_CAR (image_smob) == image_tag),
1548 image_smob, SCM_ARG1, "clear-image");
1549
1550 image = (struct image *) SCM_CDR (image_smob);
1551 area = image->width * image->height;
1552 memset (image->pixels, 0, area);
1553
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);
1557
1558 return SCM_UNSPECIFIED;
1559 @}
1560
1561
1562 SCM
1563 mark_image (SCM image_smob)
1564 @{
1565 struct image *image = (struct image *) SCM_CDR (image_smob);
1566
1567 scm_gc_mark (image->name);
1568 return image->update_func;
1569 @}
1570
1571
1572 scm_sizet
1573 free_image (SCM image_smob)
1574 @{
1575 struct image *image = (struct image *) SCM_CDR (image_smob);
1576 scm_sizet size = image->width * image->height + sizeof (*image);
1577
1578 free (image->pixels);
1579 free (image);
1580
1581 return size;
1582 @}
1583
1584
1585 int
1586 print_image (SCM obj, SCM port, scm_print_state *pstate)
1587 @{
1588 struct image *image = (struct image *) SCM_CDR (image_smob);
1589
1590 scm_gen_puts (scm_regular_string, "#<image ", port);
1591 scm_display (image->name, port);
1592 scm_gen_puts (scm_regular_string, ">", port);
1593
1594 /* non-zero means success */
1595 return 1;
1596 @}
1597
1598 scm_smobfuns image_funs = @{
1599 mark_image, free_image, print_image, 0
1600 @};
1601
1602
1603 void
1604 init_image_type ()
1605 @{
1606 image_tag = scm_newsmob (&image_funs);
1607 scm_make_gsubr ("clear-image", 1, 0, 0, clear_image);
1608 @}
1609 @end example
1610
1611 @bye