2 ** struct.c - Struct class
4 ** See Copyright Notice in mruby.h
9 #include <mruby/array.h>
10 #include <mruby/string.h>
11 #include <mruby/class.h>
12 #include <mruby/variable.h>
13 #include <mruby/hash.h>
14 #include <mruby/range.h>
15 #include <mruby/proc.h>
17 #define RSTRUCT_LEN(st) RARRAY_LEN(st)
18 #define RSTRUCT_PTR(st) RARRAY_PTR(st)
20 static struct RClass *
21 struct_class(mrb_state *mrb)
23 return mrb_class_get(mrb, "Struct");
26 static inline mrb_value
27 struct_ivar_get(mrb_state *mrb, mrb_value cls, mrb_sym id)
29 struct RClass* c = mrb_class_ptr(cls);
30 struct RClass* sclass = struct_class(mrb);
34 ans = mrb_iv_get(mrb, mrb_obj_value(c), id);
35 if (!mrb_nil_p(ans)) return ans;
37 if (c == sclass || c == 0)
38 return mrb_nil_value();
43 struct_s_members(mrb_state *mrb, struct RClass *klass)
45 mrb_value members = struct_ivar_get(mrb, mrb_obj_value(klass), mrb_intern_lit(mrb, "__members__"));
47 if (mrb_nil_p(members)) {
48 mrb_raise(mrb, E_TYPE_ERROR, "uninitialized struct");
50 if (!mrb_array_p(members)) {
51 mrb_raise(mrb, E_TYPE_ERROR, "corrupted struct");
57 struct_members(mrb_state *mrb, mrb_value s)
59 mrb_value members = struct_s_members(mrb, mrb_obj_class(mrb, s));
60 if (!mrb_array_p(s)) {
61 mrb_raise(mrb, E_TYPE_ERROR, "corrupted struct");
63 if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
64 if (RSTRUCT_LEN(s) == 0) { /* probably uninitialized */
65 mrb_ary_resize(mrb, s, RARRAY_LEN(members));
68 mrb_raisef(mrb, E_TYPE_ERROR,
69 "struct size differs (%S required %S given)",
70 mrb_fixnum_value(RARRAY_LEN(members)), mrb_fixnum_value(RSTRUCT_LEN(s)));
77 mrb_struct_s_members_m(mrb_state *mrb, mrb_value klass)
79 mrb_value members, ary;
81 members = struct_s_members(mrb, mrb_class_ptr(klass));
82 ary = mrb_ary_new_capa(mrb, RARRAY_LEN(members));
83 mrb_ary_replace(mrb, ary, members);
88 mrb_struct_modify(mrb_state *mrb, mrb_value strct)
90 if (MRB_FROZEN_P(mrb_basic_ptr(strct))) {
91 mrb_raise(mrb, E_FROZEN_ERROR, "can't modify frozen struct");
94 mrb_write_barrier(mrb, mrb_basic_ptr(strct));
100 * struct.members -> array
102 * Returns an array of strings representing the names of the instance
105 * Customer = Struct.new(:name, :address, :zip)
106 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
107 * joe.members #=> [:name, :address, :zip]
111 mrb_struct_members(mrb_state *mrb, mrb_value obj)
113 return mrb_struct_s_members_m(mrb, mrb_obj_value(mrb_obj_class(mrb, obj)));
117 mrb_struct_ref(mrb_state *mrb, mrb_value obj)
119 mrb_int i = mrb_fixnum(mrb_proc_cfunc_env_get(mrb, 0));
120 mrb_value *ptr = RSTRUCT_PTR(obj);
122 if (!ptr) return mrb_nil_value();
127 mrb_id_attrset(mrb_state *mrb, mrb_sym id)
134 name = mrb_sym2name_len(mrb, id, &len);
135 buf = (char *)mrb_malloc(mrb, (size_t)len+2);
136 memcpy(buf, name, (size_t)len);
140 mid = mrb_intern(mrb, buf, len+1);
146 mrb_struct_set_m(mrb_state *mrb, mrb_value obj)
148 mrb_int i = mrb_fixnum(mrb_proc_cfunc_env_get(mrb, 0));
152 mrb_get_args(mrb, "o", &val);
153 mrb_struct_modify(mrb, obj);
154 ptr = RSTRUCT_PTR(obj);
155 if (ptr == NULL || i >= RSTRUCT_LEN(obj)) {
156 mrb_ary_set(mrb, obj, i, val);
165 is_local_id(mrb_state *mrb, const char *name)
167 if (!name) return FALSE;
168 return !ISUPPER(name[0]);
172 is_const_id(mrb_state *mrb, const char *name)
174 if (!name) return FALSE;
175 return ISUPPER(name[0]);
179 make_struct_define_accessors(mrb_state *mrb, mrb_value members, struct RClass *c)
181 const mrb_value *ptr_members = RARRAY_PTR(members);
183 mrb_int len = RARRAY_LEN(members);
184 int ai = mrb_gc_arena_save(mrb);
186 for (i=0; i<len; i++) {
187 mrb_sym id = mrb_symbol(ptr_members[i]);
188 const char *name = mrb_sym2name_len(mrb, id, NULL);
190 if (is_local_id(mrb, name) || is_const_id(mrb, name)) {
192 mrb_value at = mrb_fixnum_value(i);
193 struct RProc *aref = mrb_proc_new_cfunc_with_env(mrb, mrb_struct_ref, 1, &at);
194 struct RProc *aset = mrb_proc_new_cfunc_with_env(mrb, mrb_struct_set_m, 1, &at);
195 MRB_METHOD_FROM_PROC(m, aref);
196 mrb_define_method_raw(mrb, c, id, m);
197 MRB_METHOD_FROM_PROC(m, aset);
198 mrb_define_method_raw(mrb, c, mrb_id_attrset(mrb, id), m);
199 mrb_gc_arena_restore(mrb, ai);
205 make_struct(mrb_state *mrb, mrb_value name, mrb_value members, struct RClass *klass)
211 if (mrb_nil_p(name)) {
212 c = mrb_class_new(mrb, klass);
215 /* old style: should we warn? */
216 mrb_to_str(mrb, name);
217 id = mrb_obj_to_sym(mrb, name);
218 if (!is_const_id(mrb, mrb_sym2name_len(mrb, id, NULL))) {
219 mrb_name_error(mrb, id, "identifier %S needs to be constant", name);
221 if (mrb_const_defined_at(mrb, mrb_obj_value(klass), id)) {
222 mrb_warn(mrb, "redefining constant Struct::%S", name);
223 mrb_const_remove(mrb, mrb_obj_value(klass), id);
225 c = mrb_define_class_under(mrb, klass, RSTRING_PTR(name), klass);
227 MRB_SET_INSTANCE_TT(c, MRB_TT_ARRAY);
228 nstr = mrb_obj_value(c);
229 mrb_iv_set(mrb, nstr, mrb_intern_lit(mrb, "__members__"), members);
231 mrb_define_class_method(mrb, c, "new", mrb_instance_new, MRB_ARGS_ANY());
232 mrb_define_class_method(mrb, c, "[]", mrb_instance_new, MRB_ARGS_ANY());
233 mrb_define_class_method(mrb, c, "members", mrb_struct_s_members_m, MRB_ARGS_NONE());
234 /* RSTRUCT(nstr)->basic.c->super = c->c; */
235 make_struct_define_accessors(mrb, members, c);
242 * Struct.new( [aString] [, aSym]+> ) -> StructClass
243 * StructClass.new(arg, ...) -> obj
244 * StructClass[arg, ...] -> obj
246 * Creates a new class, named by <i>aString</i>, containing accessor
247 * methods for the given symbols. If the name <i>aString</i> is
248 * omitted, an anonymous structure class will be created. Otherwise,
249 * the name of this struct will appear as a constant in class
250 * <code>Struct</code>, so it must be unique for all
251 * <code>Struct</code>s in the system and should start with a capital
252 * letter. Assigning a structure class to a constant effectively gives
253 * the class the name of the constant.
255 * <code>Struct::new</code> returns a new <code>Class</code> object,
256 * which can then be used to create specific instances of the new
257 * structure. The number of actual parameters must be
258 * less than or equal to the number of attributes defined for this
259 * class; unset parameters default to <code>nil</code>. Passing too many
260 * parameters will raise an <code>ArgumentError</code>.
262 * The remaining methods listed in this section (class and instance)
263 * are defined for this generated class.
265 * # Create a structure with a name in Struct
266 * Struct.new("Customer", :name, :address) #=> Struct::Customer
267 * Struct::Customer.new("Dave", "123 Main") #=> #<struct Struct::Customer name="Dave", address="123 Main">
269 * # Create a structure named by its constant
270 * Customer = Struct.new(:name, :address) #=> Customer
271 * Customer.new("Dave", "123 Main") #=> #<struct Customer name="Dave", address="123 Main">
274 mrb_struct_s_def(mrb_state *mrb, mrb_value klass)
276 mrb_value name, rest;
285 name = mrb_nil_value();
286 mrb_get_args(mrb, "*&", &argv, &argc, &b);
287 if (argc == 0) { /* special case to avoid crash */
288 mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments");
295 if (mrb_symbol_p(name)) {
296 /* 1stArgument:symbol -> name=nil rest=argv[0..n] */
297 name = mrb_nil_value();
304 rest = mrb_ary_new_from_values(mrb, argcnt, pargv);
305 for (i=0; i<argcnt; i++) {
306 id = mrb_obj_to_sym(mrb, RARRAY_PTR(rest)[i]);
307 mrb_ary_set(mrb, rest, i, mrb_symbol_value(id));
309 st = make_struct(mrb, name, rest, mrb_class_ptr(klass));
311 mrb_yield_with_class(mrb, b, 1, &st, st, mrb_class_ptr(st));
317 return mrb_nil_value();
321 num_members(mrb_state *mrb, struct RClass *klass)
325 members = struct_ivar_get(mrb, mrb_obj_value(klass), mrb_intern_lit(mrb, "__members__"));
326 if (!mrb_array_p(members)) {
327 mrb_raise(mrb, E_TYPE_ERROR, "broken members");
329 return RARRAY_LEN(members);
336 mrb_struct_initialize_withArg(mrb_state *mrb, mrb_int argc, mrb_value *argv, mrb_value self)
338 struct RClass *klass = mrb_obj_class(mrb, self);
341 n = num_members(mrb, klass);
343 mrb_raise(mrb, E_ARGUMENT_ERROR, "struct size differs");
346 for (i = 0; i < argc; i++) {
347 mrb_ary_set(mrb, self, i, argv[i]);
349 for (i = argc; i < n; i++) {
350 mrb_ary_set(mrb, self, i, mrb_nil_value());
356 mrb_struct_initialize(mrb_state *mrb, mrb_value self)
361 mrb_get_args(mrb, "*!", &argv, &argc);
362 return mrb_struct_initialize_withArg(mrb, argc, argv, self);
368 mrb_struct_init_copy(mrb_state *mrb, mrb_value copy)
372 mrb_get_args(mrb, "o", &s);
374 if (mrb_obj_equal(mrb, copy, s)) return copy;
375 if (!mrb_obj_is_instance_of(mrb, s, mrb_obj_class(mrb, copy))) {
376 mrb_raise(mrb, E_TYPE_ERROR, "wrong argument class");
378 if (!mrb_array_p(s)) {
379 mrb_raise(mrb, E_TYPE_ERROR, "corrupted struct");
381 mrb_ary_replace(mrb, copy, s);
386 struct_aref_sym(mrb_state *mrb, mrb_value obj, mrb_sym id)
388 mrb_value members, *ptr;
389 const mrb_value *ptr_members;
392 members = struct_members(mrb, obj);
393 ptr_members = RARRAY_PTR(members);
394 len = RARRAY_LEN(members);
395 ptr = RSTRUCT_PTR(obj);
396 for (i=0; i<len; i++) {
397 mrb_value slot = ptr_members[i];
398 if (mrb_symbol_p(slot) && mrb_symbol(slot) == id) {
402 mrb_name_error(mrb, id, "no member '%S' in struct", mrb_sym2str(mrb, id));
403 return mrb_nil_value(); /* not reached */
407 struct_aref_int(mrb_state *mrb, mrb_value s, mrb_int i)
409 if (i < 0) i = RSTRUCT_LEN(s) + i;
411 mrb_raisef(mrb, E_INDEX_ERROR,
412 "offset %S too small for struct(size:%S)",
413 mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
414 if (RSTRUCT_LEN(s) <= i)
415 mrb_raisef(mrb, E_INDEX_ERROR,
416 "offset %S too large for struct(size:%S)",
417 mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
418 return RSTRUCT_PTR(s)[i];
424 * struct[symbol] -> anObject
425 * struct[fixnum] -> anObject
427 * Attribute Reference---Returns the value of the instance variable
428 * named by <i>symbol</i>, or indexed (0..length-1) by
429 * <i>fixnum</i>. Will raise <code>NameError</code> if the named
430 * variable does not exist, or <code>IndexError</code> if the index is
433 * Customer = Struct.new(:name, :address, :zip)
434 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
436 * joe["name"] #=> "Joe Smith"
437 * joe[:name] #=> "Joe Smith"
438 * joe[0] #=> "Joe Smith"
441 mrb_struct_aref(mrb_state *mrb, mrb_value s)
445 mrb_get_args(mrb, "o", &idx);
446 if (mrb_string_p(idx)) {
447 mrb_value sym = mrb_check_intern_str(mrb, idx);
449 if (mrb_nil_p(sym)) {
450 mrb_name_error(mrb, mrb_intern_str(mrb, idx), "no member '%S' in struct", idx);
454 if (mrb_symbol_p(idx)) {
455 return struct_aref_sym(mrb, s, mrb_symbol(idx));
457 return struct_aref_int(mrb, s, mrb_int(mrb, idx));
461 mrb_struct_aset_sym(mrb_state *mrb, mrb_value s, mrb_sym id, mrb_value val)
463 mrb_value members, *ptr;
464 const mrb_value *ptr_members;
467 members = struct_members(mrb, s);
468 len = RARRAY_LEN(members);
469 ptr = RSTRUCT_PTR(s);
470 ptr_members = RARRAY_PTR(members);
471 for (i=0; i<len; i++) {
472 if (mrb_symbol(ptr_members[i]) == id) {
473 mrb_struct_modify(mrb, s);
478 mrb_name_error(mrb, id, "no member '%S' in struct", mrb_sym2str(mrb, id));
479 return val; /* not reach */
485 * struct[symbol] = obj -> obj
486 * struct[fixnum] = obj -> obj
488 * Attribute Assignment---Assigns to the instance variable named by
489 * <i>symbol</i> or <i>fixnum</i> the value <i>obj</i> and
490 * returns it. Will raise a <code>NameError</code> if the named
491 * variable does not exist, or an <code>IndexError</code> if the index
494 * Customer = Struct.new(:name, :address, :zip)
495 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
497 * joe["name"] = "Luke"
498 * joe[:zip] = "90210"
500 * joe.name #=> "Luke"
501 * joe.zip #=> "90210"
505 mrb_struct_aset(mrb_state *mrb, mrb_value s)
511 mrb_get_args(mrb, "oo", &idx, &val);
513 if (mrb_string_p(idx)) {
514 mrb_value sym = mrb_check_intern_str(mrb, idx);
516 if (mrb_nil_p(sym)) {
517 mrb_name_error(mrb, mrb_intern_str(mrb, idx), "no member '%S' in struct", idx);
521 if (mrb_symbol_p(idx)) {
522 return mrb_struct_aset_sym(mrb, s, mrb_symbol(idx), val);
525 i = mrb_int(mrb, idx);
526 if (i < 0) i = RSTRUCT_LEN(s) + i;
528 mrb_raisef(mrb, E_INDEX_ERROR,
529 "offset %S too small for struct(size:%S)",
530 mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
532 if (RSTRUCT_LEN(s) <= i) {
533 mrb_raisef(mrb, E_INDEX_ERROR,
534 "offset %S too large for struct(size:%S)",
535 mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
537 mrb_struct_modify(mrb, s);
538 return RSTRUCT_PTR(s)[i] = val;
544 * struct == other_struct -> true or false
546 * Equality---Returns <code>true</code> if <i>other_struct</i> is
547 * equal to this one: they must be of the same class as generated by
548 * <code>Struct::new</code>, and the values of all instance variables
549 * must be equal (according to <code>Object#==</code>).
551 * Customer = Struct.new(:name, :address, :zip)
552 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
553 * joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
554 * jane = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)
555 * joe == joejr #=> true
556 * joe == jane #=> false
560 mrb_struct_equal(mrb_state *mrb, mrb_value s)
563 mrb_value *ptr, *ptr2;
566 mrb_get_args(mrb, "o", &s2);
567 if (mrb_obj_equal(mrb, s, s2)) {
568 return mrb_true_value();
570 if (mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) {
571 return mrb_false_value();
573 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
574 mrb_bug(mrb, "inconsistent struct"); /* should never happen */
576 ptr = RSTRUCT_PTR(s);
577 ptr2 = RSTRUCT_PTR(s2);
578 len = RSTRUCT_LEN(s);
579 for (i=0; i<len; i++) {
580 if (!mrb_equal(mrb, ptr[i], ptr2[i])) {
581 return mrb_false_value();
585 return mrb_true_value();
588 /* 15.2.18.4.12(x) */
591 * struct.eql?(other) -> true or false
593 * Two structures are equal if they are the same object, or if all their
594 * fields are equal (using <code>eql?</code>).
597 mrb_struct_eql(mrb_state *mrb, mrb_value s)
600 mrb_value *ptr, *ptr2;
603 mrb_get_args(mrb, "o", &s2);
604 if (mrb_obj_equal(mrb, s, s2)) {
605 return mrb_true_value();
607 if (mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) {
608 return mrb_false_value();
610 if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
611 mrb_bug(mrb, "inconsistent struct"); /* should never happen */
613 ptr = RSTRUCT_PTR(s);
614 ptr2 = RSTRUCT_PTR(s2);
615 len = RSTRUCT_LEN(s);
616 for (i=0; i<len; i++) {
617 if (!mrb_eql(mrb, ptr[i], ptr2[i])) {
618 return mrb_false_value();
622 return mrb_true_value();
627 * struct.length -> Fixnum
628 * struct.size -> Fixnum
630 * Returns number of struct members.
633 mrb_struct_len(mrb_state *mrb, mrb_value self)
635 return mrb_fixnum_value(RSTRUCT_LEN(self));
640 * struct.to_a -> array
641 * struct.values -> array
643 * Create an array from struct values.
646 mrb_struct_to_a(mrb_state *mrb, mrb_value self)
648 return mrb_ary_new_from_values(mrb, RSTRUCT_LEN(self), RSTRUCT_PTR(self));
653 * struct.to_h -> hash
655 * Create a hash from member names and struct values.
658 mrb_struct_to_h(mrb_state *mrb, mrb_value self)
660 mrb_value members, ret;
663 members = struct_members(mrb, self);
664 ret = mrb_hash_new_capa(mrb, RARRAY_LEN(members));
666 for (i = 0; i < RARRAY_LEN(members); ++i) {
667 mrb_hash_set(mrb, ret, RARRAY_PTR(members)[i], RSTRUCT_PTR(self)[i]);
674 mrb_struct_values_at(mrb_state *mrb, mrb_value self)
679 mrb_get_args(mrb, "*", &argv, &argc);
681 return mrb_get_values_at(mrb, self, RSTRUCT_LEN(self), argc, argv, struct_aref_int);
685 * A <code>Struct</code> is a convenient way to bundle a number of
686 * attributes together, using accessor methods, without having to write
689 * The <code>Struct</code> class is a generator of specific classes,
690 * each one of which is defined to hold a set of variables and their
691 * accessors. In these examples, we'll call the generated class
692 * "<i>Customer</i>Class," and we'll show an example instance of that
693 * class as "<i>Customer</i>Inst."
695 * In the descriptions that follow, the parameter <i>symbol</i> refers
696 * to a symbol, which is either a quoted string or a
697 * <code>Symbol</code> (such as <code>:name</code>).
700 mrb_mruby_struct_gem_init(mrb_state* mrb)
703 st = mrb_define_class(mrb, "Struct", mrb->object_class);
704 MRB_SET_INSTANCE_TT(st, MRB_TT_ARRAY);
706 mrb_define_class_method(mrb, st, "new", mrb_struct_s_def, MRB_ARGS_ANY()); /* 15.2.18.3.1 */
708 mrb_define_method(mrb, st, "==", mrb_struct_equal, MRB_ARGS_REQ(1)); /* 15.2.18.4.1 */
709 mrb_define_method(mrb, st, "[]", mrb_struct_aref, MRB_ARGS_REQ(1)); /* 15.2.18.4.2 */
710 mrb_define_method(mrb, st, "[]=", mrb_struct_aset, MRB_ARGS_REQ(2)); /* 15.2.18.4.3 */
711 mrb_define_method(mrb, st, "members", mrb_struct_members, MRB_ARGS_NONE()); /* 15.2.18.4.6 */
712 mrb_define_method(mrb, st, "initialize", mrb_struct_initialize, MRB_ARGS_ANY()); /* 15.2.18.4.8 */
713 mrb_define_method(mrb, st, "initialize_copy", mrb_struct_init_copy, MRB_ARGS_REQ(1)); /* 15.2.18.4.9 */
714 mrb_define_method(mrb, st, "eql?", mrb_struct_eql, MRB_ARGS_REQ(1)); /* 15.2.18.4.12(x) */
716 mrb_define_method(mrb, st, "size", mrb_struct_len, MRB_ARGS_NONE());
717 mrb_define_method(mrb, st, "length", mrb_struct_len, MRB_ARGS_NONE());
718 mrb_define_method(mrb, st, "to_a", mrb_struct_to_a, MRB_ARGS_NONE());
719 mrb_define_method(mrb, st, "values", mrb_struct_to_a, MRB_ARGS_NONE());
720 mrb_define_method(mrb, st, "to_h", mrb_struct_to_h, MRB_ARGS_NONE());
721 mrb_define_method(mrb, st, "values_at", mrb_struct_values_at, MRB_ARGS_ANY());
725 mrb_mruby_struct_gem_final(mrb_state* mrb)