Ruby 4.1.0dev (2026-11-13 revision 293c4f9246239937ca460c9dc64639fc5180e74e)
struct.c (293c4f9246239937ca460c9dc64639fc5180e74e)
1/**********************************************************************
2
3 struct.c -
4
5 $Author$
6 created at: Tue Mar 22 18:44:30 JST 1995
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "id.h"
13#include "internal.h"
14#include "internal/class.h"
15#include "internal/error.h"
16#include "internal/hash.h"
17#include "internal/object.h"
18#include "internal/proc.h"
19#include "internal/struct.h"
20#include "internal/symbol.h"
21#include "vm_core.h"
22#include "builtin.h"
23
24/* only for struct[:field] access */
25enum {
26 AREF_HASH_UNIT = 5,
27 AREF_HASH_THRESHOLD = 10
28};
29
30/* Note: Data is a stricter version of the Struct: no attr writers & no
31 hash-alike/array-alike behavior. It shares most of the implementation
32 on the C level, but is unrelated on the Ruby level. */
34static VALUE rb_cData;
35static ID id_members, id_back_members, id_keyword_init;
36
37static VALUE struct_alloc(VALUE);
38
39static inline VALUE
40struct_ivar_get(VALUE c, ID id)
41{
42 VALUE orig = c;
43 VALUE ivar = rb_attr_get(c, id);
44
45 if (!NIL_P(ivar))
46 return ivar;
47
48 for (;;) {
50 if (c == rb_cStruct || c == rb_cData || !RTEST(c))
51 return Qnil;
53 ivar = rb_attr_get(c, id);
54 if (!NIL_P(ivar)) {
55 if (!OBJ_FROZEN(orig) && rb_class_owned_p(orig)) rb_ivar_set(orig, id, ivar);
56 return ivar;
57 }
58 }
59}
60
62rb_struct_s_keyword_init(VALUE klass)
63{
64 return struct_ivar_get(klass, id_keyword_init);
65}
66
69{
70 VALUE members = struct_ivar_get(klass, id_members);
71
72 if (NIL_P(members)) {
73 rb_raise(rb_eTypeError, "uninitialized struct");
74 }
75 if (!RB_TYPE_P(members, T_ARRAY)) {
76 rb_raise(rb_eTypeError, "corrupted struct");
77 }
78 return members;
79}
80
83{
85
86 if (RSTRUCT_LEN_RAW(s) != RARRAY_LEN(members)) {
87 rb_raise(rb_eTypeError, "struct size differs (%"PRIdLEN" required %"PRIdLEN" given)",
88 RARRAY_LEN(members), RSTRUCT_LEN_RAW(s));
89 }
90 return members;
91}
92
93static rb_len_t
94struct_member_pos_ideal(VALUE name, rb_len_t mask)
95{
96 /* (id & (mask/2)) * 2 */
97 return (SYM2ID(name) >> (ID_SCOPE_SHIFT - 1)) & mask;
98}
99
100static rb_len_t
101struct_member_pos_probe(rb_len_t prev, rb_len_t mask)
102{
103 /* (((prev/2) * AREF_HASH_UNIT + 1) & (mask/2)) * 2 */
104 return (prev * AREF_HASH_UNIT + 2) & mask;
105}
106
107static VALUE
108struct_set_members(VALUE klass, VALUE /* frozen hidden array */ members)
109{
110 VALUE back;
111 const rb_len_t members_length = RARRAY_LEN(members);
112
113 if (members_length <= AREF_HASH_THRESHOLD) {
114 back = members;
115 }
116 else {
117 rb_len_t i, j, mask = 64;
118 VALUE name;
119
120 while (mask < members_length * AREF_HASH_UNIT) mask *= 2;
121
122 back = rb_ary_hidden_new(mask + 1);
123 rb_ary_store(back, mask, INT2FIX(members_length));
124 mask -= 2; /* mask = (2**k-1)*2 */
125
126 for (i=0; i < members_length; i++) {
127 name = RARRAY_AREF(members, i);
128
129 j = struct_member_pos_ideal(name, mask);
130
131 for (;;) {
132 if (!RTEST(RARRAY_AREF(back, j))) {
133 rb_ary_store(back, j, name);
134 rb_ary_store(back, j + 1, INT2FIX(i));
135 break;
136 }
137 j = struct_member_pos_probe(j, mask);
138 }
139 }
140 OBJ_FREEZE(back);
141 }
142 rb_ivar_set(klass, id_members, members);
143 rb_ivar_set(klass, id_back_members, back);
144
145 return members;
146}
147
148static inline int
149struct_member_pos(VALUE s, VALUE name)
150{
151 VALUE back = struct_ivar_get(rb_obj_class(s), id_back_members);
152 rb_len_t j, mask;
153
154 if (UNLIKELY(NIL_P(back))) {
155 rb_raise(rb_eTypeError, "uninitialized struct");
156 }
157 if (UNLIKELY(!RB_TYPE_P(back, T_ARRAY))) {
158 rb_raise(rb_eTypeError, "corrupted struct");
159 }
160
161 mask = RARRAY_LEN(back);
162
163 if (mask <= AREF_HASH_THRESHOLD) {
164 if (UNLIKELY(RSTRUCT_LEN_RAW(s) != mask)) {
165 rb_raise(rb_eTypeError,
166 "struct size differs (%"PRIdLEN" required %"PRIdLEN" given)",
167 mask, RSTRUCT_LEN_RAW(s));
168 }
169 for (j = 0; j < mask; j++) {
170 if (RARRAY_AREF(back, j) == name)
171 return (int)j;
172 }
173 return -1;
174 }
175
176 if (UNLIKELY(RSTRUCT_LEN_RAW(s) != FIX2INT(RARRAY_AREF(back, mask-1)))) {
177 rb_raise(rb_eTypeError, "struct size differs (%d required %"PRIdLEN" given)",
178 FIX2INT(RARRAY_AREF(back, mask-1)), RSTRUCT_LEN_RAW(s));
179 }
180
181 mask -= 3;
182 j = struct_member_pos_ideal(name, mask);
183
184 for (;;) {
185 VALUE e = RARRAY_AREF(back, j);
186 if (e == name)
187 return FIX2INT(RARRAY_AREF(back, j + 1));
188 if (!RTEST(e)) {
189 return -1;
190 }
191 j = struct_member_pos_probe(j, mask);
192 }
193}
194
195/*
196 * call-seq:
197 * StructClass::members -> array_of_symbols
198 *
199 * Returns the member names of the Struct descendant as an array:
200 *
201 * Customer = Struct.new(:name, :address, :zip)
202 * Customer.members # => [:name, :address, :zip]
203 *
204 */
205
206static VALUE
207rb_struct_s_members_m(VALUE klass)
208{
209 VALUE members = rb_struct_s_members(klass);
210
211 return rb_ary_dup(members);
212}
213
214/*
215 * call-seq:
216 * members -> array_of_symbols
217 *
218 * Returns the member names from +self+ as an array:
219 *
220 * Customer = Struct.new(:name, :address, :zip)
221 * Customer.new.members # => [:name, :address, :zip]
222 *
223 * Related: #to_a.
224 */
225
226static VALUE
227rb_struct_members_m(VALUE obj)
228{
229 return rb_struct_s_members_m(rb_obj_class(obj));
230}
231
232VALUE
234{
235 VALUE slot = ID2SYM(id);
236 int i = struct_member_pos(obj, slot);
237 if (i != -1) {
238 return RSTRUCT_GET_RAW(obj, i);
239 }
240 rb_name_err_raise("'%1$s' is not a struct member", obj, ID2SYM(id));
241
243}
244
245static void
246rb_struct_modify(VALUE s)
247{
248 rb_check_frozen(s);
249}
250
251static VALUE
252anonymous_struct(VALUE klass)
253{
254 VALUE nstr = rb_class_new(klass);
255 rb_make_metaclass(nstr, RBASIC(klass)->klass);
256 return nstr;
257}
258
259NORETURN(static void invalid_struct_pos(VALUE s, VALUE idx));
260
261static void
262define_aref_method(VALUE nstr, VALUE name, VALUE off)
263{
264 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_AREF, FIX2UINT(off), METHOD_VISI_PUBLIC);
265}
266
267void
268rb_struct_define_aref_method(VALUE nstr, ID name, unsigned int off)
269{
270 rb_add_method_optimized(nstr, name, OPTIMIZED_METHOD_TYPE_STRUCT_AREF, off, METHOD_VISI_PUBLIC);
271}
272
273static void
274define_aset_method(VALUE nstr, VALUE name, VALUE off)
275{
276 rb_add_method_optimized(nstr, SYM2ID(name), OPTIMIZED_METHOD_TYPE_STRUCT_ASET, FIX2UINT(off), METHOD_VISI_PUBLIC);
277}
278
279static VALUE
280rb_struct_s_inspect(VALUE klass)
281{
282 VALUE inspect = rb_class_name(klass);
283 if (RTEST(rb_struct_s_keyword_init(klass))) {
284 rb_str_cat_cstr(inspect, "(keyword_init: true)");
285 }
286 return inspect;
287}
288
289static VALUE rb_data_initialize_m(int argc, const VALUE *argv, VALUE self);
290
291// Given every member, Data#initialize can only store them and freeze the
292// instance: it raises nothing and calls no Ruby code. So when initialize is
293// that method, the members can be stored without calling it.
294static bool
295data_initialize_default_p(VALUE klass)
296{
297 const rb_callable_method_entry_t *cme = rb_callable_method_entry(klass, idInitialize);
298 return cme && cme->def->type == VM_METHOD_TYPE_CFUNC &&
299 cme->def->body.cfunc.func == (rb_cfunc_t)rb_data_initialize_m;
300}
301
302static VALUE
303rb_data_s_new(int argc, const VALUE *argv, VALUE klass)
304{
305 if (rb_keyword_given_p()) {
306 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
307 rb_error_arity(argc, 0, 0);
308 }
309 return rb_class_new_instance_pass_kw(argc, argv, klass);
310 }
311 else {
312 VALUE members = struct_ivar_get(klass, id_members);
313 int num_members = RARRAY_LENINT(members);
314
315 rb_check_arity(argc, 0, num_members);
316 if (argc == num_members && data_initialize_default_p(klass)) {
317 VALUE self = rb_obj_alloc(klass);
318 for (rb_len_t i=0; i<argc; i++) {
319 RSTRUCT_SET_RAW(self, i, argv[i]);
320 }
321 OBJ_FREEZE(self);
322 return self;
323 }
324 VALUE arg_hash = rb_hash_new_capa(argc);
325 for (rb_len_t i=0; i<argc; i++) {
326 VALUE k = rb_ary_entry(members, i), v = argv[i];
327 rb_hash_aset(arg_hash, k, v);
328 }
329 return rb_class_new_instance_kw(1, &arg_hash, klass, RB_PASS_KEYWORDS);
330 }
331}
332
333#if 0 /* for RDoc */
334
335/*
336 * call-seq:
337 * StructClass::keyword_init? -> true or falsy value
338 *
339 * Returns +true+ if the class was initialized with <tt>keyword_init: true</tt>.
340 * Otherwise returns +nil+ or +false+.
341 *
342 * Examples:
343 * Foo = Struct.new(:a)
344 * Foo.keyword_init? # => nil
345 * Bar = Struct.new(:a, keyword_init: true)
346 * Bar.keyword_init? # => true
347 * Baz = Struct.new(:a, keyword_init: false)
348 * Baz.keyword_init? # => false
349 */
350static VALUE
351rb_struct_s_keyword_init_p(VALUE obj)
352{
353}
354#endif
355
356#define rb_struct_s_keyword_init_p rb_struct_s_keyword_init
357
358static VALUE
359setup_struct(VALUE nstr, VALUE members)
360{
361 rb_len_t i, len;
362
363 members = struct_set_members(nstr, members);
364
365 rb_define_alloc_func(nstr, struct_alloc);
368 rb_define_singleton_method(nstr, "members", rb_struct_s_members_m, 0);
369 rb_define_singleton_method(nstr, "inspect", rb_struct_s_inspect, 0);
370 rb_define_singleton_method(nstr, "keyword_init?", rb_struct_s_keyword_init_p, 0);
371
372 len = RARRAY_LEN(members);
373 for (i=0; i< len; i++) {
374 VALUE sym = RARRAY_AREF(members, i);
375 ID id = SYM2ID(sym);
376 VALUE off = LEN2NUM(i);
377
378 define_aref_method(nstr, sym, off);
379 define_aset_method(nstr, ID2SYM(rb_id_attrset(id)), off);
380 }
381
382 return nstr;
383}
384
385static VALUE
386setup_data(VALUE subclass, VALUE members)
387{
388 rb_len_t i, len;
389
390 members = struct_set_members(subclass, members);
391
392 rb_define_alloc_func(subclass, struct_alloc);
393 VALUE sclass = rb_singleton_class(subclass);
394 rb_undef_method(sclass, "define");
395 rb_define_method(sclass, "new", rb_data_s_new, -1);
396 rb_define_method(sclass, "[]", rb_data_s_new, -1);
397 rb_define_method(sclass, "members", rb_struct_s_members_m, 0);
398 rb_define_method(sclass, "inspect", rb_struct_s_inspect, 0); // FIXME: just a separate method?..
399
400 len = RARRAY_LEN(members);
401 for (i=0; i< len; i++) {
402 VALUE sym = RARRAY_AREF(members, i);
403 VALUE off = LEN2NUM(i);
404
405 define_aref_method(subclass, sym, off);
406 }
407
408 return subclass;
409}
410
411VALUE
413{
414 return struct_alloc(klass);
415}
416
417static VALUE
418struct_make_members_list(va_list ar)
419{
420 char *mem;
421 VALUE ary, list = rb_ident_hash_new();
422 RBASIC_CLEAR_CLASS(list);
423 while ((mem = va_arg(ar, char*)) != 0) {
424 VALUE sym = rb_sym_intern_ascii_cstr(mem);
425 if (RTEST(rb_hash_has_key(list, sym))) {
426 rb_raise(rb_eArgError, "duplicate member: %s", mem);
427 }
428 rb_hash_aset(list, sym, Qtrue);
429 }
430 ary = rb_hash_keys(list);
431 RBASIC_CLEAR_CLASS(ary);
432 OBJ_FREEZE(ary);
433 return ary;
434}
435
436static void
437struct_register_under(VALUE outer, VALUE name, VALUE klass)
438{
439 if (!outer) outer = rb_cObject;
440
441 name = rb_str_to_str(name);
442
443 if (!rb_is_const_name(name)) {
444 rb_name_err_raise("identifier %1$s needs to be constant",
445 outer, name);
446 }
447
448 ID id = rb_to_id(name);
449 if (rb_const_defined_at(outer, id)) {
450 rb_warn("redefining constant %"PRIsVALUE"::%"PRIsVALUE, outer, name);
451 rb_mod_remove_const(outer, ID2SYM(id));
452 }
453
454 rb_set_class_path_string(klass, outer, name);
455 rb_const_set(outer, id, klass);
456}
457
458static VALUE
459struct_define_without_accessor(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, VALUE members)
460{
461 VALUE klass = anonymous_struct(super);
462 struct_set_members(klass, members);
463
464 if (alloc) {
465 rb_define_alloc_func(klass, alloc);
466 }
467 else {
468 rb_define_alloc_func(klass, struct_alloc);
469 }
470
471 if (class_name) {
472 VALUE name = rb_enc_interned_str_cstr(class_name, rb_usascii_encoding());
473 struct_register_under(outer, name, klass);
474 rb_vm_register_global_object(klass);
475 }
476
477 rb_class_inherited(super, klass);
478
479 return klass;
480}
481
482VALUE
483rb_struct_define_without_accessor_under(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
484{
485 va_list ar;
486 VALUE members;
487
488 va_start(ar, alloc);
489 members = struct_make_members_list(ar);
490 va_end(ar);
491
492 return struct_define_without_accessor(outer, class_name, super, alloc, members);
493}
494
495VALUE
496rb_struct_define_without_accessor(const char *class_name, VALUE super, rb_alloc_func_t alloc, ...)
497{
498 va_list ar;
499 VALUE members;
500
501 va_start(ar, alloc);
502 members = struct_make_members_list(ar);
503 va_end(ar);
504
505 return struct_define_without_accessor(0, class_name, super, alloc, members);
506}
507
508VALUE
509rb_struct_define(const char *class_name, ...)
510{
511 va_list ar;
512
513 va_start(ar, class_name);
514 VALUE ary = struct_make_members_list(ar);
515 va_end(ar);
516
517 VALUE klass = anonymous_struct(rb_cStruct);
518 setup_struct(klass, ary);
519
520 if (class_name) {
521 VALUE name = rb_enc_interned_str_cstr(class_name, rb_usascii_encoding());
522 struct_register_under(rb_cStruct, name, klass);
523 rb_vm_register_global_object(klass);
524 }
525
527
528 return klass;
529}
530
531VALUE
532rb_struct_define_under(VALUE outer, const char *name, ...)
533{
534 va_list ar;
535 VALUE ary;
536
537 va_start(ar, name);
538 ary = struct_make_members_list(ar);
539 va_end(ar);
540
541 return setup_struct(rb_define_class_id_under(outer, rb_intern(name), rb_cStruct), ary);
542}
543
544/*
545 * call-seq:
546 * Struct.new(*member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
547 * Struct.new(class_name, *member_names, keyword_init: nil){|Struct_subclass| ... } -> Struct_subclass
548 * Struct_subclass.new(*member_names) -> Struct_subclass_instance
549 * Struct_subclass.new(**member_names) -> Struct_subclass_instance
550 *
551 * <tt>Struct.new</tt> returns a new subclass of +Struct+. The new subclass:
552 *
553 * - May be anonymous, or may have the name given by +class_name+.
554 * - May have members as given by +member_names+.
555 * - May have initialization via ordinary arguments, or via keyword arguments
556 *
557 * The new subclass has its own method <tt>::new</tt>; thus:
558 *
559 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
560 * f = Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
561 *
562 * <b>Class Name</b>
563 *
564 * With string argument +class_name+,
565 * returns a new subclass of +Struct+ named <tt>Struct::<em>class_name</em></tt>:
566 *
567 * Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo
568 * Foo.name # => "Struct::Foo"
569 * Foo.superclass # => Struct
570 *
571 * Without string argument +class_name+,
572 * returns a new anonymous subclass of +Struct+:
573 *
574 * Struct.new(:foo, :bar).name # => nil
575 *
576 * <b>Block</b>
577 *
578 * With a block given, the created subclass is yielded to the block:
579 *
580 * Customer = Struct.new('Customer', :name, :address) do |new_class|
581 * p "The new subclass is #{new_class}"
582 * def greeting
583 * "Hello #{name} at #{address}"
584 * end
585 * end # => Struct::Customer
586 * dave = Customer.new('Dave', '123 Main')
587 * dave # => #<struct Struct::Customer name="Dave", address="123 Main">
588 * dave.greeting # => "Hello Dave at 123 Main"
589 *
590 * Output, from <tt>Struct.new</tt>:
591 *
592 * "The new subclass is Struct::Customer"
593 *
594 * <b>Member Names</b>
595 *
596 * Symbol arguments +member_names+
597 * determines the members of the new subclass:
598 *
599 * Struct.new(:foo, :bar).members # => [:foo, :bar]
600 * Struct.new('Foo', :foo, :bar).members # => [:foo, :bar]
601 *
602 * The new subclass has instance methods corresponding to +member_names+:
603 *
604 * Foo = Struct.new('Foo', :foo, :bar)
605 * Foo.instance_methods(false) # => [:foo, :bar, :foo=, :bar=]
606 * f = Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
607 * f.foo # => nil
608 * f.foo = 0 # => 0
609 * f.bar # => nil
610 * f.bar = 1 # => 1
611 * f # => #<struct Struct::Foo foo=0, bar=1>
612 *
613 * <b>Singleton Methods</b>
614 *
615 * A subclass returned by Struct.new has these singleton methods:
616 *
617 * - Method <tt>::new </tt> creates an instance of the subclass:
618 *
619 * Foo.new # => #<struct Struct::Foo foo=nil, bar=nil>
620 * Foo.new(0) # => #<struct Struct::Foo foo=0, bar=nil>
621 * Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
622 * Foo.new(0, 1, 2) # Raises ArgumentError: struct size differs
623 *
624 * # Initialization with keyword arguments:
625 * Foo.new(foo: 0) # => #<struct Struct::Foo foo=0, bar=nil>
626 * Foo.new(foo: 0, bar: 1) # => #<struct Struct::Foo foo=0, bar=1>
627 * Foo.new(foo: 0, bar: 1, baz: 2)
628 * # Raises ArgumentError: unknown keywords: baz
629 *
630 * - Method <tt>:inspect</tt> returns a string representation of the subclass:
631 *
632 * Foo.inspect
633 * # => "Struct::Foo"
634 *
635 * - Method <tt>::members</tt> returns an array of the member names:
636 *
637 * Foo.members # => [:foo, :bar]
638 *
639 * <b>Keyword Argument</b>
640 *
641 * By default, the arguments for initializing an instance of the new subclass
642 * can be both positional and keyword arguments.
643 *
644 * Optional keyword argument <tt>keyword_init:</tt> allows to force only one
645 * type of arguments to be accepted:
646 *
647 * KeywordsOnly = Struct.new(:foo, :bar, keyword_init: true)
648 * KeywordsOnly.new(bar: 1, foo: 0)
649 * # => #<struct KeywordsOnly foo=0, bar=1>
650 * KeywordsOnly.new(0, 1)
651 * # Raises ArgumentError: wrong number of arguments
652 *
653 * PositionalOnly = Struct.new(:foo, :bar, keyword_init: false)
654 * PositionalOnly.new(0, 1)
655 * # => #<struct PositionalOnly foo=0, bar=1>
656 * PositionalOnly.new(bar: 1, foo: 0)
657 * # => #<struct PositionalOnly foo={foo: 1, bar: 2}, bar=nil>
658 * # Note that no error is raised, but arguments treated as one hash value
659 *
660 * # Same as not providing keyword_init:
661 * Any = Struct.new(:foo, :bar, keyword_init: nil)
662 * Any.new(foo: 1, bar: 2)
663 * # => #<struct Any foo=1, bar=2>
664 * Any.new(1, 2)
665 * # => #<struct Any foo=1, bar=2>
666 */
667
668static VALUE
669rb_struct_s_def(int argc, VALUE *argv, VALUE super)
670{
671 VALUE name = Qnil, keyword_init = Qnil;
672 VALUE opt;
673
674 argc = rb_scan_args(argc, argv, "0*:", NULL, &opt);
675 if (argc >= 1 && !SYMBOL_P(argv[0])) {
676 name = argv[0];
677 --argc;
678 ++argv;
679 }
680
681 if (!NIL_P(opt)) {
682 static ID keyword_ids[1];
683
684 if (!keyword_ids[0]) {
685 keyword_ids[0] = rb_intern("keyword_init");
686 }
687 rb_get_kwargs(opt, keyword_ids, 0, 1, &keyword_init);
688 if (UNDEF_P(keyword_init)) {
689 keyword_init = Qnil;
690 }
691 else if (RTEST(keyword_init)) {
692 keyword_init = Qtrue;
693 }
694 }
695
696 VALUE rest = rb_ident_hash_new();
697 RBASIC_CLEAR_CLASS(rest);
698 for (int i = 0; i < argc; i++) {
699 VALUE mem = rb_to_symbol(argv[i]);
700 if (rb_is_attrset_sym(mem)) {
701 rb_raise(rb_eArgError, "invalid struct member: %"PRIsVALUE, mem);
702 }
703 if (RTEST(rb_hash_has_key(rest, mem))) {
704 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
705 }
706 rb_hash_aset(rest, mem, Qtrue);
707 }
708 rest = rb_hash_keys(rest);
709 RBASIC_CLEAR_CLASS(rest);
710 OBJ_FREEZE(rest);
711
712 VALUE klass = anonymous_struct(super);
713 setup_struct(klass, rest);
714 rb_ivar_set(klass, id_keyword_init, keyword_init);
715
716 if (!NIL_P(name)) {
717 struct_register_under(super, rb_str_to_str(name), klass);
718 }
719
720 rb_class_inherited(super, klass);
721
722 if (rb_block_given_p()) {
723 rb_mod_module_eval(0, 0, klass);
724 }
725
726 return klass;
727}
728
729static rb_len_t
730num_members(VALUE klass)
731{
732 VALUE members;
733 members = struct_ivar_get(klass, id_members);
734 if (!RB_TYPE_P(members, T_ARRAY)) {
735 rb_bug("broken members"); /* should never happen */
736 }
737 return RARRAY_LEN(members);
738}
739
741rb_zjit_struct_num_members(VALUE klass)
742{
743 return num_members(klass);
744}
745
746/*
747 */
748
750 VALUE self;
751 VALUE unknown_keywords;
752 bool *found; // Data#initialize: which members were given
753 rb_len_t missing_count;
754};
755
756static int rb_struct_pos(VALUE s, VALUE *name, bool name_only);
757static VALUE deconstruct_keys(VALUE s, VALUE keys, bool name_only);
758static int rb_struct_pos(VALUE s, VALUE *name, bool name_only);
759
760static int
761struct_hash_aset(VALUE key, VALUE val, struct struct_hash_set_arg *args, bool name_only)
762{
763 int i = rb_struct_pos(args->self, &key, name_only);
764 if (i < 0) {
765 if (!args->unknown_keywords) {
766 args->unknown_keywords = rb_ary_new();
767 }
768 rb_ary_push(args->unknown_keywords, key);
769 }
770 else {
771 rb_struct_modify(args->self);
772 RSTRUCT_SET_RAW(args->self, i, val);
773 }
774 return i;
775}
776
777static int
778struct_hash_set_i(VALUE key, VALUE val, VALUE arg)
779{
780 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
781 struct_hash_aset(key, val, args, false);
782 return ST_CONTINUE;
783}
784
785static VALUE
786rb_struct_initialize_m(int argc, const VALUE *argv, VALUE self)
787{
788 VALUE klass = rb_obj_class(self);
789 rb_struct_modify(self);
790 rb_len_t n = RSTRUCT_LEN_RAW(self);
791 if (argc == 0) {
792 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
793 return Qnil;
794 }
795
796 bool keyword_init = false;
797 switch (rb_struct_s_keyword_init(klass)) {
798 default:
799 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
800 rb_error_arity(argc, 0, 0);
801 }
802 keyword_init = true;
803 break;
804 case Qfalse:
805 break;
806 case Qnil:
807 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
808 break;
809 }
810 keyword_init = rb_keyword_given_p();
811 break;
812 }
813 if (keyword_init) {
814 struct struct_hash_set_arg arg = {
815 .self = self,
816 };
817 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), n);
818 rb_hash_foreach(argv[0], struct_hash_set_i, (VALUE)&arg);
819 if (UNLIKELY(arg.unknown_keywords)) {
820 rb_raise(rb_eArgError, "unknown keywords: %"PRIsVALUE,
821 rb_ary_join(arg.unknown_keywords, rb_str_new2(", ")));
822 }
823 }
824 else {
825 if (n < argc) {
826 rb_raise(rb_eArgError, "struct size differs");
827 }
828 for (rb_len_t i=0; i<argc; i++) {
829 RSTRUCT_SET_RAW(self, i, argv[i]);
830 }
831 if (n > argc) {
832 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self)+argc, n-argc);
833 }
834 }
835 return Qnil;
836}
837
838VALUE
840{
841 rb_struct_initialize_m(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), self);
842 if (rb_obj_is_kind_of(self, rb_cData)) OBJ_FREEZE(self);
843 RB_GC_GUARD(values);
844 return Qnil;
845}
846
847static VALUE *
848struct_heap_alloc(VALUE st, size_t len)
849{
850 return ALLOC_N(VALUE, len);
851}
852
853STATIC_ASSERT(robject_rstruct_fields_offset, offsetof(struct RObject, as.extended) == offsetof(struct RStruct, fields_obj));
854
855static inline bool
856struct_embedded_p(rb_len_t n)
857{
858 size_t embedded_size = offsetof(struct RStruct, as.ary) + (sizeof(VALUE) * n);
859 const rb_len_t embed_len_max = RSTRUCT_EMBED_LEN_MASK >> RSTRUCT_EMBED_LEN_SHIFT;
860 return n > 0 && n <= embed_len_max && rb_gc_size_allocatable_p(embedded_size);
861}
862
863bool
864rb_zjit_struct_embedded_p(rb_len_t num_members)
865{
866 return struct_embedded_p(num_members);
867}
868
869static VALUE
870struct_alloc(VALUE klass)
871{
872 rb_len_t n = num_members(klass);
873 size_t embedded_size = offsetof(struct RStruct, as.ary) + (sizeof(VALUE) * n);
874 VALUE flags = T_STRUCT;
875
876 if (struct_embedded_p(n)) {
877 flags |= n << RSTRUCT_EMBED_LEN_SHIFT;
878
879 VALUE st = rb_newobj(GET_EC(), klass, flags, ROOT_SHAPE_ID | SHAPE_ID_LAYOUT_EXTENDED, true, embedded_size);
880 RSTRUCT_SET_FIELDS_OBJ(st, 0);
881 rb_mem_clear((VALUE *)RSTRUCT(st)->as.ary, n);
882
883 return st;
884 }
885 else {
886 VALUE obj = rb_newobj(GET_EC(), klass, flags, ROOT_SHAPE_ID | SHAPE_ID_LAYOUT_EXTENDED, true, sizeof(struct RStruct));
887 struct RStruct *st = RSTRUCT(obj);
888
889 st->fields_obj = 0;
890 st->as.heap.ptr = NULL;
891 st->as.heap.len = 0;
892
893 st->as.heap.ptr = struct_heap_alloc((VALUE)st, n);
894 rb_mem_clear((VALUE *)st->as.heap.ptr, n);
895 st->as.heap.len = n;
896
897 return obj;
898 }
899}
900
901// Whether `klass` allocates its instances with struct_alloc.
902bool
903rb_zjit_class_has_struct_allocator(VALUE klass)
904{
905 return rb_get_alloc_func(klass) == struct_alloc;
906}
907
908// The ID of the `index`th member of the Struct class `klass`. `index` must be in bounds
909// according to rb_zjit_struct_num_members().
910ID
911rb_zjit_struct_member_id(VALUE klass, rb_len_t index)
912{
913 VALUE members = struct_ivar_get(klass, id_members);
914 RUBY_ASSERT(RB_TYPE_P(members, T_ARRAY));
915 RUBY_ASSERT(index >= 0 && index < RARRAY_LEN(members));
916 return SYM2ID(RARRAY_AREF(members, index));
917}
918
919VALUE
921{
922 return rb_class_new_instance(RARRAY_LENINT(values), RARRAY_CONST_PTR(values), klass);
923}
924
925VALUE
927{
928 VALUE tmpargs[16], *mem = tmpargs;
929 int size, i;
930 va_list args;
931
932 size = rb_len2int(num_members(klass));
933 if (size > numberof(tmpargs)) {
934 tmpargs[0] = rb_ary_hidden_new(size);
935 mem = RARRAY_PTR(tmpargs[0]);
936 }
937 va_start(args, klass);
938 for (i=0; i<size; i++) {
939 mem[i] = va_arg(args, VALUE);
940 }
941 va_end(args);
942
943 return rb_class_new_instance(size, mem, klass);
944}
945
946static VALUE
947struct_enum_size(VALUE s, VALUE args, VALUE eobj)
948{
949 return rb_struct_size(s);
950}
951
952/*
953 * call-seq:
954 * each {|value| ... } -> self
955 * each -> enumerator
956 *
957 * Calls the given block with the value of each member; returns +self+:
958 *
959 * Customer = Struct.new(:name, :address, :zip)
960 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
961 * joe.each {|value| p value }
962 *
963 * Output:
964 *
965 * "Joe Smith"
966 * "123 Maple, Anytown NC"
967 * 12345
968 *
969 * Returns an Enumerator if no block is given.
970 *
971 * Related: #each_pair.
972 */
973
974static VALUE
975rb_struct_each(VALUE s)
976{
977 rb_len_t i;
978
979 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
980 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
981 rb_yield(RSTRUCT_GET_RAW(s, i));
982 }
983 return s;
984}
985
986/*
987 * call-seq:
988 * each_pair {|(name, value)| ... } -> self
989 * each_pair -> enumerator
990 *
991 * Calls the given block with each member name/value pair; returns +self+:
992 *
993 * Customer = Struct.new(:name, :address, :zip) # => Customer
994 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
995 * joe.each_pair {|(name, value)| p "#{name} => #{value}" }
996 *
997 * Output:
998 *
999 * "name => Joe Smith"
1000 * "address => 123 Maple, Anytown NC"
1001 * "zip => 12345"
1002 *
1003 * Returns an Enumerator if no block is given.
1004 *
1005 * Related: #each.
1006 *
1007 */
1008
1009static VALUE
1010rb_struct_each_pair(VALUE s)
1011{
1012 VALUE members;
1013 rb_len_t i;
1014
1015 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
1016 members = rb_struct_members(s);
1017 if (rb_block_pair_yield_optimizable()) {
1018 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
1019 VALUE key = rb_ary_entry(members, i);
1020 VALUE value = RSTRUCT_GET_RAW(s, i);
1021 rb_yield_values(2, key, value);
1022 }
1023 }
1024 else {
1025 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
1026 VALUE key = rb_ary_entry(members, i);
1027 VALUE value = RSTRUCT_GET_RAW(s, i);
1028 rb_yield(rb_assoc_new(key, value));
1029 }
1030 }
1031 return s;
1032}
1033
1034static VALUE
1035inspect_struct(VALUE s, VALUE prefix, int recur)
1036{
1037 VALUE cname = rb_class_path(rb_obj_class(s));
1038 VALUE members;
1039 VALUE str = prefix;
1040 rb_len_t i, len;
1041 char first = RSTRING_PTR(cname)[0];
1042
1043 if (recur || first != '#') {
1044 rb_str_cat2(str, " ");
1045 rb_str_append(str, cname);
1046 }
1047 if (recur) {
1048 return rb_str_cat2(str, ":...>");
1049 }
1050
1051 members = rb_struct_members(s);
1052 len = RSTRUCT_LEN_RAW(s);
1053
1054 for (i=0; i<len; i++) {
1055 VALUE slot;
1056 ID id;
1057
1058 if (i > 0) {
1059 rb_str_cat2(str, ", ");
1060 }
1061 else {
1062 rb_str_cat2(str, " ");
1063 }
1064 slot = RARRAY_AREF(members, i);
1065 id = SYM2ID(slot);
1066 if (rb_is_local_id(id) || rb_is_const_id(id)) {
1067 rb_str_append(str, rb_sym2str(slot));
1068 }
1069 else {
1070 rb_str_append(str, rb_inspect(slot));
1071 }
1072 rb_str_cat2(str, "=");
1073 rb_str_append(str, rb_inspect(RSTRUCT_GET_RAW(s, i)));
1074 }
1075 rb_str_cat2(str, ">");
1076
1077 return str;
1078}
1079
1080/*
1081 * call-seq:
1082 * inspect -> string
1083 *
1084 * Returns a string representation of +self+:
1085 *
1086 * Customer = Struct.new(:name, :address, :zip) # => Customer
1087 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1088 * joe.inspect # => "#<struct Customer name=\"Joe Smith\", address=\"123 Maple, Anytown NC\", zip=12345>"
1089 *
1090 */
1091
1092static VALUE
1093rb_struct_inspect(VALUE s)
1094{
1095 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<struct"));
1096}
1097
1098/*
1099 * call-seq:
1100 * to_a -> array
1101 *
1102 * Returns the values in +self+ as an array:
1103 *
1104 * Customer = Struct.new(:name, :address, :zip)
1105 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1106 * joe.to_a # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1107 *
1108 * Related: #members.
1109 */
1110
1111static VALUE
1112rb_struct_to_a(VALUE s)
1113{
1114 return rb_ary_new4(RSTRUCT_LEN_RAW(s), RSTRUCT_CONST_PTR(s));
1115}
1116
1117/*
1118 * call-seq:
1119 * to_h -> hash
1120 * to_h {|name, value| ... } -> hash
1121 *
1122 * Returns a hash containing the name and value for each member:
1123 *
1124 * Customer = Struct.new(:name, :address, :zip)
1125 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1126 * h = joe.to_h
1127 * h # => {name: "Joe Smith", address: "123 Maple, Anytown NC", zip: 12345}
1128 *
1129 * If a block is given, it is called with each name/value pair;
1130 * the block should return a 2-element array whose elements will become
1131 * a key/value pair in the returned hash:
1132 *
1133 * h = joe.to_h{|name, value| [name.upcase, value.to_s.upcase]}
1134 * h # => {NAME: "JOE SMITH", ADDRESS: "123 MAPLE, ANYTOWN NC", ZIP: "12345"}
1135 *
1136 * Raises ArgumentError if the block returns an inappropriate value.
1137 *
1138 */
1139
1140static VALUE
1141rb_struct_to_h(VALUE s)
1142{
1143 VALUE h = rb_hash_new_capa(RSTRUCT_LEN_RAW(s));
1144 VALUE members = rb_struct_members(s);
1145 rb_len_t i;
1146 int block_given = rb_block_given_p();
1147
1148 for (i=0; i<RSTRUCT_LEN_RAW(s); i++) {
1149 VALUE k = rb_ary_entry(members, i), v = RSTRUCT_GET_RAW(s, i);
1150 if (block_given)
1151 rb_hash_set_pair(h, rb_yield_values(2, k, v));
1152 else
1153 rb_hash_aset(h, k, v);
1154 }
1155 return h;
1156}
1157
1158/*
1159 * call-seq:
1160 * deconstruct_keys(array_of_names) -> hash
1161 *
1162 * Returns a hash of the name/value pairs for the given member names.
1163 *
1164 * Customer = Struct.new(:name, :address, :zip)
1165 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1166 * h = joe.deconstruct_keys([:zip, :address])
1167 * h # => {zip: 12345, address: "123 Maple, Anytown NC"}
1168 *
1169 * Returns all names and values if +array_of_names+ is +nil+:
1170 *
1171 * h = joe.deconstruct_keys(nil)
1172 * h # => {name: "Joseph Smith, Jr.", address: "123 Maple, Anytown NC", zip: 12345}
1173 *
1174 */
1175static VALUE
1176rb_struct_deconstruct_keys(VALUE s, VALUE keys)
1177{
1178 return deconstruct_keys(s, keys, false);
1179}
1180
1181static VALUE
1182deconstruct_keys(VALUE s, VALUE keys, bool name_only)
1183{
1184 VALUE h;
1185 rb_len_t i;
1186
1187 if (NIL_P(keys)) {
1188 return rb_struct_to_h(s);
1189 }
1190 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
1191 rb_raise(rb_eTypeError,
1192 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
1193 rb_obj_class(keys));
1194
1195 }
1196 if (RSTRUCT_LEN_RAW(s) < RARRAY_LEN(keys)) {
1197 return rb_hash_new();
1198 }
1199 h = rb_hash_new_capa(RARRAY_LEN(keys));
1200 for (i=0; i<RARRAY_LEN(keys); i++) {
1201 VALUE key = RARRAY_AREF(keys, i);
1202 int i = rb_struct_pos(s, &key, name_only);
1203 if (i < 0) {
1204 return h;
1205 }
1206 rb_hash_aset(h, key, RSTRUCT_GET_RAW(s, i));
1207 }
1208 return h;
1209}
1210
1211/* :nodoc: */
1212VALUE
1213rb_struct_init_copy(VALUE copy, VALUE s)
1214{
1215 rb_len_t i, len;
1216
1217 if (!OBJ_INIT_COPY(copy, s)) return copy;
1218 if (RSTRUCT_LEN_RAW(copy) != RSTRUCT_LEN_RAW(s)) {
1219 rb_raise(rb_eTypeError, "struct size mismatch");
1220 }
1221
1222 for (i=0, len=RSTRUCT_LEN_RAW(copy); i<len; i++) {
1223 RSTRUCT_SET_RAW(copy, i, RSTRUCT_GET_RAW(s, i));
1224 }
1225
1226 return copy;
1227}
1228
1229static int
1230rb_struct_pos(VALUE s, VALUE *name, bool name_only)
1231{
1232 rb_len_t i;
1233 VALUE idx = *name;
1234
1235 if (SYMBOL_P(idx)) {
1236 return struct_member_pos(s, idx);
1237 }
1238 else if (name_only || RB_TYPE_P(idx, T_STRING)) {
1239 idx = rb_check_symbol(name);
1240 if (NIL_P(idx)) return -1;
1241 return struct_member_pos(s, idx);
1242 }
1243 else {
1244 rb_len_t len;
1245 i = NUM2LEN(idx);
1246 len = RSTRUCT_LEN_RAW(s);
1247 if (i < 0) {
1248 if (i + len < 0) {
1249 *name = LEN2NUM(i);
1250 return -1;
1251 }
1252 i += len;
1253 }
1254 else if (len <= i) {
1255 *name = LEN2NUM(i);
1256 return -1;
1257 }
1258 return (int)i;
1259 }
1260}
1261
1262static void
1263invalid_struct_pos(VALUE s, VALUE idx)
1264{
1265 if (RB_INTEGER_TYPE_P(idx)) {
1266 rb_len_t i = NUM2LEN(idx), len = RSTRUCT_LEN_RAW(s);
1267 if (i < 0) {
1268 rb_raise(rb_eIndexError, "offset %"PRIdLEN" too small for struct(size:%"PRIdLEN")",
1269 i, len);
1270 }
1271 else {
1272 rb_raise(rb_eIndexError, "offset %"PRIdLEN" too large for struct(size:%"PRIdLEN")",
1273 i, len);
1274 }
1275 }
1276 else {
1277 rb_name_err_raise("no member '%1$s' in struct", s, idx);
1278 }
1279}
1280
1281/*
1282 * call-seq:
1283 * struct[name] -> object
1284 * struct[n] -> object
1285 *
1286 * Returns a value from +self+.
1287 *
1288 * With symbol or string argument +name+ given, returns the value for the named member:
1289 *
1290 * Customer = Struct.new(:name, :address, :zip)
1291 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1292 * joe[:zip] # => 12345
1293 *
1294 * Raises NameError if +name+ is not the name of a member.
1295 *
1296 * With integer argument +n+ given, returns <tt>self.values[n]</tt>
1297 * if +n+ is in range;
1298 * see Array@Array+Indexes:
1299 *
1300 * joe[2] # => 12345
1301 * joe[-2] # => "123 Maple, Anytown NC"
1302 *
1303 * Raises IndexError if +n+ is out of range.
1304 *
1305 */
1306
1307VALUE
1309{
1310 int i = rb_struct_pos(s, &idx, false);
1311 if (i < 0) invalid_struct_pos(s, idx);
1312 return RSTRUCT_GET_RAW(s, i);
1313}
1314
1315/*
1316 * call-seq:
1317 * struct[name] = value -> value
1318 * struct[n] = value -> value
1319 *
1320 * Assigns a value to a member.
1321 *
1322 * With symbol or string argument +name+ given, assigns the given +value+
1323 * to the named member; returns +value+:
1324 *
1325 * Customer = Struct.new(:name, :address, :zip)
1326 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1327 * joe[:zip] = 54321 # => 54321
1328 * joe # => #<struct Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=54321>
1329 *
1330 * Raises NameError if +name+ is not the name of a member.
1331 *
1332 * With integer argument +n+ given, assigns the given +value+
1333 * to the +n+-th member if +n+ is in range;
1334 * see Array@Array+Indexes:
1335 *
1336 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1337 * joe[2] = 54321 # => 54321
1338 * joe[-3] = 'Joseph Smith' # => "Joseph Smith"
1339 * joe # => #<struct Customer name="Joseph Smith", address="123 Maple, Anytown NC", zip=54321>
1340 *
1341 * Raises IndexError if +n+ is out of range.
1342 *
1343 */
1344
1345VALUE
1347{
1348 int i = rb_struct_pos(s, &idx, false);
1349 if (i < 0) invalid_struct_pos(s, idx);
1350 rb_struct_modify(s);
1351 RSTRUCT_SET_RAW(s, i, val);
1352 return val;
1353}
1354
1355FUNC_MINIMIZED(VALUE rb_struct_lookup(VALUE s, VALUE idx));
1356NOINLINE(static VALUE rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound, bool name_only));
1357
1358VALUE
1359rb_struct_lookup(VALUE s, VALUE idx)
1360{
1361 return rb_struct_lookup_default(s, idx, Qnil, false);
1362}
1363
1364static VALUE
1365rb_struct_lookup_default(VALUE s, VALUE idx, VALUE notfound, bool name_only)
1366{
1367 int i = rb_struct_pos(s, &idx, name_only);
1368 if (i < 0) return notfound;
1369 return RSTRUCT_GET_RAW(s, i);
1370}
1371
1372static VALUE
1373struct_entry(VALUE s, rb_len_t n)
1374{
1375 return rb_struct_aref(s, LEN2NUM(n));
1376}
1377
1378/*
1379 * call-seq:
1380 * values_at(*integers) -> array
1381 * values_at(integer_range) -> array
1382 *
1383 * Returns an array of values from +self+.
1384 *
1385 * With integer arguments +integers+ given,
1386 * returns an array containing each value given by one of +integers+:
1387 *
1388 * Customer = Struct.new(:name, :address, :zip)
1389 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1390 * joe.values_at(0, 2) # => ["Joe Smith", 12345]
1391 * joe.values_at(2, 0) # => [12345, "Joe Smith"]
1392 * joe.values_at(2, 1, 0) # => [12345, "123 Maple, Anytown NC", "Joe Smith"]
1393 * joe.values_at(0, -3) # => ["Joe Smith", "Joe Smith"]
1394 *
1395 * Raises IndexError if any of +integers+ is out of range;
1396 * see Array@Array+Indexes.
1397 *
1398 * With integer range argument +integer_range+ given,
1399 * returns an array containing each value given by the elements of the range;
1400 * fills with +nil+ values for range elements larger than the structure:
1401 *
1402 * joe.values_at(0..2)
1403 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1404 * joe.values_at(-3..-1)
1405 * # => ["Joe Smith", "123 Maple, Anytown NC", 12345]
1406 * joe.values_at(1..4) # => ["123 Maple, Anytown NC", 12345, nil, nil]
1407 *
1408 * Raises RangeError if any element of the range is negative and out of range;
1409 * see Array@Array+Indexes.
1410 *
1411 */
1412
1413static VALUE
1414rb_struct_values_at(int argc, VALUE *argv, VALUE s)
1415{
1416 return rb_get_values_at(s, RSTRUCT_LEN_RAW(s), argc, argv, struct_entry);
1417}
1418
1419/*
1420 * call-seq:
1421 * select {|value| ... } -> array
1422 * select -> enumerator
1423 *
1424 * With a block given, returns an array of values from +self+
1425 * for which the block returns a truthy value:
1426 *
1427 * Customer = Struct.new(:name, :address, :zip)
1428 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1429 * a = joe.select {|value| value.is_a?(String) }
1430 * a # => ["Joe Smith", "123 Maple, Anytown NC"]
1431 * a = joe.select {|value| value.is_a?(Integer) }
1432 * a # => [12345]
1433 *
1434 * With no block given, returns an Enumerator.
1435 */
1436
1437static VALUE
1438rb_struct_select(int argc, VALUE *argv, VALUE s)
1439{
1440 VALUE result;
1441 rb_len_t i;
1442
1443 rb_check_arity(argc, 0, 0);
1444 RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size);
1445 result = rb_ary_new();
1446 for (i = 0; i < RSTRUCT_LEN_RAW(s); i++) {
1447 if (RTEST(rb_yield(RSTRUCT_GET_RAW(s, i)))) {
1448 rb_ary_push(result, RSTRUCT_GET_RAW(s, i));
1449 }
1450 }
1451
1452 return result;
1453}
1454
1455static VALUE
1456recursive_equal(VALUE s, VALUE s2, int recur)
1457{
1458 rb_len_t i, len;
1459
1460 if (recur) return Qtrue; /* Subtle! */
1461 len = RSTRUCT_LEN_RAW(s);
1462 for (i=0; i<len; i++) {
1463 if (!rb_equal(RSTRUCT_GET_RAW(s, i), RSTRUCT_GET_RAW(s2, i))) return Qfalse;
1464 }
1465 return Qtrue;
1466}
1467
1468
1469/*
1470 * call-seq:
1471 * self == other -> true or false
1472 *
1473 * Returns whether both the following are true:
1474 *
1475 * - <tt>other.class == self.class</tt>.
1476 * - For each member name +name+, <tt>other.name == self.name</tt>.
1477 *
1478 * Examples:
1479 *
1480 * Customer = Struct.new(:name, :address, :zip)
1481 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1482 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1483 * joe_jr == joe # => true
1484 * joe_jr[:name] = 'Joe Smith, Jr.'
1485 * # => "Joe Smith, Jr."
1486 * joe_jr == joe # => false
1487 */
1488
1489static VALUE
1490rb_struct_equal(VALUE s, VALUE s2)
1491{
1492 if (s == s2) return Qtrue;
1493 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1494 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1495 if (RSTRUCT_LEN_RAW(s) != RSTRUCT_LEN_RAW(s2)) {
1496 rb_bug("inconsistent struct"); /* should never happen */
1497 }
1498
1499 return rb_exec_recursive_paired(recursive_equal, s, s2, s2);
1500}
1501
1502/*
1503 * call-seq:
1504 * hash -> integer
1505 *
1506 * Returns the integer hash value for +self+.
1507 *
1508 * Two structs of the same class and with the same content
1509 * will have the same hash code (and will compare using Struct#eql?):
1510 *
1511 * Customer = Struct.new(:name, :address, :zip)
1512 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1513 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1514 * joe.hash == joe_jr.hash # => true
1515 * joe_jr[:name] = 'Joe Smith, Jr.'
1516 * joe.hash == joe_jr.hash # => false
1517 *
1518 * Related: Object#hash.
1519 */
1520
1521static VALUE
1522rb_struct_hash(VALUE s)
1523{
1524 rb_len_t i, len;
1525 st_index_t h;
1526 VALUE n;
1527
1528 h = rb_hash_start(rb_hash(rb_obj_class(s)));
1529 len = RSTRUCT_LEN_RAW(s);
1530 for (i = 0; i < len; i++) {
1531 n = rb_hash(RSTRUCT_GET_RAW(s, i));
1532 h = rb_hash_uint(h, NUM2LONG(n));
1533 }
1534 h = rb_hash_end(h);
1535 return ST2FIX(h);
1536}
1537
1538static VALUE
1539recursive_eql(VALUE s, VALUE s2, int recur)
1540{
1541 rb_len_t i, len;
1542
1543 if (recur) return Qtrue; /* Subtle! */
1544 len = RSTRUCT_LEN_RAW(s);
1545 for (i=0; i<len; i++) {
1546 if (!rb_eql(RSTRUCT_GET_RAW(s, i), RSTRUCT_GET_RAW(s2, i))) return Qfalse;
1547 }
1548 return Qtrue;
1549}
1550
1551/*
1552 * call-seq:
1553 * eql?(other) -> true or false
1554 *
1555 * Returns +true+ if and only if the following are true; otherwise returns +false+:
1556 *
1557 * - <tt>other.class == self.class</tt>.
1558 * - For each member name +name+, <tt>other.name.eql?(self.name)</tt>.
1559 *
1560 * Customer = Struct.new(:name, :address, :zip)
1561 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1562 * joe_jr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1563 * joe_jr.eql?(joe) # => true
1564 * joe_jr[:name] = 'Joe Smith, Jr.'
1565 * joe_jr.eql?(joe) # => false
1566 *
1567 * Related: Object#==.
1568 */
1569
1570static VALUE
1571rb_struct_eql(VALUE s, VALUE s2)
1572{
1573 if (s == s2) return Qtrue;
1574 if (!RB_TYPE_P(s2, T_STRUCT)) return Qfalse;
1575 if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
1576 if (RSTRUCT_LEN_RAW(s) != RSTRUCT_LEN_RAW(s2)) {
1577 rb_bug("inconsistent struct"); /* should never happen */
1578 }
1579
1580 return rb_exec_recursive_paired(recursive_eql, s, s2, s2);
1581}
1582
1583/*
1584 * call-seq:
1585 * size -> integer
1586 *
1587 * Returns the number of members.
1588 *
1589 * Customer = Struct.new(:name, :address, :zip)
1590 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
1591 * joe.size #=> 3
1592 *
1593 */
1594
1595VALUE
1597{
1598 return LEN2NUM(RSTRUCT_LEN_RAW(s));
1599}
1600
1601/*
1602 * call-seq:
1603 * dig(name, *identifiers) -> object
1604 * dig(n, *identifiers) -> object
1605 *
1606 * Finds and returns an object among nested objects.
1607 * The nested objects may be instances of various classes.
1608 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
1609 *
1610 *
1611 * Given symbol or string argument +name+,
1612 * returns the object that is specified by +name+ and +identifiers+:
1613 *
1614 * Foo = Struct.new(:a)
1615 * f = Foo.new(Foo.new({b: [1, 2, 3]}))
1616 * f.dig(:a) # => #<struct Foo a={b: [1, 2, 3]}>
1617 * f.dig(:a, :a) # => {b: [1, 2, 3]}
1618 * f.dig(:a, :a, :b) # => [1, 2, 3]
1619 * f.dig(:a, :a, :b, 0) # => 1
1620 * f.dig(:b, 0) # => nil
1621 *
1622 * Given integer argument +n+,
1623 * returns the object that is specified by +n+ and +identifiers+:
1624 *
1625 * f.dig(0) # => #<struct Foo a={b: [1, 2, 3]}>
1626 * f.dig(0, 0) # => {b: [1, 2, 3]}
1627 * f.dig(0, 0, :b) # => [1, 2, 3]
1628 * f.dig(0, 0, :b, 0) # => 1
1629 * f.dig(:b, 0) # => nil
1630 *
1631 */
1632
1633static VALUE
1634rb_struct_dig(int argc, VALUE *argv, VALUE self)
1635{
1637 self = rb_struct_lookup(self, *argv);
1638 if (!--argc) return self;
1639 ++argv;
1640 return rb_obj_dig(argc, argv, self, Qnil);
1641}
1642
1643/*
1644 * Document-class: Data
1645 *
1646 * Class \Data provides a convenient way to define simple classes
1647 * for value-alike objects.
1648 *
1649 * The simplest example of usage:
1650 *
1651 * Measure = Data.define(:amount, :unit)
1652 *
1653 * # Positional arguments constructor is provided
1654 * distance = Measure.new(100, 'km')
1655 * #=> #<data Measure amount=100, unit="km">
1656 *
1657 * # Keyword arguments constructor is provided
1658 * weight = Measure.new(amount: 50, unit: 'kg')
1659 * #=> #<data Measure amount=50, unit="kg">
1660 *
1661 * # Alternative form to construct an object:
1662 * speed = Measure[10, 'mPh']
1663 * #=> #<data Measure amount=10, unit="mPh">
1664 *
1665 * # Works with keyword arguments, too:
1666 * area = Measure[amount: 1.5, unit: 'm^2']
1667 * #=> #<data Measure amount=1.5, unit="m^2">
1668 *
1669 * # Argument accessors are provided:
1670 * distance.amount #=> 100
1671 * distance.unit #=> "km"
1672 *
1673 * Constructed object also has a reasonable definitions of #==
1674 * operator, #to_h hash conversion, and #deconstruct / #deconstruct_keys
1675 * to be used in pattern matching.
1676 *
1677 * ::define method accepts an optional block and evaluates it in
1678 * the context of the newly defined class. That allows to define
1679 * additional methods:
1680 *
1681 * Measure = Data.define(:amount, :unit) do
1682 * def <=>(other)
1683 * return unless other.is_a?(self.class) && other.unit == unit
1684 * amount <=> other.amount
1685 * end
1686 *
1687 * include Comparable
1688 * end
1689 *
1690 * Measure[3, 'm'] < Measure[5, 'm'] #=> true
1691 * Measure[3, 'm'] < Measure[5, 'kg']
1692 * # comparison of Measure with Measure failed (ArgumentError)
1693 *
1694 * Data provides no member writers, or enumerators: it is meant
1695 * to be a storage for immutable atomic values. But note that
1696 * if some of data members is of a mutable class, Data does no additional
1697 * immutability enforcement:
1698 *
1699 * Event = Data.define(:time, :weekdays)
1700 * event = Event.new('18:00', %w[Tue Wed Fri])
1701 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri"]>
1702 *
1703 * # There is no #time= or #weekdays= accessors, but changes are
1704 * # still possible:
1705 * event.weekdays << 'Sat'
1706 * event
1707 * #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri", "Sat"]>
1708 *
1709 * See also Struct, which is a similar concept, but has more
1710 * container-alike API, allowing to change contents of the object
1711 * and enumerate it.
1712 */
1713
1714/*
1715 * call-seq:
1716 * define(*symbols) -> class
1717 *
1718 * Defines a new \Data class.
1719 *
1720 * measure = Data.define(:amount, :unit)
1721 * #=> #<Class:0x00007f70c6868498>
1722 * measure.new(1, 'km')
1723 * #=> #<data amount=1, unit="km">
1724 *
1725 * # It you store the new class in the constant, it will
1726 * # affect #inspect and will be more natural to use:
1727 * Measure = Data.define(:amount, :unit)
1728 * #=> Measure
1729 * Measure.new(1, 'km')
1730 * #=> #<data Measure amount=1, unit="km">
1731 *
1732 *
1733 * Note that member-less \Data is acceptable and might be a useful technique
1734 * for defining several homogeneous data classes, like
1735 *
1736 * class HTTPFetcher
1737 * Response = Data.define(:body)
1738 * NotFound = Data.define
1739 * # ... implementation
1740 * end
1741 *
1742 * Now, different kinds of responses from +HTTPFetcher+ would have consistent
1743 * representation:
1744 *
1745 * #<data HTTPFetcher::Response body="<html...">
1746 * #<data HTTPFetcher::NotFound>
1747 *
1748 * And are convenient to use in pattern matching:
1749 *
1750 * case fetcher.get(url)
1751 * in HTTPFetcher::Response(body)
1752 * # process body variable
1753 * in HTTPFetcher::NotFound
1754 * # handle not found case
1755 * end
1756 */
1757
1758static VALUE
1759rb_data_s_def(int argc, VALUE *argv, VALUE super)
1760{
1761 VALUE rest = rb_ident_hash_new();
1762 RBASIC_CLEAR_CLASS(rest);
1763 for (int i = 0; i < argc; i++) {
1764 VALUE mem = rb_to_symbol(argv[i]);
1765 if (rb_is_attrset_sym(mem)) {
1766 rb_raise(rb_eArgError, "invalid data member: %"PRIsVALUE, mem);
1767 }
1768 if (RTEST(rb_hash_has_key(rest, mem))) {
1769 rb_raise(rb_eArgError, "duplicate member: %"PRIsVALUE, mem);
1770 }
1771 rb_hash_aset(rest, mem, Qtrue);
1772 }
1773 rest = rb_hash_keys(rest);
1774 RBASIC_CLEAR_CLASS(rest);
1775 OBJ_FREEZE(rest);
1776
1777 VALUE klass = anonymous_struct(super);
1778 setup_data(klass, rest);
1779
1780 rb_class_inherited(super, klass);
1781
1782 if (rb_block_given_p()) {
1783 rb_mod_module_eval(0, 0, klass);
1784 }
1785
1786 return klass;
1787}
1788
1789VALUE
1791{
1792 va_list ar;
1793 VALUE ary;
1794 va_start(ar, super);
1795 ary = struct_make_members_list(ar);
1796 va_end(ar);
1797 if (!super) super = rb_cData;
1798 VALUE klass = setup_data(anonymous_struct(super), ary);
1799 rb_vm_register_global_object(klass);
1800 rb_class_inherited(super, klass);
1801 return klass;
1802}
1803
1804static int
1805data_hash_set_i(VALUE key, VALUE val, VALUE arg)
1806{
1807 struct struct_hash_set_arg *args = (struct struct_hash_set_arg *)arg;
1808 int i = struct_hash_aset(key, val, args, true);
1809 if (i >= 0 && !args->found[i]) {
1810 args->found[i] = true;
1811 args->missing_count--;
1812 }
1813 return ST_CONTINUE;
1814}
1815
1816/*
1817 * call-seq:
1818 * DataClass::members -> array_of_symbols
1819 *
1820 * Returns an array of member names of the data class:
1821 *
1822 * Measure = Data.define(:amount, :unit)
1823 * Measure.members # => [:amount, :unit]
1824 *
1825 */
1826
1827#define rb_data_s_members_m rb_struct_s_members_m
1828
1829
1830/*
1831 * call-seq:
1832 * new(*args) -> instance
1833 * new(**kwargs) -> instance
1834 * ::[](*args) -> instance
1835 * ::[](**kwargs) -> instance
1836 *
1837 * Constructors for classes defined with ::define accept both positional and
1838 * keyword arguments.
1839 *
1840 * Measure = Data.define(:amount, :unit)
1841 *
1842 * Measure.new(1, 'km')
1843 * #=> #<data Measure amount=1, unit="km">
1844 * Measure.new(amount: 1, unit: 'km')
1845 * #=> #<data Measure amount=1, unit="km">
1846 *
1847 * # Alternative shorter initialization with []
1848 * Measure[1, 'km']
1849 * #=> #<data Measure amount=1, unit="km">
1850 * Measure[amount: 1, unit: 'km']
1851 * #=> #<data Measure amount=1, unit="km">
1852 *
1853 * All arguments are mandatory (unlike Struct), and converted to keyword arguments:
1854 *
1855 * Measure.new(amount: 1)
1856 * # in `initialize': missing keyword: :unit (ArgumentError)
1857 *
1858 * Measure.new(1)
1859 * # in `initialize': missing keyword: :unit (ArgumentError)
1860 *
1861 * Note that <tt>Measure#initialize</tt> always receives keyword arguments, and that
1862 * mandatory arguments are checked in +initialize+, not in +new+. This can be
1863 * important for redefining initialize in order to convert arguments or provide
1864 * defaults:
1865 *
1866 * Measure = Data.define(:amount, :unit)
1867 * class Measure
1868 * NONE = Data.define
1869 *
1870 * def initialize(amount:, unit: NONE.new)
1871 * super(amount: Float(amount), unit:)
1872 * end
1873 * end
1874 *
1875 * Measure.new('10', 'km') # => #<data Measure amount=10.0, unit="km">
1876 * Measure.new(10_000) # => #<data Measure amount=10000.0, unit=#<data Measure::NONE>>
1877 *
1878 */
1879
1880static VALUE
1881rb_data_initialize_m(int argc, const VALUE *argv, VALUE self)
1882{
1883 rb_struct_modify(self);
1884 rb_len_t num_members = RSTRUCT_LEN_RAW(self);
1885
1886 if (argc == 0) {
1887 if (num_members > 0) {
1888 rb_exc_raise(rb_keyword_error_new("missing", struct_ivar_get(rb_obj_class(self), id_members)));
1889 }
1890 OBJ_FREEZE(self);
1891 return Qnil;
1892 }
1893 if (argc > 1 || !RB_TYPE_P(argv[0], T_HASH)) {
1894 rb_error_arity(argc, 0, 0);
1895 }
1896
1897 VALUE found_buffer = 0;
1898 bool *found = NULL;
1899 if (num_members > 0) {
1900 found = ALLOCV_N(bool, found_buffer, num_members);
1901 MEMZERO(found, bool, num_members);
1902 }
1903 struct struct_hash_set_arg arg = {
1904 .self = self,
1905 .found = found,
1906 .missing_count = num_members,
1907 };
1908 rb_mem_clear((VALUE *)RSTRUCT_CONST_PTR(self), num_members);
1909 rb_hash_foreach(argv[0], data_hash_set_i, (VALUE)&arg);
1910
1911 // Freeze early before potentially raising, so that we don't leave an
1912 // unfrozen copy on the heap, which could get exposed via ObjectSpace.
1913 OBJ_FREEZE(self);
1914 if (UNLIKELY(arg.missing_count > 0)) {
1915 VALUE members = struct_ivar_get(rb_obj_class(self), id_members);
1916 RUBY_ASSERT(RARRAY_LEN(members) == num_members);
1917 VALUE missing = rb_ary_new_capa(arg.missing_count);
1918 for (rb_len_t i = 0; i < num_members; i++) {
1919 if (!found[i]) rb_ary_push(missing, RARRAY_AREF(members, i));
1920 }
1921 RUBY_ASSERT(RARRAY_LEN(missing) == arg.missing_count, "missing_count=%"PRIdLEN" but %"PRIdLEN, arg.missing_count, RARRAY_LEN(missing));
1922 rb_exc_raise(rb_keyword_error_new("missing", missing));
1923 }
1924
1925 ALLOCV_END(found_buffer);
1926 if (UNLIKELY(arg.unknown_keywords)) {
1927 rb_exc_raise(rb_keyword_error_new("unknown", arg.unknown_keywords));
1928 }
1929
1930 return Qnil;
1931}
1932
1933/* :nodoc: */
1934static VALUE
1935rb_data_init_copy(VALUE copy, VALUE s)
1936{
1937 copy = rb_struct_init_copy(copy, s);
1938 RB_OBJ_FREEZE(copy);
1939 return copy;
1940}
1941
1942/*
1943 * call-seq:
1944 * with(**kwargs) -> instance
1945 *
1946 * Returns a shallow copy of +self+ --- the instance variables of
1947 * +self+ are copied, but not the objects they reference.
1948 *
1949 * If the method is supplied any keyword arguments, the copy will
1950 * be created with the respective field values updated to use the
1951 * supplied keyword argument values. Note that it is an error to
1952 * supply a keyword that the Data class does not have as a member.
1953 *
1954 * Point = Data.define(:x, :y)
1955 *
1956 * origin = Point.new(x: 0, y: 0)
1957 *
1958 * up = origin.with(x: 1)
1959 * right = origin.with(y: 1)
1960 * up_and_right = up.with(y: 1)
1961 *
1962 * p origin # #<data Point x=0, y=0>
1963 * p up # #<data Point x=1, y=0>
1964 * p right # #<data Point x=0, y=1>
1965 * p up_and_right # #<data Point x=1, y=1>
1966 *
1967 * out = origin.with(z: 1) # ArgumentError: unknown keyword: :z
1968 * some_point = origin.with(1, 2) # ArgumentError: expected keyword arguments, got positional arguments
1969 *
1970 */
1971
1972static VALUE
1973rb_data_with(int argc, const VALUE *argv, VALUE self)
1974{
1975 VALUE kwargs;
1976 rb_scan_args(argc, argv, "0:", &kwargs);
1977 if (NIL_P(kwargs)) {
1978 return self;
1979 }
1980
1981 VALUE h = rb_struct_to_h(self);
1982 rb_hash_update_by(h, kwargs, 0);
1983 return rb_class_new_instance_kw(1, &h, rb_obj_class(self), TRUE);
1984}
1985
1986/*
1987 * call-seq:
1988 * inspect -> string
1989 * to_s -> string
1990 *
1991 * Returns a string representation of +self+:
1992 *
1993 * Measure = Data.define(:amount, :unit)
1994 *
1995 * distance = Measure[10, 'km']
1996 *
1997 * p distance # uses #inspect underneath
1998 * #<data Measure amount=10, unit="km">
1999 *
2000 * puts distance # uses #to_s underneath, same representation
2001 * #<data Measure amount=10, unit="km">
2002 *
2003 */
2004
2005static VALUE
2006rb_data_inspect(VALUE s)
2007{
2008 return rb_exec_recursive(inspect_struct, s, rb_str_new2("#<data"));
2009}
2010
2011/*
2012 * call-seq:
2013 * self == other -> true or false
2014 *
2015 * Returns whether +other+ is the same class as +self+, and all members are
2016 * equal.
2017 *
2018 * Examples:
2019 *
2020 * Measure = Data.define(:amount, :unit)
2021 *
2022 * Measure[1, 'km'] == Measure[1, 'km'] #=> true
2023 * Measure[1, 'km'] == Measure[2, 'km'] #=> false
2024 * Measure[1, 'km'] == Measure[1, 'm'] #=> false
2025 *
2026 * Measurement = Data.define(:amount, :unit)
2027 * # Even though Measurement and Measure have the same "shape"
2028 * # their instances are never equal
2029 * Measure[1, 'km'] == Measurement[1, 'km'] #=> false
2030 */
2031
2032#define rb_data_equal rb_struct_equal
2033
2034/*
2035 * call-seq:
2036 * self.eql?(other) -> true or false
2037 *
2038 * Equality check that is used when two items of data are keys of a Hash.
2039 *
2040 * The subtle difference with #== is that members are also compared with their
2041 * #eql? method, which might be important in some cases:
2042 *
2043 * Measure = Data.define(:amount, :unit)
2044 *
2045 * Measure[1, 'km'] == Measure[1.0, 'km'] #=> true, they are equal as values
2046 * # ...but...
2047 * Measure[1, 'km'].eql? Measure[1.0, 'km'] #=> false, they represent different hash keys
2048 *
2049 * See also Object#eql? for further explanations of the method usage.
2050 */
2051
2052#define rb_data_eql rb_struct_eql
2053
2054/*
2055 * call-seq:
2056 * hash -> integer
2057 *
2058 * Redefines Object#hash (used to distinguish objects as Hash keys) so that
2059 * data objects of the same class with same content would have the same +hash+
2060 * value, and represented the same Hash key.
2061 *
2062 * Measure = Data.define(:amount, :unit)
2063 *
2064 * Measure[1, 'km'].hash == Measure[1, 'km'].hash #=> true
2065 * Measure[1, 'km'].hash == Measure[10, 'km'].hash #=> false
2066 * Measure[1, 'km'].hash == Measure[1, 'm'].hash #=> false
2067 * Measure[1, 'km'].hash == Measure[1.0, 'km'].hash #=> false
2068 *
2069 * # Structurally similar data class, but shouldn't be considered
2070 * # the same hash key
2071 * Measurement = Data.define(:amount, :unit)
2072 *
2073 * Measure[1, 'km'].hash == Measurement[1, 'km'].hash #=> false
2074 */
2075
2076#define rb_data_hash rb_struct_hash
2077
2078/*
2079 * call-seq:
2080 * to_h -> hash
2081 * to_h {|name, value| ... } -> hash
2082 *
2083 * Returns Hash representation of the data object.
2084 *
2085 * Measure = Data.define(:amount, :unit)
2086 * distance = Measure[10, 'km']
2087 *
2088 * distance.to_h
2089 * #=> {amount: 10, unit: "km"}
2090 *
2091 * Like Enumerable#to_h, if the block is provided, it is expected to
2092 * produce key-value pairs to construct a hash:
2093 *
2094 *
2095 * distance.to_h { |name, val| [name.to_s, val.to_s] }
2096 * #=> {"amount"=>"10", "unit"=>"km"}
2097 *
2098 * Note that there is a useful symmetry between #to_h and #initialize:
2099 *
2100 * distance2 = Measure.new(**distance.to_h)
2101 * #=> #<data Measure amount=10, unit="km">
2102 * distance2 == distance
2103 * #=> true
2104 */
2105
2106#define rb_data_to_h rb_struct_to_h
2107
2108/*
2109 * call-seq:
2110 * members -> array_of_symbols
2111 *
2112 * Returns the member names from +self+ as an array:
2113 *
2114 * Measure = Data.define(:amount, :unit)
2115 * distance = Measure[10, 'km']
2116 *
2117 * distance.members #=> [:amount, :unit]
2118 *
2119 */
2120
2121#define rb_data_members_m rb_struct_members_m
2122
2123/*
2124 * call-seq:
2125 * deconstruct -> array
2126 *
2127 * Returns the values in +self+ as an array, to use in pattern matching:
2128 *
2129 * Measure = Data.define(:amount, :unit)
2130 *
2131 * distance = Measure[10, 'km']
2132 * distance.deconstruct #=> [10, "km"]
2133 *
2134 * # usage
2135 * case distance
2136 * in n, 'km' # calls #deconstruct underneath
2137 * puts "It is #{n} kilometers away"
2138 * else
2139 * puts "Don't know how to handle it"
2140 * end
2141 * # prints "It is 10 kilometers away"
2142 *
2143 * Or, with checking the class, too:
2144 *
2145 * case distance
2146 * in Measure(n, 'km')
2147 * puts "It is #{n} kilometers away"
2148 * # ...
2149 * end
2150 */
2151
2152#define rb_data_deconstruct rb_struct_to_a
2153
2154/*
2155 * call-seq:
2156 * deconstruct_keys(array_of_names_or_nil) -> hash
2157 *
2158 * Returns a hash of the name/value pairs, to use in pattern matching.
2159 *
2160 * Measure = Data.define(:amount, :unit)
2161 *
2162 * distance = Measure[10, 'km']
2163 * distance.deconstruct_keys(nil) #=> {amount: 10, unit: "km"}
2164 * distance.deconstruct_keys([:amount]) #=> {amount: 10}
2165 *
2166 * # usage
2167 * case distance
2168 * in amount:, unit: 'km' # calls #deconstruct_keys underneath
2169 * puts "It is #{amount} kilometers away"
2170 * else
2171 * puts "Don't know how to handle it"
2172 * end
2173 * # prints "It is 10 kilometers away"
2174 *
2175 * Or, with checking the class, too:
2176 *
2177 * case distance
2178 * in Measure(amount:, unit: 'km')
2179 * puts "It is #{amount} kilometers away"
2180 * # ...
2181 * end
2182 */
2183
2184static VALUE
2185rb_data_deconstruct_keys(VALUE s, VALUE keys)
2186{
2187 return deconstruct_keys(s, keys, true);
2188}
2189
2190/*
2191 * Document-class: Struct
2192 *
2193 * Class \Struct provides a convenient way to create a simple class
2194 * that can store and fetch values.
2195 *
2196 * This example creates a subclass of +Struct+, <tt>Struct::Customer</tt>;
2197 * the first argument, a string, is the name of the subclass;
2198 * the other arguments, symbols, determine the _members_ of the new subclass.
2199 *
2200 * Customer = Struct.new('Customer', :name, :address, :zip)
2201 * Customer.name # => "Struct::Customer"
2202 * Customer.class # => Class
2203 * Customer.superclass # => Struct
2204 *
2205 * Corresponding to each member are two methods, a writer and a reader,
2206 * that store and fetch values:
2207 *
2208 * methods = Customer.instance_methods false
2209 * methods # => [:zip, :address=, :zip=, :address, :name, :name=]
2210 *
2211 * An instance of the subclass may be created,
2212 * and its members assigned values, via method <tt>::new</tt>:
2213 *
2214 * joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
2215 * joe # => #<struct Struct::Customer name="Joe Smith", address="123 Maple, Anytown NC", zip=12345>
2216 *
2217 * The member values may be managed thus:
2218 *
2219 * joe.name # => "Joe Smith"
2220 * joe.name = 'Joseph Smith'
2221 * joe.name # => "Joseph Smith"
2222 *
2223 * And thus; note that member name may be expressed as either a string or a symbol:
2224 *
2225 * joe[:name] # => "Joseph Smith"
2226 * joe[:name] = 'Joseph Smith, Jr.'
2227 * joe['name'] # => "Joseph Smith, Jr."
2228 *
2229 * See Struct::new.
2230 *
2231 * == What's Here
2232 *
2233 * First, what's elsewhere. Class \Struct:
2234 *
2235 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
2236 * - Includes {module Enumerable}[rdoc-ref:Enumerable@Whats+Here],
2237 * which provides dozens of additional methods.
2238 *
2239 * See also Data, which is a somewhat similar, but stricter concept for defining immutable
2240 * value objects.
2241 *
2242 * Here, class \Struct provides methods that are useful for:
2243 *
2244 * - {Creating a Struct Subclass}[rdoc-ref:Struct@Methods+for+Creating+a+Struct+Subclass]
2245 * - {Querying}[rdoc-ref:Struct@Methods+for+Querying]
2246 * - {Comparing}[rdoc-ref:Struct@Methods+for+Comparing]
2247 * - {Fetching}[rdoc-ref:Struct@Methods+for+Fetching]
2248 * - {Assigning}[rdoc-ref:Struct@Methods+for+Assigning]
2249 * - {Iterating}[rdoc-ref:Struct@Methods+for+Iterating]
2250 * - {Converting}[rdoc-ref:Struct@Methods+for+Converting]
2251 *
2252 * === Methods for Creating a Struct Subclass
2253 *
2254 * - ::new: Returns a new subclass of \Struct.
2255 *
2256 * === Methods for Querying
2257 *
2258 * - #hash: Returns the integer hash code.
2259 * - #size (aliased as #length): Returns the number of members.
2260 *
2261 * === Methods for Comparing
2262 *
2263 * - #==: Returns whether a given object is equal to +self+, using <tt>==</tt>
2264 * to compare member values.
2265 * - #eql?: Returns whether a given object is equal to +self+,
2266 * using <tt>eql?</tt> to compare member values.
2267 *
2268 * === Methods for Fetching
2269 *
2270 * - #[]: Returns the value associated with a given member name.
2271 * - #to_a (aliased as #values, #deconstruct): Returns the member values in +self+ as an array.
2272 * - #deconstruct_keys: Returns a hash of the name/value pairs
2273 * for given member names.
2274 * - #dig: Returns the object in nested objects that is specified
2275 * by a given member name and additional arguments.
2276 * - #members: Returns an array of the member names.
2277 * - #select (aliased as #filter): Returns an array of member values from +self+,
2278 * as selected by the given block.
2279 * - #values_at: Returns an array containing values for given member names.
2280 *
2281 * === Methods for Assigning
2282 *
2283 * - #[]=: Assigns a given value to a given member name.
2284 *
2285 * === Methods for Iterating
2286 *
2287 * - #each: Calls a given block with each member name.
2288 * - #each_pair: Calls a given block with each member name/value pair.
2289 *
2290 * === Methods for Converting
2291 *
2292 * - #inspect (aliased as #to_s): Returns a string representation of +self+.
2293 * - #to_h: Returns a hash of the member name/value pairs in +self+.
2294 *
2295 */
2296void
2297InitVM_Struct(void)
2298{
2299 rb_cStruct = rb_define_class("Struct", rb_cObject);
2301
2303 rb_define_singleton_method(rb_cStruct, "new", rb_struct_s_def, -1);
2304#if 0 /* for RDoc */
2305 rb_define_singleton_method(rb_cStruct, "keyword_init?", rb_struct_s_keyword_init_p, 0);
2306 rb_define_singleton_method(rb_cStruct, "members", rb_struct_s_members_m, 0);
2307#endif
2308
2309 rb_define_method(rb_cStruct, "initialize", rb_struct_initialize_m, -1);
2310 rb_define_method(rb_cStruct, "initialize_copy", rb_struct_init_copy, 1);
2311
2312 rb_define_method(rb_cStruct, "==", rb_struct_equal, 1);
2313 rb_define_method(rb_cStruct, "eql?", rb_struct_eql, 1);
2314 rb_define_method(rb_cStruct, "hash", rb_struct_hash, 0);
2315
2316 rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
2317 rb_define_alias(rb_cStruct, "to_s", "inspect");
2318 rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
2319 rb_define_method(rb_cStruct, "to_h", rb_struct_to_h, 0);
2320 rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
2321 rb_define_method(rb_cStruct, "size", rb_struct_size, 0);
2322 rb_define_method(rb_cStruct, "length", rb_struct_size, 0);
2323
2324 rb_define_method(rb_cStruct, "each", rb_struct_each, 0);
2325 rb_define_method(rb_cStruct, "each_pair", rb_struct_each_pair, 0);
2326 rb_define_method(rb_cStruct, "[]", rb_struct_aref, 1);
2327 rb_define_method(rb_cStruct, "[]=", rb_struct_aset, 2);
2328 rb_define_method(rb_cStruct, "select", rb_struct_select, -1);
2329 rb_define_method(rb_cStruct, "filter", rb_struct_select, -1);
2330 rb_define_method(rb_cStruct, "values_at", rb_struct_values_at, -1);
2331
2332 rb_define_method(rb_cStruct, "members", rb_struct_members_m, 0);
2333 rb_define_method(rb_cStruct, "dig", rb_struct_dig, -1);
2334
2335 rb_define_method(rb_cStruct, "deconstruct", rb_struct_to_a, 0);
2336 rb_define_method(rb_cStruct, "deconstruct_keys", rb_struct_deconstruct_keys, 1);
2337
2338 rb_cData = rb_define_class("Data", rb_cObject);
2339
2340 rb_undef_method(CLASS_OF(rb_cData), "new");
2341 rb_undef_alloc_func(rb_cData);
2342 rb_define_singleton_method(rb_cData, "define", rb_data_s_def, -1);
2343
2344#if 0 /* for RDoc */
2345 rb_define_singleton_method(rb_cData, "members", rb_data_s_members_m, 0);
2346#endif
2347
2348 rb_define_method(rb_cData, "initialize", rb_data_initialize_m, -1);
2349 rb_define_method(rb_cData, "initialize_copy", rb_data_init_copy, 1);
2350
2351 rb_define_method(rb_cData, "==", rb_data_equal, 1);
2352 rb_define_method(rb_cData, "eql?", rb_data_eql, 1);
2353 rb_define_method(rb_cData, "hash", rb_data_hash, 0);
2354
2355 rb_define_method(rb_cData, "inspect", rb_data_inspect, 0);
2356 rb_define_alias(rb_cData, "to_s", "inspect");
2357 rb_define_method(rb_cData, "to_h", rb_data_to_h, 0);
2358
2359 rb_define_method(rb_cData, "members", rb_data_members_m, 0);
2360
2361 rb_define_method(rb_cData, "deconstruct", rb_data_deconstruct, 0);
2362 rb_define_method(rb_cData, "deconstruct_keys", rb_data_deconstruct_keys, 1);
2363
2364 rb_define_method(rb_cData, "with", rb_data_with, -1);
2365}
2366
2367#undef rb_intern
2368void
2369Init_Struct(void)
2370{
2371 id_members = rb_intern("__members__");
2372 id_back_members = rb_intern("__members_back__");
2373 id_keyword_init = rb_intern("__keyword_init__");
2374
2375 InitVM(Struct);
2376}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
static void RB_OBJ_FREEZE(VALUE obj)
Freeze the given object if it is not frozen yet.
Definition fl_type.h:756
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1737
VALUE rb_class_new(VALUE super)
Creates a new, anonymous class.
Definition class.c:854
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3018
VALUE rb_define_class_id_under(VALUE outer, ID id, VALUE super)
Identical to rb_define_class_under(), except it takes the name in ID instead of C's string.
Definition class.c:1605
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
Definition class.c:1529
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3061
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2864
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3351
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1054
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1041
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3140
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1700
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define LEN2NUM
Old name of RB_LEN2NUM.
Definition len_t.h:33
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define FIX2UINT
Old name of RB_FIX2UINT.
Definition int.h:42
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define NUM2LEN
Old name of RB_NUM2LEN.
Definition len_t.h:34
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1459
VALUE rb_class_superclass(VALUE klass)
Queries the parent of the given class.
Definition object.c:2320
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2264
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2305
VALUE rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
Identical to rb_class_new_instance(), except you can specify how to handle the last element of the gi...
Definition object.c:2293
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:28
VALUE rb_cStruct
Struct class.
Definition struct.c:33
VALUE rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
Identical to rb_class_new_instance(), except it passes the passed keywords if any to the #initialize ...
Definition object.c:2282
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:902
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
VALUE rb_enc_interned_str_cstr(const char *ptr, rb_encoding *enc)
Identical to rb_enc_str_new_cstr(), except it returns a "f"string.
Definition string.c:16304
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_hidden_new(rb_len_t capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
void rb_mem_clear(VALUE *buf, rb_len_t len)
Fills the memory region with a series of RUBY_Qnil.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
VALUE rb_get_values_at(VALUE obj, rb_len_t olen, int argc, const VALUE *argv, VALUE(*func)(VALUE obj, rb_len_t oidx))
This was a generalisation of Array#values_at, Struct#values_at, and MatchData#values_at.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1242
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
Definition symbol.c:1272
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:967
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:970
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3935
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1714
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1681
VALUE rb_struct_define_without_accessor_under(VALUE outer, const char *class_name, VALUE super, rb_alloc_func_t alloc,...)
Identical to rb_struct_define_without_accessor(), except it defines the class under the specified nam...
Definition struct.c:483
VALUE rb_struct_define_under(VALUE space, const char *name,...)
Identical to rb_struct_define(), except it defines the class under the specified namespace instead of...
Definition struct.c:532
VALUE rb_struct_new(VALUE klass,...)
Creates an instance of the given struct.
Definition struct.c:926
VALUE rb_struct_initialize(VALUE self, VALUE values)
Mass-assigns a struct's fields.
Definition struct.c:839
VALUE rb_struct_define_without_accessor(const char *name, VALUE super, rb_alloc_func_t func,...)
Identical to rb_struct_define(), except it does not define accessor methods.
Definition struct.c:496
VALUE rb_struct_define(const char *name,...)
Defines a struct class.
Definition struct.c:509
VALUE rb_struct_alloc(VALUE klass, VALUE values)
Identical to rb_struct_new(), except it takes the field values as a Ruby array.
Definition struct.c:920
VALUE rb_data_define(VALUE super,...)
Defines an anonymous data class.
Definition struct.c:1790
VALUE rb_struct_alloc_noinit(VALUE klass)
Allocates an instance of the given class.
Definition struct.c:412
VALUE rb_struct_s_members(VALUE klass)
Queries the list of the names of the fields of the given struct class.
Definition struct.c:68
VALUE rb_struct_members(VALUE self)
Queries the list of the names of the fields of the class of the given struct object.
Definition struct.c:82
VALUE rb_struct_getmember(VALUE self, ID key)
Identical to rb_struct_aref(), except it takes ID instead of VALUE.
Definition struct.c:233
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2168
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition variable.c:3640
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:4018
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:517
void rb_set_class_path_string(VALUE klass, VALUE space, VALUE name)
Identical to rb_set_class_path(), except it accepts the name as Ruby's string instead of C's.
Definition variable.c:440
int rb_const_defined_at(VALUE space, ID name)
Identical to rb_const_defined(), except it doesn't look for parent classes.
Definition variable.c:3876
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:397
VALUE(* rb_alloc_func_t)(VALUE klass)
This is the type of functions that ruby calls when trying to allocate an object.
Definition vm.h:219
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1893
rb_alloc_func_t rb_get_alloc_func(VALUE klass)
Queries the allocator function of a class.
Definition vm_method.c:1902
VALUE rb_mod_module_eval(int argc, const VALUE *argv, VALUE mod)
Identical to rb_obj_instance_eval(), except it evaluates within the context of module.
Definition vm_eval.c:2503
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_check_symbol(volatile VALUE *namep)
Identical to rb_check_id(), except it returns an instance of rb_cSymbol instead.
Definition symbol.c:1355
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1155
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:16226
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:16216
int off
Offset inside of ptr.
Definition io.h:5
int len
Length of the buffer.
Definition io.h:8
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1427
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1404
#define rb_len2int
Just another name of rb_len2int_inline.
Definition len_t.h:37
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:363
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:280
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
Definition rarray.h:365
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:421
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:51
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
VALUE rb_str_to_str(VALUE obj)
Identical to rb_check_string_type(), except it raises exceptions in case of conversion failures.
Definition string.c:1842
VALUE rb_struct_aset(VALUE st, VALUE k, VALUE v)
Resembles Struct#[]=.
Definition struct.c:1346
VALUE rb_struct_size(VALUE st)
Returns the number of struct members.
Definition struct.c:1596
VALUE rb_struct_aref(VALUE st, VALUE k)
Resembles Struct#[].
Definition struct.c:1308
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
#define RB_PASS_KEYWORDS
Pass keywords, final argument must be a hash of keywords.
Definition scan_args.h:72
#define RTEST
This is an old name of RB_TEST.
Ruby's ordinal objects.
Definition robject.h:51
VALUE extended
When an object slot is too small or too complex to store instance variables inline,...
Definition robject.h:73
Definition method.h:63
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376