struct.c 24 KB
Newer Older
mimaki's avatar
mimaki committed
1 2
/*
** struct.c - Struct class
roco's avatar
roco committed
3
**
mimaki's avatar
mimaki committed
4 5
** See Copyright Notice in mruby.h
*/
mimaki's avatar
mimaki committed
6 7 8

#include <string.h>
#include <stdarg.h>
mattn's avatar
mattn committed
9 10
#include "mruby.h"
#include "mruby/array.h"
mimaki's avatar
mimaki committed
11 12
#include "mruby/string.h"
#include "mruby/class.h"
13
#include "mruby/variable.h"
mimaki's avatar
mimaki committed
14

15 16
#define RSTRUCT_LEN(st) RARRAY_LEN(st)
#define RSTRUCT_PTR(st) RARRAY_PTR(st)
mimaki's avatar
mimaki committed
17 18 19 20 21 22 23 24 25 26 27 28 29

static struct RClass *
struct_class(mrb_state *mrb)
{
  return mrb_class_get(mrb, "Struct");
}

static inline mrb_value
struct_ivar_get(mrb_state *mrb, mrb_value c, mrb_sym id)
{
  struct RClass* kclass;
  struct RClass* sclass = struct_class(mrb);
  mrb_value ans;
30 31 32 33 34 35 36 37 38

  for (;;) {
    ans = mrb_iv_get(mrb, c, id);
    if (!mrb_nil_p(ans)) return ans;
    kclass = RCLASS_SUPER(c);
    if (kclass == 0 || kclass == sclass)
      return mrb_nil_value();
    c = mrb_obj_value(kclass);
  }
mimaki's avatar
mimaki committed
39 40 41 42 43
}

mrb_value
mrb_struct_iv_get(mrb_state *mrb, mrb_value c, const char *name)
{
44
  return struct_ivar_get(mrb, c, mrb_intern_cstr(mrb, name));
mimaki's avatar
mimaki committed
45 46 47 48 49
}

mrb_value
mrb_struct_s_members(mrb_state *mrb, mrb_value klass)
{
50
  mrb_value members = struct_ivar_get(mrb, klass, mrb_intern_lit(mrb, "__members__"));
mimaki's avatar
mimaki committed
51

52 53 54 55 56 57 58
  if (mrb_nil_p(members)) {
    mrb_raise(mrb, E_TYPE_ERROR, "uninitialized struct");
  }
  if (!mrb_array_p(members)) {
    mrb_raise(mrb, E_TYPE_ERROR, "corrupted struct");
  }
  return members;
mimaki's avatar
mimaki committed
59 60 61 62 63 64
}

mrb_value
mrb_struct_members(mrb_state *mrb, mrb_value s)
{
  mrb_value members = mrb_struct_s_members(mrb, mrb_obj_value(mrb_obj_class(mrb, s)));
mattn's avatar
mattn committed
65
  if (!strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s)), "Struct")) {
mimaki's avatar
mimaki committed
66
    if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
67
      mrb_raisef(mrb, E_TYPE_ERROR,
68 69
                 "struct size differs (%S required %S given)",
                 mrb_fixnum_value(RARRAY_LEN(members)), mrb_fixnum_value(RSTRUCT_LEN(s)));
mimaki's avatar
mimaki committed
70 71 72 73 74 75 76 77
    }
  }
  return members;
}

static mrb_value
mrb_struct_s_members_m(mrb_state *mrb, mrb_value klass)
{
78 79 80 81 82 83 84 85 86 87 88
  mrb_value members, ary;
  mrb_value *p, *pend;

  members = mrb_struct_s_members(mrb, klass);
  ary = mrb_ary_new_capa(mrb, RARRAY_LEN(members));
  p = RARRAY_PTR(members); pend = p + RARRAY_LEN(members);
  while (p < pend) {
    mrb_ary_push(mrb, ary, *p);
    p++;
  }
  return ary;
mimaki's avatar
mimaki committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
}

/* 15.2.18.4.6  */
/*
 *  call-seq:
 *     struct.members    -> array
 *
 *  Returns an array of strings representing the names of the instance
 *  variables.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joe.members   #=> [:name, :address, :zip]
 */

static mrb_value
mrb_struct_members_m(mrb_state *mrb, mrb_value obj)
{
107
  return mrb_struct_s_members_m(mrb, mrb_obj_value(mrb_obj_class(mrb, obj)));
mimaki's avatar
mimaki committed
108 109 110 111 112
}

