struct.c 22.8 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/data.h"
14
#include "mruby/variable.h"
mimaki's avatar
mimaki committed
15

16
#define RSTRUCT_ARY(st) mrb_ary_ptr(st)
17 18
#define RSTRUCT_LEN(st) RSTRUCT_ARY(st)->len
#define RSTRUCT_PTR(st) RSTRUCT_ARY(st)->ptr
mimaki's avatar
mimaki committed
19 20 21 22 23 24 25 26 27 28 29 30 31

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;
32 33 34 35 36 37 38 39 40

  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
41 42 43 44 45
}

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

mrb_value
mrb_struct_s_members(mrb_state *mrb, mrb_value klass)
{
52
  mrb_value members = struct_ivar_get(mrb, klass, mrb_intern2(mrb, "__members__", 11));
mimaki's avatar
mimaki committed
53

54 55 56 57 58 59 60
  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
61 62 63 64 65 66
}

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
67
  if (!strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s)), "Struct")) {
mimaki's avatar
mimaki committed
68
    if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) {
69
      mrb_raisef(mrb, E_TYPE_ERROR,
70 71
                 "struct size differs (%S required %S given)",
                 mrb_fixnum_value(RARRAY_LEN(members)), mrb_fixnum_value(RSTRUCT_LEN(s)));
mimaki's avatar
mimaki committed
72 73 74 75 76 77 78 79
    }
  }
  return members;
}

static mrb_value
mrb_struct_s_members_m(mrb_state *mrb, mrb_value klass)
{
80 81 82 83 84 85 86 87 88 89 90
  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
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
}

/* 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)
{
109
  return mrb_struct_s_members_m(mrb, mrb_obj_value(mrb_obj_class(mrb, obj)));
mimaki's avatar
mimaki committed
110 111 112 113 114
}

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

  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
126
    }
127
  }
128
  mrb_name_error(mrb, id, "%S is not struct member", mrb_sym2str(mrb, id));
129
  return mrb_nil_value();       /* not reached */
mimaki's avatar
mimaki committed
130 131 132 133 134
}

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

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) = {
153 154 155 156 157 158 159 160 161 162
  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
163 164 165
};

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

  name = mrb_sym2name_len(mrb, id, &len);
174
  buf = (char *)mrb_malloc(mrb, len+2);
175 176 177 178 179 180 181
  memcpy(buf, name, len);
  buf[len] = '=';
  buf[len+1] = '\0';

  mid = mrb_intern2(mrb, buf, len+1);
  mrb_free(mrb, buf);
  return mid;
mimaki's avatar
mimaki committed
182 183 184 185 186
}

static mrb_value
mrb_struct_set(mrb_state *mrb, mrb_value obj, mrb_value val)
{
187
  const char *name;
188 189
  int i;
  size_t len;
190 191 192 193 194 195 196 197 198 199 200 201 202
  mrb_sym mid;
  mrb_value members, slot, *ptr, *ptr_members;

  /* get base id */
  name = mrb_sym2name_len(mrb, mrb->ci->mid, &len);
  mid = mrb_intern2(mrb, name, len-1); /* omit last "=" */

  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];
203
    if (mrb_symbol(slot) == mid) {
204
      return ptr[i] = val;
mimaki's avatar
mimaki committed
205
    }
206
  }
207
  mrb_name_error(mrb, mid, "`%S' is not a struct member",
208
             mrb_sym2str(mrb, mid));
209
  return mrb_nil_value();            /* not reached */
mimaki's avatar
mimaki committed
210 211
}

212 213 214 215 216 217 218 219 220
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);
}

mimaki's avatar
mimaki committed
221 222 223 224 225
#define is_notop_id(id) (id)//((id)>tLAST_TOKEN)
#define is_local_id(id) (is_notop_id(id))//&&((id)&ID_SCOPE_MASK)==ID_LOCAL)
int
mrb_is_local_id(mrb_sym id)
{
226
  return is_local_id(id);
mimaki's avatar
mimaki committed
227 228 229 230 231 232
}

#define is_const_id(id) (is_notop_id(id))//&&((id)&ID_SCOPE_MASK)==ID_CONST)
int
mrb_is_const_id(mrb_sym id)
{
233
  return is_const_id(id);
mimaki's avatar
mimaki committed
234 235 236 237 238
}

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

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

264 265 266
  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());
267 268 269 270 271 272 273
  //RSTRUCT(nstr)->basic.c->super = c->c;
  ptr_members = RARRAY_PTR(members);
  len = RARRAY_LEN(members);
  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) {
274
        mrb_define_method_id(mrb, c, id, ref_func[i], MRB_ARGS_NONE());
mimaki's avatar
mimaki committed
275
      }
276
      else {
277
        mrb_define_method_id(mrb, c, id, mrb_struct_ref, MRB_ARGS_NONE());
278
      }
279
      mrb_define_method_id(mrb, c, mrb_id_attrset(mrb, id), mrb_struct_set_m, MRB_ARGS_REQ(1));
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 298 299 300 301
  ary = mrb_ary_new(mrb);

  va_start(ar, name);
  while ((mem = va_arg(ar, char*)) != 0) {
    mrb_sym slot = mrb_intern(mrb, mem);
    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 350 351 352 353
  mrb_value b, st;
  mrb_sym id;
  mrb_value *argv;
  int argc;

  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 380 381 382
    for (i=0; i<RARRAY_LEN(rest); i++) {
      id = mrb_to_id(mrb, RARRAY_PTR(rest)[i]);
      RARRAY_PTR(rest)[i] = mrb_symbol_value(id);
    }
383
  }
