2 ** kernel.c - Kernel module
4 ** See Copyright Notice in mruby.h
8 #include <mruby/array.h>
9 #include <mruby/hash.h>
10 #include <mruby/class.h>
11 #include <mruby/proc.h>
12 #include <mruby/string.h>
13 #include <mruby/variable.h>
14 #include <mruby/error.h>
15 #include <mruby/istruct.h>
18 mrb_func_basic_p(mrb_state *mrb, mrb_value obj, mrb_sym mid, mrb_func_t func)
20 struct RClass *c = mrb_class(mrb, obj);
21 mrb_method_t m = mrb_method_search_vm(mrb, &c, mid);
24 if (MRB_METHOD_UNDEF_P(m)) return FALSE;
25 if (MRB_METHOD_FUNC_P(m))
26 return MRB_METHOD_FUNC(m) == func;
27 p = MRB_METHOD_PROC(m);
28 if (MRB_PROC_CFUNC_P(p) && (MRB_PROC_CFUNC(p) == func))
34 mrb_obj_basic_to_s_p(mrb_state *mrb, mrb_value obj)
36 return mrb_func_basic_p(mrb, obj, mrb_intern_lit(mrb, "to_s"), mrb_any_to_s);
42 * obj.inspect -> string
44 * Returns a string containing a human-readable representation of
45 * <i>obj</i>. If not overridden and no instance variables, uses the
46 * <code>to_s</code> method to generate the string.
47 * <i>obj</i>. If not overridden, uses the <code>to_s</code> method to
48 * generate the string.
50 * [ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]"
51 * Time.new.inspect #=> "2008-03-08 19:43:39 +0900"
54 mrb_obj_inspect(mrb_state *mrb, mrb_value obj)
56 if (mrb_object_p(obj) && mrb_obj_basic_to_s_p(mrb, obj)) {
57 return mrb_obj_iv_inspect(mrb, mrb_obj_ptr(obj));
59 return mrb_any_to_s(mrb, obj);
65 * obj === other -> true or false
67 * Case Equality---For class <code>Object</code>, effectively the same
68 * as calling <code>#==</code>, but typically overridden by descendants
69 * to provide meaningful semantics in <code>case</code> statements.
72 mrb_equal_m(mrb_state *mrb, mrb_value self)
74 mrb_value arg = mrb_get_arg1(mrb);
76 return mrb_bool_value(mrb_equal(mrb, self, arg));
82 * Document-method: __id__
83 * Document-method: object_id
86 * obj.__id__ -> fixnum
87 * obj.object_id -> fixnum
89 * Returns an integer identifier for <i>obj</i>. The same number will
90 * be returned on all calls to <code>id</code> for a given object, and
91 * no two active objects will share an id.
92 * <code>Object#object_id</code> is a different concept from the
93 * <code>:name</code> notation, which returns the symbol id of
94 * <code>name</code>. Replaces the deprecated <code>Object#id</code>.
97 mrb_obj_id_m(mrb_state *mrb, mrb_value self)
99 return mrb_fixnum_value(mrb_obj_id(self));
108 * block_given? -> true or false
109 * iterator? -> true or false
111 * Returns <code>true</code> if <code>yield</code> would execute a
112 * block in the current context. The <code>iterator?</code> form
113 * is mildly deprecated.
123 * try { "hello" } #=> "hello"
124 * try do "hello" end #=> "hello"
127 mrb_f_block_given_p_m(mrb_state *mrb, mrb_value self)
129 mrb_callinfo *ci = &mrb->c->ci[-1];
130 mrb_callinfo *cibase = mrb->c->cibase;
135 /* toplevel does not have block */
136 return mrb_false_value();
139 /* search method/class/module proc */
141 if (MRB_PROC_SCOPE_P(p)) break;
144 if (p == NULL) return mrb_false_value();
145 /* search ci corresponding to proc */
146 while (cibase < ci) {
147 if (ci->proc == p) break;
151 return mrb_false_value();
154 struct REnv *e = ci->env;
157 /* top-level does not have block slot (always false) */
158 if (e->stack == mrb->c->stbase)
159 return mrb_false_value();
160 /* use saved block arg position */
161 bidx = MRB_ENV_BIDX(e);
162 /* bidx may be useless (e.g. define_method) */
163 if (bidx >= MRB_ENV_LEN(e))
164 return mrb_false_value();
165 bp = &e->stack[bidx];
168 bp = ci[1].stackent+1;
177 return mrb_false_value();
178 return mrb_true_value();
186 * Returns the class of <i>obj</i>. This method must always be
187 * called with an explicit receiver, as <code>class</code> is also a
188 * reserved word in Ruby.
191 * self.class #=> Object
194 mrb_obj_class_m(mrb_state *mrb, mrb_value self)
196 return mrb_obj_value(mrb_obj_class(mrb, self));
199 static struct RClass*
200 mrb_singleton_class_clone(mrb_state *mrb, mrb_value obj)
202 struct RClass *klass = mrb_basic_ptr(obj)->c;
204 if (klass->tt != MRB_TT_SCLASS)
207 /* copy singleton(unnamed) class */
208 struct RClass *clone = (struct RClass*)mrb_obj_alloc(mrb, klass->tt, mrb->class_class);
210 switch (mrb_type(obj)) {
215 clone->c = mrb_singleton_class_clone(mrb, mrb_obj_value(klass));
218 clone->super = klass->super;
220 mrb_iv_copy(mrb, mrb_obj_value(clone), mrb_obj_value(klass));
221 mrb_obj_iv_set(mrb, (struct RObject*)clone, mrb_intern_lit(mrb, "__attached__"), obj);
224 clone->mt = kh_copy(mt, mrb, klass->mt);
227 clone->mt = kh_init(mt, mrb);
229 clone->tt = MRB_TT_SCLASS;
235 copy_class(mrb_state *mrb, mrb_value dst, mrb_value src)
237 struct RClass *dc = mrb_class_ptr(dst);
238 struct RClass *sc = mrb_class_ptr(src);
239 /* if the origin is not the same as the class, then the origin and
240 the current class need to be copied */
241 if (sc->flags & MRB_FL_CLASS_IS_PREPENDED) {
242 struct RClass *c0 = sc->super;
243 struct RClass *c1 = dc;
245 /* copy prepended iclasses */
246 while (!(c0->flags & MRB_FL_CLASS_IS_ORIGIN)) {
247 c1->super = mrb_class_ptr(mrb_obj_dup(mrb, mrb_obj_value(c0)));
251 c1->super = mrb_class_ptr(mrb_obj_dup(mrb, mrb_obj_value(c0)));
252 c1->super->flags |= MRB_FL_CLASS_IS_ORIGIN;
255 dc->mt = kh_copy(mt, mrb, sc->mt);
258 dc->mt = kh_init(mt, mrb);
260 dc->super = sc->super;
261 MRB_SET_INSTANCE_TT(dc, MRB_INSTANCE_TT(sc));
265 init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj)
267 switch (mrb_type(obj)) {
269 copy_class(mrb, dest, obj);
273 copy_class(mrb, dest, obj);
274 mrb_iv_copy(mrb, dest, obj);
275 mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__"));
281 case MRB_TT_EXCEPTION:
282 mrb_iv_copy(mrb, dest, obj);
285 mrb_istruct_copy(dest, obj);
291 mrb_funcall(mrb, dest, "initialize_copy", 1, obj);
297 * obj.clone -> an_object
299 * Produces a shallow copy of <i>obj</i>---the instance variables of
300 * <i>obj</i> are copied, but not the objects they reference. Copies
301 * the frozen state of <i>obj</i>. See also the discussion
302 * under <code>Object#dup</code>.
307 * s1 = Klass.new #=> #<Klass:0x401b3a38>
308 * s1.str = "Hello" #=> "Hello"
309 * s2 = s1.clone #=> #<Klass:0x401b3998 @str="Hello">
310 * s2.str[1,4] = "i" #=> "i"
311 * s1.inspect #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
312 * s2.inspect #=> "#<Klass:0x401b3998 @str=\"Hi\">"
314 * This method may have class-specific behavior. If so, that
315 * behavior will be documented under the #+initialize_copy+ method of
318 * Some Class(True False Nil Symbol Fixnum Float) Object cannot clone.
321 mrb_obj_clone(mrb_state *mrb, mrb_value self)
326 if (mrb_immediate_p(self)) {
329 if (mrb_sclass_p(self)) {
330 mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
332 p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
333 p->c = mrb_singleton_class_clone(mrb, self);
334 mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
335 clone = mrb_obj_value(p);
336 init_copy(mrb, clone, self);
337 p->flags |= mrb_obj_ptr(self)->flags & MRB_FL_OBJ_IS_FROZEN;
345 * obj.dup -> an_object
347 * Produces a shallow copy of <i>obj</i>---the instance variables of
348 * <i>obj</i> are copied, but not the objects they reference.
349 * <code>dup</code> copies the frozen state of <i>obj</i>. See also
350 * the discussion under <code>Object#clone</code>. In general,
351 * <code>clone</code> and <code>dup</code> may have different semantics
352 * in descendant classes. While <code>clone</code> is used to duplicate
353 * an object, including its internal state, <code>dup</code> typically
354 * uses the class of the descendant object to create the new instance.
356 * This method may have class-specific behavior. If so, that
357 * behavior will be documented under the #+initialize_copy+ method of
362 mrb_obj_dup(mrb_state *mrb, mrb_value obj)
367 if (mrb_immediate_p(obj)) {
370 if (mrb_sclass_p(obj)) {
371 mrb_raise(mrb, E_TYPE_ERROR, "can't dup singleton class");
373 p = mrb_obj_alloc(mrb, mrb_type(obj), mrb_obj_class(mrb, obj));
374 dup = mrb_obj_value(p);
375 init_copy(mrb, dup, obj);
381 mrb_obj_extend(mrb_state *mrb, mrb_int argc, mrb_value *argv, mrb_value obj)
386 mrb_argnum_error(mrb, argc, 1, -1);
388 for (i = 0; i < argc; i++) {
389 mrb_check_type(mrb, argv[i], MRB_TT_MODULE);
392 mrb_funcall(mrb, argv[argc], "extend_object", 1, obj);
393 mrb_funcall(mrb, argv[argc], "extended", 1, obj);
401 * obj.extend(module, ...) -> obj
403 * Adds to _obj_ the instance methods from each module given as a
408 * "Hello from Mod.\n"
414 * "Hello from Klass.\n"
419 * k.hello #=> "Hello from Klass.\n"
420 * k.extend(Mod) #=> #<Klass:0x401b3bc8>
421 * k.hello #=> "Hello from Mod.\n"
424 mrb_obj_extend_m(mrb_state *mrb, mrb_value self)
429 mrb_get_args(mrb, "*", &argv, &argc);
430 return mrb_obj_extend(mrb, argc, argv, self);
434 mrb_obj_freeze(mrb_state *mrb, mrb_value self)
436 if (!mrb_immediate_p(self)) {
437 struct RBasic *b = mrb_basic_ptr(self);
438 if (!mrb_frozen_p(b)) {
439 MRB_SET_FROZEN_FLAG(b);
440 if (b->c->tt == MRB_TT_SCLASS) MRB_SET_FROZEN_FLAG(b->c);
447 mrb_obj_frozen(mrb_state *mrb, mrb_value self)
449 return mrb_bool_value(mrb_immediate_p(self) || mrb_frozen_p(mrb_basic_ptr(self)));
457 * Generates a <code>Fixnum</code> hash value for this object. This
458 * function must have the property that <code>a.eql?(b)</code> implies
459 * <code>a.hash == b.hash</code>. The hash value is used by class
460 * <code>Hash</code>. Any hash value that exceeds the capacity of a
461 * <code>Fixnum</code> will be truncated before being used.
464 mrb_obj_hash(mrb_state *mrb, mrb_value self)
466 return mrb_fixnum_value(mrb_obj_id(self));
471 mrb_obj_init_copy(mrb_state *mrb, mrb_value self)
473 mrb_value orig = mrb_get_arg1(mrb);
475 if (mrb_obj_equal(mrb, self, orig)) return self;
476 if ((mrb_type(self) != mrb_type(orig)) || (mrb_obj_class(mrb, self) != mrb_obj_class(mrb, orig))) {
477 mrb_raise(mrb, E_TYPE_ERROR, "initialize_copy should take same class object");
484 mrb_obj_is_instance_of(mrb_state *mrb, mrb_value obj, struct RClass* c)
486 if (mrb_obj_class(mrb, obj) == c) return TRUE;
493 * obj.instance_of?(class) -> true or false
495 * Returns <code>true</code> if <i>obj</i> is an instance of the given
496 * class. See also <code>Object#kind_of?</code>.
499 obj_is_instance_of(mrb_state *mrb, mrb_value self)
503 mrb_get_args(mrb, "C", &arg);
505 return mrb_bool_value(mrb_obj_is_instance_of(mrb, self, mrb_class_ptr(arg)));
512 * obj.is_a?(class) -> true or false
513 * obj.kind_of?(class) -> true or false
515 * Returns <code>true</code> if <i>class</i> is the class of
516 * <i>obj</i>, or if <i>class</i> is one of the superclasses of
517 * <i>obj</i> or modules included in <i>obj</i>.
526 * b.instance_of? A #=> false
527 * b.instance_of? B #=> true
528 * b.instance_of? C #=> false
529 * b.instance_of? M #=> false
530 * b.kind_of? A #=> true
531 * b.kind_of? B #=> true
532 * b.kind_of? C #=> false
533 * b.kind_of? M #=> true
536 mrb_obj_is_kind_of_m(mrb_state *mrb, mrb_value self)
540 mrb_get_args(mrb, "C", &arg);
542 return mrb_bool_value(mrb_obj_is_kind_of(mrb, self, mrb_class_ptr(arg)));
545 KHASH_DECLARE(st, mrb_sym, char, FALSE)
546 KHASH_DEFINE(st, mrb_sym, char, FALSE, kh_int_hash_func, kh_int_hash_equal)
552 * <anything_else>.nil? -> false
554 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
557 mrb_false(mrb_state *mrb, mrb_value self)
559 return mrb_false_value();
568 * raise(exception [, string])
570 * With no arguments, raises a <code>RuntimeError</code>
571 * With a single +String+ argument, raises a
572 * +RuntimeError+ with the string as a message. Otherwise,
573 * the first parameter should be the name of an +Exception+
574 * class (or an object that returns an +Exception+ object when sent
575 * an +exception+ message). The optional second parameter sets the
576 * message associated with the exception, and the third parameter is an
577 * array of callback information. Exceptions are caught by the
578 * +rescue+ clause of <code>begin...end</code> blocks.
580 * raise "Failed to create socket"
581 * raise ArgumentError, "No parameters", caller
584 mrb_f_raise(mrb_state *mrb, mrb_value self)
590 argc = mrb_get_args(mrb, "|oo", &a[0], &a[1]);
593 mrb_raise(mrb, E_RUNTIME_ERROR, "");
596 if (mrb_string_p(a[0])) {
599 a[0] = mrb_obj_value(E_RUNTIME_ERROR);
603 exc = mrb_make_exception(mrb, argc, a);
604 mrb_exc_raise(mrb, exc);
607 return mrb_nil_value(); /* not reached */
613 * obj.remove_instance_variable(symbol) -> obj
615 * Removes the named instance variable from <i>obj</i>, returning that
624 * remove_instance_variable(:@var)
633 mrb_obj_remove_instance_variable(mrb_state *mrb, mrb_value self)
638 mrb_get_args(mrb, "n", &sym);
639 mrb_iv_name_sym_check(mrb, sym);
640 val = mrb_iv_remove(mrb, self, sym);
641 if (mrb_undef_p(val)) {
642 mrb_name_error(mrb, sym, "instance variable %n not defined", sym);
648 mrb_method_missing(mrb_state *mrb, mrb_sym name, mrb_value self, mrb_value args)
650 mrb_no_method_error(mrb, name, args, "undefined method '%n'", name);
656 * obj.method_missing(symbol [, *args] ) -> result
658 * Invoked by Ruby when <i>obj</i> is sent a message it cannot handle.
659 * <i>symbol</i> is the symbol for the method called, and <i>args</i>
660 * are any arguments that were passed to it. By default, the interpreter
661 * raises an error when this method is called. However, it is possible
662 * to override the method to provide more dynamic behavior.
663 * If it is decided that a particular method should not be handled, then
664 * <i>super</i> should be called, so that ancestors can pick up the
666 * The example below creates
667 * a class <code>Roman</code>, which responds to methods with names
668 * consisting of roman numerals, returning the corresponding integer
672 * def romanToInt(str)
675 * def method_missing(methId)
676 * str = methId.id2name
687 mrb_obj_missing(mrb_state *mrb, mrb_value mod)
693 mrb_get_args(mrb, "n*!", &name, &a, &alen);
694 mrb_method_missing(mrb, name, mod, mrb_ary_new_from_values(mrb, alen, a));
696 return mrb_nil_value();
699 static inline mrb_bool
700 basic_obj_respond_to(mrb_state *mrb, mrb_value obj, mrb_sym id, int pub)
702 return mrb_respond_to(mrb, obj, id);
708 * obj.respond_to?(symbol, include_private=false) -> true or false
710 * Returns +true+ if _obj_ responds to the given
711 * method. Private methods are included in the search only if the
712 * optional second parameter evaluates to +true+.
714 * If the method is not implemented,
715 * as Process.fork on Windows, File.lchmod on GNU/Linux, etc.,
718 * If the method is not defined, <code>respond_to_missing?</code>
719 * method is called and the result is returned.
722 obj_respond_to(mrb_state *mrb, mrb_value self)
725 mrb_bool priv = FALSE, respond_to_p;
727 mrb_get_args(mrb, "n|b", &id, &priv);
728 respond_to_p = basic_obj_respond_to(mrb, self, id, !priv);
730 rtm_id = mrb_intern_lit(mrb, "respond_to_missing?");
731 if (basic_obj_respond_to(mrb, self, rtm_id, !priv)) {
732 mrb_value args[2], v;
733 args[0] = mrb_symbol_value(id);
734 args[1] = mrb_bool_value(priv);
735 v = mrb_funcall_argv(mrb, self, rtm_id, 2, args);
736 return mrb_bool_value(mrb_bool(v));
739 return mrb_bool_value(respond_to_p);
743 mrb_obj_ceqq(mrb_state *mrb, mrb_value self)
745 mrb_value v = mrb_get_arg1(mrb);
747 mrb_sym eqq = mrb_intern_lit(mrb, "===");
748 mrb_value ary = mrb_ary_splat(mrb, self);
750 len = RARRAY_LEN(ary);
751 for (i=0; i<len; i++) {
752 mrb_value c = mrb_funcall_argv(mrb, mrb_ary_entry(ary, i), eqq, 1, &v);
753 if (mrb_test(c)) return mrb_true_value();
755 return mrb_false_value();
758 mrb_value mrb_obj_equal_m(mrb_state *mrb, mrb_value);
761 mrb_init_kernel(mrb_state *mrb)
765 mrb->kernel_module = krn = mrb_define_module(mrb, "Kernel"); /* 15.3.1 */
766 mrb_define_class_method(mrb, krn, "block_given?", mrb_f_block_given_p_m, MRB_ARGS_NONE()); /* 15.3.1.2.2 */
767 mrb_define_class_method(mrb, krn, "iterator?", mrb_f_block_given_p_m, MRB_ARGS_NONE()); /* 15.3.1.2.5 */
769 mrb_define_class_method(mrb, krn, "raise", mrb_f_raise, MRB_ARGS_OPT(2)); /* 15.3.1.2.12 */
772 mrb_define_method(mrb, krn, "===", mrb_equal_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.2 */
773 mrb_define_method(mrb, krn, "block_given?", mrb_f_block_given_p_m, MRB_ARGS_NONE()); /* 15.3.1.3.6 */
774 mrb_define_method(mrb, krn, "class", mrb_obj_class_m, MRB_ARGS_NONE()); /* 15.3.1.3.7 */
775 mrb_define_method(mrb, krn, "clone", mrb_obj_clone, MRB_ARGS_NONE()); /* 15.3.1.3.8 */
776 mrb_define_method(mrb, krn, "dup", mrb_obj_dup, MRB_ARGS_NONE()); /* 15.3.1.3.9 */
777 mrb_define_method(mrb, krn, "eql?", mrb_obj_equal_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.10 */
778 mrb_define_method(mrb, krn, "extend", mrb_obj_extend_m, MRB_ARGS_ANY()); /* 15.3.1.3.13 */
779 mrb_define_method(mrb, krn, "freeze", mrb_obj_freeze, MRB_ARGS_NONE());
780 mrb_define_method(mrb, krn, "frozen?", mrb_obj_frozen, MRB_ARGS_NONE());
781 mrb_define_method(mrb, krn, "hash", mrb_obj_hash, MRB_ARGS_NONE()); /* 15.3.1.3.15 */
782 mrb_define_method(mrb, krn, "initialize_copy", mrb_obj_init_copy, MRB_ARGS_REQ(1)); /* 15.3.1.3.16 */
783 mrb_define_method(mrb, krn, "inspect", mrb_obj_inspect, MRB_ARGS_NONE()); /* 15.3.1.3.17 */
784 mrb_define_method(mrb, krn, "instance_of?", obj_is_instance_of, MRB_ARGS_REQ(1)); /* 15.3.1.3.19 */
786 mrb_define_method(mrb, krn, "is_a?", mrb_obj_is_kind_of_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.24 */
787 mrb_define_method(mrb, krn, "iterator?", mrb_f_block_given_p_m, MRB_ARGS_NONE()); /* 15.3.1.3.25 */
788 mrb_define_method(mrb, krn, "kind_of?", mrb_obj_is_kind_of_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.26 */
789 mrb_define_method(mrb, krn, "method_missing", mrb_obj_missing, MRB_ARGS_ANY()); /* 15.3.1.3.30 */
790 mrb_define_method(mrb, krn, "nil?", mrb_false, MRB_ARGS_NONE()); /* 15.3.1.3.32 */
791 mrb_define_method(mrb, krn, "object_id", mrb_obj_id_m, MRB_ARGS_NONE()); /* 15.3.1.3.33 */
792 mrb_define_method(mrb, krn, "raise", mrb_f_raise, MRB_ARGS_ANY()); /* 15.3.1.3.40 */
793 mrb_define_method(mrb, krn, "remove_instance_variable", mrb_obj_remove_instance_variable,MRB_ARGS_REQ(1)); /* 15.3.1.3.41 */
794 mrb_define_method(mrb, krn, "respond_to?", obj_respond_to, MRB_ARGS_ARG(1,1)); /* 15.3.1.3.43 */
795 mrb_define_method(mrb, krn, "to_s", mrb_any_to_s, MRB_ARGS_NONE()); /* 15.3.1.3.46 */
796 mrb_define_method(mrb, krn, "__case_eqq", mrb_obj_ceqq, MRB_ARGS_REQ(1)); /* internal */
797 mrb_define_method(mrb, krn, "__to_int", mrb_to_int, MRB_ARGS_NONE()); /* internal */
798 mrb_define_method(mrb, krn, "__to_str", mrb_to_str, MRB_ARGS_NONE()); /* internal */
800 mrb_include_module(mrb, mrb->object_class, mrb->kernel_module);