mrb_value
mrb_struct_getmember(mrb_state *mrb, mrb_value obj, mrb_sym id)
{
113
  mrb_value members, slot, *ptr, *ptr_members;
114
  mrb_int i, len;
115 116 117 118 119 120 121 122 123

  ptr = RSTRUCT_PTR(obj);
  members = mrb_struct_members(mrb, obj);
  ptr_members = RARRAY_PTR(members);
  slot = mrb_symbol_value(id);
  len = RARRAY_LEN(members);
  for (i=0; i<len; i++) {
    if (mrb_obj_equal(mrb, ptr_members[i], slot)) {
      return ptr[i];
mimaki's avatar
mimaki committed
124
    }
125
  }
126
  mrb_raisef(mrb, E_INDEX_ERROR, "`%S' is not a struct member", mrb_sym2str(mrb, id));
127
  return mrb_nil_value();       /* not reached */
mimaki's avatar
mimaki committed
128 129 130 131 132
}

static mrb_value
mrb_struct_ref(mrb_state *mrb, mrb_value obj)
{
133
  return mrb_struct_getmember(mrb, obj, mrb->c->ci->mid);
mimaki's avatar
mimaki committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
}

static mrb_value mrb_struct_ref0(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[0];}
static mrb_value mrb_struct_ref1(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[1];}
static mrb_value mrb_struct_ref2(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[2];}
static mrb_value mrb_struct_ref3(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[3];}
static mrb_value mrb_struct_ref4(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[4];}
static mrb_value mrb_struct_ref5(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[5];}
static mrb_value mrb_struct_ref6(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[6];}
static mrb_value mrb_struct_ref7(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[7];}
static mrb_value mrb_struct_ref8(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[8];}
static mrb_value mrb_struct_ref9(mrb_state* mrb, mrb_value obj) {return RSTRUCT_PTR(obj)[9];}

#define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
#define N_REF_FUNC numberof(ref_func)

static mrb_value (*const ref_func[])(mrb_state*, mrb_value) = {
151 152 153 154 155 156 157 158 159 160
  mrb_struct_ref0,
  mrb_struct_ref1,
  mrb_struct_ref2,
  mrb_struct_ref3,
  mrb_struct_ref4,
  mrb_struct_ref5,
  mrb_struct_ref6,
  mrb_struct_ref7,
  mrb_struct_ref8,
  mrb_struct_ref9,
mimaki's avatar
mimaki committed
161 162 163
};

mrb_sym
164
mrb_id_attrset(mrb_state *mrb, mrb_sym id)
mimaki's avatar
mimaki committed
165
{
166 167
  const char *name;
  char *buf;
168
  mrb_int len;
169 170 171
  mrb_sym mid;

  name = mrb_sym2name_len(mrb, id, &len);
172 173
  buf = (char *)mrb_malloc(mrb, (size_t)len+2);
  memcpy(buf, name, (size_t)len);
174 175 176
  buf[len] = '=';
  buf[len+1] = '\0';

177
  mid = mrb_intern(mrb, buf, len+1);
178 179
  mrb_free(mrb, buf);
  return mid;
mimaki's avatar
mimaki committed
180 181 182 183 184
}

static mrb_value
mrb_struct_set(mrb_state *mrb, mrb_value obj, mrb_value val)
{
185
  const char *name;
186
  size_t i, len;
187
  mrb_int slen;
188 189 190 191
  mrb_sym mid;
  mrb_value members, slot, *ptr, *ptr_members;

  /* get base id */
192 193
  name = mrb_sym2name_len(mrb, mrb->c->ci->mid, &slen);
  mid = mrb_intern(mrb, name, slen-1); /* omit last "=" */
194 195 196 197 198 199 200

  members = mrb_struct_members(mrb, obj);
  ptr_members = RARRAY_PTR(members);
  len = RARRAY_LEN(members);
  ptr = RSTRUCT_PTR(obj);
  for (i=0; i<len; i++) {
    slot = ptr_members[i];
201
    if (mrb_symbol(slot) == mid) {
202
      return ptr[i] = val;
mimaki's avatar
mimaki committed
203
    }
204
  }
205 206
  mrb_raisef(mrb, E_INDEX_ERROR, "`%S' is not a struct member", mrb_sym2str(mrb, mid));
  return mrb_nil_value();       /* not reached */
mimaki's avatar
mimaki committed
207 208
}

209 210 211 212 213 214 215 216 217
static mrb_value
mrb_struct_set_m(mrb_state *mrb, mrb_value obj)
{
  mrb_value val;

  mrb_get_args(mrb, "o", &val);
  return mrb_struct_set(mrb, obj, val);
}

218 219
#define is_notop_id(id) (id) /* ((id)>tLAST_TOKEN) */
#define is_local_id(id) (is_notop_id(id)) /* &&((id)&ID_SCOPE_MASK)==ID_LOCAL) */
mimaki's avatar
mimaki committed
220 221 222
int
mrb_is_local_id(mrb_sym id)
{
223
  return is_local_id(id);
mimaki's avatar
mimaki committed
224 225
}

