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