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