226
#define is_const_id(id) (is_notop_id(id)) /* &&((id)&ID_SCOPE_MASK)==ID_CONST) */
mimaki's avatar
mimaki committed
227 228 229
int
mrb_is_const_id(mrb_sym id)
{
230
  return is_const_id(id);
mimaki's avatar
mimaki committed
231 232 233 234 235
}

static mrb_value
make_struct(mrb_state *mrb, mrb_value name, mrb_value members, struct RClass * klass)
{
236 237
  mrb_value nstr, *ptr_members;
  mrb_sym id;
238
  mrb_int i, len;
239
  struct RClass *c;
240
  int ai;
mimaki's avatar
mimaki committed
241

242 243 244 245 246 247
  if (mrb_nil_p(name)) {
    c = mrb_class_new(mrb, klass);
  }
  else {
    /* old style: should we warn? */
    name = mrb_str_to_str(mrb, name);
248
    id = mrb_obj_to_sym(mrb, name);
249
    if (!mrb_is_const_id(id)) {
250
      mrb_name_error(mrb, id, "identifier %S needs to be constant", name);
mimaki's avatar
mimaki committed
251
    }
252
    if (mrb_const_defined_at(mrb, klass, id)) {
253
      mrb_warn(mrb, "redefining constant Struct::%S", name);
254
      /* ?rb_mod_remove_const(klass, mrb_sym2name(mrb, id)); */
mimaki's avatar
mimaki committed
255
    }
256 257
    c = mrb_define_class_under(mrb, klass, RSTRING_PTR(name), klass);
  }
258
  MRB_SET_INSTANCE_TT(c, MRB_TT_ARRAY);
259
  nstr = mrb_obj_value(c);
260
  mrb_iv_set(mrb, nstr, mrb_intern_lit(mrb, "__members__"), members);
261

262 263 264
  mrb_define_class_method(mrb, c, "new", mrb_instance_new, MRB_ARGS_ANY());
  mrb_define_class_method(mrb, c, "[]", mrb_instance_new, MRB_ARGS_ANY());
  mrb_define_class_method(mrb, c, "members", mrb_struct_s_members_m, MRB_ARGS_NONE());
265
  /* RSTRUCT(nstr)->basic.c->super = c->c; */
266 267
  ptr_members = RARRAY_PTR(members);
  len = RARRAY_LEN(members);
268
  ai = mrb_gc_arena_save(mrb);
269 270 271 272
  for (i=0; i< len; i++) {
    mrb_sym id = mrb_symbol(ptr_members[i]);
    if (mrb_is_local_id(id) || mrb_is_const_id(id)) {
      if (i < N_REF_FUNC) {
273
        mrb_define_method_id(mrb, c, id, ref_func[i], MRB_ARGS_NONE());
mimaki's avatar
mimaki committed
274
      }
275
      else {
276
        mrb_define_method_id(mrb, c, id, mrb_struct_ref, MRB_ARGS_NONE());
277
      }
278
      mrb_define_method_id(mrb, c, mrb_id_attrset(mrb, id), mrb_struct_set_m, MRB_ARGS_REQ(1));
279
      mrb_gc_arena_restore(mrb, ai);
mimaki's avatar
mimaki committed
280
    }
281 282
  }
  return nstr;
mimaki's avatar
mimaki committed
283 284 285 286 287
}

mrb_value
mrb_struct_define(mrb_state *mrb, const char *name, ...)
{
288 289 290 291 292
  va_list ar;
  mrb_value nm, ary;
  char *mem;

  if (!name) nm = mrb_nil_value();
293
  else nm = mrb_str_new_cstr(mrb, name);
294 295 296 297
  ary = mrb_ary_new(mrb);

  va_start(ar, name);
  while ((mem = va_arg(ar, char*)) != 0) {
298
    mrb_sym slot = mrb_intern_cstr(mrb, mem);
299 300 301
    mrb_ary_push(mrb, ary, mrb_symbol_value(slot));
  }
  va_end(ar);
mimaki's avatar
mimaki committed
302

303
  return make_struct(mrb, nm, ary, struct_class(mrb));
mimaki's avatar
mimaki committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
}

