Reinstate 2-word displacement for structs.
[bpt/guile.git] / libguile / struct.c
1 /* Copyright (C) 1996,1997,1998,1999,2000,2001, 2003, 2004, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public License
5 * as published by the Free Software Foundation; either version 3 of
6 * the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 * 02110-1301 USA
17 */
18
19 \f
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include <alloca.h>
25 #include <assert.h>
26
27 #include "libguile/_scm.h"
28 #include "libguile/async.h"
29 #include "libguile/chars.h"
30 #include "libguile/eval.h"
31 #include "libguile/alist.h"
32 #include "libguile/weaks.h"
33 #include "libguile/hashtab.h"
34 #include "libguile/ports.h"
35 #include "libguile/strings.h"
36 #include "libguile/srfi-13.h"
37
38 #include "libguile/validate.h"
39 #include "libguile/struct.h"
40
41 #include "libguile/eq.h"
42
43 #ifdef HAVE_STRING_H
44 #include <string.h>
45 #endif
46
47 #include "libguile/bdw-gc.h"
48
49 \f
50
51 /* A needlessly obscure test. */
52 #define SCM_LAYOUT_TAILP(X) (((X) & 32) == 0) /* R, W or O */
53
54 static SCM required_vtable_fields = SCM_BOOL_F;
55 static SCM required_applicable_fields = SCM_BOOL_F;
56 static SCM required_applicable_with_setter_fields = SCM_BOOL_F;
57 SCM scm_struct_table = SCM_BOOL_F;
58 SCM scm_applicable_struct_vtable_vtable;
59 SCM scm_applicable_struct_with_setter_vtable_vtable;
60 SCM scm_standard_vtable_vtable;
61
62
63 \f
64 SCM_DEFINE (scm_make_struct_layout, "make-struct-layout", 1, 0, 0,
65 (SCM fields),
66 "Return a new structure layout object.\n\n"
67 "@var{fields} must be a string made up of pairs of characters\n"
68 "strung together. The first character of each pair describes a field\n"
69 "type, the second a field protection. Allowed types are 'p' for\n"
70 "GC-protected Scheme data, 'u' for unprotected binary data, and 's' for\n"
71 "a field that points to the structure itself. Allowed protections\n"
72 "are 'w' for mutable fields, 'h' for hidden fields, 'r' for read-only\n"
73 "fields, and 'o' for opaque fields.\n\n"
74 "Hidden fields are writable, but they will not consume an initializer arg\n"
75 "passed to @code{make-struct}. They are useful to add slots to a struct\n"
76 "in a way that preserves backward-compatibility with existing calls to\n"
77 "@code{make-struct}, especially for derived vtables.\n\n"
78 "The last field protection specification may be capitalized to indicate\n"
79 "that the field is a tail-array.")
80 #define FUNC_NAME s_scm_make_struct_layout
81 {
82 SCM new_sym;
83 scm_t_wchar c;
84
85 SCM_VALIDATE_STRING (1, fields);
86
87 { /* scope */
88 size_t len;
89 int x;
90
91 len = scm_i_string_length (fields);
92 if (len % 2 == 1)
93 SCM_MISC_ERROR ("odd length field specification: ~S",
94 scm_list_1 (fields));
95
96 for (x = 0; x < len; x += 2)
97 {
98 switch (c = scm_i_string_ref (fields, x))
99 {
100 case 'u':
101 case 'p':
102 #if 0
103 case 'i':
104 case 'd':
105 #endif
106 case 's':
107 break;
108 default:
109 SCM_MISC_ERROR ("unrecognized field type: ~S",
110 scm_list_1 (SCM_MAKE_CHAR (c)));
111 }
112
113 switch (c = scm_i_string_ref (fields, x + 1))
114 {
115 case 'w':
116 case 'h':
117 if (scm_i_string_ref (fields, x) == 's')
118 SCM_MISC_ERROR ("self fields not writable", SCM_EOL);
119 case 'r':
120 case 'o':
121 break;
122 case 'R':
123 case 'W':
124 case 'O':
125 if (scm_i_string_ref (fields, x) == 's')
126 SCM_MISC_ERROR ("self fields not allowed in tail array",
127 SCM_EOL);
128 if (x != len - 2)
129 SCM_MISC_ERROR ("tail array field must be last field in layout",
130 SCM_EOL);
131 break;
132 default:
133 SCM_MISC_ERROR ("unrecognized ref specification: ~S",
134 scm_list_1 (SCM_MAKE_CHAR (c)));
135 }
136 #if 0
137 if (scm_i_string_ref (fields, x, 'd'))
138 {
139 if (!scm_i_string_ref (fields, x+2, '-'))
140 SCM_MISC_ERROR ("missing dash field at position ~A",
141 scm_list_1 (scm_from_int (x / 2)));
142 x += 2;
143 goto recheck_ref;
144 }
145 #endif
146 }
147 new_sym = scm_string_to_symbol (fields);
148 }
149 scm_remember_upto_here_1 (fields);
150 return new_sym;
151 }
152 #undef FUNC_NAME
153
154 \f
155 /* Check whether VTABLE instances have a simple layout (i.e., either only "pr"
156 or only "pw" fields) and update its flags accordingly. */
157 static void
158 set_vtable_layout_flags (SCM vtable)
159 {
160 size_t len, field;
161 SCM layout;
162 const char *c_layout;
163 scm_t_bits flags = SCM_VTABLE_FLAG_SIMPLE;
164
165 layout = SCM_VTABLE_LAYOUT (vtable);
166 c_layout = scm_i_symbol_chars (layout);
167 len = scm_i_symbol_length (layout);
168
169 assert (len % 2 == 0);
170
171 /* Update FLAGS according to LAYOUT. */
172 for (field = 0;
173 field < len && flags & SCM_VTABLE_FLAG_SIMPLE;
174 field += 2)
175 {
176 if (c_layout[field] != 'p')
177 flags = 0;
178 else
179 switch (c_layout[field + 1])
180 {
181 case 'w':
182 case 'W':
183 if (!(flags & SCM_VTABLE_FLAG_SIMPLE_RW) && field > 0)
184 /* There's a mixture of `w' and `r' flags. */
185 flags = 0;
186 else
187 flags |= SCM_VTABLE_FLAG_SIMPLE_RW;
188 break;
189
190 case 'r':
191 case 'R':
192 if (flags & SCM_VTABLE_FLAG_SIMPLE_RW)
193 /* There's a mixture of `w' and `r' flags. */
194 flags = 0;
195 break;
196
197 default:
198 flags = 0;
199 }
200 }
201
202 if (flags & SCM_VTABLE_FLAG_SIMPLE)
203 {
204 /* VTABLE is simple so update its flags and record the size of its
205 instances. */
206 SCM_SET_VTABLE_FLAGS (vtable, flags);
207 SCM_STRUCT_DATA_SET (vtable, scm_vtable_index_size, len / 2);
208 }
209 }
210
211 /* Have OBJ, a newly created vtable, inherit flags from VTABLE. VTABLE is a
212 vtable-vtable and OBJ is an instance of VTABLE. */
213 void
214 scm_i_struct_inherit_vtable_magic (SCM vtable, SCM obj)
215 #define FUNC_NAME "%inherit-vtable-magic"
216 {
217 /* Verily, what is the deal here, you ask? Basically, we need to know a couple
218 of properties of structures at runtime. For example, "is this structure a
219 vtable of vtables (a metaclass)?"; also, "is this structure applicable?".
220 Both of these questions also imply a certain layout of the structure. So
221 instead of checking the layout at runtime, what we do is pre-verify the
222 layout -- so that at runtime we can just check the applicable flag and
223 dispatch directly to the Scheme procedure in slot 0. */
224 SCM olayout;
225
226 /* Verify that OBJ is a valid vtable. */
227 if (scm_is_false (scm_symbol_p (SCM_VTABLE_LAYOUT (obj))))
228 scm_misc_error (FUNC_NAME, "invalid layout for new vtable",
229 scm_list_1 (SCM_VTABLE_LAYOUT (obj)));
230
231 set_vtable_layout_flags (obj);
232
233 /* If OBJ's vtable is compatible with the required vtable (class) layout, it
234 is a metaclass. */
235 olayout = scm_symbol_to_string (SCM_VTABLE_LAYOUT (obj));
236 if (scm_is_true (scm_leq_p (scm_string_length (required_vtable_fields),
237 scm_string_length (olayout)))
238 && scm_is_true (scm_string_eq (olayout, required_vtable_fields,
239 scm_from_size_t (0),
240 scm_string_length (required_vtable_fields),
241 scm_from_size_t (0),
242 scm_string_length (required_vtable_fields))))
243 SCM_SET_VTABLE_FLAGS (obj, SCM_VTABLE_FLAG_VTABLE);
244
245 /* Finally, if OBJ is an applicable class, verify that its vtable is
246 compatible with the required applicable layout. */
247 if (SCM_VTABLE_FLAG_IS_SET (vtable, SCM_VTABLE_FLAG_SETTER_VTABLE))
248 {
249 if (scm_is_false (scm_string_eq (olayout, required_applicable_with_setter_fields,
250 scm_from_size_t (0),
251 scm_from_size_t (4),
252 scm_from_size_t (0),
253 scm_from_size_t (4))))
254 scm_misc_error (FUNC_NAME, "invalid applicable-with-setter struct layout",
255 scm_list_1 (olayout));
256 SCM_SET_VTABLE_FLAGS (obj, SCM_VTABLE_FLAG_APPLICABLE | SCM_VTABLE_FLAG_SETTER);
257 }
258 else if (SCM_VTABLE_FLAG_IS_SET (vtable, SCM_VTABLE_FLAG_APPLICABLE_VTABLE))
259 {
260 if (scm_is_false (scm_string_eq (olayout, required_applicable_fields,
261 scm_from_size_t (0),
262 scm_from_size_t (2),
263 scm_from_size_t (0),
264 scm_from_size_t (2))))
265 scm_misc_error (FUNC_NAME, "invalid applicable struct layout",
266 scm_list_1 (olayout));
267 SCM_SET_VTABLE_FLAGS (obj, SCM_VTABLE_FLAG_APPLICABLE);
268 }
269 }
270 #undef FUNC_NAME
271
272
273 static void
274 scm_struct_init (SCM handle, SCM layout, size_t n_tail,
275 size_t n_inits, scm_t_bits *inits)
276 {
277 SCM vtable;
278 scm_t_bits *mem;
279
280 vtable = SCM_STRUCT_VTABLE (handle);
281 mem = SCM_STRUCT_DATA (handle);
282
283 if (SCM_UNPACK (vtable) != 0
284 && SCM_VTABLE_FLAG_IS_SET (vtable, SCM_VTABLE_FLAG_SIMPLE)
285 && n_tail == 0
286 && n_inits == SCM_STRUCT_DATA_REF (vtable, scm_vtable_index_size))
287 /* The fast path: HANDLE has N_INITS "p" fields. */
288 memcpy (mem, inits, n_inits * sizeof (SCM));
289 else
290 {
291 scm_t_wchar prot = 0;
292 int n_fields = scm_i_symbol_length (layout) / 2;
293 int tailp = 0;
294 int i;
295 size_t inits_idx = 0;
296
297 i = -2;
298 while (n_fields)
299 {
300 if (!tailp)
301 {
302 i += 2;
303 prot = scm_i_symbol_ref (layout, i+1);
304 if (SCM_LAYOUT_TAILP (prot))
305 {
306 tailp = 1;
307 prot = prot == 'R' ? 'r' : prot == 'W' ? 'w' : 'o';
308 *mem++ = (scm_t_bits)n_tail;
309 n_fields += n_tail - 1;
310 if (n_fields == 0)
311 break;
312 }
313 }
314 switch (scm_i_symbol_ref (layout, i))
315 {
316 case 'u':
317 if ((prot != 'r' && prot != 'w') || inits_idx == n_inits)
318 *mem = 0;
319 else
320 {
321 *mem = scm_to_ulong (SCM_PACK (inits[inits_idx]));
322 inits_idx++;
323 }
324 break;
325
326 case 'p':
327 if ((prot != 'r' && prot != 'w') || inits_idx == n_inits)
328 *mem = SCM_UNPACK (SCM_BOOL_F);
329 else
330 {
331 *mem = inits[inits_idx];
332 inits_idx++;
333 }
334
335 break;
336
337 case 's':
338 *mem = SCM_UNPACK (handle);
339 break;
340 }
341
342 n_fields--;
343 mem++;
344 }
345 }
346 }
347
348
349 SCM_DEFINE (scm_struct_p, "struct?", 1, 0, 0,
350 (SCM x),
351 "Return @code{#t} iff @var{x} is a structure object, else\n"
352 "@code{#f}.")
353 #define FUNC_NAME s_scm_struct_p
354 {
355 return scm_from_bool(SCM_STRUCTP (x));
356 }
357 #undef FUNC_NAME
358
359 SCM_DEFINE (scm_struct_vtable_p, "struct-vtable?", 1, 0, 0,
360 (SCM x),
361 "Return @code{#t} iff @var{x} is a vtable structure.")
362 #define FUNC_NAME s_scm_struct_vtable_p
363 {
364 return scm_from_bool
365 (SCM_STRUCTP (x)
366 && SCM_STRUCT_VTABLE_FLAG_IS_SET (x, SCM_VTABLE_FLAG_VTABLE));
367 }
368 #undef FUNC_NAME
369
370
371 /* Finalization: invoke the finalizer of the struct pointed to by PTR. */
372 static void
373 struct_finalizer_trampoline (GC_PTR ptr, GC_PTR unused_data)
374 {
375 SCM obj = PTR2SCM (ptr);
376 scm_t_struct_finalize finalize = SCM_STRUCT_FINALIZER (obj);
377
378 if (finalize)
379 finalize (obj);
380 }
381
382 /* All struct data must be allocated at an address whose bottom three
383 bits are zero. This is because the tag for a struct lives in the
384 bottom three bits of the struct's car, and the upper bits point to
385 the data of its vtable, which is a struct itself. Thus, if the
386 address of that data doesn't end in three zeros, tagging it will
387 destroy the pointer.
388
389 I suppose we should make it clear here that, the data must be 8-byte aligned,
390 *within* the struct, and the struct itself should be 8-byte aligned. In
391 practice we ensure this because the data starts two words into a struct.
392
393 This function allocates an 8-byte aligned block of memory, whose first word
394 points to the given vtable data, then a data pointer, then n_words of data.
395 */
396 SCM
397 scm_i_alloc_struct (scm_t_bits *vtable_data, int n_words)
398 {
399 scm_t_bits ret;
400 ret = (scm_t_bits)scm_gc_malloc (sizeof (scm_t_bits) * (n_words + 2), "struct");
401 SCM_SET_CELL_WORD_0 (SCM_PACK (ret), (scm_t_bits)vtable_data | scm_tc3_struct);
402 SCM_SET_CELL_WORD_1 (SCM_PACK (ret),
403 (scm_t_bits)SCM_CELL_OBJECT_LOC (SCM_PACK (ret), 2));
404
405 /* vtable_data can be null when making a vtable vtable */
406 if (vtable_data && vtable_data[scm_vtable_index_instance_finalize])
407 {
408 /* Register a finalizer for the newly created instance. */
409 GC_finalization_proc prev_finalizer;
410 GC_PTR prev_finalizer_data;
411 GC_REGISTER_FINALIZER_NO_ORDER ((void*)ret,
412 struct_finalizer_trampoline,
413 NULL,
414 &prev_finalizer,
415 &prev_finalizer_data);
416 }
417
418 return SCM_PACK (ret);
419 }
420
421 \f
422 SCM
423 scm_c_make_structv (SCM vtable, size_t n_tail, size_t n_init, scm_t_bits *init)
424 #define FUNC_NAME "make-struct"
425 {
426 SCM layout;
427 size_t basic_size;
428 SCM obj;
429
430 SCM_VALIDATE_VTABLE (1, vtable);
431
432 layout = SCM_VTABLE_LAYOUT (vtable);
433 basic_size = scm_i_symbol_length (layout) / 2;
434
435 if (n_tail != 0)
436 {
437 SCM layout_str, last_char;
438
439 if (basic_size == 0)
440 {
441 bad_tail:
442 SCM_MISC_ERROR ("tail array not allowed unless layout ends R, W, or O", SCM_EOL);
443 }
444
445 layout_str = scm_symbol_to_string (layout);
446 last_char = scm_string_ref (layout_str,
447 scm_from_size_t (2 * basic_size - 1));
448 if (! SCM_LAYOUT_TAILP (SCM_CHAR (last_char)))
449 goto bad_tail;
450 }
451
452 obj = scm_i_alloc_struct (SCM_STRUCT_DATA (vtable), basic_size + n_tail);
453
454 scm_struct_init (obj, layout, n_tail, n_init, init);
455
456 /* only check things and inherit magic if the layout was passed as an initarg.
457 something of a hack, but it's for back-compatibility. */
458 if (SCM_VTABLE_FLAG_IS_SET (vtable, SCM_VTABLE_FLAG_VTABLE)
459 && scm_is_true (SCM_VTABLE_LAYOUT (obj)))
460 scm_i_struct_inherit_vtable_magic (vtable, obj);
461
462 return obj;
463 }
464 #undef FUNC_NAME
465
466 SCM
467 scm_c_make_struct (SCM vtable, size_t n_tail, size_t n_init, scm_t_bits init, ...)
468 {
469 va_list foo;
470 scm_t_bits *v;
471 size_t i;
472
473 v = alloca (sizeof (scm_t_bits) * n_init);
474
475 va_start (foo, init);
476 for (i = 0; i < n_init; i++)
477 {
478 v[i] = init;
479 init = va_arg (foo, scm_t_bits);
480 }
481 va_end (foo);
482
483 return scm_c_make_structv (vtable, n_tail, n_init, v);
484 }
485
486 SCM_DEFINE (scm_make_struct, "make-struct", 2, 0, 1,
487 (SCM vtable, SCM tail_array_size, SCM init),
488 "Create a new structure.\n\n"
489 "@var{type} must be a vtable structure (@pxref{Vtables}).\n\n"
490 "@var{tail-elts} must be a non-negative integer. If the layout\n"
491 "specification indicated by @var{type} includes a tail-array,\n"
492 "this is the number of elements allocated to that array.\n\n"
493 "The @var{init1}, @dots{} are optional arguments describing how\n"
494 "successive fields of the structure should be initialized. Only fields\n"
495 "with protection 'r' or 'w' can be initialized, except for fields of\n"
496 "type 's', which are automatically initialized to point to the new\n"
497 "structure itself. Fields with protection 'o' can not be initialized by\n"
498 "Scheme programs.\n\n"
499 "If fewer optional arguments than initializable fields are supplied,\n"
500 "fields of type 'p' get default value #f while fields of type 'u' are\n"
501 "initialized to 0.\n\n"
502 "For more information, see the documentation for @code{make-vtable-vtable}.")
503 #define FUNC_NAME s_scm_make_struct
504 {
505 size_t i, n_init;
506 long ilen;
507 scm_t_bits *v;
508
509 SCM_VALIDATE_VTABLE (1, vtable);
510 ilen = scm_ilength (init);
511 if (ilen < 0)
512 SCM_MISC_ERROR ("Rest arguments do not form a proper list.", SCM_EOL);
513
514 n_init = (size_t)ilen;
515
516 /* best to use alloca, but init could be big, so hack to avoid a possible
517 stack overflow */
518 if (n_init < 64)
519 v = alloca (n_init * sizeof(scm_t_bits));
520 else
521 v = scm_gc_malloc (n_init * sizeof(scm_t_bits), "struct");
522
523 for (i = 0; i < n_init; i++, init = SCM_CDR (init))
524 v[i] = SCM_UNPACK (SCM_CAR (init));
525
526 return scm_c_make_structv (vtable, scm_to_size_t (tail_array_size), n_init, v);
527 }
528 #undef FUNC_NAME
529
530
531
532 SCM_DEFINE (scm_make_vtable_vtable, "make-vtable-vtable", 2, 0, 1,
533 (SCM user_fields, SCM tail_array_size, SCM init),
534 "Return a new, self-describing vtable structure.\n\n"
535 "@var{user-fields} is a string describing user defined fields of the\n"
536 "vtable beginning at index @code{vtable-offset-user}\n"
537 "(see @code{make-struct-layout}).\n\n"
538 "@var{tail-size} specifies the size of the tail-array (if any) of\n"
539 "this vtable.\n\n"
540 "@var{init1}, @dots{} are the optional initializers for the fields of\n"
541 "the vtable.\n\n"
542 "Vtables have one initializable system field---the struct printer.\n"
543 "This field comes before the user fields in the initializers passed\n"
544 "to @code{make-vtable-vtable} and @code{make-struct}, and thus works as\n"
545 "a third optional argument to @code{make-vtable-vtable} and a fourth to\n"
546 "@code{make-struct} when creating vtables:\n\n"
547 "If the value is a procedure, it will be called instead of the standard\n"
548 "printer whenever a struct described by this vtable is printed.\n"
549 "The procedure will be called with arguments STRUCT and PORT.\n\n"
550 "The structure of a struct is described by a vtable, so the vtable is\n"
551 "in essence the type of the struct. The vtable is itself a struct with\n"
552 "a vtable. This could go on forever if it weren't for the\n"
553 "vtable-vtables which are self-describing vtables, and thus terminate\n"
554 "the chain.\n\n"
555 "There are several potential ways of using structs, but the standard\n"
556 "one is to use three kinds of structs, together building up a type\n"
557 "sub-system: one vtable-vtable working as the root and one or several\n"
558 "\"types\", each with a set of \"instances\". (The vtable-vtable should be\n"
559 "compared to the class <class> which is the class of itself.)\n\n"
560 "@lisp\n"
561 "(define ball-root (make-vtable-vtable \"pr\" 0))\n\n"
562 "(define (make-ball-type ball-color)\n"
563 " (make-struct ball-root 0\n"
564 " (make-struct-layout \"pw\")\n"
565 " (lambda (ball port)\n"
566 " (format port \"#<a ~A ball owned by ~A>\"\n"
567 " (color ball)\n"
568 " (owner ball)))\n"
569 " ball-color))\n"
570 "(define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))\n"
571 "(define (owner ball) (struct-ref ball 0))\n\n"
572 "(define red (make-ball-type 'red))\n"
573 "(define green (make-ball-type 'green))\n\n"
574 "(define (make-ball type owner) (make-struct type 0 owner))\n\n"
575 "(define ball (make-ball green 'Nisse))\n"
576 "ball @result{} #<a green ball owned by Nisse>\n"
577 "@end lisp")
578 #define FUNC_NAME s_scm_make_vtable_vtable
579 {
580 SCM fields, layout, obj;
581 size_t basic_size, n_tail, i, n_init;
582 long ilen;
583 scm_t_bits *v;
584
585 SCM_VALIDATE_STRING (1, user_fields);
586 ilen = scm_ilength (init);
587 if (ilen < 0)
588 SCM_MISC_ERROR ("Rest arguments do not form a proper list.", SCM_EOL);
589
590 n_init = (size_t)ilen + 1; /* + 1 for the layout */
591
592 /* best to use alloca, but init could be big, so hack to avoid a possible
593 stack overflow */
594 if (n_init < 64)
595 v = alloca (n_init * sizeof(scm_t_bits));
596 else
597 v = scm_gc_malloc (n_init * sizeof(scm_t_bits), "struct");
598
599 fields = scm_string_append (scm_list_2 (required_vtable_fields,
600 user_fields));
601 layout = scm_make_struct_layout (fields);
602 basic_size = scm_i_symbol_length (layout) / 2;
603 n_tail = scm_to_size_t (tail_array_size);
604
605 i = 0;
606 v[i++] = SCM_UNPACK (layout);
607 for (; i < n_init; i++, init = SCM_CDR (init))
608 v[i] = SCM_UNPACK (SCM_CAR (init));
609
610 SCM_CRITICAL_SECTION_START;
611 obj = scm_i_alloc_struct (NULL, basic_size + n_tail);
612 /* Make it so that the vtable of OBJ is itself. */
613 SCM_SET_CELL_WORD_0 (obj, (scm_t_bits) SCM_STRUCT_DATA (obj) | scm_tc3_struct);
614 SCM_CRITICAL_SECTION_END;
615
616 scm_struct_init (obj, layout, n_tail, n_init, v);
617 SCM_SET_VTABLE_FLAGS (obj, SCM_VTABLE_FLAG_VTABLE);
618
619 return obj;
620 }
621 #undef FUNC_NAME
622
623
624 SCM_DEFINE (scm_make_vtable, "make-vtable", 1, 1, 0,
625 (SCM fields, SCM printer),
626 "Create a vtable, for creating structures with the given\n"
627 "@var{fields}.\n"
628 "\n"
629 "The optional @var{printer} argument is a function to be called\n"
630 "@code{(@var{printer} struct port)} on the structures created.\n"
631 "It should look at @var{struct} and write to @var{port}.")
632 #define FUNC_NAME s_scm_make_vtable
633 {
634 if (SCM_UNBNDP (printer))
635 printer = SCM_BOOL_F;
636
637 return scm_make_struct (scm_standard_vtable_vtable, SCM_INUM0,
638 scm_list_2 (scm_make_struct_layout (fields),
639 printer));
640 }
641 #undef FUNC_NAME
642
643
644 /* Return true if S1 and S2 are equal structures, i.e., if their vtable and
645 contents are the same. Field protections are honored. Thus, it is an
646 error to test the equality of structures that contain opaque fields. */
647 SCM
648 scm_i_struct_equalp (SCM s1, SCM s2)
649 #define FUNC_NAME "scm_i_struct_equalp"
650 {
651 SCM vtable1, vtable2, layout;
652 size_t struct_size, field_num;
653
654 SCM_VALIDATE_STRUCT (1, s1);
655 SCM_VALIDATE_STRUCT (2, s2);
656
657 vtable1 = SCM_STRUCT_VTABLE (s1);
658 vtable2 = SCM_STRUCT_VTABLE (s2);
659
660 if (!scm_is_eq (vtable1, vtable2))
661 return SCM_BOOL_F;
662
663 layout = SCM_STRUCT_LAYOUT (s1);
664 struct_size = scm_i_symbol_length (layout) / 2;
665
666 for (field_num = 0; field_num < struct_size; field_num++)
667 {
668 SCM s_field_num;
669 SCM field1, field2;
670
671 /* We have to use `scm_struct_ref ()' here so that fields are accessed
672 consistently, notably wrt. field types and access rights. */
673 s_field_num = scm_from_size_t (field_num);
674 field1 = scm_struct_ref (s1, s_field_num);
675 field2 = scm_struct_ref (s2, s_field_num);
676
677 /* Self-referencing fields (type `s') must be skipped to avoid infinite
678 recursion. */
679 if (!(scm_is_eq (field1, s1) && (scm_is_eq (field2, s2))))
680 if (scm_is_false (scm_equal_p (field1, field2)))
681 return SCM_BOOL_F;
682 }
683
684 /* FIXME: Tail elements should be tested for equality. */
685
686 return SCM_BOOL_T;
687 }
688 #undef FUNC_NAME
689
690
691 \f
692
693
694 SCM_DEFINE (scm_struct_ref, "struct-ref", 2, 0, 0,
695 (SCM handle, SCM pos),
696 "Access the @var{n}th field of @var{struct}.\n\n"
697 "If the field is of type 'p', then it can be set to an arbitrary value.\n\n"
698 "If the field is of type 'u', then it can only be set to a non-negative\n"
699 "integer value small enough to fit in one machine word.")
700 #define FUNC_NAME s_scm_struct_ref
701 {
702 SCM vtable, answer = SCM_UNDEFINED;
703 scm_t_bits *data;
704 size_t p;
705
706 SCM_VALIDATE_STRUCT (1, handle);
707
708 vtable = SCM_STRUCT_VTABLE (handle);
709 data = SCM_STRUCT_DATA (handle);
710 p = scm_to_size_t (pos);
711
712 if (SCM_LIKELY (SCM_VTABLE_FLAG_IS_SET (vtable, SCM_VTABLE_FLAG_SIMPLE)
713 && p < SCM_STRUCT_DATA_REF (vtable, scm_vtable_index_size)))
714 {
715 /* The fast path: HANDLE is a struct with only "p" fields. */
716 answer = SCM_PACK (data[p]);
717 }
718 else
719 {
720 SCM layout;
721 size_t layout_len, n_fields;
722 scm_t_wchar field_type = 0;
723
724 layout = SCM_STRUCT_LAYOUT (handle);
725 layout_len = scm_i_symbol_length (layout);
726 n_fields = layout_len / 2;
727
728 if (SCM_LAYOUT_TAILP (scm_i_symbol_ref (layout, layout_len - 1)))
729 n_fields += data[n_fields - 1];
730
731 SCM_ASSERT_RANGE (1, pos, p < n_fields);
732
733 if (p * 2 < layout_len)
734 {
735 scm_t_wchar ref;
736 field_type = scm_i_symbol_ref (layout, p * 2);
737 ref = scm_i_symbol_ref (layout, p * 2 + 1);
738 if ((ref != 'r') && (ref != 'w') && (ref != 'h'))
739 {
740 if ((ref == 'R') || (ref == 'W'))
741 field_type = 'u';
742 else
743 SCM_MISC_ERROR ("ref denied for field ~A", scm_list_1 (pos));
744 }
745 }
746 else if (scm_i_symbol_ref (layout, layout_len - 1) != 'O')
747 field_type = scm_i_symbol_ref(layout, layout_len - 2);
748 else
749 SCM_MISC_ERROR ("ref denied for field ~A", scm_list_1 (pos));
750
751 switch (field_type)
752 {
753 case 'u':
754 answer = scm_from_ulong (data[p]);
755 break;
756
757 #if 0
758 case 'i':
759 answer = scm_from_long (data[p]);
760 break;
761
762 case 'd':
763 answer = scm_make_real (*((double *)&(data[p])));
764 break;
765 #endif
766
767 case 's':
768 case 'p':
769 answer = SCM_PACK (data[p]);
770 break;
771
772
773 default:
774 SCM_MISC_ERROR ("unrecognized field type: ~S",
775 scm_list_1 (SCM_MAKE_CHAR (field_type)));
776 }
777 }
778
779 return answer;
780 }
781 #undef FUNC_NAME
782
783
784 SCM_DEFINE (scm_struct_set_x, "struct-set!", 3, 0, 0,
785 (SCM handle, SCM pos, SCM val),
786 "Set the slot of the structure @var{handle} with index @var{pos}\n"
787 "to @var{val}. Signal an error if the slot can not be written\n"
788 "to.")
789 #define FUNC_NAME s_scm_struct_set_x
790 {
791 SCM vtable;
792 scm_t_bits *data;
793 size_t p;
794
795 SCM_VALIDATE_STRUCT (1, handle);
796
797 vtable = SCM_STRUCT_VTABLE (handle);
798 data = SCM_STRUCT_DATA (handle);
799 p = scm_to_size_t (pos);
800
801 if (SCM_LIKELY (SCM_VTABLE_FLAG_IS_SET (vtable, SCM_VTABLE_FLAG_SIMPLE)
802 && SCM_VTABLE_FLAG_IS_SET (vtable, SCM_VTABLE_FLAG_SIMPLE_RW)
803 && p < SCM_STRUCT_DATA_REF (vtable, scm_vtable_index_size)))
804 /* The fast path: HANDLE is a struct with only "p" fields. */
805 data[p] = SCM_UNPACK (val);
806 else
807 {
808 SCM layout;
809 size_t layout_len, n_fields;
810 scm_t_wchar field_type = 0;
811
812 layout = SCM_STRUCT_LAYOUT (handle);
813 layout_len = scm_i_symbol_length (layout);
814 n_fields = layout_len / 2;
815
816 if (SCM_LAYOUT_TAILP (scm_i_symbol_ref (layout, layout_len - 1)))
817 n_fields += data[n_fields - 1];
818
819 SCM_ASSERT_RANGE (1, pos, p < n_fields);
820
821 if (p * 2 < layout_len)
822 {
823 char set_x;
824 field_type = scm_i_symbol_ref (layout, p * 2);
825 set_x = scm_i_symbol_ref (layout, p * 2 + 1);
826 if (set_x != 'w' && set_x != 'h')
827 SCM_MISC_ERROR ("set! denied for field ~A", scm_list_1 (pos));
828 }
829 else if (scm_i_symbol_ref (layout, layout_len - 1) == 'W')
830 field_type = scm_i_symbol_ref (layout, layout_len - 2);
831 else
832 SCM_MISC_ERROR ("set! denied for field ~A", scm_list_1 (pos));
833
834 switch (field_type)
835 {
836 case 'u':
837 data[p] = SCM_NUM2ULONG (3, val);
838 break;
839
840 #if 0
841 case 'i':
842 data[p] = SCM_NUM2LONG (3, val);
843 break;
844
845 case 'd':
846 *((double *)&(data[p])) = scm_num2dbl (val, (char *)SCM_ARG3);
847 break;
848 #endif
849
850 case 'p':
851 data[p] = SCM_UNPACK (val);
852 break;
853
854 case 's':
855 SCM_MISC_ERROR ("self fields immutable", SCM_EOL);
856
857 default:
858 SCM_MISC_ERROR ("unrecognized field type: ~S",
859 scm_list_1 (SCM_MAKE_CHAR (field_type)));
860 }
861 }
862
863 return val;
864 }
865 #undef FUNC_NAME
866
867
868 SCM_DEFINE (scm_struct_vtable, "struct-vtable", 1, 0, 0,
869 (SCM handle),
870 "Return the vtable structure that describes the type of @var{struct}.")
871 #define FUNC_NAME s_scm_struct_vtable
872 {
873 SCM_VALIDATE_STRUCT (1, handle);
874 return SCM_STRUCT_VTABLE (handle);
875 }
876 #undef FUNC_NAME
877
878
879 SCM_DEFINE (scm_struct_vtable_tag, "struct-vtable-tag", 1, 0, 0,
880 (SCM handle),
881 "Return the vtable tag of the structure @var{handle}.")
882 #define FUNC_NAME s_scm_struct_vtable_tag
883 {
884 SCM_VALIDATE_VTABLE (1, handle);
885 return scm_from_ulong (((unsigned long)SCM_STRUCT_DATA (handle)) >> 3);
886 }
887 #undef FUNC_NAME
888
889 /* {Associating names and classes with vtables}
890 *
891 * The name of a vtable should probably be stored as a slot. This is
892 * a backward compatible solution until agreement has been achieved on
893 * how to associate names with vtables.
894 */
895
896 unsigned long
897 scm_struct_ihashq (SCM obj, unsigned long n, void *closure)
898 {
899 /* The length of the hash table should be a relative prime it's not
900 necessary to shift down the address. */
901 return SCM_UNPACK (obj) % n;
902 }
903
904 SCM
905 scm_struct_create_handle (SCM obj)
906 {
907 SCM handle = scm_hash_fn_create_handle_x (scm_struct_table,
908 obj,
909 SCM_BOOL_F,
910 scm_struct_ihashq,
911 (scm_t_assoc_fn) scm_sloppy_assq,
912 0);
913 if (scm_is_false (SCM_CDR (handle)))
914 SCM_SETCDR (handle, scm_cons (SCM_BOOL_F, SCM_BOOL_F));
915 return handle;
916 }
917
918 SCM_DEFINE (scm_struct_vtable_name, "struct-vtable-name", 1, 0, 0,
919 (SCM vtable),
920 "Return the name of the vtable @var{vtable}.")
921 #define FUNC_NAME s_scm_struct_vtable_name
922 {
923 SCM_VALIDATE_VTABLE (1, vtable);
924 return SCM_STRUCT_TABLE_NAME (SCM_CDR (scm_struct_create_handle (vtable)));
925 }
926 #undef FUNC_NAME
927
928 SCM_DEFINE (scm_set_struct_vtable_name_x, "set-struct-vtable-name!", 2, 0, 0,
929 (SCM vtable, SCM name),
930 "Set the name of the vtable @var{vtable} to @var{name}.")
931 #define FUNC_NAME s_scm_set_struct_vtable_name_x
932 {
933 SCM_VALIDATE_VTABLE (1, vtable);
934 SCM_VALIDATE_SYMBOL (2, name);
935 SCM_SET_STRUCT_TABLE_NAME (SCM_CDR (scm_struct_create_handle (vtable)),
936 name);
937 return SCM_UNSPECIFIED;
938 }
939 #undef FUNC_NAME
940
941
942 \f
943
944 void
945 scm_print_struct (SCM exp, SCM port, scm_print_state *pstate)
946 {
947 if (scm_is_true (scm_procedure_p (SCM_STRUCT_PRINTER (exp))))
948 scm_printer_apply (SCM_STRUCT_PRINTER (exp), exp, port, pstate);
949 else
950 {
951 SCM vtable = SCM_STRUCT_VTABLE (exp);
952 SCM name = scm_struct_vtable_name (vtable);
953 scm_puts ("#<", port);
954 if (scm_is_true (name))
955 {
956 scm_display (name, port);
957 scm_putc (' ', port);
958 }
959 else
960 {
961 if (SCM_VTABLE_FLAG_IS_SET (vtable, SCM_VTABLE_FLAG_VTABLE))
962 scm_puts ("vtable:", port);
963 else
964 scm_puts ("struct:", port);
965 scm_uintprint (SCM_UNPACK (vtable), 16, port);
966 scm_putc (' ', port);
967 scm_write (SCM_VTABLE_LAYOUT (vtable), port);
968 scm_putc (' ', port);
969 }
970 scm_uintprint (SCM_UNPACK (exp), 16, port);
971 /* hackety hack */
972 if (SCM_STRUCT_APPLICABLE_P (exp))
973 {
974 if (scm_is_true (SCM_STRUCT_PROCEDURE (exp)))
975 {
976 scm_puts (" proc: ", port);
977 if (scm_is_true (scm_procedure_p (SCM_STRUCT_PROCEDURE (exp))))
978 scm_write (SCM_STRUCT_PROCEDURE (exp), port);
979 else
980 scm_puts ("(not a procedure?)", port);
981 }
982 if (SCM_STRUCT_SETTER_P (exp))
983 {
984 scm_puts (" setter: ", port);
985 scm_write (SCM_STRUCT_SETTER (exp), port);
986 }
987 }
988 scm_putc ('>', port);
989 }
990 }
991
992 void
993 scm_init_struct ()
994 {
995 /* The first word of a struct is equal to `SCM_STRUCT_DATA (vtable) +
996 scm_tc3_struct', and `SCM_STRUCT_DATA (vtable)' is 2 words after VTABLE by
997 default. */
998 GC_REGISTER_DISPLACEMENT (2 * sizeof (scm_t_bits) + scm_tc3_struct);
999
1000 /* In the general case, `SCM_STRUCT_DATA (obj)' points 2 words after the
1001 beginning of a GC-allocated region; that region is different from that of
1002 OBJ once OBJ has undergone class redefinition. */
1003 GC_REGISTER_DISPLACEMENT (2 * sizeof (scm_t_bits));
1004
1005 scm_struct_table = scm_make_weak_key_hash_table (scm_from_int (31));
1006 required_vtable_fields = scm_from_locale_string (SCM_VTABLE_BASE_LAYOUT);
1007 required_applicable_fields = scm_from_locale_string (SCM_APPLICABLE_BASE_LAYOUT);
1008 required_applicable_with_setter_fields = scm_from_locale_string (SCM_APPLICABLE_WITH_SETTER_BASE_LAYOUT);
1009
1010 scm_standard_vtable_vtable =
1011 scm_make_vtable_vtable (scm_nullstr, SCM_INUM0, SCM_EOL);
1012
1013 scm_applicable_struct_vtable_vtable =
1014 scm_make_struct (scm_standard_vtable_vtable, SCM_INUM0,
1015 scm_list_1 (scm_make_struct_layout (required_vtable_fields)));
1016 SCM_SET_VTABLE_FLAGS (scm_applicable_struct_vtable_vtable,
1017 SCM_VTABLE_FLAG_APPLICABLE_VTABLE);
1018 scm_c_define ("<applicable-struct-vtable>", scm_applicable_struct_vtable_vtable);
1019
1020 scm_applicable_struct_with_setter_vtable_vtable =
1021 scm_make_struct (scm_standard_vtable_vtable, SCM_INUM0,
1022 scm_list_1 (scm_make_struct_layout (required_vtable_fields)));
1023 SCM_SET_VTABLE_FLAGS (scm_applicable_struct_with_setter_vtable_vtable,
1024 SCM_VTABLE_FLAG_APPLICABLE_VTABLE | SCM_VTABLE_FLAG_SETTER_VTABLE);
1025 scm_c_define ("<applicable-struct-with-setter-vtable>", scm_applicable_struct_with_setter_vtable_vtable);
1026
1027 scm_c_define ("vtable-index-layout", scm_from_int (scm_vtable_index_layout));
1028 scm_c_define ("vtable-index-printer",
1029 scm_from_int (scm_vtable_index_instance_printer));
1030 scm_c_define ("vtable-offset-user", scm_from_int (scm_vtable_offset_user));
1031 #include "libguile/struct.x"
1032 }
1033
1034 /*
1035 Local Variables:
1036 c-file-style: "gnu"
1037 End:
1038 */