diff options
Diffstat (limited to 'vm_eval.c')
| -rw-r--r-- | vm_eval.c | 3219 |
1 files changed, 2075 insertions, 1144 deletions
@@ -1,6 +1,6 @@ /********************************************************************** - vm_eval.c - + vm_eval.c - Included into vm.c. $Author$ created at: Sat May 24 16:02:32 JST 2008 @@ -11,581 +11,888 @@ **********************************************************************/ -static inline VALUE method_missing(VALUE obj, ID id, int argc, const VALUE *argv, int call_status); -static inline VALUE vm_yield_with_cref(rb_thread_t *th, int argc, const VALUE *argv, const NODE *cref); -static inline VALUE vm_yield(rb_thread_t *th, int argc, const VALUE *argv); -static NODE *vm_cref_push(rb_thread_t *th, VALUE klass, int noex, rb_block_t *blockptr); -static VALUE vm_exec(rb_thread_t *th); -static void vm_set_eval_stack(rb_thread_t * th, VALUE iseqval, const NODE *cref, rb_block_t *base_block); -static int vm_collect_local_variables_in_heap(rb_thread_t *th, VALUE *dfp, VALUE ary); +#include "internal/thread.h" +struct local_var_list { + VALUE tbl; +}; -/* vm_backtrace.c */ -VALUE vm_backtrace_str_ary(rb_thread_t *th, int lev, int n); +static inline VALUE method_missing(rb_execution_context_t *ec, VALUE obj, ID id, int argc, const VALUE *argv, enum method_missing_reason call_status, int kw_splat); +static inline VALUE vm_yield_with_cref(rb_execution_context_t *ec, int argc, const VALUE *argv, int kw_splat, const rb_cref_t *cref, int is_lambda); +static inline VALUE vm_yield(rb_execution_context_t *ec, int argc, const VALUE *argv, int kw_splat); +static inline VALUE vm_yield_with_block(rb_execution_context_t *ec, int argc, const VALUE *argv, VALUE block_handler, int kw_splat); +static inline VALUE vm_yield_force_blockarg(rb_execution_context_t *ec, VALUE args); +VALUE vm_exec(rb_execution_context_t *ec); +static void vm_set_eval_stack(rb_execution_context_t * th, const rb_iseq_t *iseq, const rb_cref_t *cref, const struct rb_block *base_block); +static int vm_collect_local_variables_in_heap(const VALUE *dfp, const struct local_var_list *vars); -typedef enum call_type { - CALL_PUBLIC, - CALL_FCALL, - CALL_VCALL, - CALL_TYPE_MAX -} call_type; +static VALUE rb_eUncaughtThrow; +static ID id_result, id_tag, id_value; +#define id_mesg idMesg static VALUE send_internal(int argc, const VALUE *argv, VALUE recv, call_type scope); +static VALUE vm_call0_body(rb_execution_context_t* ec, struct rb_calling_info *calling, const VALUE *argv); -static VALUE vm_call0_body(rb_thread_t* th, rb_call_info_t *ci, const VALUE *argv); +static VALUE * +vm_argv_ruby_array(VALUE *av, const VALUE *argv, int *flags, int *argc, int kw_splat) +{ + *flags |= VM_CALL_ARGS_SPLAT; + VALUE argv_ary = rb_ary_hidden_new(*argc); + rb_ary_cat(argv_ary, argv, *argc); + *argc = 2; + av[0] = argv_ary; + if (kw_splat) { + av[1] = rb_ary_pop(argv_ary); + } + else { + // Make sure flagged keyword hash passed as regular argument + // isn't treated as keywords + *flags |= VM_CALL_KW_SPLAT; + av[1] = rb_hash_new(); + } + return av; +} -static VALUE -vm_call0(rb_thread_t* th, VALUE recv, ID id, int argc, const VALUE *argv, - const rb_method_entry_t *me, VALUE defined_class) +static inline VALUE vm_call0_cc(rb_execution_context_t *ec, VALUE recv, ID id, int argc, const VALUE *argv, const struct rb_callcache *cc, int kw_splat); + +VALUE +rb_vm_call0(rb_execution_context_t *ec, VALUE recv, ID id, int argc, const VALUE *argv, const rb_callable_method_entry_t *cme, int kw_splat) +{ + const struct rb_callcache cc = VM_CC_ON_STACK(Qundef, vm_call_general, {{ 0 }}, cme); + return vm_call0_cc(ec, recv, id, argc, argv, &cc, kw_splat); +} + +VALUE +rb_vm_call_with_refinements(rb_execution_context_t *ec, VALUE recv, ID id, int argc, const VALUE *argv, int kw_splat) { - rb_call_info_t ci_entry, *ci = &ci_entry; + const rb_callable_method_entry_t *me = + rb_callable_method_entry_with_refinements(CLASS_OF(recv), id, NULL); + if (me) { + return rb_vm_call0(ec, recv, id, argc, argv, me, kw_splat); + } + else { + /* fallback to funcall (e.g. method_missing) */ + return rb_funcallv(recv, id, argc, argv); + } +} + +static inline VALUE +vm_call0_cc(rb_execution_context_t *ec, VALUE recv, ID id, int argc, const VALUE *argv, const struct rb_callcache *cc, int kw_splat) +{ + int flags = kw_splat ? VM_CALL_KW_SPLAT : 0; + VALUE *use_argv = (VALUE *)argv; + VALUE av[2]; + + if (UNLIKELY(vm_cc_cme(cc)->def->type == VM_METHOD_TYPE_ISEQ && argc > VM_ARGC_STACK_MAX)) { + use_argv = vm_argv_ruby_array(av, argv, &flags, &argc, kw_splat); + } - ci->flag = 0; - ci->mid = id; - ci->recv = recv; - ci->defined_class = defined_class; - ci->argc = argc; - ci->me = me; + struct rb_calling_info calling = { + .cd = &(struct rb_call_data) { + .ci = &VM_CI_ON_STACK(id, flags, argc, NULL), + .cc = NULL, + }, + .cc = cc, + .block_handler = vm_passed_block_handler(ec), + .recv = recv, + .argc = argc, + .kw_splat = kw_splat, + }; - return vm_call0_body(th, ci, argv); + return vm_call0_body(ec, &calling, use_argv); } -#if OPT_CALL_CFUNC_WITHOUT_FRAME static VALUE -vm_call0_cfunc(rb_thread_t* th, rb_call_info_t *ci, const VALUE *argv) +vm_call0_cme(rb_execution_context_t *ec, struct rb_calling_info *calling, const VALUE *argv, const rb_callable_method_entry_t *cme) { - VALUE val; + calling->cc = &VM_CC_ON_STACK(Qundef, vm_call_general, {{ 0 }}, cme); + return vm_call0_body(ec, calling, argv); +} - RUBY_DTRACE_CMETHOD_ENTRY_HOOK(th, ci->defined_class, ci->mid); - EXEC_EVENT_HOOK(th, RUBY_EVENT_C_CALL, ci->recv, ci->mid, ci->defined_class, Qnil); - { - rb_control_frame_t *reg_cfp = th->cfp; - const rb_method_entry_t *me = ci->me; - const rb_method_cfunc_t *cfunc = &me->def->body.cfunc; - int len = cfunc->argc; - - if (len >= 0) rb_check_arity(ci->argc, len, len); - - th->passed_ci = ci; - ci->aux.inc_sp = 0; - VM_PROFILE_UP(2); - val = (*cfunc->invoker)(cfunc->func, ci, argv); - - if (reg_cfp == th->cfp) { - if (UNLIKELY(th->passed_ci != ci)) { - rb_bug("vm_call0_cfunc: passed_ci error (ci: %p, passed_ci: %p)", ci, th->passed_ci); - } - th->passed_ci = 0; - } - else { - if (reg_cfp != th->cfp + 1) { - rb_bug("vm_call0_cfunc: cfp consistency error"); - } - VM_PROFILE_UP(3); - vm_pop_frame(th); - } - } - EXEC_EVENT_HOOK(th, RUBY_EVENT_C_RETURN, ci->recv, ci->mid, ci->defined_class, val); - RUBY_DTRACE_CMETHOD_RETURN_HOOK(th, ci->defined_class, ci->mid); +static VALUE +vm_call0_super(rb_execution_context_t *ec, struct rb_calling_info *calling, const VALUE *argv, VALUE klass, enum method_missing_reason ex) +{ + ID mid = vm_ci_mid(calling->cd->ci); + klass = RCLASS_SUPER(klass); - return val; + if (klass) { + const rb_callable_method_entry_t *cme = rb_callable_method_entry(klass, mid); + + if (cme) { + RUBY_VM_CHECK_INTS(ec); + return vm_call0_cme(ec, calling, argv, cme); + } + } + + vm_passed_block_handler_set(ec, calling->block_handler); + return method_missing(ec, calling->recv, mid, calling->argc, argv, ex, calling->kw_splat); } -#else + static VALUE -vm_call0_cfunc_with_frame(rb_thread_t* th, rb_call_info_t *ci, const VALUE *argv) +vm_call0_cfunc_with_frame(rb_execution_context_t* ec, struct rb_calling_info *calling, const VALUE *argv) { + const struct rb_callinfo *ci = calling->cd->ci; VALUE val; - const rb_method_entry_t *me = ci->me; - const rb_method_cfunc_t *cfunc = &me->def->body.cfunc; + const rb_callable_method_entry_t *me = vm_cc_cme(calling->cc); + const rb_method_cfunc_t *cfunc = UNALIGNED_MEMBER_PTR(me->def, body.cfunc); int len = cfunc->argc; - VALUE recv = ci->recv; - VALUE defined_class = ci->defined_class; - int argc = ci->argc; - ID mid = ci->mid; - rb_block_t *blockptr = ci->blockptr; - - RUBY_DTRACE_CMETHOD_ENTRY_HOOK(th, defined_class, mid); - EXEC_EVENT_HOOK(th, RUBY_EVENT_C_CALL, recv, mid, defined_class, Qnil); + VALUE recv = calling->recv; + int argc = calling->argc; + ID mid = vm_ci_mid(ci); + VALUE block_handler = calling->block_handler; + int frame_flags = VM_FRAME_MAGIC_CFUNC | VM_FRAME_FLAG_CFRAME | VM_ENV_FLAG_LOCAL; + + if (calling->kw_splat) { + if (argc > 0 && RB_TYPE_P(argv[argc-1], T_HASH) && RHASH_EMPTY_P(argv[argc-1])) { + argc--; + } + else { + frame_flags |= VM_FRAME_FLAG_CFRAME_KW; + } + } + + RUBY_DTRACE_CMETHOD_ENTRY_HOOK(ec, me->owner, me->def->original_id); + EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, recv, me->def->original_id, mid, me->owner, Qnil); { - rb_control_frame_t *reg_cfp = th->cfp; + rb_control_frame_t *reg_cfp = ec->cfp; - vm_push_frame(th, 0, VM_FRAME_MAGIC_CFUNC, recv, defined_class, - VM_ENVVAL_BLOCK_PTR(blockptr), 0, reg_cfp->sp, 1, me); + vm_push_frame(ec, 0, frame_flags, recv, + block_handler, (VALUE)me, + 0, reg_cfp->sp, 0, 0); - if (len >= 0) rb_check_arity(argc, len, len); + if (len >= 0) rb_check_arity(argc, len, len); - VM_PROFILE_UP(2); - val = (*cfunc->invoker)(cfunc->func, recv, argc, argv); + val = (*cfunc->invoker)(recv, argc, argv, cfunc->func); - if (UNLIKELY(reg_cfp != th->cfp + 1)) { - rb_bug("vm_call0_cfunc_with_frame: cfp consistency error"); - } - VM_PROFILE_UP(3); - vm_pop_frame(th); + CHECK_CFP_CONSISTENCY("vm_call0_cfunc_with_frame"); + rb_vm_pop_frame(ec); } - EXEC_EVENT_HOOK(th, RUBY_EVENT_C_RETURN, recv, mid, defined_class, val); - RUBY_DTRACE_CMETHOD_RETURN_HOOK(th, defined_class, mid); + EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, recv, me->def->original_id, mid, me->owner, val); + RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, me->owner, me->def->original_id); return val; } static VALUE -vm_call0_cfunc(rb_thread_t* th, rb_call_info_t *ci, const VALUE *argv) +vm_call0_cfunc(rb_execution_context_t *ec, struct rb_calling_info *calling, const VALUE *argv) { - return vm_call0_cfunc_with_frame(th, ci, argv); + return vm_call0_cfunc_with_frame(ec, calling, argv); +} + +static void +vm_call_check_arity(struct rb_calling_info *calling, int argc, const VALUE *argv) +{ + if (calling->kw_splat && + calling->argc > 0 && + RB_TYPE_P(argv[calling->argc-1], T_HASH) && + RHASH_EMPTY_P(argv[calling->argc-1])) { + calling->argc--; + } + + rb_check_arity(calling->argc, argc, argc); } -#endif /* `ci' should point temporal value (on stack value) */ static VALUE -vm_call0_body(rb_thread_t* th, rb_call_info_t *ci, const VALUE *argv) +vm_call0_body(rb_execution_context_t *ec, struct rb_calling_info *calling, const VALUE *argv) { + const struct rb_callinfo *ci = calling->cd->ci; + const struct rb_callcache *cc = calling->cc; VALUE ret; - if (!ci->me->def) return Qnil; + retry: - if (th->passed_block) { - ci->blockptr = (rb_block_t *)th->passed_block; - th->passed_block = 0; - } - else { - ci->blockptr = 0; - } - - again: - switch (ci->me->def->type) { + switch (vm_cc_cme(cc)->def->type) { case VM_METHOD_TYPE_ISEQ: - { - rb_control_frame_t *reg_cfp = th->cfp; - int i; - - CHECK_VM_STACK_OVERFLOW(reg_cfp, ci->argc + 1); - - *reg_cfp->sp++ = ci->recv; - for (i = 0; i < ci->argc; i++) { - *reg_cfp->sp++ = argv[i]; - } - - vm_call_iseq_setup(th, reg_cfp, ci); - th->cfp->flag |= VM_FRAME_FLAG_FINISH; - return vm_exec(th); /* CHECK_INTS in this function */ - } + { + rb_control_frame_t *reg_cfp = ec->cfp; + int i; + + CHECK_VM_STACK_OVERFLOW(reg_cfp, calling->argc + 1); + vm_check_canary(ec, reg_cfp->sp); + + *reg_cfp->sp++ = calling->recv; + for (i = 0; i < calling->argc; i++) { + *reg_cfp->sp++ = argv[i]; + } + + if (ISEQ_BODY(def_iseq_ptr(vm_cc_cme(cc)->def))->param.flags.forwardable) { + vm_call_iseq_fwd_setup(ec, reg_cfp, calling); + } + else { + vm_call_iseq_setup(ec, reg_cfp, calling); + } + VM_ENV_FLAGS_SET(ec->cfp->ep, VM_FRAME_FLAG_FINISH); + return vm_exec(ec); // CHECK_INTS in this function + } case VM_METHOD_TYPE_NOTIMPLEMENTED: case VM_METHOD_TYPE_CFUNC: - ret = vm_call0_cfunc(th, ci, argv); - goto success; + ret = vm_call0_cfunc(ec, calling, argv); + goto success; case VM_METHOD_TYPE_ATTRSET: - rb_check_arity(ci->argc, 1, 1); - ret = rb_ivar_set(ci->recv, ci->me->def->body.attr.id, argv[0]); - goto success; + vm_call_check_arity(calling, 1, argv); + VM_CALL_METHOD_ATTR(ret, + rb_ivar_set(calling->recv, vm_cc_cme(cc)->def->body.attr.id, argv[0]), + (void)0); + goto success; case VM_METHOD_TYPE_IVAR: - rb_check_arity(ci->argc, 0, 0); - ret = rb_attr_get(ci->recv, ci->me->def->body.attr.id); - goto success; + vm_call_check_arity(calling, 0, argv); + VM_CALL_METHOD_ATTR(ret, + rb_attr_get(calling->recv, vm_cc_cme(cc)->def->body.attr.id), + (void)0); + goto success; case VM_METHOD_TYPE_BMETHOD: - ret = vm_call_bmethod_body(th, ci, argv); - goto success; + ret = vm_call_bmethod_body(ec, calling, argv); + goto success; case VM_METHOD_TYPE_ZSUPER: + { + VALUE klass = RCLASS_ORIGIN(vm_cc_cme(cc)->defined_class); + return vm_call0_super(ec, calling, argv, klass, MISSING_SUPER); + } case VM_METHOD_TYPE_REFINED: - { - if (ci->me->def->type == VM_METHOD_TYPE_REFINED && - ci->me->def->body.orig_me) { - ci->me = ci->me->def->body.orig_me; - goto again; - } - - ci->defined_class = RCLASS_SUPER(ci->defined_class); - - if (!ci->defined_class || !(ci->me = rb_method_entry(ci->defined_class, ci->mid, &ci->defined_class))) { - ret = method_missing(ci->recv, ci->mid, ci->argc, argv, NOEX_SUPER); - goto success; - } - RUBY_VM_CHECK_INTS(th); - if (!ci->me->def) return Qnil; - goto again; - } + { + const rb_callable_method_entry_t *cme = vm_cc_cme(cc); + + if (cme->def->body.refined.orig_me) { + const rb_callable_method_entry_t *orig_cme = refined_method_callable_without_refinement(cme); + return vm_call0_cme(ec, calling, argv, orig_cme); + } + + VALUE klass = cme->defined_class; + return vm_call0_super(ec, calling, argv, klass, 0); + } + case VM_METHOD_TYPE_ALIAS: + { + const rb_callable_method_entry_t *cme = vm_cc_cme(cc); + const rb_callable_method_entry_t *orig_cme = aliased_callable_method_entry(cme); + + if (cme == orig_cme) rb_bug("same!!"); + + if (vm_cc_markable(cc)) { + return vm_call0_cme(ec, calling, argv, orig_cme); + } + else { + *((const rb_callable_method_entry_t **)&cc->cme_) = orig_cme; + goto retry; + } + } case VM_METHOD_TYPE_MISSING: - { - VALUE new_args = rb_ary_new4(ci->argc, argv); - - RB_GC_GUARD(new_args); - rb_ary_unshift(new_args, ID2SYM(ci->mid)); - th->passed_block = ci->blockptr; - return rb_funcall2(ci->recv, idMethodMissing, ci->argc+1, RARRAY_PTR(new_args)); - } + { + vm_passed_block_handler_set(ec, calling->block_handler); + return method_missing(ec, calling->recv, vm_ci_mid(ci), calling->argc, + argv, MISSING_NOENTRY, calling->kw_splat); + } case VM_METHOD_TYPE_OPTIMIZED: - switch (ci->me->def->body.optimize_type) { - case OPTIMIZED_METHOD_TYPE_SEND: - ret = send_internal(ci->argc, argv, ci->recv, CALL_FCALL); - goto success; - case OPTIMIZED_METHOD_TYPE_CALL: - { - rb_proc_t *proc; - GetProcPtr(ci->recv, proc); - ret = rb_vm_invoke_proc(th, proc, ci->argc, argv, ci->blockptr); - goto success; - } - default: - rb_bug("vm_call0: unsupported optimized method type (%d)", ci->me->def->body.optimize_type); - } - break; + switch (vm_cc_cme(cc)->def->body.optimized.type) { + case OPTIMIZED_METHOD_TYPE_SEND: + ret = send_internal(calling->argc, argv, calling->recv, calling->kw_splat ? CALL_FCALL_KW : CALL_FCALL); + goto success; + case OPTIMIZED_METHOD_TYPE_CALL: + { + rb_proc_t *proc; + GetProcPtr(calling->recv, proc); + ret = rb_vm_invoke_proc(ec, proc, calling->argc, argv, calling->kw_splat, calling->block_handler); + goto success; + } + case OPTIMIZED_METHOD_TYPE_STRUCT_AREF: + vm_call_check_arity(calling, 0, argv); + VM_CALL_METHOD_ATTR(ret, + vm_call_opt_struct_aref0(ec, calling), + (void)0); + goto success; + case OPTIMIZED_METHOD_TYPE_STRUCT_ASET: + vm_call_check_arity(calling, 1, argv); + VM_CALL_METHOD_ATTR(ret, + vm_call_opt_struct_aset0(ec, calling, argv[0]), + (void)0); + goto success; + default: + rb_bug("vm_call0: unsupported optimized method type (%d)", vm_cc_cme(cc)->def->body.optimized.type); + } + break; case VM_METHOD_TYPE_UNDEF: - break; + break; } - rb_bug("vm_call0: unsupported method type (%d)", ci->me->def->type); + rb_bug("vm_call0: unsupported method type (%d)", vm_cc_cme(cc)->def->type); return Qundef; success: - RUBY_VM_CHECK_INTS(th); + RUBY_VM_CHECK_INTS(ec); return ret; } VALUE -rb_vm_call(rb_thread_t *th, VALUE recv, VALUE id, int argc, const VALUE *argv, - const rb_method_entry_t *me, VALUE defined_class) +rb_vm_call_kw(rb_execution_context_t *ec, VALUE recv, VALUE id, int argc, const VALUE *argv, const rb_callable_method_entry_t *me, int kw_splat) { - return vm_call0(th, recv, id, argc, argv, me, defined_class); + return rb_vm_call0(ec, recv, id, argc, argv, me, kw_splat); } static inline VALUE -vm_call_super(rb_thread_t *th, int argc, const VALUE *argv) +vm_call_super(rb_execution_context_t *ec, int argc, const VALUE *argv, int kw_splat) { - VALUE recv = th->cfp->self; + VALUE recv = ec->cfp->self; VALUE klass; ID id; - rb_method_entry_t *me; - rb_control_frame_t *cfp = th->cfp; + rb_control_frame_t *cfp = ec->cfp; + const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp); - if (cfp->iseq || NIL_P(cfp->klass)) { - rb_bug("vm_call_super: should not be reached"); + if (VM_FRAME_RUBYFRAME_P(cfp)) { + rb_bug("vm_call_super: should not be reached"); } - klass = RCLASS_SUPER(cfp->klass); - id = cfp->me->def->original_id; - me = rb_method_entry(klass, id, &klass); + klass = RCLASS_ORIGIN(me->defined_class); + klass = RCLASS_SUPER(klass); + id = me->def->original_id; + me = rb_callable_method_entry(klass, id); + if (!me) { - return method_missing(recv, id, argc, argv, NOEX_SUPER); + return method_missing(ec, recv, id, argc, argv, MISSING_SUPER, kw_splat); } + return rb_vm_call_kw(ec, recv, id, argc, argv, me, kw_splat); +} - return vm_call0(th, recv, id, argc, argv, me, klass); +VALUE +rb_call_super_kw(int argc, const VALUE *argv, int kw_splat) +{ + rb_execution_context_t *ec = GET_EC(); + PASS_PASSED_BLOCK_HANDLER_EC(ec); + return vm_call_super(ec, argc, argv, kw_splat); } VALUE rb_call_super(int argc, const VALUE *argv) { - PASS_PASSED_BLOCK(); - return vm_call_super(GET_THREAD(), argc, argv); + return rb_call_super_kw(argc, argv, RB_NO_KEYWORDS); +} + +VALUE +rb_current_receiver(void) +{ + const rb_execution_context_t *ec = GET_EC(); + rb_control_frame_t *cfp; + if (!ec || !(cfp = ec->cfp)) { + rb_raise(rb_eRuntimeError, "no self, no life"); + } + return cfp->self; } static inline void -stack_check(void) +stack_check(rb_execution_context_t *ec) { - rb_thread_t *th = GET_THREAD(); + if (!rb_ec_raised_p(ec, RAISED_STACKOVERFLOW) && + rb_ec_stack_check(ec)) { + rb_ec_raised_set(ec, RAISED_STACKOVERFLOW); + rb_ec_stack_overflow(ec, 0); + } +} + +void +rb_check_stack_overflow(void) +{ +#ifndef RB_THREAD_LOCAL_SPECIFIER + if (!ruby_current_ec_key) return; +#endif + rb_execution_context_t *ec = GET_EC(); + if (ec) stack_check(ec); +} + +NORETURN(static void uncallable_object(VALUE recv, ID mid)); +static inline const rb_callable_method_entry_t *rb_search_method_entry(VALUE recv, ID mid); +static inline enum method_missing_reason rb_method_call_status(rb_execution_context_t *ec, const rb_callable_method_entry_t *me, call_type scope, VALUE self); + +static VALUE +gccct_hash(VALUE klass, VALUE box_value, ID mid) +{ + return ((klass ^ box_value) >> 3) ^ (VALUE)mid; +} + +NOINLINE(static const struct rb_callcache *gccct_method_search_slowpath(rb_vm_t *vm, VALUE klass, unsigned int index, const struct rb_callinfo * ci)); + +static const struct rb_callcache * +gccct_method_search_slowpath(rb_vm_t *vm, VALUE klass, unsigned int index, const struct rb_callinfo *ci) +{ + struct rb_call_data cd = { + .ci = ci, + .cc = NULL + }; + + vm_search_method_slowpath0(vm->self, &cd, klass); + + return vm->global_cc_cache_table[index] = cd.cc; +} - if (!rb_thread_raised_p(th, RAISED_STACKOVERFLOW) && ruby_stack_check()) { - rb_thread_raised_set(th, RAISED_STACKOVERFLOW); - rb_exc_raise(sysstack_error); +static void +scope_to_ci(call_type scope, ID mid, int argc, struct rb_callinfo *ci) +{ + int flags = 0; + + switch(scope) { + case CALL_PUBLIC: + break; + case CALL_FCALL: + flags |= VM_CALL_FCALL; + break; + case CALL_VCALL: + flags |= VM_CALL_VCALL; + break; + case CALL_PUBLIC_KW: + flags |= VM_CALL_KWARG; + break; + case CALL_FCALL_KW: + flags |= (VM_CALL_KWARG | VM_CALL_FCALL); + break; } + *ci = VM_CI_ON_STACK(mid, flags, argc, NULL); } -static inline rb_method_entry_t * - rb_search_method_entry(VALUE recv, ID mid, VALUE *defined_class_ptr); -static inline int rb_method_call_status(rb_thread_t *th, const rb_method_entry_t *me, call_type scope, VALUE self); -#define NOEX_OK NOEX_NOSUPER +static inline const struct rb_callcache * +gccct_method_search(rb_execution_context_t *ec, VALUE recv, ID mid, const struct rb_callinfo *ci) +{ + VALUE klass, box_value; + const rb_box_t *box = rb_current_box(); + + if (!SPECIAL_CONST_P(recv)) { + klass = RBASIC_CLASS(recv); + if (UNLIKELY(!klass)) uncallable_object(recv, mid); + } + else { + klass = CLASS_OF(recv); + } + + if (BOX_USER_P(box)) { + box_value = box->box_object; + } + else { + box_value = 0; + } + // search global method cache + unsigned int index = (unsigned int)(gccct_hash(klass, box_value, mid) % VM_GLOBAL_CC_CACHE_TABLE_SIZE); + rb_vm_t *vm = rb_ec_vm_ptr(ec); + const struct rb_callcache *cc = vm->global_cc_cache_table[index]; + + if (LIKELY(cc)) { + if (LIKELY(vm_cc_class_check(cc, klass))) { + const rb_callable_method_entry_t *cme = vm_cc_cme(cc); + if (LIKELY(!METHOD_ENTRY_INVALIDATED(cme) && + cme->called_id == mid)) { -/*! - * \internal + VM_ASSERT(vm_cc_check_cme(cc, rb_callable_method_entry(klass, mid))); + RB_DEBUG_COUNTER_INC(gccct_hit); + + return cc; + } + } + } + else { + RB_DEBUG_COUNTER_INC(gccct_null); + } + + RB_DEBUG_COUNTER_INC(gccct_miss); + return gccct_method_search_slowpath(vm, klass, index, ci); +} + +VALUE +rb_gccct_clear_table(VALUE _self) +{ + int i; + rb_vm_t *vm = GET_VM(); + for (i=0; i<VM_GLOBAL_CC_CACHE_TABLE_SIZE; i++) { + vm->global_cc_cache_table[i] = NULL; + } + return Qnil; +} + +/** + * @internal * calls the specified method. * * This function is called by functions in rb_call* family. - * \param recv receiver of the method - * \param mid an ID that represents the name of the method - * \param argc the number of method arguments - * \param argv a pointer to an array of method arguments - * \param scope - * \param self self in the caller. Qundef means no self is considered and + * @param ec current execution context + * @param recv receiver of the method + * @param mid an ID that represents the name of the method + * @param argc the number of method arguments + * @param argv a pointer to an array of method arguments + * @param scope + * @param self self in the caller. Qundef means no self is considered and * protected methods cannot be called * - * \note \a self is used in order to controlling access to protected methods. + * @note `self` is used in order to controlling access to protected methods. */ static inline VALUE -rb_call0(VALUE recv, ID mid, int argc, const VALUE *argv, - call_type scope, VALUE self) -{ - VALUE defined_class; - rb_method_entry_t *me = - rb_search_method_entry(recv, mid, &defined_class); - rb_thread_t *th = GET_THREAD(); - int call_status = rb_method_call_status(th, me, scope, self); +rb_call0(rb_execution_context_t *ec, + VALUE recv, ID mid, int argc, const VALUE *argv, + call_type call_scope, VALUE self) +{ + enum method_missing_reason call_status; + call_type scope = call_scope; + int kw_splat = RB_NO_KEYWORDS; + + switch (scope) { + case CALL_PUBLIC_KW: + scope = CALL_PUBLIC; + kw_splat = 1; + break; + case CALL_FCALL_KW: + scope = CALL_FCALL; + kw_splat = 1; + break; + default: + break; + } + + struct rb_callinfo ci; + scope_to_ci(scope, mid, argc, &ci); + + const struct rb_callcache *cc = gccct_method_search(ec, recv, mid, &ci); + + if (scope == CALL_PUBLIC) { + RB_DEBUG_COUNTER_INC(call0_public); + + const rb_callable_method_entry_t *cc_cme = cc ? vm_cc_cme(cc) : NULL; + const rb_callable_method_entry_t *cme = callable_method_entry_refinements0(CLASS_OF(recv), mid, NULL, true, cc_cme); + call_status = rb_method_call_status(ec, cme, scope, self); - if (call_status != NOEX_OK) { - return method_missing(recv, mid, argc, argv, call_status); + if (UNLIKELY(call_status != MISSING_NONE)) { + return method_missing(ec, recv, mid, argc, argv, call_status, kw_splat); + } + else if (UNLIKELY(cc_cme != cme)) { // refinement is solved + stack_check(ec); + return rb_vm_call_kw(ec, recv, mid, argc, argv, cme, kw_splat); + } + } + else { + RB_DEBUG_COUNTER_INC(call0_other); + call_status = rb_method_call_status(ec, cc ? vm_cc_cme(cc) : NULL, scope, self); + + if (UNLIKELY(call_status != MISSING_NONE)) { + return method_missing(ec, recv, mid, argc, argv, call_status, kw_splat); + } } - stack_check(); - return vm_call0(th, recv, mid, argc, argv, me, defined_class); + + stack_check(ec); + return vm_call0_cc(ec, recv, mid, argc, argv, cc, kw_splat); } struct rescue_funcall_args { + VALUE defined_class; VALUE recv; - VALUE sym; + ID mid; + rb_execution_context_t *ec; + const rb_callable_method_entry_t *cme; + unsigned int respond: 1; + unsigned int respond_to_missing: 1; int argc; - VALUE *argv; + const VALUE *argv; + int kw_splat; }; static VALUE -check_funcall_exec(struct rescue_funcall_args *args) +check_funcall_exec(VALUE v) { - VALUE new_args = rb_ary_new4(args->argc, args->argv); - - RB_GC_GUARD(new_args); - rb_ary_unshift(new_args, args->sym); - return rb_funcall2(args->recv, idMethodMissing, - args->argc+1, RARRAY_PTR(new_args)); + struct rescue_funcall_args *args = (void *)v; + return call_method_entry(args->ec, args->defined_class, + args->recv, idMethodMissing, + args->cme, args->argc, args->argv, args->kw_splat); } static VALUE -check_funcall_failed(struct rescue_funcall_args *args, VALUE e) -{ - if (rb_respond_to(args->recv, SYM2ID(args->sym))) { - rb_exc_raise(e); +check_funcall_failed(VALUE v, VALUE e) +{ + struct rescue_funcall_args *args = (void *)v; + int ret = args->respond; + if (!ret) { + switch (method_boundp(args->defined_class, args->mid, + BOUND_PRIVATE|BOUND_RESPONDS)) { + case 2: + ret = TRUE; + break; + case 0: + ret = args->respond_to_missing; + break; + default: + ret = FALSE; + break; + } + } + if (ret) { + rb_exc_raise(e); } return Qundef; } static int -check_funcall_respond_to(rb_thread_t *th, VALUE klass, VALUE recv, ID mid) +check_funcall_respond_to(rb_execution_context_t *ec, VALUE klass, VALUE recv, ID mid) { - VALUE defined_class; - const rb_method_entry_t *me = rb_method_entry(klass, idRespond_to, &defined_class); - - if (me && !(me->flag & NOEX_BASIC)) { - const rb_block_t *passed_block = th->passed_block; - VALUE args[2], result; - int arity = rb_method_entry_arity(me); - - if (arity > 2) - rb_raise(rb_eArgError, "respond_to? must accept 1 or 2 arguments (requires %d)", arity); - - if (arity < 1) arity = 2; - - args[0] = ID2SYM(mid); - args[1] = Qtrue; - result = vm_call0(th, recv, idRespond_to, arity, args, me, defined_class); - th->passed_block = passed_block; - if (!RTEST(result)) { - return FALSE; - } - } - return TRUE; + return vm_respond_to(ec, klass, recv, mid, TRUE); } static int -check_funcall_callable(rb_thread_t *th, const rb_method_entry_t *me) +check_funcall_callable(rb_execution_context_t *ec, const rb_callable_method_entry_t *me) { - return rb_method_call_status(th, me, CALL_FCALL, th->cfp->self) == NOEX_OK; + return rb_method_call_status(ec, me, CALL_FCALL, ec->cfp->self) == MISSING_NONE; } static VALUE -check_funcall_missing(rb_thread_t *th, VALUE klass, VALUE recv, ID mid, int argc, VALUE *argv) -{ - if (rb_method_basic_definition_p(klass, idMethodMissing)) { - return Qundef; +check_funcall_missing(rb_execution_context_t *ec, VALUE klass, VALUE recv, ID mid, int argc, const VALUE *argv, int respond, VALUE def, int kw_splat) +{ + struct rescue_funcall_args args; + const rb_callable_method_entry_t *cme; + VALUE ret = Qundef; + + ret = basic_obj_respond_to_missing(ec, klass, recv, + ID2SYM(mid), Qtrue); + if (!RTEST(ret)) return def; + args.respond = respond > 0; + args.respond_to_missing = !UNDEF_P(ret); + ret = def; + cme = callable_method_entry(klass, idMethodMissing, &args.defined_class); + + if (cme && !METHOD_ENTRY_BASIC(cme)) { + VALUE argbuf, *new_args = ALLOCV_N(VALUE, argbuf, argc+1); + + new_args[0] = ID2SYM(mid); + #ifdef __GLIBC__ + if (!argv) { + static const VALUE buf = Qfalse; + VM_ASSERT(argc == 0); + argv = &buf; + } + #endif + MEMCPY(new_args+1, argv, VALUE, argc); + ec->method_missing_reason = MISSING_NOENTRY; + args.ec = ec; + args.recv = recv; + args.cme = cme; + args.mid = mid; + args.argc = argc + 1; + args.argv = new_args; + args.kw_splat = kw_splat; + ret = rb_rescue2(check_funcall_exec, (VALUE)&args, + check_funcall_failed, (VALUE)&args, + rb_eNoMethodError, (VALUE)0); + ALLOCV_END(argbuf); } - else { - struct rescue_funcall_args args; + return ret; +} - th->method_missing_reason = 0; - args.recv = recv; - args.sym = ID2SYM(mid); - args.argc = argc; - args.argv = argv; - return rb_rescue2(check_funcall_exec, (VALUE)&args, - check_funcall_failed, (VALUE)&args, - rb_eNoMethodError, (VALUE)0); - } +static VALUE rb_check_funcall_default_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE def, int kw_splat); + +VALUE +rb_check_funcall_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat) +{ + return rb_check_funcall_default_kw(recv, mid, argc, argv, Qundef, kw_splat); } VALUE -rb_check_funcall(VALUE recv, ID mid, int argc, VALUE *argv) +rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv) { + return rb_check_funcall_default_kw(recv, mid, argc, argv, Qundef, RB_NO_KEYWORDS); +} + +static VALUE +rb_check_funcall_default_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE def, int kw_splat) +{ + VM_ASSERT(ruby_thread_has_gvl_p()); + VALUE klass = CLASS_OF(recv); - const rb_method_entry_t *me; - rb_thread_t *th = GET_THREAD(); - VALUE defined_class; + const rb_callable_method_entry_t *me; + rb_execution_context_t *ec = GET_EC(); + int respond = check_funcall_respond_to(ec, klass, recv, mid); - if (!check_funcall_respond_to(th, klass, recv, mid)) - return Qundef; + if (!respond) + return def; - me = rb_search_method_entry(recv, mid, &defined_class); - if (check_funcall_callable(th, me) != NOEX_OK) { - return check_funcall_missing(th, klass, recv, mid, argc, argv); + me = rb_search_method_entry(recv, mid); + if (!check_funcall_callable(ec, me)) { + VALUE ret = check_funcall_missing(ec, klass, recv, mid, argc, argv, + respond, def, kw_splat); + if (UNDEF_P(ret)) ret = def; + return ret; } - stack_check(); - return vm_call0(th, recv, mid, argc, argv, me, defined_class); + stack_check(ec); + return rb_vm_call_kw(ec, recv, mid, argc, argv, me, kw_splat); +} + +VALUE +rb_check_funcall_default(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE def) +{ + return rb_check_funcall_default_kw(recv, mid, argc, argv, def, RB_NO_KEYWORDS); } VALUE -rb_check_funcall_with_hook(VALUE recv, ID mid, int argc, VALUE *argv, - rb_check_funcall_hook *hook, VALUE arg) +rb_check_funcall_with_hook_kw(VALUE recv, ID mid, int argc, const VALUE *argv, + rb_check_funcall_hook *hook, VALUE arg, int kw_splat) { VALUE klass = CLASS_OF(recv); - const rb_method_entry_t *me; - rb_thread_t *th = GET_THREAD(); - VALUE defined_class; + const rb_callable_method_entry_t *me; + rb_execution_context_t *ec = GET_EC(); + int respond = check_funcall_respond_to(ec, klass, recv, mid); - if (!check_funcall_respond_to(th, klass, recv, mid)) - return Qundef; + if (!respond) { + (*hook)(FALSE, recv, mid, argc, argv, arg); + return Qundef; + } - me = rb_search_method_entry(recv, mid, &defined_class); - if (check_funcall_callable(th, me) != NOEX_OK) { - (*hook)(FALSE, recv, mid, argc, argv, arg); - return check_funcall_missing(th, klass, recv, mid, argc, argv); + me = rb_search_method_entry(recv, mid); + if (!check_funcall_callable(ec, me)) { + VALUE ret = check_funcall_missing(ec, klass, recv, mid, argc, argv, + respond, Qundef, kw_splat); + (*hook)(!UNDEF_P(ret), recv, mid, argc, argv, arg); + return ret; } - stack_check(); + stack_check(ec); (*hook)(TRUE, recv, mid, argc, argv, arg); - return vm_call0(th, recv, mid, argc, argv, me, defined_class); + return rb_vm_call_kw(ec, recv, mid, argc, argv, me, kw_splat); } -static const char * +const char * rb_type_str(enum ruby_value_type type) { -#define type_case(t) case t: return #t; +#define type_case(t) t: return #t switch (type) { - type_case(T_NONE) - type_case(T_OBJECT) - type_case(T_CLASS) - type_case(T_MODULE) - type_case(T_FLOAT) - type_case(T_STRING) - type_case(T_REGEXP) - type_case(T_ARRAY) - type_case(T_HASH) - type_case(T_STRUCT) - type_case(T_BIGNUM) - type_case(T_FILE) - type_case(T_DATA) - type_case(T_MATCH) - type_case(T_COMPLEX) - type_case(T_RATIONAL) - type_case(T_NIL) - type_case(T_TRUE) - type_case(T_FALSE) - type_case(T_SYMBOL) - type_case(T_FIXNUM) - type_case(T_UNDEF) - type_case(T_NODE) - type_case(T_ICLASS) - type_case(T_ZOMBIE) - default: return NULL; + case type_case(T_NONE); + case type_case(T_OBJECT); + case type_case(T_CLASS); + case type_case(T_MODULE); + case type_case(T_FLOAT); + case type_case(T_STRING); + case type_case(T_REGEXP); + case type_case(T_ARRAY); + case type_case(T_HASH); + case type_case(T_STRUCT); + case type_case(T_BIGNUM); + case type_case(T_FILE); + case type_case(T_DATA); + case type_case(T_MATCH); + case type_case(T_COMPLEX); + case type_case(T_RATIONAL); + case type_case(T_NIL); + case type_case(T_TRUE); + case type_case(T_FALSE); + case type_case(T_SYMBOL); + case type_case(T_FIXNUM); + case type_case(T_IMEMO); + case type_case(T_UNDEF); + case type_case(T_NODE); + case type_case(T_ICLASS); + case type_case(T_ZOMBIE); + case type_case(T_MOVED); + case T_MASK: break; } #undef type_case + return NULL; } -static inline rb_method_entry_t * -rb_search_method_entry(VALUE recv, ID mid, VALUE *defined_class_ptr) +static void +uncallable_object(VALUE recv, ID mid) +{ + VALUE flags; + int type; + const char *typestr; + VALUE mname = rb_id2str(mid); + + if (SPECIAL_CONST_P(recv)) { + rb_raise(rb_eNotImpError, + "method '%"PRIsVALUE"' called on unexpected immediate object (%p)", + mname, (void *)recv); + } + else if ((flags = RBASIC(recv)->flags) == 0) { + rb_raise(rb_eNotImpError, + "method '%"PRIsVALUE"' called on terminated object (%p)", + mname, (void *)recv); + } + else if (!(typestr = rb_type_str(type = BUILTIN_TYPE(recv)))) { + rb_raise(rb_eNotImpError, + "method '%"PRIsVALUE"' called on broken T_?""?""?(0x%02x) object" + " (%p flags=0x%"PRIxVALUE")", + mname, type, (void *)recv, flags); + } + else if (T_OBJECT <= type && type < T_NIL) { + rb_raise(rb_eNotImpError, + "method '%"PRIsVALUE"' called on hidden %s object" + " (%p flags=0x%"PRIxVALUE")", + mname, typestr, (void *)recv, flags); + } + else { + rb_raise(rb_eNotImpError, + "method '%"PRIsVALUE"' called on unexpected %s object" + " (%p flags=0x%"PRIxVALUE")", + mname, typestr, (void *)recv, flags); + } +} + +static inline const rb_callable_method_entry_t * +rb_search_method_entry(VALUE recv, ID mid) { VALUE klass = CLASS_OF(recv); - if (!klass) { - VALUE flags; - if (SPECIAL_CONST_P(recv)) { - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on unexpected immediate object (%p)", - rb_id2str(mid), (void *)recv); - } - flags = RBASIC(recv)->flags; - if (flags == 0) { - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on terminated object" - " (%p flags=0x%"PRIxVALUE")", - rb_id2str(mid), (void *)recv, flags); - } - else { - int type = BUILTIN_TYPE(recv); - const char *typestr = rb_type_str(type); - if (typestr && T_OBJECT <= type && type < T_NIL) - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on hidden %s object" - " (%p flags=0x%"PRIxVALUE")", - rb_id2str(mid), typestr, (void *)recv, flags); - if (typestr) - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on unexpected %s object" - " (%p flags=0x%"PRIxVALUE")", - rb_id2str(mid), typestr, (void *)recv, flags); - else - rb_raise(rb_eNotImpError, - "method `%"PRIsVALUE"' called on broken T_???" "(0x%02x) object" - " (%p flags=0x%"PRIxVALUE")", - rb_id2str(mid), type, (void *)recv, flags); - } - } - return rb_method_entry(klass, mid, defined_class_ptr); + if (!klass) uncallable_object(recv, mid); + return rb_callable_method_entry(klass, mid); } -static inline int -rb_method_call_status(rb_thread_t *th, const rb_method_entry_t *me, call_type scope, VALUE self) +static inline enum method_missing_reason +rb_method_call_status(rb_execution_context_t *ec, const rb_callable_method_entry_t *me, call_type scope, VALUE self) { - VALUE klass; - ID oid; - int noex; - - if (UNDEFINED_METHOD_ENTRY_P(me)) { - return scope == CALL_VCALL ? NOEX_VCALL : 0; + if (UNLIKELY(UNDEFINED_METHOD_ENTRY_P(me))) { + goto undefined; + } + else if (UNLIKELY(me->def->type == VM_METHOD_TYPE_REFINED)) { + me = rb_resolve_refined_method_callable(Qnil, me); + if (UNDEFINED_METHOD_ENTRY_P(me)) goto undefined; } - klass = me->klass; - oid = me->def->original_id; - noex = me->flag; - - if (oid != idMethodMissing) { - /* receiver specified form for private method */ - if (UNLIKELY(noex)) { - if (((noex & NOEX_MASK) & NOEX_PRIVATE) && scope == CALL_PUBLIC) { - return NOEX_PRIVATE; - } - /* self must be kind of a specified form for protected method */ - if (((noex & NOEX_MASK) & NOEX_PROTECTED) && scope == CALL_PUBLIC) { - VALUE defined_class = klass; + rb_method_visibility_t visi = METHOD_ENTRY_VISI(me); - if (RB_TYPE_P(defined_class, T_ICLASS)) { - defined_class = RBASIC(defined_class)->klass; - } + /* receiver specified form for private method */ + if (UNLIKELY(visi != METHOD_VISI_PUBLIC)) { + if (me->def->original_id == idMethodMissing) { + return MISSING_NONE; + } + else if (visi == METHOD_VISI_PRIVATE && + scope == CALL_PUBLIC) { + return MISSING_PRIVATE; + } + /* self must be kind of a specified form for protected method */ + else if (visi == METHOD_VISI_PROTECTED && + scope == CALL_PUBLIC) { + + VALUE defined_class = me->owner; + if (RB_TYPE_P(defined_class, T_ICLASS)) { + defined_class = RBASIC(defined_class)->klass; + } + + if (UNDEF_P(self) || !rb_obj_is_kind_of(self, defined_class)) { + return MISSING_PROTECTED; + } + } + } - if (self == Qundef || !rb_obj_is_kind_of(self, defined_class)) { - return NOEX_PROTECTED; - } - } + return MISSING_NONE; - if (NOEX_SAFE(noex) > th->safe_level) { - rb_raise(rb_eSecurityError, "calling insecure method: %s", - rb_id2name(me->called_id)); - } - } - } - return NOEX_OK; + undefined: + return scope == CALL_VCALL ? MISSING_VCALL : MISSING_NOENTRY; } -/*! - * \internal +/** + * @internal * calls the specified method. * * This function is called by functions in rb_call* family. - * \param recv receiver - * \param mid an ID that represents the name of the method - * \param argc the number of method arguments - * \param argv a pointer to an array of method arguments - * \param scope + * @param recv receiver + * @param mid an ID that represents the name of the method + * @param argc the number of method arguments + * @param argv a pointer to an array of method arguments + * @param scope */ static inline VALUE rb_call(VALUE recv, ID mid, int argc, const VALUE *argv, call_type scope) { - rb_thread_t *th = GET_THREAD(); - return rb_call0(recv, mid, argc, argv, scope, th->cfp->self); + rb_execution_context_t *ec = GET_EC(); + return rb_call0(ec, recv, mid, argc, argv, scope, ec->cfp->self); } -NORETURN(static void raise_method_missing(rb_thread_t *th, int argc, const VALUE *argv, - VALUE obj, int call_status)); +NORETURN(static void raise_method_missing(rb_execution_context_t *ec, int argc, const VALUE *argv, + VALUE obj, enum method_missing_reason call_status)); /* * call-seq: @@ -608,9 +915,14 @@ NORETURN(static void raise_method_missing(rb_thread_t *th, int argc, const VALUE * def roman_to_int(str) * # ... * end - * def method_missing(methId) - * str = methId.id2name - * roman_to_int(str) + * + * def method_missing(symbol, *args) + * str = symbol.id2name + * begin + * roman_to_int(str) + * rescue + * super(symbol, *args) + * end * end * end * @@ -618,128 +930,164 @@ NORETURN(static void raise_method_missing(rb_thread_t *th, int argc, const VALUE * r.iv #=> 4 * r.xxiii #=> 23 * r.mm #=> 2000 + * r.foo #=> NoMethodError */ static VALUE rb_method_missing(int argc, const VALUE *argv, VALUE obj) { - rb_thread_t *th = GET_THREAD(); - raise_method_missing(th, argc, argv, obj, th->method_missing_reason); - UNREACHABLE; + rb_execution_context_t *ec = GET_EC(); + raise_method_missing(ec, argc, argv, obj, ec->method_missing_reason); + UNREACHABLE_RETURN(Qnil); } -#define NOEX_MISSING 0x80 - -static VALUE -make_no_method_exception(VALUE exc, const char *format, VALUE obj, int argc, const VALUE *argv) +VALUE +rb_make_no_method_exception(VALUE exc, VALUE format, VALUE obj, + int argc, const VALUE *argv, int priv) { - int n = 0; - VALUE mesg; - VALUE args[3]; + VALUE name = argv[0]; if (!format) { - format = "undefined method `%s' for %s"; + format = rb_fstring_lit("undefined method '%1$s' for %3$s%4$s"); } - mesg = rb_const_get(exc, rb_intern("message")); - if (rb_method_basic_definition_p(CLASS_OF(mesg), '!')) { - args[n++] = rb_name_err_mesg_new(mesg, rb_str_new2(format), obj, argv[0]); + if (exc == rb_eNoMethodError) { + VALUE args = rb_ary_new4(argc - 1, argv + 1); + return rb_nomethod_err_new(format, obj, name, args, priv); } else { - args[n++] = rb_funcall(mesg, '!', 3, rb_str_new2(format), obj, argv[0]); - } - args[n++] = argv[0]; - if (exc == rb_eNoMethodError) { - args[n++] = rb_ary_new4(argc - 1, argv + 1); + return rb_name_err_new(format, obj, name); } - return rb_class_new_instance(n, args, exc); } static void -raise_method_missing(rb_thread_t *th, int argc, const VALUE *argv, VALUE obj, - int last_call_status) +raise_method_missing(rb_execution_context_t *ec, int argc, const VALUE *argv, VALUE obj, + enum method_missing_reason last_call_status) { VALUE exc = rb_eNoMethodError; - const char *format = 0; + VALUE format = 0; - if (argc == 0 || !SYMBOL_P(argv[0])) { - rb_raise(rb_eArgError, "no id given"); + if (UNLIKELY(argc == 0)) { + rb_raise(rb_eArgError, "no method name given"); + } + else if (UNLIKELY(!SYMBOL_P(argv[0]))) { + const VALUE e = rb_eArgError; /* TODO: TypeError? */ + rb_raise(e, "method name must be a Symbol but %"PRIsVALUE" is given", + rb_obj_class(argv[0])); } - stack_check(); + stack_check(ec); - if (last_call_status & NOEX_PRIVATE) { - format = "private method `%s' called for %s"; + if (last_call_status & MISSING_PRIVATE) { + format = rb_fstring_lit("private method '%1$s' called for %3$s%4$s"); } - else if (last_call_status & NOEX_PROTECTED) { - format = "protected method `%s' called for %s"; + else if (last_call_status & MISSING_PROTECTED) { + format = rb_fstring_lit("protected method '%1$s' called for %3$s%4$s"); } - else if (last_call_status & NOEX_VCALL) { - format = "undefined local variable or method `%s' for %s"; - exc = rb_eNameError; + else if (last_call_status & MISSING_VCALL) { + format = rb_fstring_lit("undefined local variable or method '%1$s' for %3$s%4$s"); + exc = rb_eNameError; } - else if (last_call_status & NOEX_SUPER) { - format = "super: no superclass method `%s' for %s"; + else if (last_call_status & MISSING_SUPER) { + format = rb_fstring_lit("super: no superclass method '%1$s' for %3$s%4$s"); } { - exc = make_no_method_exception(exc, format, obj, argc, argv); - if (!(last_call_status & NOEX_MISSING)) { - rb_vm_pop_cfunc_frame(); - } - rb_exc_raise(exc); + exc = rb_make_no_method_exception(exc, format, obj, argc, argv, + last_call_status & (MISSING_FCALL|MISSING_VCALL)); + if (!(last_call_status & MISSING_MISSING)) { + rb_vm_pop_cfunc_frame(); + } + rb_exc_raise(exc); } } +static void +vm_raise_method_missing(rb_execution_context_t *ec, int argc, const VALUE *argv, + VALUE obj, int call_status) +{ + vm_passed_block_handler_set(ec, VM_BLOCK_HANDLER_NONE); + raise_method_missing(ec, argc, argv, obj, call_status | MISSING_MISSING); +} + static inline VALUE -method_missing(VALUE obj, ID id, int argc, const VALUE *argv, int call_status) +method_missing(rb_execution_context_t *ec, VALUE obj, ID id, int argc, const VALUE *argv, enum method_missing_reason call_status, int kw_splat) { - VALUE *nargv, result, argv_ary = 0; - rb_thread_t *th = GET_THREAD(); - const rb_block_t *blockptr = th->passed_block; + VALUE *nargv, result, work, klass; + VALUE block_handler = vm_passed_block_handler(ec); + const rb_callable_method_entry_t *me; - th->method_missing_reason = call_status; - th->passed_block = 0; + ec->method_missing_reason = call_status; if (id == idMethodMissing) { - raise_method_missing(th, argc, argv, obj, call_status | NOEX_MISSING); + goto missing; } - if (argc < 0x100) { - nargv = ALLOCA_N(VALUE, argc + 1); - } - else { - argv_ary = rb_ary_tmp_new(argc + 1); - nargv = RARRAY_PTR(argv_ary); - } + nargv = ALLOCV_N(VALUE, work, argc + 1); nargv[0] = ID2SYM(id); + #ifdef __GLIBC__ + if (!argv) { + static const VALUE buf = Qfalse; + VM_ASSERT(argc == 0); + argv = &buf; + } + #endif MEMCPY(nargv + 1, argv, VALUE, argc); - if (argv_ary) rb_ary_set_len(argv_ary, argc + 1); + ++argc; + argv = nargv; + + klass = CLASS_OF(obj); + if (!klass) goto missing; + me = rb_callable_method_entry(klass, idMethodMissing); + if (!me || METHOD_ENTRY_BASIC(me)) goto missing; + vm_passed_block_handler_set(ec, block_handler); + result = rb_vm_call_kw(ec, obj, idMethodMissing, argc, argv, me, kw_splat); + if (work) ALLOCV_END(work); + return result; + missing: + raise_method_missing(ec, argc, argv, obj, call_status | MISSING_MISSING); + UNREACHABLE_RETURN(Qundef); +} + +static inline VALUE +rb_funcallv_scope(VALUE recv, ID mid, int argc, const VALUE *argv, call_type scope) +{ + rb_execution_context_t *ec = GET_EC(); - if (rb_method_basic_definition_p(CLASS_OF(obj) , idMethodMissing)) { - raise_method_missing(th, argc+1, nargv, obj, call_status | NOEX_MISSING); + struct rb_callinfo ci; + scope_to_ci(scope, mid, argc, &ci); + + const struct rb_callcache *cc = gccct_method_search(ec, recv, mid, &ci); + VALUE self = ec->cfp->self; + + if (LIKELY(cc) && + LIKELY(rb_method_call_status(ec, vm_cc_cme(cc), scope, self) == MISSING_NONE)) { + // fastpath + return vm_call0_cc(ec, recv, mid, argc, argv, cc, false); + } + else { + return rb_call0(ec, recv, mid, argc, argv, scope, self); } - th->passed_block = blockptr; - result = rb_funcall2(obj, idMethodMissing, argc + 1, nargv); - if (argv_ary) rb_ary_clear(argv_ary); - return result; } -void -rb_raise_method_missing(rb_thread_t *th, int argc, VALUE *argv, - VALUE obj, int call_status) +#ifdef rb_funcallv +#undef rb_funcallv +#endif +VALUE +rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv) { - th->passed_block = 0; - raise_method_missing(th, argc, argv, obj, call_status | NOEX_MISSING); + VM_ASSERT(ruby_thread_has_gvl_p()); + + return rb_funcallv_scope(recv, mid, argc, argv, CALL_FCALL); +} + +VALUE +rb_funcallv_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat) +{ + VM_ASSERT(ruby_thread_has_gvl_p()); + + return rb_call(recv, mid, argc, argv, kw_splat ? CALL_FCALL_KW : CALL_FCALL); } -/*! - * Calls a method - * \param recv receiver of the method - * \param mid an ID that represents the name of the method - * \param args an Array object which contains method arguments - * - * \pre \a args must refer an Array object. - */ VALUE rb_apply(VALUE recv, ID mid, VALUE args) { @@ -748,27 +1096,23 @@ rb_apply(VALUE recv, ID mid, VALUE args) argc = RARRAY_LENINT(args); if (argc >= 0x100) { - args = rb_ary_subseq(args, 0, argc); - RBASIC(args)->klass = 0; - OBJ_FREEZE(args); - ret = rb_call(recv, mid, argc, RARRAY_PTR(args), CALL_FCALL); - RB_GC_GUARD(args); - return ret; + args = rb_ary_subseq(args, 0, argc); + RBASIC_CLEAR_CLASS(args); + OBJ_FREEZE(args); + ret = rb_call(recv, mid, argc, RARRAY_CONST_PTR(args), CALL_FCALL); + RB_GC_GUARD(args); + return ret; } argv = ALLOCA_N(VALUE, argc); - MEMCPY(argv, RARRAY_PTR(args), VALUE, argc); - return rb_call(recv, mid, argc, argv, CALL_FCALL); + MEMCPY(argv, RARRAY_CONST_PTR(args), VALUE, argc); + + return rb_funcallv(recv, mid, argc, argv); } -/*! - * Calls a method - * \param recv receiver of the method - * \param mid an ID that represents the name of the method - * \param n the number of arguments - * \param ... arbitrary number of method arguments - * - * \pre each of arguments after \a n must be a VALUE. - */ +#ifdef rb_funcall +#undef rb_funcall +#endif + VALUE rb_funcall(VALUE recv, ID mid, int n, ...) { @@ -776,74 +1120,103 @@ rb_funcall(VALUE recv, ID mid, int n, ...) va_list ar; if (n > 0) { - long i; + long i; - va_init_list(ar, n); + va_start(ar, n); - argv = ALLOCA_N(VALUE, n); + argv = ALLOCA_N(VALUE, n); - for (i = 0; i < n; i++) { - argv[i] = va_arg(ar, VALUE); - } - va_end(ar); + for (i = 0; i < n; i++) { + argv[i] = va_arg(ar, VALUE); + } + va_end(ar); } else { - argv = 0; + argv = 0; } - return rb_call(recv, mid, n, argv, CALL_FCALL); + return rb_funcallv(recv, mid, n, argv); } -/*! - * Calls a method - * \param recv receiver of the method - * \param mid an ID that represents the name of the method - * \param argc the number of arguments - * \param argv pointer to an array of method arguments +/** + * Calls a method only if it is the basic method of `ancestor` + * otherwise returns Qundef; + * @param recv receiver of the method + * @param mid an ID that represents the name of the method + * @param ancestor the Class that defined the basic method + * @param argc the number of arguments + * @param argv pointer to an array of method arguments + * @param kw_splat bool */ VALUE -rb_funcall2(VALUE recv, ID mid, int argc, const VALUE *argv) +rb_check_funcall_basic_kw(VALUE recv, ID mid, VALUE ancestor, int argc, const VALUE *argv, int kw_splat) { - return rb_call(recv, mid, argc, argv, CALL_FCALL); + const rb_callable_method_entry_t *cme; + rb_execution_context_t *ec; + VALUE klass = CLASS_OF(recv); + if (!klass) return Qundef; /* hidden object */ + + cme = rb_callable_method_entry(klass, mid); + if (cme && METHOD_ENTRY_BASIC(cme) && RBASIC_CLASS(cme->defined_class) == ancestor) { + ec = GET_EC(); + return rb_vm_call0(ec, recv, mid, argc, argv, cme, kw_splat); + } + + return Qundef; +} + +VALUE +rb_funcallv_public(VALUE recv, ID mid, int argc, const VALUE *argv) +{ + return rb_funcallv_scope(recv, mid, argc, argv, CALL_PUBLIC); } -/*! - * Calls a method. - * - * Same as rb_funcall2 but this function can call only public methods. - * \param recv receiver of the method - * \param mid an ID that represents the name of the method - * \param argc the number of arguments - * \param argv pointer to an array of method arguments - */ VALUE -rb_funcall3(VALUE recv, ID mid, int argc, const VALUE *argv) +rb_funcallv_public_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat) { - return rb_call(recv, mid, argc, argv, CALL_PUBLIC); + return rb_call(recv, mid, argc, argv, kw_splat ? CALL_PUBLIC_KW : CALL_PUBLIC); } VALUE rb_funcall_passing_block(VALUE recv, ID mid, int argc, const VALUE *argv) { - PASS_PASSED_BLOCK_TH(GET_THREAD()); + PASS_PASSED_BLOCK_HANDLER(); + return rb_funcallv_public(recv, mid, argc, argv); +} - return rb_call(recv, mid, argc, argv, CALL_PUBLIC); +VALUE +rb_funcall_passing_block_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat) +{ + PASS_PASSED_BLOCK_HANDLER(); + return rb_call(recv, mid, argc, argv, kw_splat ? CALL_PUBLIC_KW : CALL_PUBLIC); } VALUE -rb_funcall_with_block(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE pass_procval) +rb_funcall_with_block(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE passed_procval) { - if (!NIL_P(pass_procval)) { - rb_thread_t *th = GET_THREAD(); - rb_block_t *block = 0; + if (!NIL_P(passed_procval)) { + vm_passed_block_handler_set(GET_EC(), passed_procval); + } - rb_proc_t *pass_proc; - GetProcPtr(pass_procval, pass_proc); - block = &pass_proc->block; + return rb_funcallv_public(recv, mid, argc, argv); +} - th->passed_block = block; +VALUE +rb_funcall_with_block_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE passed_procval, int kw_splat) +{ + if (!NIL_P(passed_procval)) { + vm_passed_block_handler_set(GET_EC(), passed_procval); } - return rb_call(recv, mid, argc, argv, CALL_PUBLIC); + return rb_call(recv, mid, argc, argv, kw_splat ? CALL_PUBLIC_KW : CALL_PUBLIC); +} + +static VALUE * +current_vm_stack_arg(const rb_execution_context_t *ec, const VALUE *argv) +{ + rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp); + if (RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, prev_cfp)) return NULL; + if (prev_cfp->sp + 1 != argv) return NULL; + return prev_cfp->sp + 1; } static VALUE @@ -852,42 +1225,93 @@ send_internal(int argc, const VALUE *argv, VALUE recv, call_type scope) ID id; VALUE vid; VALUE self; - rb_thread_t *th = GET_THREAD(); + VALUE ret, vargv = 0; + rb_execution_context_t *ec = GET_EC(); + int public = scope == CALL_PUBLIC || scope == CALL_PUBLIC_KW; - if (scope == CALL_PUBLIC) { - self = Qundef; + if (public) { + self = Qundef; } else { - self = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp)->self; + self = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp)->self; } if (argc == 0) { - rb_raise(rb_eArgError, "no method name given"); + rb_raise(rb_eArgError, "no method name given"); } - vid = *argv++; argc--; + vid = *argv; id = rb_check_id(&vid); if (!id) { - if (rb_method_basic_definition_p(CLASS_OF(recv), idMethodMissing)) { - VALUE exc = make_no_method_exception(rb_eNoMethodError, NULL, - recv, ++argc, --argv); - rb_exc_raise(exc); - } - id = rb_to_id(vid); + if (rb_method_basic_definition_p(CLASS_OF(recv), idMethodMissing)) { + VALUE exc = rb_make_no_method_exception(rb_eNoMethodError, 0, + recv, argc, argv, + !public); + rb_exc_raise(exc); + } + if (!SYMBOL_P(*argv)) { + VALUE *tmp_argv = current_vm_stack_arg(ec, argv); + vid = rb_str_intern(vid); + if (tmp_argv) { + tmp_argv[0] = vid; + } + else if (argc > 1) { + tmp_argv = ALLOCV_N(VALUE, vargv, argc); + tmp_argv[0] = vid; + MEMCPY(tmp_argv+1, argv+1, VALUE, argc-1); + argv = tmp_argv; + } + else { + argv = &vid; + } + } + id = idMethodMissing; + ec->method_missing_reason = MISSING_NOENTRY; + } + else { + argv++; argc--; } - PASS_PASSED_BLOCK_TH(th); - return rb_call0(recv, id, argc, argv, scope, self); + PASS_PASSED_BLOCK_HANDLER_EC(ec); + ret = rb_call0(ec, recv, id, argc, argv, scope, self); + ALLOCV_END(vargv); + return ret; +} + +static VALUE +send_internal_kw(int argc, const VALUE *argv, VALUE recv, call_type scope) +{ + if (rb_keyword_given_p()) { + switch (scope) { + case CALL_PUBLIC: + scope = CALL_PUBLIC_KW; + break; + case CALL_FCALL: + scope = CALL_FCALL_KW; + break; + default: + break; + } + } + return send_internal(argc, argv, recv, scope); } /* - * call-seq: - * foo.send(symbol [, args...]) -> obj - * foo.__send__(symbol [, args...]) -> obj + * call-seq: + * foo.send(symbol [, args...]) -> obj + * foo.__send__(symbol [, args...]) -> obj + * foo.send(string [, args...]) -> obj + * foo.__send__(string [, args...]) -> obj * * Invokes the method identified by _symbol_, passing it any - * arguments specified. You can use <code>__send__</code> if the name - * +send+ clashes with an existing method in _obj_. + * arguments specified. + * When the method is identified by a string, the string is converted + * to a symbol. + * + * BasicObject implements +__send__+, Kernel implements +send+. + * <code>__send__</code> is safer than +send+ + * when _obj_ has the same method name like <code>Socket</code>. + * See also <code>public_send</code>. * * class Klass * def hello(*args) @@ -901,64 +1325,91 @@ send_internal(int argc, const VALUE *argv, VALUE recv, call_type scope) VALUE rb_f_send(int argc, VALUE *argv, VALUE recv) { - return send_internal(argc, argv, recv, CALL_FCALL); + return send_internal_kw(argc, argv, recv, CALL_FCALL); } /* * call-seq: * obj.public_send(symbol [, args...]) -> obj + * obj.public_send(string [, args...]) -> obj * * Invokes the method identified by _symbol_, passing it any * arguments specified. Unlike send, public_send calls public * methods only. + * When the method is identified by a string, the string is converted + * to a symbol. * * 1.public_send(:puts, "hello") # causes NoMethodError */ -VALUE +static VALUE rb_f_public_send(int argc, VALUE *argv, VALUE recv) { - return send_internal(argc, argv, recv, CALL_PUBLIC); + return send_internal_kw(argc, argv, recv, CALL_PUBLIC); } /* yield */ static inline VALUE +rb_yield_0_kw(int argc, const VALUE * argv, int kw_splat) +{ + return vm_yield(GET_EC(), argc, argv, kw_splat); +} + +static inline VALUE rb_yield_0(int argc, const VALUE * argv) { - return vm_yield(GET_THREAD(), argc, argv); + return vm_yield(GET_EC(), argc, argv, RB_NO_KEYWORDS); +} + +VALUE +rb_yield_1(VALUE val) +{ + return rb_yield_0(1, &val); } VALUE rb_yield(VALUE val) { - if (val == Qundef) { - return rb_yield_0(0, 0); + if (UNDEF_P(val)) { + return rb_yield_0(0, NULL); } else { - return rb_yield_0(1, &val); + return rb_yield_0(1, &val); } } VALUE +rb_ec_yield(rb_execution_context_t *ec, VALUE val) +{ + if (UNDEF_P(val)) { + return vm_yield(ec, 0, NULL, RB_NO_KEYWORDS); + } + else { + return vm_yield(ec, 1, &val, RB_NO_KEYWORDS); + } +} + +#undef rb_yield_values +VALUE rb_yield_values(int n, ...) { if (n == 0) { - return rb_yield_0(0, 0); + return rb_yield_0(0, 0); } else { - int i; - VALUE *argv; - va_list args; - argv = ALLOCA_N(VALUE, n); - - va_init_list(args, n); - for (i=0; i<n; i++) { - argv[i] = va_arg(args, VALUE); - } - va_end(args); + int i; + VALUE *argv; + va_list args; + argv = ALLOCA_N(VALUE, n); + + va_start(args, n); + for (i=0; i<n; i++) { + argv[i] = va_arg(args, VALUE); + } + va_end(args); - return rb_yield_0(n, argv); + return rb_yield_0(n, argv); } } @@ -969,58 +1420,49 @@ rb_yield_values2(int argc, const VALUE *argv) } VALUE +rb_yield_values_kw(int argc, const VALUE *argv, int kw_splat) +{ + return rb_yield_0_kw(argc, argv, kw_splat); +} + +VALUE rb_yield_splat(VALUE values) { VALUE tmp = rb_check_array_type(values); - volatile VALUE v; + VALUE v; if (NIL_P(tmp)) { rb_raise(rb_eArgError, "not an array"); } - v = rb_yield_0(RARRAY_LENINT(tmp), RARRAY_PTR(tmp)); + v = rb_yield_0(RARRAY_LENINT(tmp), RARRAY_CONST_PTR(tmp)); RB_GC_GUARD(tmp); return v; } -static VALUE -loop_i(void) +VALUE +rb_yield_splat_kw(VALUE values, int kw_splat) { - for (;;) { - rb_yield_0(0, 0); + VALUE tmp = rb_check_array_type(values); + VALUE v; + if (NIL_P(tmp)) { + rb_raise(rb_eArgError, "not an array"); } - return Qnil; + v = rb_yield_0_kw(RARRAY_LENINT(tmp), RARRAY_CONST_PTR(tmp), kw_splat); + RB_GC_GUARD(tmp); + return v; } -static VALUE -rb_f_loop_size(VALUE self, VALUE args) +VALUE +rb_yield_force_blockarg(VALUE values) { - return DBL2NUM(INFINITY); + return vm_yield_force_blockarg(GET_EC(), values); } -/* - * call-seq: - * loop { block } - * loop -> an_enumerator - * - * Repeatedly executes the block. - * - * If no block is given, an enumerator is returned instead. - * - * loop do - * print "Input: " - * line = gets - * break if !line or line =~ /^qQ/ - * # ... - * end - * - * StopIteration raised in the block breaks the loop. - */ - -static VALUE -rb_f_loop(VALUE self) +VALUE +rb_yield_block(RB_BLOCK_CALL_FUNC_ARGLIST(val, arg)) { - RETURN_SIZED_ENUMERATOR(self, 0, 0, rb_f_loop_size); - rb_rescue2(loop_i, (VALUE)0, 0, 0, rb_eStopIteration, (VALUE)0); - return Qnil; /* dummy */ + return vm_yield_with_block(GET_EC(), argc, argv, + NIL_P(blockarg) ? VM_BLOCK_HANDLER_NONE : blockarg, + rb_keyword_given_p()); } #if VMDEBUG @@ -1028,83 +1470,75 @@ static const char * vm_frametype_name(const rb_control_frame_t *cfp); #endif -VALUE -rb_iterate(VALUE (* it_proc) (VALUE), VALUE data1, - VALUE (* bl_proc) (ANYARGS), VALUE data2) +static VALUE +rb_iterate0(VALUE (* it_proc) (VALUE), VALUE data1, + const struct vm_ifunc *const ifunc, + rb_execution_context_t *ec) { - int state; + enum ruby_tag_type state; volatile VALUE retval = Qnil; - NODE *node = NEW_IFUNC(bl_proc, data2); - rb_thread_t *th = GET_THREAD(); - rb_control_frame_t *volatile cfp = th->cfp; + rb_control_frame_t *const cfp = ec->cfp; - node->nd_aid = rb_frame_this_func(); - TH_PUSH_TAG(th); - state = TH_EXEC_TAG(); + EC_PUSH_TAG(ec); + state = EC_EXEC_TAG(); if (state == 0) { iter_retry: - { - rb_block_t *blockptr; - if (bl_proc) { - blockptr = RUBY_VM_GET_BLOCK_PTR_IN_CFP(th->cfp); - blockptr->iseq = (void *)node; - blockptr->proc = 0; - } - else { - blockptr = VM_CF_BLOCK_PTR(th->cfp); - } - th->passed_block = blockptr; - } - retval = (*it_proc) (data1); + { + VALUE block_handler; + + if (ifunc) { + struct rb_captured_block *captured = VM_CFP_TO_CAPTURED_BLOCK(cfp); + captured->code.ifunc = ifunc; + block_handler = VM_BH_FROM_IFUNC_BLOCK(captured); + } + else { + block_handler = VM_CF_BLOCK_HANDLER(cfp); + } + vm_passed_block_handler_set(ec, block_handler); + } + retval = (*it_proc) (data1); } - else { - VALUE err = th->errinfo; - if (state == TAG_BREAK) { - VALUE *escape_ep = GET_THROWOBJ_CATCH_POINT(err); - VALUE *cep = cfp->ep; - - if (cep == escape_ep) { - state = 0; - th->state = 0; - th->errinfo = Qnil; - retval = GET_THROWOBJ_VAL(err); - - rb_vm_rewind_cfp(th, cfp); - } - else{ - /* SDR(); printf("%p, %p\n", cdfp, escape_dfp); */ - } - } - else if (state == TAG_RETRY) { - VALUE *escape_ep = GET_THROWOBJ_CATCH_POINT(err); - VALUE *cep = cfp->ep; - - if (cep == escape_ep) { - rb_vm_rewind_cfp(th, cfp); - - state = 0; - th->state = 0; - th->errinfo = Qnil; - goto iter_retry; - } - } - } - TH_POP_TAG(); - - switch (state) { - case 0: - break; - default: - TH_JUMP_TAG(th, state); + else if (state == TAG_BREAK || state == TAG_RETRY) { + const struct vm_throw_data *const err = (struct vm_throw_data *)ec->errinfo; + const rb_control_frame_t *const escape_cfp = THROW_DATA_CATCH_FRAME(err); + + if (cfp == escape_cfp) { + rb_vm_rewind_cfp(ec, cfp); + + state = 0; + ec->tag->state = TAG_NONE; + ec->errinfo = Qnil; + + if (state == TAG_RETRY) goto iter_retry; + retval = THROW_DATA_VAL(err); + } + else if (0) { + SDR(); fprintf(stderr, "%p, %p\n", (void *)cfp, (void *)escape_cfp); + } + } + EC_POP_TAG(); + + if (state) { + EC_JUMP_TAG(ec, state); } return retval; } +static VALUE +rb_iterate_internal(VALUE (* it_proc)(VALUE), VALUE data1, + rb_block_call_func_t bl_proc, VALUE data2) +{ + return rb_iterate0(it_proc, data1, + bl_proc ? rb_vm_ifunc_proc_new(bl_proc, (void *)data2) : 0, + GET_EC()); +} + struct iter_method_arg { VALUE obj; ID mid; int argc; - VALUE *argv; + const VALUE *argv; + int kw_splat; }; static VALUE @@ -1113,12 +1547,47 @@ iterate_method(VALUE obj) const struct iter_method_arg * arg = (struct iter_method_arg *) obj; - return rb_call(arg->obj, arg->mid, arg->argc, arg->argv, CALL_FCALL); + return rb_call(arg->obj, arg->mid, arg->argc, arg->argv, arg->kw_splat ? CALL_FCALL_KW : CALL_FCALL); +} + +VALUE rb_block_call_kw(VALUE obj, ID mid, int argc, const VALUE * argv, rb_block_call_func_t bl_proc, VALUE data2, int kw_splat); + +VALUE +rb_block_call(VALUE obj, ID mid, int argc, const VALUE * argv, + rb_block_call_func_t bl_proc, VALUE data2) +{ + return rb_block_call_kw(obj, mid, argc, argv, bl_proc, data2, RB_NO_KEYWORDS); +} + +VALUE +rb_block_call_kw(VALUE obj, ID mid, int argc, const VALUE * argv, + rb_block_call_func_t bl_proc, VALUE data2, int kw_splat) +{ + struct iter_method_arg arg; + + arg.obj = obj; + arg.mid = mid; + arg.argc = argc; + arg.argv = argv; + arg.kw_splat = kw_splat; + return rb_iterate_internal(iterate_method, (VALUE)&arg, bl_proc, data2); } +/* + * A flexible variant of rb_block_call and rb_block_call_kw. + * This function accepts flags: + * + * RB_NO_KEYWORDS, RB_PASS_KEYWORDS, RB_PASS_CALLED_KEYWORDS: + * Works as the same as rb_block_call_kw. + * + * RB_BLOCK_NO_USE_PACKED_ARGS: + * The given block ("bl_proc") does not use "yielded_arg" of rb_block_call_func_t. + * Instead, the block accesses the yielded arguments via "argc" and "argv". + * This flag allows the called method to yield arguments without allocating an Array. + */ VALUE -rb_block_call(VALUE obj, ID mid, int argc, VALUE * argv, - VALUE (*bl_proc) (ANYARGS), VALUE data2) +rb_block_call2(VALUE obj, ID mid, int argc, const VALUE *argv, + rb_block_call_func_t bl_proc, VALUE data2, long flags) { struct iter_method_arg arg; @@ -1126,7 +1595,31 @@ rb_block_call(VALUE obj, ID mid, int argc, VALUE * argv, arg.mid = mid; arg.argc = argc; arg.argv = argv; - return rb_iterate(iterate_method, (VALUE)&arg, bl_proc, data2); + arg.kw_splat = flags & 1; + + struct vm_ifunc *ifunc = rb_vm_ifunc_proc_new(bl_proc, (void *)data2); + if (flags & RB_BLOCK_NO_USE_PACKED_ARGS) + ifunc->flags |= IFUNC_YIELD_OPTIMIZABLE; + + return rb_iterate0(iterate_method, (VALUE)&arg, ifunc, GET_EC()); +} + +VALUE +rb_lambda_call(VALUE obj, ID mid, int argc, const VALUE *argv, + rb_block_call_func_t bl_proc, int min_argc, int max_argc, + VALUE data2) +{ + struct iter_method_arg arg; + struct vm_ifunc *block; + + if (!bl_proc) rb_raise(rb_eArgError, "NULL lambda function"); + arg.obj = obj; + arg.mid = mid; + arg.argc = argc; + arg.argv = argv; + arg.kw_splat = 0; + block = rb_vm_ifunc_new(bl_proc, (void *)data2, min_argc, max_argc); + return rb_iterate0(iterate_method, (VALUE)&arg, block, GET_EC()); } static VALUE @@ -1139,8 +1632,8 @@ iterate_check_method(VALUE obj) } VALUE -rb_check_block_call(VALUE obj, ID mid, int argc, VALUE * argv, - VALUE (*bl_proc) (ANYARGS), VALUE data2) +rb_check_block_call(VALUE obj, ID mid, int argc, const VALUE *argv, + rb_block_call_func_t bl_proc, VALUE data2) { struct iter_method_arg arg; @@ -1148,7 +1641,8 @@ rb_check_block_call(VALUE obj, ID mid, int argc, VALUE * argv, arg.mid = mid; arg.argc = argc; arg.argv = argv; - return rb_iterate(iterate_check_method, (VALUE)&arg, bl_proc, data2); + arg.kw_splat = 0; + return rb_iterate_internal(iterate_check_method, (VALUE)&arg, bl_proc, data2); } VALUE @@ -1157,138 +1651,383 @@ rb_each(VALUE obj) return rb_call(obj, idEach, 0, 0, CALL_FCALL); } +static VALUE eval_default_path = Qfalse; + +#define EVAL_LOCATION_MARK "eval at " +#define EVAL_LOCATION_MARK_LEN (int)rb_strlen_lit(EVAL_LOCATION_MARK) + static VALUE -eval_string_with_cref(VALUE self, VALUE src, VALUE scope, NODE *cref, volatile VALUE file, volatile int line) +get_eval_default_path(void) { - int state; - VALUE result = Qundef; - VALUE envval; - rb_thread_t *th = GET_THREAD(); - rb_env_t *env = NULL; - rb_block_t block, *base_block; - volatile int parse_in_eval; - volatile int mild_compile_error; - - if (file == 0) { - file = rb_sourcefilename(); - line = rb_sourceline(); - } - - parse_in_eval = th->parse_in_eval; - mild_compile_error = th->mild_compile_error; - TH_PUSH_TAG(th); - if ((state = TH_EXEC_TAG()) == 0) { - rb_binding_t *bind = 0; - rb_iseq_t *iseq; - volatile VALUE iseqval; - VALUE absolute_path = Qnil; - VALUE fname; - - if (file != Qundef) { - absolute_path = file; - } - - if (!NIL_P(scope)) { - if (rb_obj_is_kind_of(scope, rb_cBinding)) { - GetBindingPtr(scope, bind); - envval = bind->env; - if (NIL_P(absolute_path) && !NIL_P(bind->path)) { - file = bind->path; - line = bind->first_lineno; - absolute_path = rb_current_realfilepath(); - } - } - else { - rb_raise(rb_eTypeError, - "wrong argument type %s (expected Binding)", - rb_obj_classname(scope)); - } - GetEnvPtr(envval, env); - base_block = &env->block; - } - else { - rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(th, th->cfp); - - if (cfp != 0) { - block = *RUBY_VM_GET_BLOCK_PTR_IN_CFP(cfp); - base_block = █ - base_block->self = self; - base_block->iseq = cfp->iseq; /* TODO */ - } - else { - rb_raise(rb_eRuntimeError, "Can't eval on top of Fiber or Thread"); - } - } - - if ((fname = file) == Qundef) { - fname = rb_usascii_str_new_cstr("(eval)"); - } - - /* make eval iseq */ - th->parse_in_eval++; - th->mild_compile_error++; - iseqval = rb_iseq_compile_with_option(src, fname, absolute_path, INT2FIX(line), base_block, Qnil); - th->mild_compile_error--; - th->parse_in_eval--; - - vm_set_eval_stack(th, iseqval, cref, base_block); - th->cfp->klass = CLASS_OF(base_block->self); - - if (0) { /* for debug */ - VALUE disasm = rb_iseq_disasm(iseqval); - printf("%s\n", StringValuePtr(disasm)); - } - - /* save new env */ - GetISeqPtr(iseqval, iseq); - if (bind && iseq->local_table_size > 0) { - bind->env = rb_vm_make_env_object(th, th->cfp); - } - - /* kick */ - CHECK_VM_STACK_OVERFLOW(th->cfp, iseq->stack_max); - result = vm_exec(th); - } - TH_POP_TAG(); - th->mild_compile_error = mild_compile_error; - th->parse_in_eval = parse_in_eval; + int location_lineno; + VALUE location_path = rb_source_location(&location_lineno); + if (!NIL_P(location_path)) { + return rb_fstring(rb_sprintf("("EVAL_LOCATION_MARK"%"PRIsVALUE":%d)", + location_path, location_lineno)); + } - if (state) { - if (state == TAG_RAISE) { - VALUE errinfo = th->errinfo; - if (file == Qundef) { - VALUE mesg, errat, bt2; - ID id_mesg; - - CONST_ID(id_mesg, "mesg"); - errat = rb_get_backtrace(errinfo); - mesg = rb_attr_get(errinfo, id_mesg); - if (!NIL_P(errat) && RB_TYPE_P(errat, T_ARRAY) && - (bt2 = vm_backtrace_str_ary(th, 0, 0), RARRAY_LEN(bt2) > 0)) { - if (!NIL_P(mesg) && RB_TYPE_P(mesg, T_STRING) && !RSTRING_LEN(mesg)) { - if (OBJ_FROZEN(mesg)) { - VALUE m = rb_str_cat(rb_str_dup(RARRAY_PTR(errat)[0]), ": ", 2); - rb_ivar_set(errinfo, id_mesg, rb_str_append(m, mesg)); - } - else { - rb_str_update(mesg, 0, 0, rb_str_new2(": ")); - rb_str_update(mesg, 0, 0, RARRAY_PTR(errat)[0]); - } - } - RARRAY_PTR(errat)[0] = RARRAY_PTR(bt2)[0]; - } - } - rb_exc_raise(errinfo); - } - JUMP_TAG(state); + if (!eval_default_path) { + eval_default_path = rb_fstring_lit("(eval)"); + rb_vm_register_global_object(eval_default_path); } - return result; + return eval_default_path; +} + +static inline int +compute_isolated_depth_from_ep(const VALUE *ep) +{ + int depth = 1; + while (1) { + if (VM_ENV_FLAGS(ep, VM_ENV_FLAG_ISOLATED)) return depth; + if (VM_ENV_LOCAL_P(ep)) return 0; + ep = VM_ENV_PREV_EP(ep); + depth++; + } +} + +static inline int +compute_isolated_depth_from_block(const struct rb_block *blk) +{ + return compute_isolated_depth_from_ep(vm_block_ep(blk)); +} + +static const rb_iseq_t * +pm_eval_make_iseq(VALUE src, VALUE fname, int line, + const struct rb_block *base_block) +{ + const rb_iseq_t *const parent = vm_block_iseq(base_block); + const rb_iseq_t *iseq = parent; + VALUE name = rb_fstring_lit("<compiled>"); + + int coverage_enabled = ((rb_get_coverage_mode() & COVERAGE_TARGET_EVAL) != 0) ? 1 : 0; + int isolated_depth = compute_isolated_depth_from_block(base_block); + + if (!fname) { + fname = rb_source_location(&line); + } + + if (!UNDEF_P(fname)) { + if (!NIL_P(fname)) fname = rb_fstring(fname); + } + else { + fname = get_eval_default_path(); + coverage_enabled = 0; + } + + pm_parse_result_t result = { 0 }; + pm_options_line_set(&result.options, line); + result.node.coverage_enabled = coverage_enabled; + + // Cout scopes, one for each parent iseq, plus one for our local scope + int scopes_count = 0; + do { + scopes_count++; + } while ((iseq = ISEQ_BODY(iseq)->parent_iseq)); + pm_options_scopes_init(&result.options, scopes_count + 1); + + // Walk over the scope tree, adding known locals at the correct depths. The + // scope array should be deepest -> shallowest. so lower indexes in the + // scopes array refer to root nodes on the tree, and higher indexes are the + // leaf nodes. + iseq = parent; + rb_encoding *encoding = rb_enc_get(src); + +#define FORWARDING_POSITIONALS_CHR '*' +#define FORWARDING_POSITIONALS_STR "*" +#define FORWARDING_KEYWORDS_CHR ':' +#define FORWARDING_KEYWORDS_STR ":" +#define FORWARDING_BLOCK_CHR '&' +#define FORWARDING_BLOCK_STR "&" +#define FORWARDING_ALL_CHR '.' +#define FORWARDING_ALL_STR "." + + for (int scopes_index = 0; scopes_index < scopes_count; scopes_index++) { + VALUE iseq_value = (VALUE)iseq; + int locals_count = ISEQ_BODY(iseq)->local_table_size; + + pm_options_scope_t *options_scope = &result.options.scopes[scopes_count - scopes_index - 1]; + pm_options_scope_init(options_scope, locals_count); + + uint8_t forwarding = PM_OPTIONS_SCOPE_FORWARDING_NONE; + + for (int local_index = 0; local_index < locals_count; local_index++) { + pm_string_t *scope_local = &options_scope->locals[local_index]; + ID local = ISEQ_BODY(iseq)->local_table[local_index]; + + if (rb_is_local_id(local)) { + VALUE name_obj = rb_id2str(local); + const char *name = RSTRING_PTR(name_obj); + size_t length = strlen(name); + + // Explicitly skip numbered parameters. These should not be sent + // into the eval. + if (length == 2 && name[0] == '_' && name[1] >= '1' && name[1] <= '9') { + continue; + } + + // Check here if this local can be represented validly in the + // encoding of the source string. If it _cannot_, then it should + // not be added to the constant pool as it would not be able to + // be referenced anyway. + if (rb_enc_str_coderange_scan(name_obj, encoding) == ENC_CODERANGE_BROKEN) { + continue; + } + + /* We need to duplicate the string because the Ruby string may + * be embedded so compaction could move the string and the pointer + * will change. */ + char *name_dup = xmalloc(length + 1); + strlcpy(name_dup, name, length + 1); + + RB_GC_GUARD(name_obj); + + pm_string_owned_init(scope_local, (uint8_t *) name_dup, length); + } + else if (local == idMULT) { + forwarding |= PM_OPTIONS_SCOPE_FORWARDING_POSITIONALS; + pm_string_constant_init(scope_local, FORWARDING_POSITIONALS_STR, 1); + } + else if (local == idPow) { + forwarding |= PM_OPTIONS_SCOPE_FORWARDING_KEYWORDS; + pm_string_constant_init(scope_local, FORWARDING_KEYWORDS_STR, 1); + } + else if (local == idAnd) { + forwarding |= PM_OPTIONS_SCOPE_FORWARDING_BLOCK; + pm_string_constant_init(scope_local, FORWARDING_BLOCK_STR, 1); + } + else if (local == idDot3) { + forwarding |= PM_OPTIONS_SCOPE_FORWARDING_ALL; + pm_string_constant_init(scope_local, FORWARDING_ALL_STR, 1); + } + } + + pm_options_scope_forwarding_set(options_scope, forwarding); + iseq = ISEQ_BODY(iseq)->parent_iseq; + + /* We need to GC guard the iseq because the code above malloc memory + * which could trigger a GC. Since we only use ISEQ_BODY, the compiler + * may optimize out the iseq local variable so we need to GC guard it. */ + RB_GC_GUARD(iseq_value); + } + + // Add our empty local scope at the very end of the array for our eval + // scope's locals. + pm_options_scope_init(&result.options.scopes[scopes_count], 0); + + VALUE script_lines; + VALUE error = pm_parse_string(&result, src, fname, ruby_vm_keep_script_lines ? &script_lines : NULL); + + // If the parse failed, clean up and raise. + if (error != Qnil) { + pm_parse_result_free(&result); + rb_exc_raise(error); + } + + // Create one scope node for each scope passed in, initialize the local + // lookup table with all the local variable information attached to the + // scope used by the parser. + pm_scope_node_t *node = &result.node; + iseq = parent; + + for (int scopes_index = 0; scopes_index < scopes_count; scopes_index++) { + pm_scope_node_t *parent_scope = ruby_xcalloc(1, sizeof(pm_scope_node_t)); + RUBY_ASSERT(parent_scope != NULL); + + pm_options_scope_t *options_scope = &result.options.scopes[scopes_count - scopes_index - 1]; + parent_scope->coverage_enabled = coverage_enabled; + parent_scope->parser = &result.parser; + parent_scope->index_lookup_table = st_init_numtable(); + + int locals_count = ISEQ_BODY(iseq)->local_table_size; + parent_scope->local_table_for_iseq_size = locals_count; + pm_constant_id_list_init(&parent_scope->locals); + + for (int local_index = 0; local_index < locals_count; local_index++) { + const pm_string_t *scope_local = &options_scope->locals[local_index]; + pm_constant_id_t constant_id = 0; + + const uint8_t *source = pm_string_source(scope_local); + size_t length = pm_string_length(scope_local); + + if (length > 0) { + if (length == 1) { + switch (*source) { + case FORWARDING_POSITIONALS_CHR: + constant_id = PM_CONSTANT_MULT; + break; + case FORWARDING_KEYWORDS_CHR: + constant_id = PM_CONSTANT_POW; + break; + case FORWARDING_BLOCK_CHR: + constant_id = PM_CONSTANT_AND; + break; + case FORWARDING_ALL_CHR: + constant_id = PM_CONSTANT_DOT3; + break; + default: + constant_id = pm_constant_pool_insert_constant(&result.parser.constant_pool, source, length); + break; + } + } + else { + constant_id = pm_constant_pool_insert_constant(&result.parser.constant_pool, source, length); + } + + st_insert(parent_scope->index_lookup_table, (st_data_t) constant_id, (st_data_t) local_index); + } + + pm_constant_id_list_append(&parent_scope->locals, constant_id); + } + + node->previous = parent_scope; + node = parent_scope; + iseq = ISEQ_BODY(iseq)->parent_iseq; + } + +#undef FORWARDING_POSITIONALS_CHR +#undef FORWARDING_POSITIONALS_STR +#undef FORWARDING_KEYWORDS_CHR +#undef FORWARDING_KEYWORDS_STR +#undef FORWARDING_BLOCK_CHR +#undef FORWARDING_BLOCK_STR +#undef FORWARDING_ALL_CHR +#undef FORWARDING_ALL_STR + + int error_state; + iseq = pm_iseq_new_eval(&result.node, name, fname, Qnil, line, parent, isolated_depth, &error_state); + + pm_scope_node_t *prev = result.node.previous; + while (prev) { + pm_scope_node_t *next = prev->previous; + pm_constant_id_list_free(&prev->locals); + pm_scope_node_destroy(prev); + ruby_xfree(prev); + prev = next; + } + + pm_parse_result_free(&result); + + // If there was an error, raise it after memory has been cleaned up + if (error_state) { + RUBY_ASSERT(iseq == NULL); + rb_jump_tag(error_state); + } + + rb_exec_event_hook_script_compiled(GET_EC(), iseq, src); + + return iseq; +} + +static const rb_iseq_t * +eval_make_iseq(VALUE src, VALUE fname, int line, + const struct rb_block *base_block) +{ + if (rb_ruby_prism_p()) { + return pm_eval_make_iseq(src, fname, line, base_block); + } + const VALUE parser = rb_parser_new(); + const rb_iseq_t *const parent = vm_block_iseq(base_block); + rb_iseq_t *iseq = NULL; + VALUE ast_value; + rb_ast_t *ast; + + int coverage_enabled = (rb_get_coverage_mode() & COVERAGE_TARGET_EVAL) != 0; + int isolated_depth = compute_isolated_depth_from_block(base_block); + + if (!fname) { + fname = rb_source_location(&line); + } + + if (!UNDEF_P(fname)) { + if (!NIL_P(fname)) fname = rb_fstring(fname); + } + else { + fname = get_eval_default_path(); + coverage_enabled = FALSE; + } + + rb_parser_set_context(parser, parent, FALSE); + if (ruby_vm_keep_script_lines) rb_parser_set_script_lines(parser); + ast_value = rb_parser_compile_string_path(parser, fname, src, line); + + ast = rb_ruby_ast_data_get(ast_value); + + if (ast->body.root) { + ast->body.coverage_enabled = coverage_enabled; + iseq = rb_iseq_new_eval(ast_value, + ISEQ_BODY(parent)->location.label, + fname, Qnil, line, + parent, isolated_depth); + } + rb_ast_dispose(ast); + + if (iseq != NULL) { + if (0 && iseq) { /* for debug */ + VALUE disasm = rb_iseq_disasm(iseq); + printf("%s\n", StringValuePtr(disasm)); + } + + rb_exec_event_hook_script_compiled(GET_EC(), iseq, src); + } + + return iseq; } static VALUE -eval_string(VALUE self, VALUE src, VALUE scope, VALUE file, int line) +eval_string_with_cref(VALUE self, VALUE src, rb_cref_t *cref, VALUE file, int line) { - return eval_string_with_cref(self, src, scope, 0, file, line); + rb_execution_context_t *ec = GET_EC(); + struct rb_block block; + const rb_iseq_t *iseq; + rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp); + if (!cfp) { + rb_raise(rb_eRuntimeError, "Can't eval on top of Fiber or Thread"); + } + + block.as.captured = *VM_CFP_TO_CAPTURED_BLOCK(cfp); + block.as.captured.self = self; + block.as.captured.code.iseq = cfp->iseq; + block.type = block_type_iseq; + + // EP is not escaped to the heap here, but captured and reused by another frame. + // ZJIT's locals are incompatible with it unlike YJIT's, so invalidate the ISEQ for ZJIT. + rb_zjit_invalidate_no_ep_escape(cfp->iseq); + + iseq = eval_make_iseq(src, file, line, &block); + if (!iseq) { + rb_exc_raise(ec->errinfo); + } + + /* TODO: what the code checking? */ + if (!cref && block.as.captured.code.val) { + rb_cref_t *orig_cref = vm_get_cref(vm_block_ep(&block)); + cref = vm_cref_dup(orig_cref); + } + vm_set_eval_stack(ec, iseq, cref, &block); + + /* kick */ + return vm_exec(ec); +} + +static VALUE +eval_string_with_scope(VALUE scope, VALUE src, VALUE file, int line) +{ + rb_execution_context_t *ec = GET_EC(); + rb_binding_t *bind = Check_TypedStruct(scope, &ruby_binding_data_type); + const rb_iseq_t *iseq = eval_make_iseq(src, file, line, &bind->block); + if (!iseq) { + rb_exc_raise(ec->errinfo); + } + + vm_set_eval_stack(ec, iseq, NULL, &bind->block); + + /* save new env */ + if (ISEQ_BODY(iseq)->local_table_size > 0) { + vm_bind_update_env(scope, bind, vm_make_env_object(ec, ec->cfp)); + } + + /* kick */ + return vm_exec(ec); } /* @@ -1296,10 +2035,10 @@ eval_string(VALUE self, VALUE src, VALUE scope, VALUE file, int line) * eval(string [, binding [, filename [,lineno]]]) -> obj * * Evaluates the Ruby expression(s) in <em>string</em>. If - * <em>binding</em> is given, which must be a <code>Binding</code> - * object, the evaluation is performed in its context. If the - * optional <em>filename</em> and <em>lineno</em> parameters are - * present, they will be used when reporting syntax errors. + * <em>binding</em> is given, which must be a Binding object, the + * evaluation is performed in its context. If the optional + * <em>filename</em> and <em>lineno</em> parameters are present, they + * will be used when reporting syntax errors. * * def get_binding(str) * return binding @@ -1310,33 +2049,28 @@ eval_string(VALUE self, VALUE src, VALUE scope, VALUE file, int line) */ VALUE -rb_f_eval(int argc, VALUE *argv, VALUE self) +rb_f_eval(int argc, const VALUE *argv, VALUE self) { VALUE src, scope, vfile, vline; VALUE file = Qundef; int line = 1; rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline); - if (rb_safe_level() >= 4) { - StringValue(src); - if (!NIL_P(scope) && !OBJ_TAINTED(scope)) { - rb_raise(rb_eSecurityError, - "Insecure: can't modify trusted binding"); - } - } - else { - SafeStringValue(src); - } + StringValue(src); if (argc >= 3) { - StringValue(vfile); + StringValue(vfile); } if (argc >= 4) { - line = NUM2INT(vline); + line = NUM2INT(vline); } if (!NIL_P(vfile)) - file = vfile; - return eval_string(self, src, scope, file, line); + file = vfile; + + if (NIL_P(scope)) + return eval_string_with_cref(self, src, NULL, file, line); + else + return eval_string_with_scope(scope, src, file, line); } /** @note This function name is not stable. */ @@ -1344,266 +2078,266 @@ VALUE ruby_eval_string_from_file(const char *str, const char *filename) { VALUE file = filename ? rb_str_new_cstr(filename) : 0; - return eval_string(rb_vm_top_self(), rb_str_new2(str), Qnil, file, 1); + rb_execution_context_t *ec = GET_EC(); + rb_control_frame_t *cfp = ec ? rb_vm_get_ruby_level_next_cfp(ec, ec->cfp) : NULL; + VALUE self = cfp ? cfp->self : rb_vm_top_self(); + return eval_string_with_cref(self, rb_str_new2(str), NULL, file, 1); } -struct eval_string_from_file_arg { - VALUE str; - VALUE filename; -}; - -static VALUE -eval_string_from_file_helper(void *data) +VALUE +rb_eval_string(const char *str) { - const struct eval_string_from_file_arg *const arg = (struct eval_string_from_file_arg*)data; - return eval_string(rb_vm_top_self(), arg->str, Qnil, arg->filename, 1); + return ruby_eval_string_from_file(str, "eval"); } -VALUE -ruby_eval_string_from_file_protect(const char *str, const char *filename, int *state) +static VALUE +eval_string_protect(VALUE str) { - struct eval_string_from_file_arg arg; - arg.str = rb_str_new_cstr(str); - arg.filename = filename ? rb_str_new_cstr(filename) : 0; - return rb_protect((VALUE (*)(VALUE))eval_string_from_file_helper, (VALUE)&arg, state); + return rb_eval_string((char *)str); } -/** - * Evaluates the given string in an isolated binding. - * - * Here "isolated" means the binding does not inherit any other binding. This - * behaves same as the binding for required libraries. - * - * __FILE__ will be "(eval)", and __LINE__ starts from 1 in the evaluation. - * - * @param str Ruby code to evaluate. - * @return The evaluated result. - * @throw Exception Raises an exception on error. - */ VALUE -rb_eval_string(const char *str) +rb_eval_string_protect(const char *str, int *pstate) { - return ruby_eval_string_from_file(str, "eval"); + return rb_protect(eval_string_protect, (VALUE)str, pstate); } -/** - * Evaluates the given string in an isolated binding. - * - * __FILE__ will be "(eval)", and __LINE__ starts from 1 in the evaluation. - * - * @sa rb_eval_string - * @param str Ruby code to evaluate. - * @param state Being set to zero if succeeded. Nonzero if an error occurred. - * @return The evaluated result if succeeded, an undefined value if otherwise. - */ -VALUE -rb_eval_string_protect(const char *str, int *state) +struct eval_string_wrap_arg { + VALUE top_self; + VALUE klass; + const char *str; +}; + +static VALUE +eval_string_wrap_protect(VALUE data) { - return rb_protect((VALUE (*)(VALUE))rb_eval_string, (VALUE)str, state); + const struct eval_string_wrap_arg *const arg = (struct eval_string_wrap_arg*)data; + rb_cref_t *cref = rb_vm_cref_new_toplevel(); + cref->klass_or_self = arg->klass; + return eval_string_with_cref(arg->top_self, rb_str_new_cstr(arg->str), cref, rb_str_new_cstr("eval"), 1); } -/** - * Evaluates the given string under a module binding in an isolated binding. - * This is same as the binding for required libraries on "require('foo', true)". - * - * __FILE__ will be "(eval)", and __LINE__ starts from 1 in the evaluation. - * - * @sa rb_eval_string - * @param str Ruby code to evaluate. - * @param state Being set to zero if succeeded. Nonzero if an error occurred. - * @return The evaluated result if succeeded, an undefined value if otherwise. - */ VALUE -rb_eval_string_wrap(const char *str, int *state) +rb_eval_string_wrap(const char *str, int *pstate) { - int status; + int state; rb_thread_t *th = GET_THREAD(); VALUE self = th->top_self; VALUE wrapper = th->top_wrapper; VALUE val; + struct eval_string_wrap_arg data; th->top_wrapper = rb_module_new(); th->top_self = rb_obj_clone(rb_vm_top_self()); rb_extend_object(th->top_self, th->top_wrapper); - val = rb_eval_string_protect(str, &status); + data.top_self = th->top_self; + data.klass = th->top_wrapper; + data.str = str; + + val = rb_protect(eval_string_wrap_protect, (VALUE)&data, &state); th->top_self = self; th->top_wrapper = wrapper; - if (state) { - *state = status; + if (pstate) { + *pstate = state; } - else if (status) { - JUMP_TAG(status); + else if (state != TAG_NONE) { + EC_JUMP_TAG(th->ec, state); } return val; } VALUE -rb_eval_cmd(VALUE cmd, VALUE arg, int level) +rb_eval_cmd_kw(VALUE cmd, VALUE arg, int kw_splat) { - int state; - VALUE val = Qnil; /* OK */ - volatile int safe = rb_safe_level(); - - if (OBJ_TAINTED(cmd)) { - level = 4; - } - - if (!RB_TYPE_P(cmd, T_STRING)) { - PUSH_TAG(); - rb_set_safe_level_force(level); - if ((state = EXEC_TAG()) == 0) { - val = rb_funcall2(cmd, rb_intern("call"), RARRAY_LENINT(arg), - RARRAY_PTR(arg)); - } - POP_TAG(); - - rb_set_safe_level_force(safe); + Check_Type(arg, T_ARRAY); + int argc = RARRAY_LENINT(arg); + const VALUE *argv = RARRAY_CONST_PTR(arg); + VALUE val = rb_eval_cmd_call_kw(cmd, argc, argv, kw_splat); + RB_GC_GUARD(arg); + return val; +} - if (state) - JUMP_TAG(state); - return val; - } +VALUE +rb_eval_cmd_call_kw(VALUE cmd, int argc, const VALUE *argv, int kw_splat) +{ + enum ruby_tag_type state; + volatile VALUE val = Qnil; /* OK */ + rb_execution_context_t * volatile ec = GET_EC(); - PUSH_TAG(); - if ((state = EXEC_TAG()) == 0) { - val = eval_string(rb_vm_top_self(), cmd, Qnil, 0, 0); + EC_PUSH_TAG(ec); + if ((state = EC_EXEC_TAG()) == TAG_NONE) { + if (!RB_TYPE_P(cmd, T_STRING)) { + val = rb_funcallv_kw(cmd, idCall, argc, argv, kw_splat); + } + else { + val = eval_string_with_cref(rb_vm_top_self(), cmd, NULL, 0, 0); + } } - POP_TAG(); + EC_POP_TAG(); - rb_set_safe_level_force(safe); - if (state) JUMP_TAG(state); + if (state) EC_JUMP_TAG(ec, state); return val; } /* block eval under the class/module context */ static VALUE -yield_under(VALUE under, VALUE self, VALUE values) -{ - rb_thread_t *th = GET_THREAD(); - rb_block_t block, *blockptr; - NODE *cref; +yield_under(VALUE self, int singleton, int argc, const VALUE *argv, int kw_splat) +{ + rb_execution_context_t *ec = GET_EC(); + rb_control_frame_t *cfp = ec->cfp; + VALUE block_handler = VM_CF_BLOCK_HANDLER(cfp); + VALUE new_block_handler = 0; + const struct rb_captured_block *captured = NULL; + struct rb_captured_block new_captured; + const VALUE *ep = NULL; + rb_cref_t *cref; + int is_lambda = FALSE; + + if (block_handler != VM_BLOCK_HANDLER_NONE) { + again: + switch (vm_block_handler_type(block_handler)) { + case block_handler_type_iseq: + captured = VM_BH_TO_CAPT_BLOCK(block_handler); + new_captured = *captured; + new_block_handler = VM_BH_FROM_ISEQ_BLOCK(&new_captured); + break; + case block_handler_type_ifunc: + captured = VM_BH_TO_CAPT_BLOCK(block_handler); + new_captured = *captured; + new_block_handler = VM_BH_FROM_IFUNC_BLOCK(&new_captured); + break; + case block_handler_type_proc: + is_lambda = rb_proc_lambda_p(block_handler) != Qfalse; + block_handler = vm_proc_to_block_handler(VM_BH_TO_PROC(block_handler)); + goto again; + case block_handler_type_symbol: + return rb_sym_proc_call(SYM2ID(VM_BH_TO_SYMBOL(block_handler)), + argc, argv, kw_splat, + VM_BLOCK_HANDLER_NONE); + } - if ((blockptr = VM_CF_BLOCK_PTR(th->cfp)) != 0) { - block = *blockptr; - block.self = self; - VM_CF_LEP(th->cfp)[0] = VM_ENVVAL_BLOCK_PTR(&block); - } - cref = vm_cref_push(th, under, NOEX_PUBLIC, blockptr); - cref->flags |= NODE_FL_CREF_PUSHED_BY_EVAL; + new_captured.self = self; + ep = captured->ep; - if (values == Qundef) { - return vm_yield_with_cref(th, 1, &self, cref); - } - else { - return vm_yield_with_cref(th, RARRAY_LENINT(values), RARRAY_PTR(values), cref); + VM_FORCE_WRITE_SPECIAL_CONST(&VM_CF_LEP(ec->cfp)[VM_ENV_DATA_INDEX_SPECVAL], new_block_handler); } + + VM_ASSERT(singleton || RB_TYPE_P(self, T_MODULE) || RB_TYPE_P(self, T_CLASS)); + cref = vm_cref_push(ec, self, ep, TRUE, singleton); + + return vm_yield_with_cref(ec, argc, argv, kw_splat, cref, is_lambda); } VALUE rb_yield_refine_block(VALUE refinement, VALUE refinements) { - rb_thread_t *th = GET_THREAD(); - rb_block_t block, *blockptr; - NODE *cref; + rb_execution_context_t *ec = GET_EC(); + VALUE block_handler = VM_CF_BLOCK_HANDLER(ec->cfp); - if ((blockptr = VM_CF_BLOCK_PTR(th->cfp)) != 0) { - block = *blockptr; - block.self = refinement; - VM_CF_LEP(th->cfp)[0] = VM_ENVVAL_BLOCK_PTR(&block); + if (vm_block_handler_type(block_handler) != block_handler_type_iseq) { + rb_bug("rb_yield_refine_block: an iseq block is required"); + } + else { + const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(block_handler); + struct rb_captured_block new_captured = *captured; + const VALUE *const argv = &new_captured.self; /* dummy to suppress nonnull warning from gcc */ + VALUE new_block_handler = VM_BH_FROM_ISEQ_BLOCK(&new_captured); + const VALUE *ep = captured->ep; + rb_cref_t *cref = vm_cref_push(ec, refinement, ep, TRUE, FALSE); + CREF_REFINEMENTS_SET(cref, refinements); + VM_FORCE_WRITE_SPECIAL_CONST(&VM_CF_LEP(ec->cfp)[VM_ENV_DATA_INDEX_SPECVAL], new_block_handler); + new_captured.self = refinement; + return vm_yield_with_cref(ec, 0, argv, RB_NO_KEYWORDS, cref, FALSE); } - cref = vm_cref_push(th, refinement, NOEX_PUBLIC, blockptr); - cref->flags |= NODE_FL_CREF_PUSHED_BY_EVAL; - cref->nd_refinements = refinements; - - return vm_yield_with_cref(th, 0, NULL, cref); } /* string eval under the class/module context */ static VALUE -eval_under(VALUE under, VALUE self, VALUE src, VALUE file, int line) +eval_under(VALUE self, int singleton, VALUE src, VALUE file, int line) { - NODE *cref = vm_cref_push(GET_THREAD(), under, NOEX_PUBLIC, NULL); + rb_cref_t *cref = vm_cref_push(GET_EC(), self, NULL, FALSE, singleton); + StringValue(src); - if (SPECIAL_CONST_P(self) && !NIL_P(under)) { - cref->flags |= NODE_FL_CREF_PUSHED_BY_EVAL; - } - if (rb_safe_level() >= 4) { - StringValue(src); - } - else { - SafeStringValue(src); - } - - return eval_string_with_cref(self, src, Qnil, cref, file, line); + return eval_string_with_cref(self, src, cref, file, line); } static VALUE -specific_eval(int argc, VALUE *argv, VALUE klass, VALUE self) +specific_eval(int argc, const VALUE *argv, VALUE self, int singleton, int kw_splat) { if (rb_block_given_p()) { - rb_check_arity(argc, 0, 0); - return yield_under(klass, self, Qundef); + rb_check_arity(argc, 0, 0); + return yield_under(self, singleton, 1, &self, kw_splat); } else { - VALUE file = Qundef; - int line = 1; - - rb_check_arity(argc, 1, 3); - if (rb_safe_level() >= 4) { - StringValue(argv[0]); - } - else { - SafeStringValue(argv[0]); - } - if (argc > 2) - line = NUM2INT(argv[2]); - if (argc > 1) { - file = argv[1]; - if (!NIL_P(file)) StringValue(file); - } - return eval_under(klass, self, argv[0], file, line); + VALUE file = Qnil; + int line = 1; + VALUE code; + + rb_check_arity(argc, 1, 3); + code = argv[0]; + StringValue(code); + if (argc > 2) + line = NUM2INT(argv[2]); + if (argc > 1) { + file = argv[1]; + if (!NIL_P(file)) StringValue(file); + } + + if (NIL_P(file)) { + file = get_eval_default_path(); + } + + return eval_under(self, singleton, code, file, line); } } /* * call-seq: * obj.instance_eval(string [, filename [, lineno]] ) -> obj - * obj.instance_eval {| | block } -> obj + * obj.instance_eval {|obj| block } -> obj * * Evaluates a string containing Ruby source code, or the given block, * within the context of the receiver (_obj_). In order to set the * context, the variable +self+ is set to _obj_ while * the code is executing, giving the code access to _obj_'s - * instance variables. In the version of <code>instance_eval</code> - * that takes a +String+, the optional second and third - * parameters supply a filename and starting line number that are used - * when reporting compilation errors. + * instance variables and private methods. + * + * When <code>instance_eval</code> is given a block, _obj_ is also + * passed in as the block's only argument. + * + * When <code>instance_eval</code> is given a +String+, the optional + * second and third parameters supply a filename and starting line number + * that are used when reporting compilation errors. * * class KlassWithSecret * def initialize * @secret = 99 * end + * private + * def the_secret + * "Ssssh! The secret is #{@secret}." + * end * end * k = KlassWithSecret.new - * k.instance_eval { @secret } #=> 99 + * k.instance_eval { @secret } #=> 99 + * k.instance_eval { the_secret } #=> "Ssssh! The secret is 99." + * k.instance_eval {|obj| obj == self } #=> true */ -VALUE -rb_obj_instance_eval(int argc, VALUE *argv, VALUE self) +static VALUE +rb_obj_instance_eval_internal(int argc, const VALUE *argv, VALUE self) { - VALUE klass; + return specific_eval(argc, argv, self, TRUE, RB_PASS_CALLED_KEYWORDS); +} - if (SPECIAL_CONST_P(self)) { - klass = rb_special_singleton_class(self); - } - else { - klass = rb_singleton_class(self); - } - return specific_eval(argc, argv, klass, self); +VALUE +rb_obj_instance_eval(int argc, const VALUE *argv, VALUE self) +{ + return specific_eval(argc, argv, self, TRUE, RB_NO_KEYWORDS); } /* @@ -1624,24 +2358,24 @@ rb_obj_instance_eval(int argc, VALUE *argv, VALUE self) * k.instance_exec(5) {|x| @secret+x } #=> 104 */ -VALUE -rb_obj_instance_exec(int argc, VALUE *argv, VALUE self) +static VALUE +rb_obj_instance_exec_internal(int argc, const VALUE *argv, VALUE self) { - VALUE klass; + return yield_under(self, TRUE, argc, argv, RB_PASS_CALLED_KEYWORDS); +} - if (SPECIAL_CONST_P(self)) { - klass = rb_special_singleton_class(self); - } - else { - klass = rb_singleton_class(self); - } - return yield_under(klass, self, rb_ary_new4(argc, argv)); +VALUE +rb_obj_instance_exec(int argc, const VALUE *argv, VALUE self) +{ + return yield_under(self, TRUE, argc, argv, RB_NO_KEYWORDS); } /* * call-seq: * mod.class_eval(string [, filename [, lineno]]) -> obj - * mod.module_eval {|| block } -> obj + * mod.class_eval {|mod| block } -> obj + * mod.module_eval(string [, filename [, lineno]]) -> obj + * mod.module_eval {|mod| block } -> obj * * Evaluates the string or block in the context of _mod_, except that when * a block is given, constant/class variable lookup is not affected. This @@ -1663,10 +2397,16 @@ rb_obj_instance_exec(int argc, VALUE *argv, VALUE self) * or method `code' for Thing:Class */ +static VALUE +rb_mod_module_eval_internal(int argc, const VALUE *argv, VALUE mod) +{ + return specific_eval(argc, argv, mod, FALSE, RB_PASS_CALLED_KEYWORDS); +} + VALUE -rb_mod_module_eval(int argc, VALUE *argv, VALUE mod) +rb_mod_module_eval(int argc, const VALUE *argv, VALUE mod) { - return specific_eval(argc, argv, mod, mod); + return specific_eval(argc, argv, mod, FALSE, RB_NO_KEYWORDS); } /* @@ -1676,6 +2416,8 @@ rb_mod_module_eval(int argc, VALUE *argv, VALUE mod) * * Evaluates the given block in the context of the class/module. * The method defined in the block will belong to the receiver. + * Any arguments passed to the method will be passed to the block. + * This can be used if the block needs to access instance variables. * * class Thing * end @@ -1689,10 +2431,80 @@ rb_mod_module_eval(int argc, VALUE *argv, VALUE mod) * Hello there! */ +static VALUE +rb_mod_module_exec_internal(int argc, const VALUE *argv, VALUE mod) +{ + return yield_under(mod, FALSE, argc, argv, RB_PASS_CALLED_KEYWORDS); +} + VALUE -rb_mod_module_exec(int argc, VALUE *argv, VALUE mod) +rb_mod_module_exec(int argc, const VALUE *argv, VALUE mod) { - return yield_under(mod, mod, rb_ary_new4(argc, argv)); + return yield_under(mod, FALSE, argc, argv, RB_NO_KEYWORDS); +} + +/* + * Document-class: UncaughtThrowError + * + * Raised when +throw+ is called with a _tag_ which does not have + * corresponding +catch+ block. + * + * throw "foo", "bar" + * + * <em>raises the exception:</em> + * + * UncaughtThrowError: uncaught throw "foo" + */ + +static VALUE +uncaught_throw_init(int argc, const VALUE *argv, VALUE exc) +{ + rb_check_arity(argc, 2, UNLIMITED_ARGUMENTS); + rb_call_super(argc - 2, argv + 2); + rb_ivar_set(exc, id_tag, argv[0]); + rb_ivar_set(exc, id_value, argv[1]); + return exc; +} + +/* + * call-seq: + * uncaught_throw.tag -> obj + * + * Return the tag object which was called for. + */ + +static VALUE +uncaught_throw_tag(VALUE exc) +{ + return rb_ivar_get(exc, id_tag); +} + +/* + * call-seq: + * uncaught_throw.value -> obj + * + * Return the return value which was called for. + */ + +static VALUE +uncaught_throw_value(VALUE exc) +{ + return rb_ivar_get(exc, id_value); +} + +/* + * call-seq: + * uncaught_throw.to_s -> string + * + * Returns formatted message with the inspected tag. + */ + +static VALUE +uncaught_throw_to_s(VALUE exc) +{ + VALUE mesg = rb_attr_get(exc, id_mesg); + VALUE tag = uncaught_throw_tag(exc); + return rb_str_format(1, &tag, mesg); } /* @@ -1700,145 +2512,225 @@ rb_mod_module_exec(int argc, VALUE *argv, VALUE mod) * throw(tag [, obj]) * * Transfers control to the end of the active +catch+ block - * waiting for _tag_. Raises +ArgumentError+ if there + * waiting for _tag_. Raises +UncaughtThrowError+ if there * is no +catch+ block for the _tag_. The optional second * parameter supplies a return value for the +catch+ block, * which otherwise defaults to +nil+. For examples, see - * <code>Kernel::catch</code>. + * Kernel::catch. */ static VALUE -rb_f_throw(int argc, VALUE *argv) +rb_f_throw(int argc, VALUE *argv, VALUE _) { VALUE tag, value; rb_scan_args(argc, argv, "11", &tag, &value); rb_throw_obj(tag, value); - UNREACHABLE; + UNREACHABLE_RETURN(Qnil); } void rb_throw_obj(VALUE tag, VALUE value) { - rb_thread_t *th = GET_THREAD(); - struct rb_vm_tag *tt = th->tag; + rb_execution_context_t *ec = GET_EC(); + struct rb_vm_tag *tt = ec->tag; while (tt) { - if (tt->tag == tag) { - tt->retval = value; - break; - } - tt = tt->prev; + if (tt->tag == tag) { + tt->retval = value; + break; + } + tt = tt->prev; } if (!tt) { - VALUE desc = rb_inspect(tag); - RB_GC_GUARD(desc); - rb_raise(rb_eArgError, "uncaught throw %s", RSTRING_PTR(desc)); + VALUE desc[3]; + desc[0] = tag; + desc[1] = value; + desc[2] = rb_str_new_cstr("uncaught throw %p"); + rb_exc_raise(rb_class_new_instance(numberof(desc), desc, rb_eUncaughtThrow)); } - th->errinfo = NEW_THROW_OBJECT(tag, 0, TAG_THROW); - JUMP_TAG(TAG_THROW); + ec->errinfo = (VALUE)THROW_DATA_NEW(tag, NULL, TAG_THROW); + EC_JUMP_TAG(ec, TAG_THROW); } void rb_throw(const char *tag, VALUE val) { - rb_throw_obj(ID2SYM(rb_intern(tag)), val); + rb_throw_obj(rb_sym_intern_ascii_cstr(tag), val); } static VALUE -catch_i(VALUE tag, VALUE data) +catch_i(RB_BLOCK_CALL_FUNC_ARGLIST(tag, _)) { return rb_yield_0(1, &tag); } /* * call-seq: - * catch([arg]) {|tag| block } -> obj + * catch([tag]) {|tag| block } -> obj * - * +catch+ executes its block. If a +throw+ is - * executed, Ruby searches up its stack for a +catch+ block - * with a tag corresponding to the +throw+'s - * _tag_. If found, that block is terminated, and - * +catch+ returns the value given to +throw+. If - * +throw+ is not called, the block terminates normally, and - * the value of +catch+ is the value of the last expression - * evaluated. +catch+ expressions may be nested, and the - * +throw+ call need not be in lexical scope. + * +catch+ executes its block. If +throw+ is not called, the block executes + * normally, and +catch+ returns the value of the last expression evaluated. * - * def routine(n) - * puts n - * throw :done if n <= 0 - * routine(n-1) - * end + * catch(1) { 123 } # => 123 * + * If <code>throw(tag2, val)</code> is called, Ruby searches up its stack for + * a +catch+ block whose +tag+ has the same +object_id+ as _tag2_. When found, + * the block stops executing and returns _val_ (or +nil+ if no second argument + * was given to +throw+). * - * catch(:done) { routine(3) } + * catch(1) { throw(1, 456) } # => 456 + * catch(1) { throw(1) } # => nil * - * <em>produces:</em> + * When +tag+ is passed as the first argument, +catch+ yields it as the + * parameter of the block. + * + * catch(1) {|x| x + 2 } # => 3 + * + * When no +tag+ is given, +catch+ yields a new unique object (as from + * +Object.new+) as the block parameter. This object can then be used as the + * argument to +throw+, and will match the correct +catch+ block. + * + * catch do |obj_A| + * catch do |obj_B| + * throw(obj_B, 123) + * puts "This puts is not reached" + * end * - * 3 - * 2 - * 1 - * 0 + * puts "This puts is displayed" + * 456 + * end * - * when _arg_ is given, +catch+ yields it as is, or when no - * _arg_ is given, +catch+ assigns a new unique object to - * +throw+. this is useful for nested +catch+. _arg_ can - * be an arbitrary object, not only Symbol. + * # => 456 * + * catch do |obj_A| + * catch do |obj_B| + * throw(obj_A, 123) + * puts "This puts is still not reached" + * end + * + * puts "Now this puts is also not reached" + * 456 + * end + * + * # => 123 */ static VALUE -rb_f_catch(int argc, VALUE *argv) +rb_f_catch(int argc, VALUE *argv, VALUE self) { - VALUE tag; - - if (argc == 0) { - tag = rb_obj_alloc(rb_cObject); - } - else { - rb_scan_args(argc, argv, "01", &tag); - } + VALUE tag = rb_check_arity(argc, 0, 1) ? argv[0] : rb_obj_alloc(rb_cObject); return rb_catch_obj(tag, catch_i, 0); } VALUE -rb_catch(const char *tag, VALUE (*func)(), VALUE data) +rb_catch(const char *tag, rb_block_call_func_t func, VALUE data) { - VALUE vtag = tag ? ID2SYM(rb_intern(tag)) : rb_obj_alloc(rb_cObject); + VALUE vtag = tag ? rb_sym_intern_ascii_cstr(tag) : rb_obj_alloc(rb_cObject); return rb_catch_obj(vtag, func, data); } -VALUE -rb_catch_obj(VALUE tag, VALUE (*func)(), VALUE data) +static VALUE +vm_catch_protect(VALUE tag, rb_block_call_func *func, VALUE data, + enum ruby_tag_type *stateptr, rb_execution_context_t *volatile ec) { - int state; - volatile VALUE val = Qnil; /* OK */ - rb_thread_t *th = GET_THREAD(); - rb_control_frame_t *saved_cfp = th->cfp; + enum ruby_tag_type state; + VALUE val = Qnil; /* OK */ + rb_control_frame_t *volatile saved_cfp = ec->cfp; - TH_PUSH_TAG(th); + EC_PUSH_TAG(ec); - th->tag->tag = tag; + _tag.tag = tag; - if ((state = TH_EXEC_TAG()) == 0) { - /* call with argc=1, argv = [tag], block = Qnil to insure compatibility */ - val = (*func)(tag, data, 1, &tag, Qnil); + if ((state = EC_EXEC_TAG()) == TAG_NONE) { + /* call with argc=1, argv = [tag], block = Qnil to insure compatibility */ + val = (*func)(tag, data, 1, (const VALUE *)&tag, Qnil); } - else if (state == TAG_THROW && RNODE(th->errinfo)->u1.value == tag) { - rb_vm_rewind_cfp(th, saved_cfp); - val = th->tag->retval; - th->errinfo = Qnil; - state = 0; + else if (state == TAG_THROW && THROW_DATA_VAL((struct vm_throw_data *)ec->errinfo) == tag) { + rb_vm_rewind_cfp(ec, saved_cfp); + val = ec->tag->retval; + ec->errinfo = Qnil; + state = 0; } - TH_POP_TAG(); - if (state) - JUMP_TAG(state); + EC_POP_TAG(); + if (stateptr) + *stateptr = state; + + return val; +} + +VALUE +rb_catch_protect(VALUE t, rb_block_call_func *func, VALUE data, enum ruby_tag_type *stateptr) +{ + return vm_catch_protect(t, func, data, stateptr, GET_EC()); +} +VALUE +rb_catch_obj(VALUE t, rb_block_call_func_t func, VALUE data) +{ + enum ruby_tag_type state; + rb_execution_context_t *ec = GET_EC(); + VALUE val = vm_catch_protect(t, (rb_block_call_func *)func, data, &state, ec); + if (state) EC_JUMP_TAG(ec, state); return val; } +static void +local_var_list_init(struct local_var_list *vars) +{ + vars->tbl = rb_ident_hash_new(); + RBASIC_CLEAR_CLASS(vars->tbl); +} + +static VALUE +local_var_list_finish(struct local_var_list *vars) +{ + /* TODO: not to depend on the order of st_table */ + VALUE ary = rb_hash_keys(vars->tbl); + rb_hash_clear(vars->tbl); + vars->tbl = 0; + return ary; +} + +static int +local_var_list_update(st_data_t *key, st_data_t *value, st_data_t arg, int existing) +{ + if (existing) return ST_STOP; + *value = (st_data_t)Qtrue; /* INT2FIX(arg) */ + return ST_CONTINUE; +} + +extern int rb_numparam_id_p(ID id); + +static void +local_var_list_add(const struct local_var_list *vars, ID lid) +{ + /* should skip temporary variable */ + if (!lid) return; + if (!rb_is_local_id(lid)) return; + + /* should skip numbered parameters as well */ + if (rb_numparam_id_p(lid)) return; + + st_data_t idx = 0; /* tbl->num_entries */ + rb_hash_stlike_update(vars->tbl, ID2SYM(lid), local_var_list_update, idx); +} + +static void +numparam_list_add(const struct local_var_list *vars, ID lid) +{ + /* should skip temporary variable */ + if (!lid) return; + if (!rb_is_local_id(lid)) return; + + /* should skip anything but numbered parameters */ + if (rb_numparam_id_p(lid)) { + st_data_t idx = 0; /* tbl->num_entries */ + rb_hash_stlike_update(vars->tbl, ID2SYM(lid), local_var_list_update, idx); + } +} + /* * call-seq: * local_variables -> array @@ -1853,51 +2745,43 @@ rb_catch_obj(VALUE tag, VALUE (*func)(), VALUE data) */ static VALUE -rb_f_local_variables(void) +rb_f_local_variables(VALUE _) { - VALUE ary = rb_ary_new(); - rb_thread_t *th = GET_THREAD(); - rb_control_frame_t *cfp = - vm_get_ruby_level_caller_cfp(th, RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp)); - int i; + struct local_var_list vars; + rb_execution_context_t *ec = GET_EC(); + rb_control_frame_t *cfp = vm_get_ruby_level_caller_cfp(ec, RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp)); + unsigned int i; + local_var_list_init(&vars); while (cfp) { - if (cfp->iseq) { - for (i = 0; i < cfp->iseq->local_table_size; i++) { - ID lid = cfp->iseq->local_table[i]; - if (lid) { - const char *vname = rb_id2name(lid); - /* should skip temporary variable */ - if (vname) { - rb_ary_push(ary, ID2SYM(lid)); - } - } - } - } - if (!VM_EP_LEP_P(cfp->ep)) { - /* block */ - VALUE *ep = VM_CF_PREV_EP(cfp); - - if (vm_collect_local_variables_in_heap(th, ep, ary)) { - break; - } - else { - while (cfp->ep != ep) { - cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); - } - } - } - else { - break; - } + if (cfp->iseq) { + for (i = 0; i < ISEQ_BODY(cfp->iseq)->local_table_size; i++) { + local_var_list_add(&vars, ISEQ_BODY(cfp->iseq)->local_table[i]); + } + } + if (!VM_ENV_LOCAL_P(cfp->ep)) { + /* block */ + const VALUE *ep = VM_CF_PREV_EP(cfp); + + if (vm_collect_local_variables_in_heap(ep, &vars)) { + break; + } + else { + while (cfp->ep != ep) { + cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); + } + } + } + else { + break; + } } - return ary; + return local_var_list_finish(&vars); } /* * call-seq: * block_given? -> true or false - * iterator? -> true or false * * Returns <code>true</code> if <code>yield</code> would execute a * block in the current context. The <code>iterator?</code> form @@ -1915,62 +2799,109 @@ rb_f_local_variables(void) * try do "hello" end #=> "hello" */ - -VALUE -rb_f_block_given_p(void) +static VALUE +rb_f_block_given_p(VALUE _) { - rb_thread_t *th = GET_THREAD(); - rb_control_frame_t *cfp = th->cfp; - cfp = vm_get_ruby_level_caller_cfp(th, RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)); + rb_execution_context_t *ec = GET_EC(); + rb_control_frame_t *cfp = ec->cfp; + cfp = vm_get_ruby_level_caller_cfp(ec, RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)); - if (cfp != 0 && VM_CF_BLOCK_PTR(cfp)) { - return Qtrue; - } - else { - return Qfalse; - } + return RBOOL(cfp != NULL && VM_CF_BLOCK_HANDLER(cfp) != VM_BLOCK_HANDLER_NONE); +} + +/* + * call-seq: + * iterator? -> true or false + * + * Deprecated. Use block_given? instead. + */ + +static VALUE +rb_f_iterator_p(VALUE self) +{ + rb_warn_deprecated("iterator?", "block_given?"); + return rb_f_block_given_p(self); } VALUE rb_current_realfilepath(void) { - rb_thread_t *th = GET_THREAD(); - rb_control_frame_t *cfp = th->cfp; - cfp = vm_get_ruby_level_caller_cfp(th, RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)); - if (cfp != 0) return cfp->iseq->location.absolute_path; + const rb_execution_context_t *ec = GET_EC(); + rb_control_frame_t *cfp = ec->cfp; + cfp = vm_get_ruby_level_caller_cfp(ec, RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)); + if (cfp != NULL) { + VALUE path = rb_iseq_realpath(cfp->iseq); + if (RTEST(path)) return path; + // eval context + path = rb_iseq_path(cfp->iseq); + if (path == eval_default_path) { + return Qnil; + } + + // [Feature #19755] implicit eval location is "(eval at #{__FILE__}:#{__LINE__})" + const long len = RSTRING_LEN(path); + if (len > EVAL_LOCATION_MARK_LEN+1) { + const char *const ptr = RSTRING_PTR(path); + if (ptr[len - 1] == ')' && + memcmp(ptr, "("EVAL_LOCATION_MARK, EVAL_LOCATION_MARK_LEN+1) == 0) { + return Qnil; + } + } + + return path; + } return Qnil; } +// Assert that an internal function is running and return +// the imemo object that represents it. +struct vm_ifunc * +rb_current_ifunc(void) +{ + // Search VM_FRAME_MAGIC_IFUNC to see ifunc imemos put on the iseq field. + VALUE ifunc = (VALUE)GET_EC()->cfp->iseq; + RUBY_ASSERT_ALWAYS(imemo_type_p(ifunc, imemo_ifunc)); + return (struct vm_ifunc *)ifunc; +} + void Init_vm_eval(void) { rb_define_global_function("eval", rb_f_eval, -1); rb_define_global_function("local_variables", rb_f_local_variables, 0); - rb_define_global_function("iterator?", rb_f_block_given_p, 0); + rb_define_global_function("iterator?", rb_f_iterator_p, 0); rb_define_global_function("block_given?", rb_f_block_given_p, 0); rb_define_global_function("catch", rb_f_catch, -1); rb_define_global_function("throw", rb_f_throw, -1); - rb_define_global_function("loop", rb_f_loop, 0); - - rb_define_method(rb_cBasicObject, "instance_eval", rb_obj_instance_eval, -1); - rb_define_method(rb_cBasicObject, "instance_exec", rb_obj_instance_exec, -1); + rb_define_method(rb_cBasicObject, "instance_eval", rb_obj_instance_eval_internal, -1); + rb_define_method(rb_cBasicObject, "instance_exec", rb_obj_instance_exec_internal, -1); rb_define_private_method(rb_cBasicObject, "method_missing", rb_method_missing, -1); #if 1 - rb_add_method(rb_cBasicObject, rb_intern("__send__"), - VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, 0); - rb_add_method(rb_mKernel, rb_intern("send"), - VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, 0); + rb_add_method(rb_cBasicObject, id__send__, + VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, METHOD_VISI_PUBLIC); + rb_add_method(rb_mKernel, idSend, + VM_METHOD_TYPE_OPTIMIZED, (void *)OPTIMIZED_METHOD_TYPE_SEND, METHOD_VISI_PUBLIC); #else rb_define_method(rb_cBasicObject, "__send__", rb_f_send, -1); rb_define_method(rb_mKernel, "send", rb_f_send, -1); #endif rb_define_method(rb_mKernel, "public_send", rb_f_public_send, -1); - rb_define_method(rb_cModule, "module_exec", rb_mod_module_exec, -1); - rb_define_method(rb_cModule, "class_exec", rb_mod_module_exec, -1); - rb_define_method(rb_cModule, "module_eval", rb_mod_module_eval, -1); - rb_define_method(rb_cModule, "class_eval", rb_mod_module_eval, -1); + rb_define_method(rb_cModule, "module_exec", rb_mod_module_exec_internal, -1); + rb_define_method(rb_cModule, "class_exec", rb_mod_module_exec_internal, -1); + rb_define_method(rb_cModule, "module_eval", rb_mod_module_eval_internal, -1); + rb_define_method(rb_cModule, "class_eval", rb_mod_module_eval_internal, -1); + + rb_eUncaughtThrow = rb_define_class("UncaughtThrowError", rb_eArgError); + rb_define_method(rb_eUncaughtThrow, "initialize", uncaught_throw_init, -1); + rb_define_method(rb_eUncaughtThrow, "tag", uncaught_throw_tag, 0); + rb_define_method(rb_eUncaughtThrow, "value", uncaught_throw_value, 0); + rb_define_method(rb_eUncaughtThrow, "to_s", uncaught_throw_to_s, 0); + + id_result = rb_intern_const("result"); + id_tag = rb_intern_const("tag"); + id_value = rb_intern_const("value"); } |