/* 15.2.18.3.1  */
/*
 *  call-seq:
 *     Struct.new( [aString] [, aSym]+> )    -> StructClass
 *     StructClass.new(arg, ...)             -> obj
 *     StructClass[arg, ...]                 -> obj
 *
 *  Creates a new class, named by <i>aString</i>, containing accessor
 *  methods for the given symbols. If the name <i>aString</i> is
 *  omitted, an anonymous structure class will be created. Otherwise,
 *  the name of this struct will appear as a constant in class
 *  <code>Struct</code>, so it must be unique for all
 *  <code>Struct</code>s in the system and should start with a capital
 *  letter. Assigning a structure class to a constant effectively gives
 *  the class the name of the constant.
 *
 *  <code>Struct::new</code> returns a new <code>Class</code> object,
 *  which can then be used to create specific instances of the new
 *  structure. The number of actual parameters must be
 *  less than or equal to the number of attributes defined for this
 *  class; unset parameters default to <code>nil</code>.  Passing too many
 *  parameters will raise an <code>ArgumentError</code>.
 *
 *  The remaining methods listed in this section (class and instance)
 *  are defined for this generated class.
 *
 *     # Create a structure with a name in Struct
 *     Struct.new("Customer", :name, :address)    #=> Struct::Customer
 *     Struct::Customer.new("Dave", "123 Main")   #=> #<struct Struct::Customer name="Dave", address="123 Main">
 *
 *     # Create a structure named by its constant
 *     Customer = Struct.new(:name, :address)     #=> Customer
 *     Customer.new("Dave", "123 Main")           #=> #<struct Customer name="Dave", address="123 Main">
 */
static mrb_value
mrb_struct_s_def(mrb_state *mrb, mrb_value klass)
{
  mrb_value name, rest;
  mrb_value *pargv;
  int argcnt;
346
  mrb_int i;
mimaki's avatar
mimaki committed
347 348 349
  mrb_value b, st;
  mrb_sym id;
  mrb_value *argv;
350
  mrb_int argc;
mimaki's avatar
mimaki committed
351 352 353

  name = mrb_nil_value();
  rest = mrb_nil_value();
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
354
  mrb_get_args(mrb, "*&", &argv, &argc, &b);
355 356
  if (argc == 0) { /* special case to avoid crash */
    rest = mrb_ary_new(mrb);
357 358
  }
  else {
359 360
    if (argc > 0) name = argv[0];
    if (argc > 1) rest = argv[1];
361
    if (mrb_array_p(rest)) {
362
      if (!mrb_nil_p(name) && mrb_symbol_p(name)) {
363 364 365 366
        /* 1stArgument:symbol -> name=nil rest=argv[0]-[n] */
        mrb_ary_unshift(mrb, rest, name);
        name = mrb_nil_value();
      }
mimaki's avatar
mimaki committed
367
    }
368 369 370
    else {
      pargv = &argv[1];
      argcnt = argc-1;
371
      if (!mrb_nil_p(name) && mrb_symbol_p(name)) {
372 373 374 375 376 377
        /* 1stArgument:symbol -> name=nil rest=argv[0]-[n] */
        name = mrb_nil_value();
        pargv = &argv[0];
        argcnt++;
      }
      rest = mrb_ary_new_from_values(mrb, argcnt, pargv);
mimaki's avatar
mimaki committed
378
    }
379
    for (i=0; i<RARRAY_LEN(rest); i++) {
380
      id = mrb_obj_to_sym(mrb, RARRAY_PTR(rest)[i]);
381 382
      RARRAY_PTR(rest)[i] = mrb_symbol_value(id);
    }
383
  }
mimaki's avatar
mimaki committed
384 385
  st = make_struct(mrb, name, rest, struct_class(mrb));
  if (!mrb_nil_p(b)) {
386
    mrb_yield_with_class(mrb, b, 1, &st, st, mrb_class_ptr(klass));
mimaki's avatar
mimaki committed
387 388 389 390 391
  }

  return st;
}

Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
392
static int
mimaki's avatar
mimaki committed
393 394
num_members(mrb_state *mrb, struct RClass *klass)
{
395 396
  mrb_value members;

397
  members = struct_ivar_get(mrb, mrb_obj_value(klass), mrb_intern_lit(mrb, "__members__"));
398 399 400 401
  if (!mrb_array_p(members)) {
    mrb_raise(mrb, E_TYPE_ERROR, "broken members");
  }
  return RARRAY_LEN(members);
mimaki's avatar
mimaki committed
402 403 404 405 406 407 408 409 410
}

/* 15.2.18.4.8  */
/*
 */
static mrb_value
mrb_struct_initialize_withArg(mrb_state *mrb, int argc, mrb_value *argv, mrb_value self)
{
  struct RClass *klass = mrb_obj_class(mrb, self);
mattn's avatar
mattn committed
411
  int i, n;
mimaki's avatar
mimaki committed
412 413 414 415 416

  n = num_members(mrb, klass);
  if (n < argc) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "struct size differs");
  }
417