mimaki's avatar
mimaki committed
384 385 386 387 388 389 390 391
  st = make_struct(mrb, name, rest, struct_class(mrb));
  if (!mrb_nil_p(b)) {
    mrb_funcall(mrb, b, "call", 1, &st);
  }

  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_intern2(mrb, "__members__", 11));
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 431 432 433 434 435 436 437 438 439
  return self;
}

static mrb_value
mrb_struct_initialize_m(mrb_state *mrb, /*int argc, mrb_value *argv,*/ mrb_value self)
{
  mrb_value *argv;
  int argc;

  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 447 448
  const char *cn = mrb_class_name(mrb, mrb_obj_class(mrb, s));
  mrb_value members, str = mrb_str_new(mrb, "#<struct ", 9);
  mrb_value *ptr, *ptr_members;
449
  mrb_int i, len;
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464

  if (cn) {
    mrb_str_append(mrb, str, mrb_str_new_cstr(mrb, cn));
  }
  if (recur) {
    return mrb_str_cat2(mrb, str, ":...>");
  }

  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 467
    if (i > 0) {
      mrb_str_cat2(mrb, str, ", ");
mimaki's avatar
mimaki committed
468
    }
469 470
    else if (cn) {
      mrb_str_cat2(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
      size_t 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 484 485 486 487
    else {
      mrb_str_append(mrb, str, mrb_inspect(mrb, slot));
    }
    mrb_str_cat2(mrb, str, "=");
    mrb_str_append(mrb, str, mrb_inspect(mrb, ptr[i]));
  }
  mrb_str_cat2(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;
511
  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_name_error(mrb, id, "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
  if (mrb_string_p(idx) || mrb_symbol_p(idx)) {
mimaki's avatar
mimaki committed
576 577 578 579 580 581
    return mrb_struct_aref_id(mrb, s, mrb_to_id(mrb, idx));
  }

  i = mrb_fixnum(idx);
  if (i < 0) i = RSTRUCT_LEN(s) + i;
  if (i < 0)
582
      mrb_raisef(mrb, E_INDEX_ERROR,
583 584
                 "offset %S too small for struct(size:%S)",
                 mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
mimaki's avatar
mimaki committed
585
  if (RSTRUCT_LEN(s) <= i)
586
    mrb_raisef(mrb, E_INDEX_ERROR,
587 588
               "offset %S too large for struct(size:%S)",
               mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s)));
mimaki's avatar
mimaki committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
  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)
{
604
  mrb_value members, *ptr, *ptr_members;
605
  mrb_int i, len;
mimaki's avatar
mimaki committed
606

607 608 609
  members = mrb_struct_members(mrb, s);
  len = RARRAY_LEN(members);
  if (RSTRUCT_LEN(s) != len) {
610
    mrb_raisef(mrb, E_TYPE_ERROR,
611 612
               "struct size differs (%S required %S given)",
               mrb_fixnum_value(len), mrb_fixnum_value(RSTRUCT_LEN(s)));
613 614 615 616 617 618 619
  }
  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
620
    }
621
  }
622
  mrb_name_error(mrb, id, "no member '%S' in struct", mrb_sym2str(mrb, id));
623
  return val;                   /* not reach */
mimaki's avatar
mimaki committed
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
}

/* 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)
{
651
  mrb_int i;
mimaki's avatar
mimaki committed
652 653
  mrb_value idx;
  mrb_value val;
654

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

657
  if (mrb_string_p(idx) || mrb_symbol_p(idx)) {
658 659
    return mrb_struct_aset_id(mrb, s, mrb_to_id(mrb, idx), val);
  }
mimaki's avatar
mimaki committed
660

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

/* 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;
698
  mrb_value *ptr, *ptr2;
699
  mrb_int i, len;
700
  mrb_bool equal_p;
mimaki's avatar
mimaki committed
701 702

  mrb_get_args(mrb, "o", &s2);
703 704 705 706 707 708 709 710
  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)) {
mimaki's avatar
mimaki committed
711
    mrb_bug("inconsistent struct"); /* should never happen */
712
    equal_p = 0; /* This substuture is just to suppress warnings. never called. */
mimaki's avatar
mimaki committed
713
  }
714 715 716 717 718 719 720 721 722 723 724
  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;
      }
    }
725
  }
726

727
  return mrb_bool_value(equal_p);
mimaki's avatar
mimaki committed
728 729 730 731 732 733 734 735 736 737 738 739 740 741
}

/* 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;
742
  mrb_value *ptr, *ptr2;
743
  mrb_int i, len;
744
  mrb_bool eql_p;
mimaki's avatar
mimaki committed
745 746

  mrb_get_args(mrb, "o", &s2);
747 748 749 750 751 752 753 754
  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)) {
mimaki's avatar
mimaki committed
755
    mrb_bug("inconsistent struct"); /* should never happen */
756
    eql_p = 0; /* This substuture is just to suppress warnings. never called. */
mimaki's avatar
mimaki committed
757
  }
758 759 760 761 762 763 764 765 766 767 768
  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;
      }
    }
769
  }
770

771
  return mrb_bool_value(eql_p);
mimaki's avatar
mimaki committed
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
}

/*
 *  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
790
mrb_mruby_struct_gem_init(mrb_state* mrb)
mimaki's avatar
mimaki committed
791 792 793 794
{
  struct RClass *st;
  st = mrb_define_class(mrb, "Struct",  mrb->object_class);

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

797 798 799 800 801 802 803
  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
804
  mrb_define_alias(mrb, st,        "to_s", "inspect");                                      /* 15.2.18.4.11(x)  */
805
  mrb_define_method(mrb, st,       "eql?",            mrb_struct_eql,         MRB_ARGS_REQ(1)); /* 15.2.18.4.12(x)  */
mimaki's avatar
mimaki committed
806
}
mattn's avatar
mattn committed
807 808 809 810 811

void
mrb_mruby_struct_gem_final(mrb_state* mrb)
{
}