418
  for (i = 0; i < argc; i++) {
419
    mrb_ary_set(mrb, self, i, argv[i]);
420
  }
mattn's avatar
mattn committed
421
  for (i = argc; i < n; i++) {
422
    mrb_ary_set(mrb, self, i, mrb_nil_value());
mattn's avatar
mattn committed
423
  }
mimaki's avatar
mimaki committed
424 425 426 427 428 429 430
  return self;
}

static mrb_value
mrb_struct_initialize_m(mrb_state *mrb, /*int argc, mrb_value *argv,*/ mrb_value self)
{
  mrb_value *argv;
431
  mrb_int argc;
mimaki's avatar
mimaki committed
432 433 434 435 436 437 438 439

  mrb_get_args(mrb, "*", &argv, &argc);
  return mrb_struct_initialize_withArg(mrb, argc, argv, self);
}

mrb_value
mrb_struct_initialize(mrb_state *mrb, mrb_value self, mrb_value values)
{
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
440
  return mrb_struct_initialize_withArg(mrb, RARRAY_LEN(values), RARRAY_PTR(values), self);
mimaki's avatar
mimaki committed
441 442 443
}

static mrb_value
444
inspect_struct(mrb_state *mrb, mrb_value s, int recur)
mimaki's avatar
mimaki committed
445
{
446
  const char *cn = mrb_class_name(mrb, mrb_obj_class(mrb, s));
447
  mrb_value members, str = mrb_str_new_lit(mrb, "#<struct ");
448
  mrb_value *ptr, *ptr_members;
449
  mrb_int i, len;
450 451 452 453 454

  if (cn) {
    mrb_str_append(mrb, str, mrb_str_new_cstr(mrb, cn));
  }
  if (recur) {
455
    return mrb_str_cat_lit(mrb, str, ":...>");
456 457 458 459 460 461 462 463 464
  }

  members = mrb_struct_members(mrb, s);
  ptr_members = RARRAY_PTR(members);
  ptr = RSTRUCT_PTR(s);
  len = RSTRUCT_LEN(s);
  for (i=0; i<len; i++) {
    mrb_value slot;
    mrb_sym id;
mimaki's avatar
mimaki committed
465

466
    if (i > 0) {
467
      mrb_str_cat_lit(mrb, str, ", ");
mimaki's avatar
mimaki committed
468
    }
469
    else if (cn) {
470
      mrb_str_cat_lit(mrb, str, " ");
mimaki's avatar
mimaki committed
471
    }
472 473 474 475
    slot = ptr_members[i];
    id = mrb_symbol(slot);
    if (mrb_is_local_id(id) || mrb_is_const_id(id)) {
      const char *name;
476
      mrb_int len;
mimaki's avatar
mimaki committed
477

478 479
      name = mrb_sym2name_len(mrb, id, &len);
      mrb_str_append(mrb, str, mrb_str_new(mrb, name, len));
mimaki's avatar
mimaki committed
480
    }
481 482 483
    else {
      mrb_str_append(mrb, str, mrb_inspect(mrb, slot));
    }
484
    mrb_str_cat_lit(mrb, str, "=");
485 486
    mrb_str_append(mrb, str, mrb_inspect(mrb, ptr[i]));
  }
487
  mrb_str_cat_lit(mrb, str, ">");
mimaki's avatar
mimaki committed
488

489
  return str;
mimaki's avatar
mimaki committed
490 491 492 493 494 495 496 497 498 499 500 501
}

/*
 * call-seq:
 *   struct.to_s      -> string
 *   struct.inspect   -> string
 *
 * Describe the contents of this struct in a string.
 */
static mrb_value
mrb_struct_inspect(mrb_state *mrb, mrb_value s)
{
502
  return inspect_struct(mrb, s, 0);
mimaki's avatar
mimaki committed
503 504 505 506 507 508 509
}

/* 15.2.18.4.9  */
/* :nodoc: */
mrb_value
mrb_struct_init_copy(mrb_state *mrb, mrb_value copy)
{
510
  mrb_value s;
cubicdaiya's avatar
cubicdaiya committed
511
  mrb_int i, len;
512

mimaki's avatar
mimaki committed
513 514
  mrb_get_args(mrb, "o", &s);

515
  if (mrb_obj_equal(mrb, copy, s)) return copy;
516 517 518 519 520 521 522
  if (!mrb_obj_is_instance_of(mrb, s, mrb_obj_class(mrb, copy))) {
    mrb_raise(mrb, E_TYPE_ERROR, "wrong argument class");
  }
  if (!mrb_array_p(s)) {
    mrb_raise(mrb, E_TYPE_ERROR, "corrupted struct");
  }
  if (RSTRUCT_LEN(copy) != RSTRUCT_LEN(s)) {
523 524
    mrb_raise(mrb, E_TYPE_ERROR, "struct size mismatch");
  }
525
  len = RSTRUCT_LEN(copy);
526
  for (i = 0; i < len; i++) {
527
    mrb_ary_set(mrb, copy, i, RSTRUCT_PTR(s)[i]);
528
  }
529
  return copy;
mimaki's avatar
mimaki committed
530 531 532 533 534
}

static mrb_value
mrb_struct_aref_id(mrb_state *mrb, mrb_value s, mrb_sym id)
{
535
  mrb_value *ptr, members, *ptr_members;
536
  mrb_int i, len;
537 538 539 540 541 542 543 544

  ptr = RSTRUCT_PTR(s);
  members = mrb_struct_members(mrb, s);
  ptr_members = RARRAY_PTR(members);
  len = RARRAY_LEN(members);
  for (i=0; i<len; i++) {
    if (mrb_symbol(ptr_members[i]) == id) {
      return ptr[i];
mimaki's avatar
mimaki committed
545
    }
546
  }
547
  mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", mrb_sym2str(mrb, id));
548
  return mrb_nil_value();       /* not reached */
mimaki's avatar
mimaki committed
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
}

/* 15.2.18.4.2  */
/*
 *  call-seq:
 *     struct[symbol]    -> anObject
 *     struct[fixnum]    -> anObject
 *
 *  Attribute Reference---Returns the value of the instance variable
 *  named by <i>symbol</i>, or indexed (0..length-1) by
 *  <i>fixnum</i>. Will raise <code>NameError</code> if the named
 *  variable does not exist, or <code>IndexError</code> if the index is
 *  out of range.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *
 *     joe["name"]   #=> "Joe Smith"
 *     joe[:name]    #=> "Joe Smith"
 *     joe[0]        #=> "Joe Smith"
 */
mrb_value
mrb_struct_aref_n(mrb_state *mrb, mrb_value s, mrb_value idx)
{
573
  mrb_int i;
mimaki's avatar
mimaki committed
574

575 576 577 578 579 580 581 582 583 584
  if (mrb_string_p(idx)) {
    mrb_value sym = mrb_check_intern_str(mrb, idx);

    if (mrb_nil_p(sym)) {
      mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", idx);
    }
    idx = sym;
  }
  if (mrb_symbol_p(idx)) {
    return mrb_struct_aref_id(mrb, s, mrb_symbol(idx));
mimaki's avatar
mimaki committed
585 586 587 588 589
  }

  i = mrb_fixnum(idx);
  if (i < 0) i = RSTRUCT_LEN(s) + i;
  if (i < 0)
590
      mrb_raisef(mrb, E_INDEX_ERROR,
591 592
                 "offset %S too small for struct(size:%S)",
                 mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
mimaki's avatar
mimaki committed
593
  if (RSTRUCT_LEN(s) <= i)
594
    mrb_raisef(mrb, E_INDEX_ERROR,
595 596
               "offset %S too large for struct(size:%S)",
               mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
mimaki's avatar
mimaki committed
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
  return RSTRUCT_PTR(s)[i];
}

mrb_value
mrb_struct_aref(mrb_state *mrb, mrb_value s)
{
  mrb_value idx;

  mrb_get_args(mrb, "o", &idx);
  return mrb_struct_aref_n(mrb, s, idx);
}

static mrb_value
mrb_struct_aset_id(mrb_state *mrb, mrb_value s, mrb_sym id, mrb_value val)
{
612
  mrb_value members, *ptr, *ptr_members;
613
  mrb_int i, len;
mimaki's avatar
mimaki committed
614

615 616 617
  members = mrb_struct_members(mrb, s);
  len = RARRAY_LEN(members);
  if (RSTRUCT_LEN(s) != len) {
618
    mrb_raisef(mrb, E_TYPE_ERROR,
619 620
               "struct size differs (%S required %S given)",
               mrb_fixnum_value(len), mrb_fixnum_value(RSTRUCT_LEN(s)));
621 622 623 624 625 626 627
  }
  ptr = RSTRUCT_PTR(s);
  ptr_members = RARRAY_PTR(members);
  for (i=0; i<len; i++) {
    if (mrb_symbol(ptr_members[i]) == id) {
      ptr[i] = val;
      return val;
mimaki's avatar
mimaki committed
628
    }
629
  }
630
  mrb_raisef(mrb, E_INDEX_ERROR, "no member '%S' in struct", mrb_sym2str(mrb, id));
631
  return val;                   /* not reach */
mimaki's avatar
mimaki committed
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
}

/* 15.2.18.4.3  */
/*
 *  call-seq:
 *     struct[symbol] = obj    -> obj
 *     struct[fixnum] = obj    -> obj
 *
 *  Attribute Assignment---Assigns to the instance variable named by
 *  <i>symbol</i> or <i>fixnum</i> the value <i>obj</i> and
 *  returns it. Will raise a <code>NameError</code> if the named
 *  variable does not exist, or an <code>IndexError</code> if the index
 *  is out of range.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *
 *     joe["name"] = "Luke"
 *     joe[:zip]   = "90210"
 *
 *     joe.name   #=> "Luke"
 *     joe.zip    #=> "90210"
 */

mrb_value
mrb_struct_aset(mrb_state *mrb, mrb_value s)
{
659
  mrb_int i;
mimaki's avatar
mimaki committed
660 661
  mrb_value idx;
  mrb_value val;
662

mimaki's avatar
mimaki committed
663 664
  mrb_get_args(mrb, "oo", &idx, &val);

665
  if (mrb_string_p(idx) || mrb_symbol_p(idx)) {
666
    return mrb_struct_aset_id(mrb, s, mrb_obj_to_sym(mrb, idx), val);
667
  }
mimaki's avatar
mimaki committed
668

669 670 671
  i = mrb_fixnum(idx);
  if (i < 0) i = RSTRUCT_LEN(s) + i;
  if (i < 0) {
672
    mrb_raisef(mrb, E_INDEX_ERROR,
673 674
               "offset %S too small for struct(size:%S)",
               mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
675 676
  }
  if (RSTRUCT_LEN(s) <= i) {
677
    mrb_raisef(mrb, E_INDEX_ERROR,
678 679
               "offset %S too large for struct(size:%S)",
               mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
680 681
  }
  return RSTRUCT_PTR(s)[i] = val;
mimaki's avatar
mimaki committed
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
}

/* 15.2.18.4.1  */
/*
 *  call-seq:
 *     struct == other_struct     -> true or false
 *
 *  Equality---Returns <code>true</code> if <i>other_struct</i> is
 *  equal to this one: they must be of the same class as generated by
 *  <code>Struct::new</code>, and the values of all instance variables
 *  must be equal (according to <code>Object#==</code>).
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe   = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     jane  = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)
 *     joe == joejr   #=> true
 *     joe == jane    #=> false
 */

static mrb_value
mrb_struct_equal(mrb_state *mrb, mrb_value s)
{
  mrb_value s2;
706
  mrb_value *ptr, *ptr2;
707
  mrb_int i, len;
708
  mrb_bool equal_p;
mimaki's avatar
mimaki committed
709 710

  mrb_get_args(mrb, "o", &s2);
711 712 713 714 715 716 717 718
  if (mrb_obj_equal(mrb, s, s2)) {
    equal_p = 1;
  }
  else if (!strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s)), "Struct") ||
           mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) {
    equal_p = 0;
  }
  else if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
719
    mrb_bug(mrb, "inconsistent struct"); /* should never happen */
720
    equal_p = 0; /* This substuture is just to suppress warnings. never called. */
mimaki's avatar
mimaki committed
721
  }
722 723 724 725 726 727 728 729 730 731 732
  else {
    ptr = RSTRUCT_PTR(s);
    ptr2 = RSTRUCT_PTR(s2);
    len = RSTRUCT_LEN(s);
    equal_p = 1;
    for (i=0; i<len; i++) {
      if (!mrb_equal(mrb, ptr[i], ptr2[i])) {
        equal_p = 0;
        break;
      }
    }
733
  }
734

735
  return mrb_bool_value(equal_p);
mimaki's avatar
mimaki committed
736 737 738 739 740 741 742 743 744 745 746 747 748 749
}

/* 15.2.18.4.12(x)  */
/*
 * code-seq:
 *   struct.eql?(other)   -> true or false
 *
 * Two structures are equal if they are the same object, or if all their
 * fields are equal (using <code>eql?</code>).
 */
static mrb_value
mrb_struct_eql(mrb_state *mrb, mrb_value s)
{
  mrb_value s2;
750
  mrb_value *ptr, *ptr2;
751
  mrb_int i, len;
752
  mrb_bool eql_p;
mimaki's avatar
mimaki committed
753 754

  mrb_get_args(mrb, "o", &s2);
755 756 757 758 759 760 761 762
  if (mrb_obj_equal(mrb, s, s2)) {
    eql_p = 1;
  }
  else if (strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s2)), "Struct") ||
           mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) {
    eql_p = 0;
  }
  else if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) {
763
    mrb_bug(mrb, "inconsistent struct"); /* should never happen */
764
    eql_p = 0; /* This substuture is just to suppress warnings. never called. */
mimaki's avatar
mimaki committed
765
  }
766 767 768 769 770 771 772 773 774 775 776
  else {
    ptr = RSTRUCT_PTR(s);
    ptr2 = RSTRUCT_PTR(s2);
    len = RSTRUCT_LEN(s);
    eql_p = 1;
    for (i=0; i<len; i++) {
      if (!mrb_eql(mrb, ptr[i], ptr2[i])) {
        eql_p = 0;
        break;
      }
    }
777
  }
778

779
  return mrb_bool_value(eql_p);
mimaki's avatar
mimaki committed
780 781
}

782 783 784 785 786 787 788 789 790 791 792 793 794
/*
 * call-seq:
 *    struct.length   -> Fixnum
 *    struct.size     -> Fixnum
 *
 * Returns number of struct members.
 */
static mrb_value
mrb_struct_len(mrb_state *mrb, mrb_value self)
{
  return mrb_fixnum_value(RSTRUCT_LEN(self));
}

795 796 797 798 799 800 801 802 803 804 805 806 807
/*
 * call-seq:
 *    struct.to_a    -> array
 *    struct.values  -> array
 *
 * Create an array from struct values.
 */
static mrb_value
mrb_struct_to_a(mrb_state *mrb, mrb_value self)
{
  return mrb_ary_new_from_values(mrb, RSTRUCT_LEN(self), RSTRUCT_PTR(self));
}

mimaki's avatar
mimaki committed
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
/*
 *  A <code>Struct</code> is a convenient way to bundle a number of
 *  attributes together, using accessor methods, without having to write
 *  an explicit class.
 *
 *  The <code>Struct</code> class is a generator of specific classes,
 *  each one of which is defined to hold a set of variables and their
 *  accessors. In these examples, we'll call the generated class
 *  ``<i>Customer</i>Class,'' and we'll show an example instance of that
 *  class as ``<i>Customer</i>Inst.''
 *
 *  In the descriptions that follow, the parameter <i>symbol</i> refers
 *  to a symbol, which is either a quoted string or a
 *  <code>Symbol</code> (such as <code>:name</code>).
 */
void
mattn's avatar
mattn committed
824
mrb_mruby_struct_gem_init(mrb_state* mrb)
mimaki's avatar
mimaki committed
825 826 827 828
{
  struct RClass *st;
  st = mrb_define_class(mrb, "Struct",  mrb->object_class);

829
  mrb_define_class_method(mrb, st, "new",             mrb_struct_s_def,       MRB_ARGS_ANY());  /* 15.2.18.3.1  */
mimaki's avatar
mimaki committed
830

831 832 833 834 835 836 837
  mrb_define_method(mrb, st,       "==",              mrb_struct_equal,       MRB_ARGS_REQ(1)); /* 15.2.18.4.1  */
  mrb_define_method(mrb, st,       "[]",              mrb_struct_aref,        MRB_ARGS_REQ(1)); /* 15.2.18.4.2  */
  mrb_define_method(mrb, st,       "[]=",             mrb_struct_aset,        MRB_ARGS_REQ(2)); /* 15.2.18.4.3  */
  mrb_define_method(mrb, st,       "members",         mrb_struct_members_m,   MRB_ARGS_NONE()); /* 15.2.18.4.6  */
  mrb_define_method(mrb, st,       "initialize",      mrb_struct_initialize_m,MRB_ARGS_ANY());  /* 15.2.18.4.8  */
  mrb_define_method(mrb, st,       "initialize_copy", mrb_struct_init_copy,   MRB_ARGS_REQ(1)); /* 15.2.18.4.9  */
  mrb_define_method(mrb, st,       "inspect",         mrb_struct_inspect,     MRB_ARGS_NONE()); /* 15.2.18.4.10(x)  */
mimaki's avatar
mimaki committed
838
  mrb_define_alias(mrb, st,        "to_s", "inspect");                                      /* 15.2.18.4.11(x)  */
839
  mrb_define_method(mrb, st,       "eql?",            mrb_struct_eql,         MRB_ARGS_REQ(1)); /* 15.2.18.4.12(x)  */
840 841 842

  mrb_define_method(mrb, st,        "size",           mrb_struct_len,         MRB_ARGS_NONE());
  mrb_define_method(mrb, st,        "length",         mrb_struct_len,         MRB_ARGS_NONE());
843 844
  mrb_define_method(mrb, st,        "to_a",           mrb_struct_to_a,        MRB_ARGS_NONE());
  mrb_define_method(mrb, st,        "values",         mrb_struct_to_a,        MRB_ARGS_NONE());
mimaki's avatar
mimaki committed
845
}
mattn's avatar
mattn committed
846 847 848 849 850

void
mrb_mruby_struct_gem_final(mrb_state* mrb)
{
}