use crate::encoding_table::{EncodingInfo, ALIASES, ENCODINGS, NAME_LIST};
use crate::host::encoding_info;
use crate::host::ops;
use crate::host::{
call_instance_method, call_method, call_proc, current_block, has_pending_signal,
raise_signal_break, raise_signal_next, raise_signal_redo, raise_signal_retry,
raise_signal_return, raise_signal_throw, take_break, take_throw, with_host, Derive, GenSize,
MatchPart, RKey, RubyHost,
};
use fusevm::{Value, VM};
use indexmap::IndexMap;
use num_traits::{ToPrimitive as _, Zero as _};
use unicode_normalization::UnicodeNormalization;
use unicode_segmentation::UnicodeSegmentation;
pub fn install(vm: &mut VM) {
vm.register_builtin(ops::GETLOCAL, b_getlocal);
vm.register_builtin(ops::GETLOCAL_DECLARED, b_getlocal_declared);
vm.register_builtin(ops::MARK_KWARGS, b_mark_kwargs);
vm.register_builtin(ops::KWSPLAT_ARGS, b_kwsplat_args);
vm.register_builtin(ops::BITNOT, b_bitnot);
vm.register_builtin(ops::METHOD_HOOK, b_method_hook);
vm.register_builtin(ops::MKBSTR, b_mkbstr);
vm.register_builtin(ops::SETLOCAL, b_setlocal);
vm.register_builtin(ops::GETIVAR, b_getivar);
vm.register_builtin(ops::SETIVAR, b_setivar);
vm.register_builtin(ops::GETCVAR, b_getcvar);
vm.register_builtin(ops::SETCVAR, b_setcvar);
vm.register_builtin(ops::GETGVAR, b_getgvar);
vm.register_builtin(ops::SETGVAR, b_setgvar);
vm.register_builtin(ops::GETCONST, b_getconst);
vm.register_builtin(ops::SETCONST, b_setconst);
vm.register_builtin(ops::CALL, b_call);
vm.register_builtin(ops::CALL_BLK, b_call_blk);
vm.register_builtin(ops::CALL_METHOD, b_call_method);
vm.register_builtin(ops::CALL_METHOD_BLK, b_call_method_blk);
vm.register_builtin(ops::MKSTR, b_mkstr);
vm.register_builtin(ops::MKSTRF, b_mkstrf);
vm.register_builtin(ops::MKSTRC, b_mkstrc);
vm.register_builtin(ops::MKSYM, b_mksym);
vm.register_builtin(ops::MKARRAY, b_mkarray);
vm.register_builtin(ops::MKHASH, b_mkhash);
vm.register_builtin(ops::MKRANGE, b_mkrange);
vm.register_builtin(ops::MKPROC, b_mkproc);
vm.register_builtin(ops::MKLAMBDA, b_mklambda);
vm.register_builtin(ops::MKREGEX, b_mkregex);
vm.register_builtin(ops::REGEX_ONCE, b_regex_once);
vm.register_builtin(ops::YIELD, b_yield);
vm.register_builtin(ops::TRUTHY, b_truthy);
vm.register_builtin(ops::INDEX_GET, b_index_get);
vm.register_builtin(ops::INDEX_SET, b_index_set);
vm.register_builtin(ops::TOSTR, b_tostr);
vm.register_builtin(ops::DEFINED, b_defined);
vm.register_builtin(ops::SIG_BREAK, b_sig_break);
vm.register_builtin(ops::SIG_NEXT, b_sig_next);
vm.register_builtin(ops::SIG_RETURN, b_sig_return);
vm.register_builtin(ops::SIG_RETRY, b_sig_retry);
vm.register_builtin(ops::SIG_REDO, b_sig_redo);
vm.register_builtin(ops::TAKE_LOOP_REDO, b_take_loop_redo);
vm.register_builtin(ops::NO_MATCH, b_no_match);
vm.register_builtin(ops::GETSELF, b_getself);
vm.register_builtin(ops::BEGIN, b_begin);
vm.register_builtin(ops::SUPER, b_super);
vm.register_builtin(ops::SUPER_FWD, b_super_fwd);
vm.register_builtin(ops::SUPER_BLK, b_super_blk);
vm.register_builtin(ops::SUPER_FWD_BLK, b_super_fwd_blk);
vm.register_builtin(ops::MKARGS, b_mkargs);
vm.register_builtin(ops::MKHASH_MERGE, b_mkhash_merge);
vm.register_builtin(ops::TAKE_LOOP_NEXT, b_take_loop_next);
vm.register_builtin(ops::PEEK_LOOP_BREAK, b_peek_loop_break);
vm.register_builtin(ops::TAKE_LOOP_BREAK, b_take_loop_break);
vm.register_builtin(ops::BEGIN_IN_LOOP, b_begin_in_loop);
vm.register_builtin(ops::CALL_ARR, b_call_arr);
vm.register_builtin(ops::CALL_METHOD_ARR, b_call_method_arr);
vm.register_builtin(ops::CALL_ARR_BLK, b_call_arr_blk);
vm.register_builtin(ops::CALL_METHOD_ARR_BLK, b_call_method_arr_blk);
vm.register_builtin(ops::DEFINED_DESC, b_defined_desc);
vm.register_builtin(ops::DEFINE_SINGLETON, b_define_singleton);
vm.register_builtin(ops::DEFINE_METHOD_DYN, b_define_method_dyn);
vm.register_builtin(ops::FIRE_HOOK, b_fire_hook);
}
pub(crate) fn is_kernel_function(name: &str) -> bool {
matches!(
name,
"puts"
| "print"
| "p"
| "pp"
| "gets"
| "open"
| "require"
| "require_relative"
| "load"
| "intercept"
| "raise"
| "fail"
| "abort"
| "warn"
| "exit"
| "exit!"
| "at_exit"
| "loop"
| "lambda"
| "proc"
| "format"
| "sprintf"
| "printf"
| "putc"
| "sleep"
| "`"
| "system"
| "rand"
| "srand"
| "catch"
| "throw"
| "eval"
| "block_given?"
| "caller"
| "caller_locations"
| "Integer"
| "Float"
| "String"
| "Array"
)
}
fn b_defined_desc(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
let kind = name_of(&vm.pop());
let set = |v: Value| !matches!(v, Value::Undef);
let desc: Option<&str> = match kind.as_str() {
"const" => {
let defined = with_host(|h| {
set(h.get_const(&name))
|| h.has_const(&name)
|| h.class_exists(&name)
|| h.is_builtin_class(&name)
}) || (builtin_exception_const(&name));
defined.then_some("constant")
}
"ivar" => with_host(|h| set(h.get_ivar(&name)) || h.ivar_defined(&name))
.then_some("instance-variable"),
"gvar" => with_host(|h| match h.match_global(&name) {
Some(v) => set(v),
None => set(h.get_global(&name)) || h.global_defined(&name),
})
.then_some("global-variable"),
"cvar" => with_host(|h| {
let this = h.current_self();
h.cvar_owner(&this)
.map(|cls| set(h.get_cvar(&cls, &name)))
.unwrap_or(false)
})
.then_some("class variable"),
"local" => {
if with_host(|h| h.local_defined(&name)) {
Some("local-variable")
} else if with_host(|h| h.responds_to(&name)) || is_kernel_function(&name) {
Some("method")
} else {
None
}
}
"yield" => current_block().is_some().then_some("yield"),
"super" => super_defined().then_some("super"),
_ => None,
};
match desc {
Some(s) => new_str(s.to_string()),
None => Value::Undef,
}
}
fn super_defined() -> bool {
let (this, method, def_class, _) = with_host(|h| h.super_context());
let (Some(method), Some(def_class)) = (method, def_class) else {
return false;
};
with_host(|h| {
let method = h.alias_original(&def_class, &method).unwrap_or(method);
let user = match (h.object_class(&this), h.classref_name(&this)) {
(None, Some(cls)) => h
.find_super_class_method(&cls, &def_class, &method)
.is_some(),
(recv_class, _) => {
let recv_class = recv_class.unwrap_or_else(|| def_class.clone());
h.find_super(&recv_class, &def_class, &method).is_some()
}
};
user || h.builtin_owner(&this, &method).is_some()
})
}
fn b_mkhash_merge(vm: &mut VM, argc: u8) -> Value {
let pieces = pop_n(vm, argc as usize);
let mut map: IndexMap<RKey, Value> = IndexMap::new();
for p in &pieces {
if let Some(m) = with_host(|h| h.as_hash(p)) {
for (k, v) in m {
map.insert(k, v);
}
}
}
with_host(|h| h.new_hash(map))
}
fn b_mkargs(vm: &mut VM, argc: u8) -> Value {
let pieces = pop_n(vm, argc as usize);
let mut out = Vec::new();
for p in &pieces {
match with_host(|h| h.as_array(p)) {
Some(xs) => out.extend(xs),
None if matches!(p, Value::Undef) => {}
None if with_host(|h| {
h.is_a(p, "Range")
|| h.is_a(p, "Hash")
|| h.is_a(p, "Struct")
|| h.is_a(p, "Set")
|| h.is_a(p, "Enumerator")
|| h.is_a(p, "MatchData")
}) || defines_own(p, "to_a") =>
{
match dispatch(p, "to_a", &[], None)
.ok()
.and_then(|a| with_host(|h| h.as_array(&a)))
{
Some(xs) => out.extend(xs),
None => out.push(p.clone()),
}
}
None => out.push(p.clone()),
}
}
with_host(|h| h.new_array(out))
}
fn b_call_arr(vm: &mut VM, _: u8) -> Value {
let arr = vm.pop();
let name = name_of(&vm.pop());
let args = with_host(|h| h.as_array(&arr).unwrap_or_default());
let this = with_host(|h| h.current_self());
match at_call_site(vm, None, || {
with_builtin_frame(&this, &name, &args, dispatch_call(&name, &args, None))
}) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn block_operand(v: Value) -> Option<Value> {
match v {
Value::Undef => None,
other => Some(other),
}
}
fn b_call_arr_blk(vm: &mut VM, _: u8) -> Value {
let block = block_operand(vm.pop());
let owns = crate::host::take_block_literal();
let arr = vm.pop();
let name = name_of(&vm.pop());
let args = with_host(|h| h.as_array(&arr).unwrap_or_default());
let home = owns
.then(|| crate::host::enter_block_home(block.as_ref()))
.flatten();
let site = block
.as_ref()
.map(|_| (with_host(|h| h.current_self()), name.as_str()));
let this = with_host(|h| h.current_self());
let out = at_call_site(vm, site, || {
with_builtin_frame(&this, &name, &args, dispatch_call(&name, &args, block))
});
crate::host::leave_block_home(home);
match out {
Ok(v) => finish_block_call(vm, owns, v),
Err(e) => abort(vm, e),
}
}
fn b_call_method_arr_blk(vm: &mut VM, _: u8) -> Value {
let block = block_operand(vm.pop());
let owns = crate::host::take_block_literal();
let arr = vm.pop();
let name = name_of(&vm.pop());
let recv = vm.pop();
let args = with_host(|h| h.as_array(&arr).unwrap_or_default());
if let Err(e) = check_visibility(&recv, &name) {
return abort(vm, e);
}
let home = owns
.then(|| crate::host::enter_block_home(block.as_ref()))
.flatten();
let site = block.as_ref().map(|_| (recv.clone(), name.as_str()));
let out = at_call_site(vm, site, || {
with_builtin_frame(&recv, &name, &args, dispatch(&recv, &name, &args, block))
});
crate::host::leave_block_home(home);
match out {
Ok(v) => finish_block_call(vm, owns, v),
Err(e) => abort(vm, e),
}
}
fn b_call_method_arr(vm: &mut VM, _: u8) -> Value {
let arr = vm.pop();
let name = name_of(&vm.pop());
let recv = vm.pop();
let args = with_host(|h| h.as_array(&arr).unwrap_or_default());
if let Err(e) = check_visibility(&recv, &name) {
return abort(vm, e);
}
match at_call_site(vm, None, || {
with_builtin_frame(&recv, &name, &args, dispatch(&recv, &name, &args, None))
}) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn b_getself(_vm: &mut VM, _: u8) -> Value {
with_host(|h| h.current_self())
}
fn b_super(vm: &mut VM, argc: u8) -> Value {
let args = pop_n(vm, argc as usize);
match at_call_site(vm, None, || crate::host::call_super(Some(args))) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn b_super_fwd(vm: &mut VM, _: u8) -> Value {
match at_call_site(vm, None, || crate::host::call_super(None)) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn b_super_blk(vm: &mut VM, argc: u8) -> Value {
let block = block_operand(vm.pop());
let owns = crate::host::take_block_literal();
let args = pop_n(vm, argc.saturating_sub(1) as usize);
match at_call_site(vm, None, || crate::host::call_super_blk(Some(args), block)) {
Ok(v) => finish_block_call(vm, owns, v),
Err(e) => abort(vm, e),
}
}
fn b_super_fwd_blk(vm: &mut VM, _: u8) -> Value {
let block = block_operand(vm.pop());
let owns = crate::host::take_block_literal();
match at_call_site(vm, None, || crate::host::call_super_blk(None, block)) {
Ok(v) => finish_block_call(vm, owns, v),
Err(e) => abort(vm, e),
}
}
fn b_begin(vm: &mut VM, _: u8) -> Value {
let id = match vm.pop() {
Value::Int(n) => n as usize,
_ => return abort(vm, "bad begin id".into()),
};
match crate::host::run_begin(id) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn b_begin_in_loop(vm: &mut VM, _: u8) -> Value {
let id = match vm.pop() {
Value::Int(n) => n as usize,
_ => return abort(vm, "bad begin id".into()),
};
let out = crate::host::run_begin(id);
if crate::host::pending_signal_is_loop_flow() {
return out.unwrap_or(Value::Undef);
}
match out {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn b_take_loop_next(_: &mut VM, _: u8) -> Value {
Value::Bool(crate::host::take_next().is_some())
}
fn b_take_loop_redo(_: &mut VM, _: u8) -> Value {
Value::Bool(crate::host::take_redo_signal())
}
fn b_peek_loop_break(_: &mut VM, _: u8) -> Value {
crate::host::peek_break()
}
fn b_take_loop_break(_: &mut VM, _: u8) -> Value {
take_break().unwrap_or(Value::Undef)
}
fn pop_n(vm: &mut VM, n: usize) -> Vec<Value> {
let mut v = Vec::with_capacity(n);
for _ in 0..n {
v.push(vm.pop());
}
v.reverse();
v
}
fn b_no_match(vm: &mut VM, argc: u8) -> Value {
let reason = if argc == 2 {
with_host(|h| h.as_array(&vm.pop()))
} else {
None
};
let subj = vm.pop();
let insp = |v: &Value| with_host(|h| h.inspect(v));
let mut msg = insp(&subj);
let mut class = "NoMatchingPatternError";
let mut fields = Vec::new();
if let Some(r) = reason.filter(|r| !r.is_empty()) {
let kind = with_host(|h| h.as_symbol(&r[0])).unwrap_or_default();
let arg = |i: usize| r.get(i).cloned().unwrap_or(Value::Undef);
let why = match kind.as_str() {
"eqq" => format!(
"{} === {} does not return true",
insp(&arg(1)),
insp(&arg(2))
),
"length" => format!(
"{} length mismatch (given {}, expected {})",
insp(&arg(1)),
insp(&arg(2)),
with_host(|h| h.to_s(&arg(3)))
),
"deconstruct" | "deconstruct_keys" => {
format!("{} does not respond to #{kind}", insp(&arg(1)))
}
"key" => {
class = "NoMatchingPatternKeyError";
fields = vec![("key", arg(1)), ("matchee", arg(2))];
format!("key not found: {}", insp(&arg(1)))
}
"rest" => format!("rest of {} is not empty", insp(&arg(1))),
"empty" => format!("{} is not empty", insp(&arg(1))),
"find" => format!("{} does not match to find pattern", insp(&arg(1))),
"guard" => "guard clause does not return true".to_string(),
_ => String::new(),
};
if !why.is_empty() {
msg = format!("{msg}: {why}");
}
}
let e = raise_exc_with(class, &msg, &fields);
abort(vm, e)
}
fn abort(vm: &mut VM, e: String) -> Value {
let line = op_line(vm);
let src = crate::host::current_file_path().unwrap_or_else(|| "-e".into());
if with_host(|h| h.pending_exc_needs_backtrace()) {
let stack = crate::host::raise_backtrace(line);
with_host(|h| h.record_raise_backtrace(stack));
} else {
with_host(|h| h.record_backtrace_frame(&src, line));
}
with_host(|h| h.error = Some(e));
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn op_line(vm: &VM) -> u32 {
vm.chunk
.lines
.get(vm.ip.wrapping_sub(1))
.copied()
.unwrap_or(0)
}
fn at_call_site<T>(vm: &VM, yielder: Option<(Value, &str)>, call: impl FnOnce() -> T) -> T {
let yielder = yielder.map(|(recv, name)| (recv, name.to_string()));
let depth = crate::host::enter_call_site(op_line(vm), yielder);
let out = call();
crate::host::leave_call_site(depth);
out
}
fn with_builtin_frame<T>(
recv: &Value,
name: &str,
args: &[Value],
out: Result<T, String>,
) -> Result<T, String> {
let out = match out {
Err(e) if !has_pending_signal() && !with_host(|h| h.has_pending_exc()) => {
let class = crate::host::infer_exc_class(&e);
Err(if class == "NoMethodError" {
raise_exc_with(&class, &e, &[("receiver", recv.clone())])
} else {
raise_exc(&class, &e)
})
}
other => other,
};
if out.is_err() && with_host(|h| h.pending_exc_needs_backtrace()) {
let labels = builtin_raise_labels(recv, name, args);
if !labels.is_empty() {
let mut stack = crate::host::live_backtrace();
if let Some(top) = stack.first() {
let (path, line) = (top.path.clone(), top.line);
let frames = labels.into_iter().map(|label| crate::host::LiveFrame {
path: path.clone(),
line,
label,
});
stack.splice(0..0, frames);
with_host(|h| h.record_raise_backtrace(stack));
}
}
}
out
}
fn builtin_raise_labels(recv: &Value, name: &str, args: &[Value]) -> Vec<String> {
match name {
"raise" | "fail" | "new" => Vec::new(),
"send" | "__send__" | "public_send" => {
let Some((target, rest)) = args.split_first() else {
return Vec::new();
};
let mut labels = builtin_raise_labels(recv, &name_of(target), rest);
if name == "public_send" && !labels.is_empty() {
labels.push(with_host(|h| h.builtin_frame_label(recv, name)));
}
labels
}
_ => with_host(|h| match h.resolve_method_shape(recv, name, false) {
Some(crate::host::MethodShape::Builtin { .. }) => {
vec![h.builtin_frame_label(recv, name)]
}
_ => Vec::new(),
}),
}
}
fn name_of(v: &Value) -> String {
with_host(|h| {
h.as_str(v)
.or_else(|| h.as_symbol(v))
.or_else(|| h.classref_name(v))
.unwrap_or_default()
})
}
fn b_mark_kwargs(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
with_host(|h| h.mark_kwargs(&v));
v
}
fn b_bitnot(vm: &mut VM, _: u8) -> Value {
match vm.pop() {
Value::Int(n) => Value::Int(!n),
v => match dispatch(&v, "~", &[], None) {
Ok(r) => r,
Err(e) => abort(vm, e),
},
}
}
fn b_kwsplat_args(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
with_host(|h| {
let empty = h.as_hash(&v).is_some_and(|m| m.is_empty());
h.new_array(if empty { vec![] } else { vec![v] })
})
}
fn b_getlocal_declared(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
with_host(|h| h.get_local(&name))
}
fn b_getlocal(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
let (defined, v) = with_host(|h| (h.local_defined(&name), h.get_local(&name)));
if defined {
return v;
}
match name.as_str() {
"block_given?" => return Value::Bool(current_block().is_some()),
"__method__" => {
return with_host(|h| {
let (_, m, _, _) = h.super_context();
match m {
Some(name) => h.new_symbol(&name),
None => Value::Undef,
}
})
}
"__dir__" => {
return match crate::host::current_file_path().as_deref() {
Some("-e") | Some("-") => new_str(".".to_string()),
_ => match crate::host::current_file_dir() {
Some(d) => new_str(d.to_string_lossy().to_string()),
None => Value::Undef,
},
}
}
"__FILE__" => {
return match crate::host::current_file_path() {
Some(p) => new_str(p),
None => Value::Undef,
}
}
_ => {}
}
let depth = crate::host::enter_call_site(op_line(vm), None);
let out = bareword_call(vm, name);
crate::host::leave_call_site(depth);
out
}
fn bareword_call(vm: &mut VM, name: String) -> Value {
let this = with_host(|h| h.current_self());
let builtin_self =
with_host(|h| h.object_class(&this).is_none() && h.classref_name(&this).is_none());
if builtin_self {
match dispatch(&this, &name, &[], None) {
Ok(v) => return propagate(vm, v),
Err(e) if e.starts_with("undefined method") => {}
Err(e) => return abort(vm, e),
}
}
if let Some(cls) = with_host(|h| h.object_class(&this)) {
if with_host(|h| h.attr_access(&cls, &name)).is_some()
|| with_host(|h| h.find_define_method(&cls, &name)).is_some()
|| is_universal_object_method(&name)
{
return match dispatch(&this, &name, &[], None) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
};
}
if with_host(|h| h.super_context().1).as_deref() == Some(name.as_str()) {
return Value::Undef;
}
if with_host(|h| h.find_method_owner(&cls, "method_missing").is_some()) {
match dispatch(&this, &name, &[], None) {
Ok(v) => return propagate(vm, v),
Err(e) if e.starts_with("undefined method") => {}
Err(e) => return abort(vm, e),
}
}
match native_self_call(&this, &name, &[], None) {
Some(Ok(v)) => return propagate(vm, v),
Some(Err(e)) => return abort(vm, e),
None => {}
}
}
if let Some(cls) = with_host(|h| h.classref_name(&this)) {
let sclass = format!("#<Class:{cls}>");
if with_host(|h| h.attr_access(&sclass, &name)).is_some()
|| with_host(|h| h.find_class_define_method(&cls, &name)).is_some()
{
return match dispatch(&this, &name, &[], None) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
};
}
}
if name == "module_function" {
if let Some(cls) = with_host(|h| h.classref_name(&h.current_self())) {
with_host(|h| h.mark_module_function(&cls));
}
return Value::Undef;
}
if visibility_directive(&name).is_some()
&& with_host(|h| h.classref_name(&h.current_self())).is_some()
{
return Value::Undef;
}
if with_host(|h| h.responds_to(&name)) {
return match dispatch_call(&name, &[], None) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
};
}
match kernel(&name, &[], None) {
Ok(v) => propagate(vm, v),
Err(e) if e.starts_with("undefined method") && !with_host(|h| h.has_pending_exc()) => {
let this = with_host(|h| h.current_self());
let sym = with_host(|h| h.new_symbol(&name));
abort(
vm,
raise_exc_with(
"NameError",
&format!(
"undefined local variable or method '{name}' for {}",
receiver_phrase(&this)
),
&[("name", sym), ("receiver", this.clone())],
),
)
}
Err(e) => abort(vm, e),
}
}
fn propagate(vm: &mut VM, v: Value) -> Value {
if has_pending_signal() {
vm.ip = vm.chunk.ops.len();
}
v
}
fn finish_block_call(vm: &mut VM, owns_break: bool, v: Value) -> Value {
if owns_break {
if let Some(bv) = take_break() {
return bv;
}
}
propagate(vm, v)
}
fn b_setlocal(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = name_of(&vm.pop());
with_host(|h| h.set_local(&name, val.clone()));
val
}
fn b_getivar(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
with_host(|h| h.get_ivar(&name))
}
fn b_setivar(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = name_of(&vm.pop());
let this = with_host(|h| h.current_self());
if with_host(|h| h.is_frozen(&this) && h.object_class(&this).is_some()) {
let (cls, insp) = with_host(|h| (h.class_of(&this).to_string(), h.inspect(&this)));
return abort(
vm,
raise_exc_with(
"FrozenError",
&format!("can't modify frozen {cls}: {insp}"),
&[("receiver", this)],
),
);
}
with_host(|h| h.set_ivar(&name, val.clone()));
val
}
fn b_getcvar(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
with_host(|h| match h.cvar_class() {
Some(cls) => h.get_cvar(&cls, &name),
None => Value::Undef,
})
}
fn b_setcvar(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = name_of(&vm.pop());
with_host(|h| {
if let Some(cls) = h.cvar_class() {
h.set_cvar(&cls, &name, val.clone());
}
});
val
}
fn b_getgvar(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
if name == "@" {
let bang = with_host(|h| h.get_global("!"));
if matches!(bang, Value::Undef) {
return Value::Undef;
}
return match dispatch(&bang, "backtrace", &[], None) {
Ok(v) => v,
Err(e) => abort(vm, e),
};
}
with_host(|h| h.match_global(&name).unwrap_or_else(|| h.get_global(&name)))
}
fn b_setgvar(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = name_of(&vm.pop());
with_host(|h| h.set_global(&name, val.clone()));
val
}
fn b_getconst(vm: &mut VM, _: u8) -> Value {
let encoded = name_of(&vm.pop());
for name in encoded.split('\u{1f}') {
let v = with_host(|h| h.get_const(name));
if !matches!(v, Value::Undef) || with_host(|h| h.has_const(name)) {
return v;
}
if with_host(|h| h.class_exists(name) || h.is_builtin_class(name))
|| (builtin_exception_const(name))
{
return with_host(|h| h.class_ref(name));
}
if let Some(path) = with_host(|h| h.take_autoload(name)) {
let pv = with_host(|h| h.new_string(path));
if let Err(e) = do_require(&[pv], ReqMode::Require) {
return abort(vm, e);
}
let v = with_host(|h| h.get_const(name));
if !matches!(v, Value::Undef) {
return v;
}
if with_host(|h| h.class_exists(name) || h.is_builtin_class(name)) {
return with_host(|h| h.class_ref(name));
}
}
if let Some((ns, cn)) = name.rsplit_once("::") {
let inherited = with_host(|h| {
for anc in h.class_ancestry(ns) {
if anc == ns {
continue;
}
let qualified = format!("{anc}::{cn}");
let val = h.get_const(&qualified);
if !matches!(val, Value::Undef) {
return val;
}
if h.class_exists(&qualified) {
return h.class_ref(&qualified);
}
}
Value::Undef
});
if !matches!(inherited, Value::Undef) {
return inherited;
}
}
}
match const_miss(&encoded) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn const_miss(encoded: &str) -> Result<Value, String> {
let first = encoded.split('\u{1f}').next().unwrap_or(encoded);
let (cref, bare) = first.rsplit_once("::").unwrap_or(("Object", first));
if let Some(def) = with_host(|h| h.find_class_method(cref, "const_missing")) {
let recv = with_host(|h| h.class_ref(cref));
let sym = with_host(|h| h.new_symbol(bare));
return crate::host::call_class_method(recv, &def, "const_missing", cref, &[sym], None);
}
let fields = with_host(|h| {
[
("name", h.new_symbol(bare)),
("receiver", h.class_ref(cref)),
]
});
Err(raise_exc_with(
"NameError",
&format!("uninitialized constant {first}"),
&fields,
))
}
fn is_builtin_exception(name: &str) -> bool {
name.ends_with("Error")
|| matches!(
name,
"Exception" | "StopIteration" | "SystemExit" | "SignalException" | "Interrupt"
)
|| name.starts_with("Errno::")
}
fn builtin_exception_const(name: &str) -> bool {
is_builtin_exception(name) && (!name.contains("::") || name.starts_with("Errno::"))
}
fn errno_of_class(cls: &str) -> Option<i32> {
let mut cur = Some(cls.to_string());
while let Some(name) = cur {
if name.starts_with("Errno::") {
return errno_table()
.iter()
.find(|(_, s)| *s == name)
.map(|(n, _)| *n);
}
cur = with_host(|h| h.superclass_of(&name));
}
None
}
fn strerror_text(code: i32) -> String {
let text = std::io::Error::from_raw_os_error(code).to_string();
text.split(" (os error").next().unwrap_or(&text).to_string()
}
fn errno_class(code: i32) -> Option<&'static str> {
errno_table()
.iter()
.find(|(n, _)| *n == code)
.map(|(_, s)| *s)
}
fn errno_table() -> &'static [(i32, &'static str)] {
const TABLE: &[(i32, &str)] = &[
(libc::EPERM, "Errno::EPERM"),
(libc::ENOENT, "Errno::ENOENT"),
(libc::ESRCH, "Errno::ESRCH"),
(libc::EINTR, "Errno::EINTR"),
(libc::EIO, "Errno::EIO"),
(libc::ENXIO, "Errno::ENXIO"),
(libc::E2BIG, "Errno::E2BIG"),
(libc::ENOEXEC, "Errno::ENOEXEC"),
(libc::EBADF, "Errno::EBADF"),
(libc::ECHILD, "Errno::ECHILD"),
(libc::ENOMEM, "Errno::ENOMEM"),
(libc::EACCES, "Errno::EACCES"),
(libc::EFAULT, "Errno::EFAULT"),
(libc::EBUSY, "Errno::EBUSY"),
(libc::EEXIST, "Errno::EEXIST"),
(libc::EXDEV, "Errno::EXDEV"),
(libc::ENODEV, "Errno::ENODEV"),
(libc::ENOTDIR, "Errno::ENOTDIR"),
(libc::EISDIR, "Errno::EISDIR"),
(libc::EINVAL, "Errno::EINVAL"),
(libc::ENFILE, "Errno::ENFILE"),
(libc::EMFILE, "Errno::EMFILE"),
(libc::ENOTTY, "Errno::ENOTTY"),
(libc::EFBIG, "Errno::EFBIG"),
(libc::ENOSPC, "Errno::ENOSPC"),
(libc::ESPIPE, "Errno::ESPIPE"),
(libc::EROFS, "Errno::EROFS"),
(libc::EMLINK, "Errno::EMLINK"),
(libc::EPIPE, "Errno::EPIPE"),
(libc::EDOM, "Errno::EDOM"),
(libc::ERANGE, "Errno::ERANGE"),
(libc::EAGAIN, "Errno::EAGAIN"),
(libc::ENAMETOOLONG, "Errno::ENAMETOOLONG"),
(libc::ENOTEMPTY, "Errno::ENOTEMPTY"),
(libc::ELOOP, "Errno::ELOOP"),
(libc::EADDRINUSE, "Errno::EADDRINUSE"),
(libc::ECONNREFUSED, "Errno::ECONNREFUSED"),
(libc::ECONNRESET, "Errno::ECONNRESET"),
(libc::ECONNABORTED, "Errno::ECONNABORTED"),
(libc::ENOTCONN, "Errno::ENOTCONN"),
(libc::ETIMEDOUT, "Errno::ETIMEDOUT"),
(libc::EHOSTUNREACH, "Errno::EHOSTUNREACH"),
(libc::ENETUNREACH, "Errno::ENETUNREACH"),
(libc::EAFNOSUPPORT, "Errno::EAFNOSUPPORT"),
(libc::EINPROGRESS, "Errno::EINPROGRESS"),
(libc::ENOTSOCK, "Errno::ENOTSOCK"),
];
TABLE
}
pub(crate) fn is_exception_class(cls: &str) -> bool {
if is_builtin_exception(cls) {
return true;
}
with_host(|h| {
let mut cur = h.superclass_of(cls);
while let Some(name) = cur {
if is_builtin_exception(&name) {
return true;
}
cur = h.superclass_of(&name);
}
false
})
}
fn b_setconst(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = name_of(&vm.pop());
let val = with_host(|h| match h.classref_name(&val) {
Some(cref) if cref.starts_with("#<") && h.struct_defs_contain(&cref) => {
h.rename_struct(&cref, &name);
h.rename_class(&cref, &name);
val.clone()
}
Some(cref) if h.is_anon_class(&cref) => {
h.rename_class(&cref, &name);
val.clone()
}
_ => val.clone(),
});
with_host(|h| h.set_const(&name, val.clone()));
val
}
fn b_defined(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
Value::Bool(with_host(|h| h.local_defined(&name)))
}
fn b_define_singleton(vm: &mut VM, _: u8) -> Value {
let synth = name_of(&vm.pop());
let name = name_of(&vm.pop());
let recv = vm.pop();
let Some(def) = with_host(|h| h.method_def(&synth)) else {
return abort(vm, format!("internal: missing method body '{synth}'"));
};
if let Err(e) = at_call_site(vm, None, || unchill(&recv)) {
return abort(vm, e);
}
if with_host(|h| h.classref_name(&recv).is_none() && h.is_frozen(&recv)) {
let (cls, insp) = with_host(|h| (h.class_of(&recv), h.inspect(&recv)));
return abort(
vm,
raise_exc_with(
"FrozenError",
&format!("can't modify frozen {cls}: {insp}"),
&[("receiver", recv.clone())],
),
);
}
with_host(|h| {
if let Some(cls) = h.classref_name(&recv) {
h.add_class_method(&cls, &name, def);
} else if let Value::Obj(id) = recv {
h.add_singleton_method(id, &name, def);
}
});
if let Err(e) = fire_method_hook(&recv, "singleton_method_added", &name) {
return abort(vm, e);
}
with_host(|h| h.new_symbol(&name))
}
fn b_define_method_dyn(vm: &mut VM, _: u8) -> Value {
let synth = name_of(&vm.pop());
let name = name_of(&vm.pop());
if let Some(target) = crate::host::apply_def_target(&name, &synth) {
let fired = match target {
crate::host::DefTarget::Instance(c) => fire_added_on(&c, &name),
crate::host::DefTarget::ClassMethod(c) => {
let recv = with_host(|h| h.class_ref(&c));
fire_method_hook(&recv, "singleton_method_added", &name)
}
crate::host::DefTarget::Singleton(id) => {
fire_method_hook(&Value::Obj(id), "singleton_method_added", &name)
}
crate::host::DefTarget::None => Ok(()),
};
if let Err(e) = fired {
return abort(vm, e);
}
} else if crate::host::is_main(&with_host(|h| h.current_self())) {
if let Err(e) = fire_added_on("Object", &name) {
return abort(vm, e);
}
}
with_host(|h| h.new_symbol(&name))
}
fn b_method_hook(vm: &mut VM, argc: u8) -> Value {
let vals = pop_n(vm, argc as usize);
let hook = name_of(&vals[0]);
let target = with_host(|h| h.current_self());
let names: Vec<String> = vals[1..].iter().map(name_of).collect();
if hook == "singleton_method_added" {
if let Some(cls) = with_host(|h| h.classref_name(&target)) {
with_host(|h| names.iter().for_each(|n| h.activate_hoisted_hook(&cls, n)));
}
} else if let Some(cls) = with_host(|h| h.classref_name(&target)) {
with_host(|h| names.iter().for_each(|n| h.reassert_hoisted_def(&cls, n)));
}
for n in &names {
if let Err(e) = fire_method_hook(&target, &hook, n) {
return abort(vm, e);
}
}
Value::Undef
}
pub(crate) fn fire_method_hook(target: &Value, hook: &str, name: &str) -> Result<(), String> {
let sym = with_host(|h| h.new_symbol(name));
if let Some(cls) = with_host(|h| h.classref_name(target)) {
if let Some((def, owner)) = with_host(|h| h.find_class_method_owner(&cls, hook)) {
crate::host::call_class_method(target.clone(), &def, hook, &owner, &[sym], None)?;
}
} else if hook == "singleton_method_added"
&& with_host(|h| h.find_singleton_method(target, hook)).is_some()
{
dispatch(target, hook, &[sym], None)?;
}
Ok(())
}
fn fire_added_on(cls: &str, name: &str) -> Result<(), String> {
match crate::host::RubyHost::metaclass_attached(cls) {
Some(attached) => {
let recv = with_host(|h| h.class_ref(attached));
fire_method_hook(&recv, "singleton_method_added", name)
}
None => {
let recv = with_host(|h| h.class_ref(cls));
fire_method_hook(&recv, "method_added", name)
}
}
}
fn b_fire_hook(vm: &mut VM, _: u8) -> Value {
let target = name_of(&vm.pop());
let hook = name_of(&vm.pop());
let module = name_of(&vm.pop());
let module = with_host(|h| {
if h.class_exists(&module) {
return module.clone();
}
let nested = format!("{target}::{module}");
if h.class_exists(&nested) {
return nested;
}
let mut prefix = target.as_str();
while let Some(idx) = prefix.rfind("::") {
prefix = &prefix[..idx];
let cand = format!("{prefix}::{module}");
if h.class_exists(&cand) {
return cand;
}
}
module.clone()
});
let feature = match hook.as_str() {
"included" => Some(("append_features", "include")),
"prepended" => Some(("prepend_features", "prepend")),
_ => None,
};
if let Some((feat, kind)) = feature {
if let Some(def) = with_host(|h| h.find_class_method(&module, feat)) {
with_host(|h| h.remove_mixin(&target, &module, kind));
let recv = with_host(|h| h.class_ref(&module));
let arg = with_host(|h| h.class_ref(&target));
if let Err(e) = crate::host::call_class_method(recv, &def, feat, &module, &[arg], None)
{
return abort(vm, e);
}
}
}
if let Some(def) = with_host(|h| h.find_class_method(&module, &hook)) {
let recv = with_host(|h| h.class_ref(&module));
let arg = with_host(|h| h.class_ref(&target));
if let Err(e) = crate::host::call_class_method(recv, &def, &hook, &module, &[arg], None) {
return abort(vm, e);
}
}
Value::Undef
}
fn b_call(vm: &mut VM, argc: u8) -> Value {
let mut vals = pop_n(vm, argc as usize);
let name = name_of(&vals.remove(0));
let this = with_host(|h| h.current_self());
match at_call_site(vm, None, || {
with_builtin_frame(&this, &name, &vals, dispatch_call(&name, &vals, None))
}) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn b_call_blk(vm: &mut VM, argc: u8) -> Value {
let mut vals = pop_n(vm, argc as usize);
let block = block_operand(vals.pop().unwrap_or(Value::Undef));
let owns = crate::host::take_block_literal();
let name = name_of(&vals.remove(0));
let home = owns
.then(|| crate::host::enter_block_home(block.as_ref()))
.flatten();
let site = block
.as_ref()
.map(|_| (with_host(|h| h.current_self()), name.as_str()));
let this = with_host(|h| h.current_self());
let out = at_call_site(vm, site, || {
with_builtin_frame(&this, &name, &vals, dispatch_call(&name, &vals, block))
});
crate::host::leave_block_home(home);
match out {
Ok(v) => finish_block_call(vm, owns, v),
Err(e) => abort(vm, e),
}
}
fn b_call_method(vm: &mut VM, argc: u8) -> Value {
let mut vals = pop_n(vm, argc as usize);
let recv = vals.remove(0);
let name = name_of(&vals.remove(0));
if let Err(e) = check_visibility(&recv, &name) {
return abort(vm, e);
}
match at_call_site(vm, None, || {
with_builtin_frame(&recv, &name, &vals, dispatch(&recv, &name, &vals, None))
}) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn b_call_method_blk(vm: &mut VM, argc: u8) -> Value {
let mut vals = pop_n(vm, argc as usize);
let block = block_operand(vals.pop().unwrap_or(Value::Undef));
let owns = crate::host::take_block_literal();
let recv = vals.remove(0);
let name = name_of(&vals.remove(0));
if let Err(e) = check_visibility(&recv, &name) {
return abort(vm, e);
}
let home = owns
.then(|| crate::host::enter_block_home(block.as_ref()))
.flatten();
let site = block.as_ref().map(|_| (recv.clone(), name.as_str()));
let out = at_call_site(vm, site, || {
with_builtin_frame(&recv, &name, &vals, dispatch(&recv, &name, &vals, block))
});
crate::host::leave_block_home(home);
match out {
Ok(v) => finish_block_call(vm, owns, v),
Err(e) => abort(vm, e),
}
}
fn b_mkstr(vm: &mut VM, argc: u8) -> Value {
let parts = pop_n(vm, argc as usize);
if parts
.iter()
.any(|p| with_host(|h| h.as_str(p).is_some() && h.string_encoding(p).is_some()))
{
return match join_string_bytes(&parts) {
Ok(v) => v,
Err(e) => abort(vm, e),
};
}
let mut s = String::new();
for p in &parts {
s.push_str(&display(p));
}
with_host(|h| h.new_string(s))
}
fn b_mkstrf(vm: &mut VM, argc: u8) -> Value {
let s = b_mkstr(vm, argc);
with_host(|h| h.freeze_value(&s));
s
}
fn b_mkstrc(vm: &mut VM, argc: u8) -> Value {
let s = b_mkstr(vm, argc);
with_host(|h| h.mark_chilled(&s));
s
}
fn b_mksym(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
with_host(|h| h.new_symbol(&name))
}
fn b_mkarray(vm: &mut VM, argc: u8) -> Value {
let items = pop_n(vm, argc as usize);
with_host(|h| h.new_array(items))
}
fn b_mkhash(vm: &mut VM, argc: u8) -> Value {
let vals = pop_n(vm, argc as usize);
let keys: Vec<Value> = vals
.chunks_exact(2)
.map(|p| p[0].clone())
.filter(|k| with_host(|h| h.user_hash_candidate(k)))
.collect();
if !keys.is_empty() {
if let Err(e) = canon_user_keys(&keys) {
return abort(vm, e);
}
}
with_host(|h| {
let mut m = IndexMap::new();
for pair in vals.chunks_exact(2) {
let key = h.value_to_key(&pair[0]);
m.insert(key, pair[1].clone());
}
h.new_hash(m)
})
}
fn b_mkrange(vm: &mut VM, _: u8) -> Value {
let excl = vm.pop();
let hi = vm.pop();
let lo = vm.pop();
match make_range(&lo, &hi, matches!(excl, Value::Bool(true))) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
pub(crate) fn make_range(lo: &Value, hi: &Value, excl: bool) -> Result<Value, String> {
let numeric = |v: &Value| matches!(v, Value::Int(_) | Value::Float(_));
let lo = &match lo {
Value::Int(crate::host::RANGE_BEGINLESS) if !numeric(hi) => Value::Undef,
Value::Undef if matches!(hi, Value::Int(_)) => Value::Int(crate::host::RANGE_BEGINLESS),
_ => lo.clone(),
};
let hi = &match hi {
Value::Int(crate::host::RANGE_ENDLESS) if !numeric(lo) => Value::Undef,
Value::Undef if matches!(lo, Value::Int(_)) => Value::Int(crate::host::RANGE_ENDLESS),
_ => hi.clone(),
};
let bound = |v: &Value, endless_sentinel: i64| -> Option<i64> {
match v {
Value::Int(n) => Some(*n),
Value::Float(f) if f.is_infinite() => Some(endless_sentinel),
_ => None,
}
};
if let (Some(a), Some(b)) = (
bound(lo, crate::host::RANGE_BEGINLESS),
bound(hi, crate::host::RANGE_ENDLESS),
) {
return Ok(with_host(|h| h.new_range(a, b, excl)));
}
Ok(match (lo, hi) {
(Value::Int(a), Value::Int(b)) => with_host(|h| h.new_range(*a, *b, excl)),
(Value::Float(_), Value::Float(_)) => {
with_host(|h| h.new_float_range(as_f(lo), as_f(hi), excl))
}
(Value::Float(_) | Value::Int(_), Value::Float(_) | Value::Int(_)) => {
with_host(|h| h.new_obj_range(lo.clone(), hi.clone(), excl))
}
_ => {
let ls = with_host(|h| h.as_str(lo));
let hs = with_host(|h| h.as_str(hi));
match (ls, hs) {
(Some(a), Some(b)) => with_host(|h| h.new_str_range(a, b, excl)),
_ => {
if !matches!(lo, Value::Undef) && !matches!(hi, Value::Undef) {
let cmp = probe_dispatch(lo, "<=>", std::slice::from_ref(hi));
if matches!(cmp, None | Some(Value::Undef)) {
return Err(raise_exc("ArgumentError", "bad value for range"));
}
}
with_host(|h| h.new_obj_range(lo.clone(), hi.clone(), excl))
}
}
}
})
}
fn b_mkproc(vm: &mut VM, _: u8) -> Value {
let id = match vm.pop() {
Value::Int(n) => n as usize,
_ => return abort(vm, "bad proc id".into()),
};
crate::host::mark_block_literal();
with_host(|h| h.new_proc(id))
}
fn b_mklambda(vm: &mut VM, _: u8) -> Value {
let id = match vm.pop() {
Value::Int(n) => n as usize,
_ => return abort(vm, "bad proc id".into()),
};
with_host(|h| h.new_lambda(id))
}
fn b_mkregex(vm: &mut VM, _: u8) -> Value {
let site = match vm.pop() {
Value::Int(n) if n > 0 => Some(n),
_ => None,
};
let flags = name_of(&vm.pop());
let source = name_of(&vm.pop());
if let Some(re) = site.and_then(|n| with_host(|h| h.regex_site(n))) {
return re;
}
match with_host(|h| h.new_regex(&source, &flags)) {
Ok(v) => {
with_host(|h| {
h.freeze_value(&v);
if let Some(n) = site {
h.set_regex_site(n, v.clone());
}
});
v
}
Err(e) => abort(vm, e),
}
}
fn b_regex_once(vm: &mut VM, _: u8) -> Value {
match vm.pop() {
Value::Int(n) if n > 0 => with_host(|h| h.regex_site(n)).unwrap_or(Value::Undef),
_ => Value::Undef,
}
}
fn b_yield(vm: &mut VM, argc: u8) -> Value {
let args = pop_n(vm, argc as usize);
let Some(block) = current_block() else {
let e = raise_exc_with(
"LocalJumpError",
"no block given (yield)",
&[("reason", with_host(|h| h.new_symbol("noreason")))],
);
return abort(vm, e);
};
match at_call_site(vm, None, || call_proc(&block, &args)) {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn b_truthy(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
Value::Bool(with_host(|h| h.truthy(&v)))
}
fn b_tostr(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
with_host(|h| {
let s = h.to_s(&v);
h.new_string(s)
})
}
fn b_index_get(vm: &mut VM, argc: u8) -> Value {
let mut vals = pop_n(vm, argc as usize);
let recv = vals.remove(0);
match at_call_site(vm, None, || {
with_builtin_frame(&recv, "[]", &vals, dispatch(&recv, "[]", &vals, None))
}) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn b_index_set(vm: &mut VM, argc: u8) -> Value {
let mut vals = pop_n(vm, argc as usize);
let recv = vals.remove(0);
match at_call_site(vm, None, || {
with_builtin_frame(&recv, "[]=", &vals, dispatch(&recv, "[]=", &vals, None))
}) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn b_sig_break(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
crate::host::mark_lexical_break();
raise_signal_break(v);
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn b_sig_next(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
raise_signal_next(v);
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn b_sig_return(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
raise_signal_return(v);
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn b_sig_retry(vm: &mut VM, _: u8) -> Value {
vm.pop(); raise_signal_retry();
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn b_sig_redo(vm: &mut VM, _: u8) -> Value {
vm.pop(); raise_signal_redo();
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn dispatch_call(name: &str, args: &[Value], block: Option<Value>) -> Result<Value, String> {
if name == "__rust_compile" {
let b64 = args
.first()
.and_then(|v| with_host(|h| h.as_str(v)))
.unwrap_or_default();
return fusevm::ffi::compile_and_register(&b64).map(|_| Value::Undef);
}
let this = with_host(|h| h.current_self());
if name == "alias_method" && args.len() >= 2 && crate::host::is_main(&this) {
let (new_name, old_name) = (name_of(&args[0]), name_of(&args[1]));
let done = with_host(|h| h.alias_top_level_method(&new_name, &old_name));
if !done {
with_host(|h| h.register_alias("Object", &new_name, &old_name));
}
return Ok(with_host(|h| h.new_symbol(&new_name)));
}
if name == "autoload" && args.len() >= 2 {
let const_name = name_of(&args[0]);
let path = with_host(|h| h.as_str(&args[1])).unwrap_or_default();
let full = match with_host(|h| h.classref_name(&this)) {
Some(cls) => format!("{cls}::{const_name}"),
None => const_name,
};
with_host(|h| h.set_autoload(&full, &path));
return Ok(Value::Undef);
}
if name == "autoload?" && !args.is_empty() {
let const_name = name_of(&args[0]);
let full = match with_host(|h| h.classref_name(&this)) {
Some(cls) => format!("{cls}::{const_name}"),
None => const_name,
};
return Ok(with_host(|h| match h.autoload_path(&full) {
Some(p) => h.new_string(p),
None => Value::Undef,
}));
}
if name == "define_method" && crate::host::is_main(&this) {
let object = with_host(|h| h.class_ref("Object"));
return dispatch(&object, "define_method", args, block);
}
if name == "include" && !args.is_empty() && crate::host::is_main(&this) {
let object = with_host(|h| h.class_ref("Object"));
return dispatch(&object, "include", args, block);
}
if let Some(cls) = with_host(|h| h.classref_name(&this)) {
if name == "define_method" {
let mname = name_of(&args[0]);
let proc = block.or_else(|| args.get(1).cloned()).ok_or_else(|| {
raise_exc(
"ArgumentError",
"tried to create Proc object without a block",
)
})?;
with_host(|h| h.add_define_method(&cls, &mname, proc));
if let Some(attached) = crate::host::RubyHost::metaclass_attached(&cls) {
let attached = attached.to_string();
with_host(|h| h.remove_class_method(&attached, &mname));
}
fire_added_on(&cls, &mname)?;
return Ok(with_host(|h| h.new_symbol(&mname)));
}
if name == "alias_method" && args.len() >= 2 {
let (new_name, old_name) = (name_of(&args[0]), name_of(&args[1]));
with_host(|h| h.register_alias(&cls, &new_name, &old_name));
fire_added_on(&cls, &new_name)?;
return Ok(with_host(|h| h.new_symbol(&new_name)));
}
if matches!(name, "include" | "prepend" | "extend") && !args.is_empty() {
return dispatch(&this, name, args, block);
}
if matches!(name, "class_eval" | "module_eval") {
return dispatch(&this, name, args, block);
}
if matches!(
name,
"method_defined?"
| "public_method_defined?"
| "private_method_defined?"
| "protected_method_defined?"
| "instance_methods"
| "public_instance_methods"
| "private_instance_methods"
| "instance_method"
| "const_defined?"
| "const_get"
| "const_set"
| "remove_const"
| "class_variable_get"
| "class_variable_set"
| "class_variable_defined?"
| "class_variables"
) && !args.is_empty()
{
return dispatch(&this, name, args, block);
}
if is_universal_object_method(name) {
return dispatch(&this, name, args, block);
}
if matches!(name, "undef" | "undef_method" | "remove_method") && !args.is_empty() {
for a in args {
let m = name_of(a);
with_host(|h| h.remove_instance_method(&cls, &m));
}
return Ok(Value::Undef);
}
if matches!(
name,
"attr" | "attr_accessor" | "attr_reader" | "attr_writer"
) {
let reader = name != "attr_writer";
let writer = matches!(name, "attr_accessor" | "attr_writer");
for a in args {
if matches!(a, Value::Bool(_)) {
continue; }
let field = name_of(a);
with_host(|h| h.add_attr(&cls, &field, reader, writer));
}
return Ok(Value::Undef);
}
if matches!(
name,
"private"
| "public"
| "protected"
| "module_function"
| "private_constant"
| "public_constant"
| "private_class_method"
| "public_class_method"
| "deprecate_constant"
| "ruby2_keywords"
) {
if name == "module_function" && args.is_empty() {
if let Some(cls) = with_host(|h| h.classref_name(&h.current_self())) {
with_host(|h| h.mark_module_function(&cls));
}
}
if let Some(vis) = visibility_directive(name) {
for a in args {
let m = name_of(a);
with_host(|h| h.set_method_visibility(&cls, &m, vis));
}
}
if let Some(vis) = class_visibility_directive(name) {
for a in args {
let m = name_of(a);
with_host(|h| h.set_class_method_visibility(&cls, &m, vis));
}
}
let this = with_host(|h| h.current_self());
return Ok(directive_result(name, &this, args));
}
if name == "new"
|| matches!(
name,
"name"
| "to_s"
| "inspect"
| "singleton_class"
| "instance_methods"
| "public_instance_methods"
| "private_instance_methods"
| "class_variables"
| "constants"
| "ancestors"
| "superclass"
| "refine"
| "using"
| "import_methods"
)
|| with_host(|h| h.class_responds_to(&cls, name))
{
return dispatch_classref(&cls, name, args, block);
}
if with_host(|h| h.has_method(name)) {
return call_method(name, args, block);
}
if let Some(nat) = with_host(|h| h.native_kernel_alias(&cls, name)) {
return kernel(&nat, args, block);
}
return kernel(name, args, block);
}
if with_host(|h| {
h.find_singleton_method(&this, name).is_some()
|| h.find_singleton_define_method(&this, name).is_some()
}) {
return dispatch(&this, name, args, block);
}
if let Some(cls) = with_host(|h| h.object_class(&this)) {
if with_host(|h| h.find_define_method(&cls, name)).is_some()
|| is_universal_object_method(name)
|| with_host(|h| h.attr_access(&cls, name)).is_some()
|| with_host(|h| h.find_method_owner(&cls, name)).is_some()
|| (!is_kernel_function(name)
&& with_host(|h| h.find_method_owner(&cls, "method_missing")).is_some())
{
return dispatch(&this, name, args, block);
}
if let Some((members, _)) = with_host(|h| h.struct_def(&cls)) {
let member = name.strip_suffix('=').unwrap_or(name);
if members.iter().any(|m| m == member) {
return dispatch(&this, name, args, block);
}
}
if let Some(r) = native_self_call(&this, name, args, block.clone()) {
return r;
}
}
if with_host(|h| h.object_class(&this).is_none() && h.classref_name(&this).is_none()) {
match dispatch(&this, name, args, block.clone()) {
Ok(v) => return Ok(v),
Err(e) if e.starts_with("undefined method") => {}
Err(e) => return Err(e),
}
}
let self_cls = with_host(|h| h.class_of(&this));
if let Some(nat) = with_host(|h| h.native_kernel_alias(&self_cls, name)) {
return kernel(&nat, args, block);
}
if with_host(|h| h.responds_to(name)) {
return call_method(name, args, block);
}
if fusevm::ffi::is_registered(name) {
let marshalled: Vec<Value> = args
.iter()
.map(|v| match with_host(|h| h.as_str(v)) {
Some(s) => Value::str(s),
None => v.clone(),
})
.collect();
if let Some(r) = fusevm::ffi::try_call(name, &marshalled) {
return r;
}
}
kernel(name, args, block)
}
fn method_object_or_name_error(recv: &Value, m: &str, unbound: bool) -> Result<(), String> {
if with_host(|h| h.method_defined_on(recv, m, unbound)) {
return Ok(());
}
if !unbound {
if let Some(def) = with_host(|h| h.find_singleton_method(recv, "respond_to_missing?")) {
let sym = with_host(|h| h.new_symbol(m));
let r = crate::host::call_singleton(
recv.clone(),
&def,
"respond_to_missing?",
&[sym, Value::Bool(true)],
None,
)?;
if with_host(|h| h.truthy(&r)) {
return Ok(());
}
} else if let Some(cls) = with_host(|h| h.object_class(recv)) {
if with_host(|h| h.find_method_owner(&cls, "respond_to_missing?")).is_some() {
let sym = with_host(|h| h.new_symbol(m));
let r = call_instance_method(
recv.clone(),
&cls,
"respond_to_missing?",
&[sym, Value::Bool(true)],
None,
)?;
if with_host(|h| h.truthy(&r)) {
return Ok(());
}
}
}
}
let (lookup, word) = with_host(|h| {
let lookup = h.method_lookup_class(recv, unbound);
let word = h.class_or_module_word(&lookup);
(lookup, word)
});
Err(raise_exc(
"NameError",
&format!("undefined method '{m}' for {word} '{lookup}'"),
))
}
fn native_self_call(
this: &Value,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Option<Result<Value, String>> {
const FRAME_SENSITIVE: &[&str] = &[
"binding",
"caller",
"caller_locations",
"__method__",
"__callee__",
"__dir__",
"local_variables",
"iterator?",
];
if is_kernel_function(name) || FRAME_SENSITIVE.contains(&name) {
return None;
}
match dispatch(this, name, args, block) {
Err(e)
if e.starts_with(&format!("undefined method '{name}' for"))
|| e.starts_with(&format!("private method '{name}' called")) =>
{
with_host(|h| h.take_pending_exc());
None
}
r => Some(r),
}
}
fn ivar_name_arg(arg: &Value) -> Result<String, String> {
let Some(raw) = with_host(|h| h.as_str(arg).or_else(|| h.as_symbol(arg))) else {
let shown = with_host(|h| h.inspect(arg));
return Err(raise_exc(
"TypeError",
&format!("{shown} is not a symbol nor a string"),
));
};
let ident = |c: char| c.is_alphanumeric() || c == '_' || !c.is_ascii();
let valid = raw.strip_prefix('@').is_some_and(|rest| {
rest.chars().next().is_some_and(|c| !c.is_ascii_digit()) && rest.chars().all(ident)
});
if valid {
return Ok(raw[1..].to_string());
}
Err(raise_exc_with(
"NameError",
&format!("'{raw}' is not allowed as an instance variable name"),
&[("name", arg.clone())],
))
}
const ACCURATE_RESPOND_CLASSES: &[&str] = &[
"Integer",
"Float",
"Rational",
"Complex",
"String",
"Symbol",
"Array",
"Hash",
"Range",
"Regexp",
"MatchData",
"Set",
];
const CORE_EXTENDING_LIBS: &[&str] = &[
"json",
"json/ext",
"bigdecimal",
"bigdecimal/util",
"csv",
"shellwords",
"yaml",
"psych",
"date",
"time",
"prime",
"abbrev",
"active_support",
"erb",
"cgi",
"uri",
"optparse",
"io/console",
"pathname",
];
fn builtin_responds(recv: &Value, name: &str, include_all: Option<&Value>) -> Option<bool> {
let include_all = include_all.is_some_and(|a| with_host(|h| h.truthy(a)));
if CHAIN_UNDEFINED.contains(&name) && with_host(|h| h.enum_chain_parts(recv).is_some()) {
return Some(false);
}
let Some(owner) = with_host(|h| h.builtin_owner(recv, name)) else {
let module_only = ["Module", "Class"]
.iter()
.any(|o| crate::arity_table::lookup(o, name).is_some());
let plain_value = with_host(|h| h.classref_name(recv).is_none())
&& !crate::host::is_main(recv)
&& with_host(|h| h.find_method("Object", name).is_none());
return (module_only && plain_value).then_some(false);
};
Some(include_all || !crate::private_builtins::is_private(owner, name))
}
fn is_universal_object_method(name: &str) -> bool {
matches!(
name,
"instance_variable_get"
| "instance_variable_set"
| "instance_variables"
| "instance_variable_defined?"
| "remove_instance_variable"
| "send"
| "__send__"
| "public_send"
| "respond_to?"
| "method"
| "is_a?"
| "kind_of?"
| "instance_of?"
| "tap"
| "then"
| "yield_self"
| "itself"
| "freeze"
| "frozen?"
| "dup"
| "clone"
| "methods"
| "singleton_methods"
| "singleton_class"
| "enum_for"
| "to_enum"
| "instance_eval"
| "instance_exec"
| "define_singleton_method"
)
}
fn eval_target(recv: &Value, instance: bool) -> crate::host::DefTarget {
use crate::host::DefTarget;
if let Some(cls) = with_host(|h| h.classref_name(recv)) {
if instance {
DefTarget::ClassMethod(cls)
} else {
DefTarget::Instance(cls)
}
} else if let Value::Obj(id) = recv {
DefTarget::Singleton(*id)
} else {
DefTarget::None
}
}
pub(crate) fn dispatch_by_type(
class: &str,
recv: &Value,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
if name == "chain" && CHAIN_RECEIVERS.contains(&class) {
return Ok(make_enum_chain(recv, args));
}
if class == "Enumerator::Lazy" && (name == "chain" || (name == "+" && args.len() == 1)) {
return dispatch(&make_enum_chain(recv, args), "lazy", &[], None);
}
if name == "+"
&& args.len() == 1
&& matches!(
class,
"Enumerator" | "Enumerator::ArithmeticSequence" | "Enumerator::Chain"
)
{
return Ok(make_enum_chain(recv, args));
}
match class {
"Integer" | "Float" => dispatch_number(recv, name, args, block),
"String" => dispatch_string(recv, name, args, block),
"Array" => dispatch_array(recv, name, args, block),
"Hash" => dispatch_hash(recv, name, args, block),
"Range" => dispatch_range(recv, name, args, block),
"Symbol" => dispatch_symbol(recv, name, args),
"Proc" => dispatch_proc(recv, name, args, block),
"Method" | "UnboundMethod" => dispatch_method(recv, name, args, block),
"Regexp" => dispatch_regexp(recv, name, args, block),
"MatchData" => dispatch_matchdata(recv, name, args),
"Set" => dispatch_set(recv, name, args, block),
"Time" => dispatch_time(recv, name, args),
"Binding" => dispatch_binding(recv, name, args),
"Date" => dispatch_date(recv, name, args),
"DateTime" => dispatch_datetime(recv, name, args),
"Enumerator" => dispatch_enumerator(recv, name, args, block),
"Enumerator::ArithmeticSequence" => dispatch_arith_seq(recv, name, args, block),
"Enumerator::Chain" => dispatch_enum_chain(recv, name, args, block),
"Fiber" => dispatch_fiber(recv, name, args),
"Thread" => dispatch_thread(recv, name, args),
"IO" | "File" => dispatch_io(recv, name, args, block),
"TCPServer" => dispatch_tcp_server(recv, name, args, block),
"TCPSocket" => dispatch_tcp_socket(recv, name, args, block),
"SQLite3::Database" => dispatch_sqlite_db(recv, name, args, block),
"Fiddle::Handle" => dispatch_fiddle_handle(recv, name, args),
"Fiddle::Function" => dispatch_fiddle_function(recv, name, args),
"Fiddle::Pointer" => dispatch_fiddle_pointer(recv, name, args),
"Enumerator::Lazy" => dispatch_lazy(recv, name, args, block),
"Enumerator::Yielder" => dispatch_yielder(recv, name, args),
"Rational" => dispatch_rational(recv, name, args),
"Complex" => dispatch_complex(recv, name, args),
"TrueClass" | "FalseClass" | "NilClass" => dispatch_bool(recv, name, args),
_ => Err(no_method_error(recv, name)),
}
}
fn check_builtin_arity(
recv: &Value,
name: &str,
args: &[Value],
block: Option<&Value>,
) -> Result<(), String> {
if matches!(name, "[]" | "new" | "members" | "keyword_init?")
&& with_host(|h| {
h.classref_name(recv)
.is_some_and(|c| h.struct_def(&c).is_some())
})
{
return Ok(());
}
let Some(owner) = with_host(|h| h.builtin_owner(recv, name)) else {
return Ok(());
};
let has_block = block.is_some();
if args.is_empty() {
if let Some((no_block, with_block)) = crate::arity_table::zero_arg_error(owner, name) {
let msg = if has_block { with_block } else { no_block };
if !msg.is_empty() {
return Err(raise_exc("ArgumentError", msg));
}
}
}
let Some((min, max, expected, block_min, block_max, block_expected, keywords)) =
crate::arity_table::arg_shape(owner, name)
else {
return Ok(());
};
let (min, max, expected) = if !has_block {
(min, max, expected)
} else if min < 0 || block_min < 0 {
return Ok(());
} else {
let widest = if max < 0 || block_max < 0 {
-1
} else {
max.max(block_max)
};
let expected = if block_min < min || widest > max {
block_expected
} else {
expected
};
(min.min(block_min), widest, expected)
};
if min < 0 || expected.is_empty() {
return Ok(());
}
let given = args.len() as i16;
let fits = |n: i16| n >= min && (max < 0 || n <= max);
if fits(given) {
return Ok(());
}
if keywords
&& given > 0
&& with_host(|h| h.as_hash(args.last().unwrap()).is_some())
&& fits(given - 1)
{
return Ok(());
}
Err(raise_exc(
"ArgumentError",
&format!("wrong number of arguments (given {given}, expected {expected})"),
))
}
fn run_copy_hook(copy: &Value, orig: &Value, specific: &str) -> Result<(), String> {
let Some(cls) = with_host(|h| h.object_class(copy)) else {
return Ok(());
};
let defined = |m: &str| {
with_host(|h| {
h.find_method_owner(&cls, m).is_some() || h.find_define_method(&cls, m).is_some()
})
};
let hook = if defined(specific) {
specific
} else if defined("initialize_copy") {
"initialize_copy"
} else {
return Ok(());
};
dispatch(copy, hook, std::slice::from_ref(orig), None).map(|_| ())
}
fn top_level_method_for(recv: &Value, m: &str) -> Option<crate::host::MethodDef> {
let visible = with_host(|h| {
if h.find_singleton_method(recv, m).is_some()
|| h.find_singleton_define_method(recv, m).is_some()
{
return true;
}
let cls = h.object_class(recv).unwrap_or_else(|| h.class_of(recv));
h.find_method_owner(&cls, m).is_some() || h.find_define_method(&cls, m).is_some()
});
if visible {
return None;
}
with_host(|h| h.method_def(m))
}
fn canon_user_keys(vals: &[Value]) -> Result<(), String> {
for v in vals {
let Value::Obj(id) = v else {
continue;
};
let hv = dispatch(v, "hash", &[], None)?;
let hk = match hv {
Value::Int(n) => n,
other => with_host(|h| h.value_hash(&other)),
};
let mut rep = *id;
for r in with_host(|h| h.user_key_reps(hk)) {
if r == *id {
break;
}
let same = dispatch(v, "eql?", &[Value::Obj(r)], None)?;
if with_host(|h| h.truthy(&same)) {
rep = r;
break;
}
}
with_host(|h| h.set_user_key_canon(*id, rep, hk));
}
Ok(())
}
pub(crate) fn dispatch(
recv: &Value,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
match dispatch_resolved(recv, name, args, block.clone()) {
Err(e)
if is_kernel_module_function_of(recv, name)
&& e == format!("undefined method '{name}' for {}", receiver_phrase(recv)) =>
{
with_host(|h| h.take_pending_exc());
kernel(name, args, block)
}
r => tag_ascii_repr(r, recv, name),
}
}
const ASCII_REPR_CLASSES: &[&str] = &[
"NilClass",
"TrueClass",
"FalseClass",
"Integer",
"Float",
"Symbol",
"Rational",
"Complex",
"Class",
"Module",
];
fn ascii_repr_receiver(h: &RubyHost, v: &Value, depth: usize) -> bool {
if depth > 8 {
return false;
}
if ASCII_REPR_CLASSES.contains(&h.class_of(v).as_str()) {
return true;
}
if let Some(items) = h.as_array(v) {
return items.iter().all(|e| ascii_repr_receiver(h, e, depth + 1));
}
if let Some(map) = h.as_hash(v) {
return map.iter().all(|(k, e)| {
matches!(
k,
RKey::Int(_) | RKey::FloatBits(_) | RKey::Bool(_) | RKey::Nil | RKey::Sym(_)
) && ascii_repr_receiver(h, e, depth + 1)
});
}
if let Some((lo, hi, _)) = h.as_obj_range(v) {
return ascii_repr_receiver(h, &lo, depth + 1) && ascii_repr_receiver(h, &hi, depth + 1);
}
h.as_range(v).is_some() || h.as_float_range(v).is_some()
}
fn tag_ascii_repr(r: Result<Value, String>, recv: &Value, name: &str) -> Result<Value, String> {
if !matches!(name, "to_s" | "inspect" | "name") {
return r;
}
if let Ok(v) = &r {
with_host(|h| {
let ascii = h.as_str(v).is_some_and(|s| s.is_ascii());
if ascii && h.string_encoding(v).is_none() && ascii_repr_receiver(h, recv, 0) {
h.set_string_encoding(v, "US-ASCII");
}
});
}
r
}
fn dispatch_resolved(
recv: &Value,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
let keyed = with_host(|h| h.user_keyed_operands(recv, name, args));
if !keyed.is_empty() {
canon_user_keys(&keyed)?;
}
enum Owner {
Singleton(Box<crate::host::MethodDef>),
SingletonProc(Value),
DefineMethod(Value),
UserMethod,
Builtin,
Refined(Box<crate::host::MethodDef>, String),
}
let (owner, cls) = with_host(|h| {
if let Some(def) = h.find_singleton_method(recv, name) {
return (Owner::Singleton(Box::new(def)), String::new());
}
if let Some(p) = h.find_singleton_define_method(recv, name) {
return (Owner::SingletonProc(p), String::new());
}
if h.refinements_active() {
if let Some((def, refname)) = h.find_refined_method(recv, name) {
return (Owner::Refined(Box::new(def), refname), String::new());
}
}
let cls = h.object_class(recv).unwrap_or_else(|| h.class_of(recv));
if h.has_own_define_method(&cls, name) && !h.has_own_method(&cls, name) {
if let Some(p) = h.find_define_method(&cls, name) {
return (Owner::DefineMethod(p), cls);
}
}
if h.classref_name(recv).is_none() && h.find_method_owner(&cls, name).is_some() {
return (Owner::UserMethod, cls);
}
(Owner::Builtin, cls)
});
match owner {
Owner::Singleton(def) => {
return crate::host::call_singleton(recv.clone(), &def, name, args, block)
}
Owner::SingletonProc(p) => return crate::host::call_proc_self(&p, args, Some(recv)),
Owner::Refined(def, refname) => {
return crate::host::call_class_method(recv.clone(), &def, name, &refname, args, block)
}
Owner::DefineMethod(p) => {
return crate::host::call_proc_self_ctx(
&p,
args,
Some(recv),
Some((name.to_string(), cls)),
block,
)
}
Owner::UserMethod => return call_instance_method(recv.clone(), &cls, name, args, block),
Owner::Builtin => {}
}
check_builtin_arity(recv, name, args, block.as_ref())?;
match name {
"to_s" if args.is_empty() && is_container(recv) && reaches_user_inspect(recv, 0) => {
return Ok(new_str(inspect_of(recv)?));
}
"to_s" | "to_str" if args.is_empty() && with_host(|h| h.rstr(recv).is_some()) => {
return Ok(with_host(|h| {
if h.class_of(recv) == "String" {
return recv.clone();
}
let content = h
.rstr(recv)
.cloned()
.unwrap_or(crate::rstr::RStr::Text(String::new()));
h.new_rstr(content)
}));
}
"to_s" if args.is_empty() => {
return Ok(with_host(|h| {
let s = h.to_s(recv);
let tagged = h.string_encoding(recv).is_some();
let ascii = tagged && s.is_ascii();
let from_string = tagged && h.dispatch_class(recv) == "String";
let out = h.new_string(s);
if from_string {
h.inherit_string_encoding(&out, recv, ascii);
}
if matches!(recv, Value::Undef | Value::Bool(_)) {
h.freeze_value(&out);
} else if let Some(sym) = h.as_symbol(recv) {
h.mark_chilled_symbol(&out, &sym);
}
out
}));
}
"inspect" => return Ok(new_str(inspect_of(recv)?)),
"class" => {
return Ok(with_host(|h| {
let name = h.class_of(recv).to_string();
h.class_ref(&name)
}));
}
"nil?" => return Ok(Value::Bool(matches!(recv, Value::Undef))),
"==" | "eql?" | "hash" if with_host(|h| h.as_method(recv).is_some()) => {
return dispatch_method(recv, name, args, block);
}
"hash" if args.is_empty() => return Ok(Value::Int(with_host(|h| h.value_hash(recv)))),
"to_json" => {
return match with_host(|h| json_encode(h, recv)) {
Ok(s) => Ok(new_str(s)),
Err(e) => Err(raise_exc("JSON::GeneratorError", &e)),
};
}
"==" => return Ok(Value::Bool(eq_fallback(recv, &args[0])?)),
"!=" => return Ok(Value::Bool(!rb_equal_d(recv, &args[0])?)),
"eql?" if args.len() == 1 => {
return Ok(Value::Bool(with_host(|h| h.eql_values(recv, &args[0]))));
}
"===" => {
if with_host(|h| h.class_of(recv)) == "Proc" {
return crate::host::call_proc_block(recv, args, block);
}
if let Some(cls) = with_host(|h| h.classref_name(recv)) {
return Ok(Value::Bool(with_host(|h| h.is_a(&args[0], &cls))));
}
if let Some((re, _)) = with_host(|h| h.as_regex(recv)) {
let matchable =
with_host(|h| h.as_str(&args[0]).is_some() || h.as_symbol(&args[0]).is_some());
if !matchable {
set_match_globals(None, &re, recv);
return Ok(Value::Bool(false));
}
let hit = dispatch_regexp(recv, "=~", args, None)?;
return Ok(Value::Bool(!matches!(hit, Value::Undef)));
}
if let Some((lo, hi, excl)) = with_host(|h| h.as_range(recv)) {
let n = as_i(&args[0]);
let below = if hi == crate::host::RANGE_ENDLESS {
true
} else if excl {
n < hi
} else {
n <= hi
};
return Ok(Value::Bool(n >= lo && below));
}
if let Some((lo, hi, excl)) = with_host(|h| h.as_float_range(recv)) {
let x = as_f(&args[0]);
return Ok(Value::Bool(if excl {
x >= lo && x < hi
} else {
x >= lo && x <= hi
}));
}
if with_host(|h| h.is_str_or_obj_range(recv)) {
return dispatch(recv, "cover?", args, None);
}
return Ok(Value::Bool(with_host(|h| h.eq_values(recv, &args[0]))));
}
"is_a?" | "kind_of?" => {
let cls = name_of(&args[0]);
return Ok(Value::Bool(with_host(|h| h.is_a(recv, &cls))));
}
"instance_of?" => {
let cls = name_of(&args[0]);
return Ok(Value::Bool(with_host(|h| h.class_of(recv)) == cls));
}
"itself" => return Ok(recv.clone()),
"display" if args.len() <= 1 => {
let port = match args.first() {
Some(p) => p.clone(),
None => with_host(|h| h.get_global("stdout")),
};
if matches!(port, Value::Undef) {
let text = dispatch(recv, "to_s", &[], None)?;
crate::host::write_stdout(&with_host(|h| h.to_s(&text)));
} else {
dispatch(&port, "write", std::slice::from_ref(recv), None)?;
}
return Ok(Value::Undef);
}
"freeze" => {
with_host(|h| h.freeze_value(recv));
return Ok(recv.clone());
}
"equal?" => return Ok(Value::Bool(identical(recv, &args[0]))),
"object_id" | "__id__" => {
let id = match recv {
Value::Int(n) => n.wrapping_mul(2).wrapping_add(1),
Value::Undef => 4,
Value::Bool(false) => 0,
Value::Bool(true) => 20,
Value::Obj(h) => match with_host(|host| host.classref_name(recv)) {
Some(class) => with_host(|host| host.class_object_id(&class)),
None => (*h as i64 + 1).wrapping_mul(8),
},
Value::Float(f) => (f.to_bits() as i64) | 1,
_ => 8,
};
return Ok(Value::Int(id));
}
"dup" => {
let copy = with_host(|h| h.dup_value(recv));
run_copy_hook(©, recv, "initialize_dup")?;
return Ok(copy);
}
"+@" if args.is_empty() => {
if with_host(|h| {
h.dispatch_class(recv) == "String" && (h.is_frozen(recv) || h.is_chilled(recv))
}) {
return Ok(with_host(|h| h.dup_value(recv)));
}
return Ok(recv.clone());
}
"-@" if args.is_empty() && with_host(|h| h.dispatch_class(recv)) == "String" => {
if with_host(|h| h.is_frozen(recv)) {
return Ok(recv.clone());
}
return Ok(with_host(|h| {
let copy = h.dup_value(recv);
h.freeze_value(©);
copy
}));
}
"-@" if args.is_empty() && matches!(recv, Value::Int(_) | Value::Float(_)) => {
return with_host(|h| h.num_op(fusevm::NumOp::Neg, recv, &Value::Undef));
}
"~" if args.is_empty() && matches!(recv, Value::Int(_)) => {
let Value::Int(n) = recv else { unreachable!() };
return Ok(Value::Int(!n));
}
"!" if args.is_empty() => {
return Ok(Value::Bool(!with_host(|h| h.truthy(recv))));
}
"define_method" if crate::host::is_main(recv) => {
let object = with_host(|h| h.class_ref("Object"));
return dispatch(&object, "define_method", args, block);
}
"clone" => {
let freeze_opt = args
.first()
.and_then(|a| with_host(|h| h.as_hash(a)))
.and_then(|k| k.get(&RKey::Sym("freeze".into())).cloned());
let freeze = match &freeze_opt {
Some(v) => with_host(|h| h.truthy(v)),
None => with_host(|h| h.is_frozen(recv)),
};
let immediate = matches!(
recv,
Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::Undef
) || with_host(|h| h.as_symbol(recv).is_some());
if immediate && freeze_opt.is_some() && !freeze {
let cls = with_host(|h| h.class_of(recv));
return Err(raise_exc("ArgumentError", &format!("can't unfreeze {cls}")));
}
let copy = with_host(|h| h.dup_value(recv));
with_host(|h| h.copy_singleton(recv, ©));
run_copy_hook(©, recv, "initialize_clone")?;
if freeze {
with_host(|h| h.freeze_value(©));
} else if freeze_opt.is_none() {
with_host(|h| h.copy_chill(recv, ©));
}
return Ok(copy);
}
"private"
| "public"
| "protected"
| "module_function"
| "private_constant"
| "public_constant"
| "private_class_method"
| "public_class_method"
| "private_constant?" => {
if let Some(cls) = with_host(|h| h.classref_name(recv)) {
if let Some(vis) = visibility_directive(name) {
for a in args {
let m = name_of(a);
with_host(|h| h.set_method_visibility(&cls, &m, vis));
}
}
if let Some(vis) = class_visibility_directive(name) {
for a in args {
let m = name_of(a);
with_host(|h| h.set_class_method_visibility(&cls, &m, vis));
}
}
}
return Ok(directive_result(name, recv, args));
}
"frozen?" => return Ok(Value::Bool(with_host(|h| h.is_frozen(recv)))),
"instance_variable_get" => {
let key = ivar_name_arg(&args[0])?;
return Ok(with_host(|h| h.ivar_of(recv, &key)));
}
"instance_variable_set" => {
if with_host(|h| h.is_frozen(recv)) {
let (cls, insp) = with_host(|h| (h.class_of(recv).to_string(), h.inspect(recv)));
return Err(raise_exc_with(
"FrozenError",
&format!("can't modify frozen {cls}: {insp}"),
&[("receiver", recv.clone())],
));
}
unchill(recv)?;
let key = ivar_name_arg(&args[0])?;
let val = args[1].clone();
with_host(|h| h.set_ivar_of(recv, &key, val.clone()));
return Ok(val);
}
"instance_variables" => {
let mut names = with_host(|h| h.ivar_names(recv));
if let Some((members, _)) =
with_host(|h| h.object_class(recv).and_then(|c| h.struct_def(&c)))
{
names.retain(|n| !members.iter().any(|m| n.trim_start_matches('@') == m));
}
return Ok(with_host(|h| {
let syms: Vec<Value> = names.iter().map(|n| h.new_symbol(n)).collect();
h.new_array(syms)
}));
}
"instance_variable_defined?" => {
let key = format!("@{}", ivar_name_arg(&args[0])?);
let has = with_host(|h| h.ivar_names(recv).contains(&key));
return Ok(Value::Bool(has));
}
"remove_instance_variable" if args.len() == 1 => {
let key = ivar_name_arg(&args[0])?;
if with_host(|h| h.is_frozen(recv)) {
let (cls, insp) = with_host(|h| (h.class_of(recv).to_string(), h.inspect(recv)));
return Err(raise_exc_with(
"FrozenError",
&format!("can't modify frozen {cls}: {insp}"),
&[("receiver", recv.clone())],
));
}
return match with_host(|h| h.remove_ivar_of(recv, &key)) {
Some(v) => Ok(v),
None => Err(raise_exc_with(
"NameError",
&format!("instance variable @{key} not defined"),
&[("name", args[0].clone()), ("receiver", recv.clone())],
)),
};
}
"pretty_inspect" if args.is_empty() && with_host(|h| h.builtin_lib_loaded("pp")) => {
let s = crate::pp::pretty_inspect(recv, crate::pp::env_width() - 1)?;
return Ok(with_host(|h| h.new_string(s)));
}
"tap" => {
if let Some(b) = &block {
call_proc(b, std::slice::from_ref(recv))?;
}
return Ok(recv.clone());
}
"then" | "yield_self" => {
if let Some(b) = &block {
return call_proc(b, std::slice::from_ref(recv));
}
return Ok(recv.clone());
}
"to_enum" | "enum_for" => {
let method = args
.first()
.map(name_of)
.unwrap_or_else(|| "each".to_string());
let rest: Vec<Value> = if args.len() > 1 {
args[1..].to_vec()
} else {
vec![]
};
if method == "each" && rest.is_empty() {
if let Some((lo, hi, _)) = with_host(|h| h.as_range(recv)) {
if hi == crate::host::RANGE_ENDLESS {
return Ok(endless_range_enum(recv, lo, "to_enum", &[], Derive::Each));
}
}
if let Some(gb) = with_host(|h| h.generator_block(recv)) {
return Ok(derived_enum(recv, gb, "to_enum", &[], Derive::Each));
}
}
let user_method = top_level_method_for(recv, &method);
let ruby_defined = user_method.is_some()
|| with_host(|h| h.object_class(recv).is_some())
|| with_host(|h| h.find_singleton_method(recv, &method).is_some());
if ruby_defined {
let gen = crate::host::eval_erb_with_locals(
"Enumerator.new { |y| __recv.__send__(__meth, *__args) { |*x| y.yield(*x) } }",
vec![
("__recv".to_string(), recv.clone()),
("__meth".to_string(), with_host(|h| h.new_symbol(&method))),
("__args".to_string(), new_arr(rest.clone())),
],
)?;
let label = enum_label(recv, &method, &rest);
with_host(|h| {
let size = match &block {
Some(b) => GenSize::Call(b.clone(), rest.clone()),
None => GenSize::Fixed(Value::Undef),
};
h.set_generator_size(&gen, size);
h.set_generator_label(&gen, label);
});
return Ok(gen);
}
let sink = with_host(|h| h.new_enum_sink());
let ret = if let Some(def) = &user_method {
crate::host::run_top_method(def, recv.clone(), &method, &rest, Some(sink))?
} else {
dispatch(recv, &method, &rest, Some(sink))?
};
let collected = with_host(|h| h.take_enum_sink());
let e = with_host(|h| h.new_enumerator(collected, &method));
with_host(|h| h.set_enum_size_fn(&e, block.clone(), rest.clone()));
if user_method.is_some() || with_host(|h| h.object_class(recv)).is_some() {
with_host(|h| h.set_enum_source(&e, ret));
}
let label = enum_label(recv, &method, &rest);
with_host(|h| h.set_enum_label(&e, label));
return Ok(e);
}
"lazy"
if with_host(|h| h.lazy_parts(recv).is_none() && h.as_float_range(recv).is_none()) =>
{
let source = if let Some(parts) = with_host(|h| h.enum_chain_parts(recv)) {
enum_chain_generator(recv, parts)?
} else if let Some(seq) = with_host(|h| h.arith_seq(recv)) {
if with_host(|h| h.generator_block(&seq.inner).is_some()) {
seq.inner
} else {
dispatch(&seq.inner, "to_a", &[], None)?
}
} else if with_host(|h| {
h.as_range(recv).is_some()
|| h.as_array(recv).is_some()
|| h.generator_block(recv).is_some()
}) {
recv.clone()
} else {
let src = dispatch(recv, "to_a", &[], None)?;
if with_host(|h| h.enum_method(recv)).is_some_and(|m| is_multi_yield_source(&m)) {
for v in with_host(|h| h.as_array(&src)).unwrap_or_default() {
with_host(|h| h.mark_multi_yield(&v));
}
}
src
};
return Ok(with_host(|h| h.new_lazy_of(source, vec![], recv.clone())));
}
"methods" | "public_methods" | "private_methods" | "protected_methods"
if args.is_empty() || matches!(args.first(), Some(Value::Bool(_))) =>
{
use crate::host::Visibility::{Private, Protected, Public};
let want: &[crate::host::Visibility] = match name {
"methods" => &[Public, Protected],
"public_methods" => &[Public],
"private_methods" => &[Private],
_ => &[Protected],
};
let all = args
.first()
.map(|a| with_host(|h| h.truthy(a)))
.unwrap_or(true);
if name == "methods" && !all {
return dispatch(recv, "singleton_methods", &[], None);
}
if let Some(cls) = with_host(|h| h.object_class(recv)) {
return Ok(with_host(|h| {
let mut names = h.instance_method_names_vis(&cls, all, want);
if name == "private_methods" && all {
names.extend(h.top_level_method_names());
}
let mut seen = std::collections::HashSet::new();
names.retain(|n| seen.insert(n.clone()));
let syms: Vec<Value> = names.iter().map(|n| h.new_symbol(n)).collect();
h.new_array(syms)
}));
}
return Ok(new_arr(vec![]));
}
"singleton_class" if args.is_empty() && with_host(|h| h.classref_name(recv)).is_none() => {
unchill(recv)?;
return match recv {
Value::Undef => Ok(with_host(|h| h.class_ref("NilClass"))),
Value::Bool(b) => Ok(with_host(|h| {
h.class_ref(if *b { "TrueClass" } else { "FalseClass" })
})),
Value::Int(_) | Value::Float(_) => {
Err(raise_exc("TypeError", "can't define singleton"))
}
Value::Obj(id) => {
let cls = with_host(|h| h.class_of(recv));
if matches!(cls.as_str(), "Symbol" | "Integer" | "Float") {
return Err(raise_exc("TypeError", "can't define singleton"));
}
Ok(with_host(|h| {
h.class_ref(&crate::host::RubyHost::object_singleton_class_name(
&cls, *id,
))
}))
}
_ => Err(raise_exc("TypeError", "can't define singleton")),
};
}
"singleton_methods" if args.is_empty() || matches!(args.first(), Some(Value::Bool(_))) => {
let all = !matches!(args.first(), Some(Value::Bool(false)));
return Ok(with_host(|h| {
let syms: Vec<Value> = h
.singleton_method_names(recv, all)
.iter()
.map(|n| h.new_symbol(n))
.collect();
h.new_array(syms)
}));
}
"send" | "__send__" => {
let m = name_of(&args[0]);
if let Some(def) = top_level_method_for(recv, &m) {
return crate::host::run_top_method(&def, recv.clone(), &m, &args[1..], block);
}
return dispatch(recv, &m, &args[1..], block);
}
"public_send" => {
let m = name_of(&args[0]);
check_public_visibility(recv, &m)?;
return dispatch(recv, &m, &args[1..], block);
}
"method" => {
let m = name_of(&args[0]);
method_object_or_name_error(recv, &m, false)?;
return Ok(with_host(|h| h.new_method(recv.clone(), &m)));
}
"public_method" if args.len() == 1 => {
let m = name_of(&args[0]);
method_object_or_name_error(recv, &m, false)?;
let vis = receiver_visibility(recv, &m);
if vis != crate::host::Visibility::Public {
let (lookup, word) = with_host(|h| {
let lookup = h.method_lookup_class(recv, false);
let word = h.class_or_module_word(&lookup);
(lookup, word)
});
return Err(raise_exc(
"NameError",
&format!("method '{m}' for {word} '{lookup}' is {}", vis.word()),
));
}
return Ok(with_host(|h| h.new_method(recv.clone(), &m)));
}
"singleton_method" if args.len() == 1 => {
let m = name_of(&args[0]);
let found = with_host(|h| {
if let Some(cls) = h.classref_name(recv) {
h.has_own_class_method(&cls, &m)
} else {
h.find_singleton_method(recv, &m).is_some()
|| h.find_singleton_define_method(recv, &m).is_some()
}
});
if !found {
let shown = inspect_of(recv)?;
return Err(raise_exc(
"NameError",
&format!("undefined singleton method '{m}' for '{shown}'"),
));
}
return Ok(with_host(|h| h.new_method(recv.clone(), &m)));
}
"respond_to?" => {
let m = name_of(&args[0]);
if with_host(|h| h.find_singleton_method(recv, &m)).is_some()
|| with_host(|h| h.find_singleton_define_method(recv, &m)).is_some()
{
return Ok(Value::Bool(true));
}
if with_host(|h| h.refinements_active() && h.find_refined_method(recv, &m).is_some()) {
return Ok(Value::Bool(true));
}
if m == "pretty_inspect" && !with_host(|h| h.builtin_lib_loaded("pp")) {
return Ok(Value::Bool(false));
}
if args.get(1).is_some_and(|a| with_host(|h| h.truthy(a)))
&& with_host(|h| h.has_method(&m))
{
return Ok(Value::Bool(true));
}
if let Some(cls) = with_host(|h| h.object_class(recv)) {
if with_host(|h| h.find_method_owner(&cls, &m)).is_some()
|| with_host(|h| h.find_define_method(&cls, &m)).is_some()
|| with_host(|h| h.find_alias(&cls, &m)).is_some()
{
let include_private = args
.get(1)
.map(|a| with_host(|h| h.truthy(a)))
.unwrap_or(false);
let restricted = with_host(|h| h.method_visibility(&cls, &m))
!= crate::host::Visibility::Public;
return Ok(Value::Bool(include_private || !restricted));
}
if let Some(answer) = builtin_responds(recv, &m, args.get(1)) {
return Ok(Value::Bool(answer));
}
if let Some(def) =
with_host(|h| h.find_singleton_method(recv, "respond_to_missing?"))
{
let include_private = args.get(1).cloned().unwrap_or(Value::Bool(false));
let sym = with_host(|h| h.new_symbol(&m));
let r = crate::host::call_singleton(
recv.clone(),
&def,
"respond_to_missing?",
&[sym, include_private],
None,
)?;
return Ok(Value::Bool(with_host(|h| h.truthy(&r))));
}
if with_host(|h| h.find_method_owner(&cls, "respond_to_missing?")).is_some() {
let include_private = args.get(1).cloned().unwrap_or(Value::Bool(false));
let sym = with_host(|h| h.new_symbol(&m));
let r = call_instance_method(
recv.clone(),
&cls,
"respond_to_missing?",
&[sym, include_private],
None,
)?;
return Ok(Value::Bool(with_host(|h| h.truthy(&r))));
}
if with_host(|h| h.is_exception_class(&cls)) {
if let Some(owner) = with_host(|h| h.builtin_owner(recv, &m)) {
if !(owner == "Kernel" && is_kernel_function(&m)) {
return Ok(Value::Bool(true));
}
}
}
if mixin_provides(&cls, &m) {
return Ok(Value::Bool(true));
}
if (COMPARABLE_METHODS.contains(&m.as_str())
&& with_host(|h| h.is_a(recv, "Comparable")))
|| (ENUMERABLE_METHODS.contains(&m.as_str())
&& with_host(|h| h.is_a(recv, "Enumerable")))
{
return Ok(Value::Bool(true));
}
if let Some((members, _)) = with_host(|h| h.struct_def(&cls)) {
let is_data = with_host(|h| h.is_data_class(&cls));
let member = m.strip_suffix('=').unwrap_or(&m);
let is_member =
members.iter().any(|x| x == member) && (!is_data || !m.ends_with('='));
let generated: &[&str] = if is_data {
&[
"to_h",
"with",
"members",
"deconstruct",
"deconstruct_keys",
"==",
]
} else {
&[
"each",
"each_pair",
"to_a",
"to_h",
"values",
"values_at",
"members",
"size",
"length",
"dig",
"[]",
"[]=",
"deconstruct",
"deconstruct_keys",
"==",
]
};
if is_member || generated.contains(&m.as_str()) {
return Ok(Value::Bool(true));
}
}
if cls == "OpenStruct" {
let field = m.trim_end_matches('=');
let has = with_host(|h| {
h.ivar_names(recv)
.iter()
.any(|n| n.trim_start_matches('@') == field)
});
let always = matches!(
m.as_str(),
"to_h" | "each_pair" | "each" | "[]" | "[]=" | "dig" | "members"
);
return Ok(Value::Bool(has || always));
}
return Ok(Value::Bool(false));
}
if let Some(cname) = with_host(|h| h.classref_name(recv)) {
let is_module = with_host(|h| h.is_module_name(&cname));
let absent: &[&str] = if is_module {
&["new", "allocate", "superclass", "inherited", "subclasses"]
} else {
&[
"module_function",
"refine",
"append_features",
"prepend_features",
"extend_object",
]
};
if absent.contains(&m.as_str())
&& with_host(|h| h.find_class_method(&cname, &m).is_none())
{
return Ok(Value::Bool(false));
}
if with_host(|h| h.class_responds_to(&cname, &m)) {
let include_private = args
.get(1)
.map(|a| with_host(|h| h.truthy(a)))
.unwrap_or(false);
let private = with_host(|h| h.class_method_visibility(&cname, &m))
== crate::host::Visibility::Private;
return Ok(Value::Bool(include_private || !private));
}
if let Some(answer) = builtin_responds(recv, &m, args.get(1)) {
return Ok(Value::Bool(answer));
}
if let Some((def, owner)) =
with_host(|h| h.find_class_method_owner(&cname, "respond_to_missing?"))
{
let include_private = args.get(1).cloned().unwrap_or(Value::Bool(false));
let sym = with_host(|h| h.new_symbol(&m));
let r = crate::host::call_class_method(
recv.clone(),
&def,
"respond_to_missing?",
&owner,
&[sym, include_private],
None,
)?;
return Ok(Value::Bool(with_host(|h| h.truthy(&r))));
}
let sclass = format!("#<Class:{cname}>");
if with_host(|h| h.find_method_owner(&sclass, "respond_to_missing?")).is_some() {
let include_private = args.get(1).cloned().unwrap_or(Value::Bool(false));
let sym = with_host(|h| h.new_symbol(&m));
let r = call_instance_method(
recv.clone(),
&sclass,
"respond_to_missing?",
&[sym, include_private],
None,
)?;
return Ok(Value::Bool(with_host(|h| h.truthy(&r))));
}
if cname == "Kernel" {
return Ok(Value::Bool(is_kernel_function(&m)));
}
let permissive = with_host(|h| h.is_builtin_class(&cname))
&& !matches!(cname.as_str(), "BasicObject" | "Object");
return Ok(Value::Bool(permissive));
}
if let Some(answer) = builtin_responds(recv, &m, args.get(1)) {
return Ok(Value::Bool(answer));
}
match name_of(&args[0]).as_str() {
"deconstruct" => {
return Ok(Value::Bool(with_host(|h| {
h.is_a(recv, "Array") || h.is_a(recv, "MatchData")
})))
}
"deconstruct_keys" => {
return Ok(Value::Bool(with_host(|h| {
h.is_a(recv, "Hash") || h.is_a(recv, "MatchData")
})))
}
"to_str" => return Ok(Value::Bool(with_host(|h| h.is_a(recv, "String")))),
"to_int" => return Ok(Value::Bool(with_host(|h| h.is_a(recv, "Integer")))),
"to_ary" => return Ok(Value::Bool(with_host(|h| h.is_a(recv, "Array")))),
"to_hash" => return Ok(Value::Bool(with_host(|h| h.is_a(recv, "Hash")))),
"force_encoding" | "encode" | "encode!" | "encoding" | "unpack" | "unpack1"
| "valid_encoding?" | "scrub" | "bytesize" | "getbyte" | "setbyte" | "b" => {
return Ok(Value::Bool(with_host(|h| h.is_a(recv, "String"))))
}
"new" | "allocate" | "superclass" => return Ok(Value::Bool(false)),
"close" => return Ok(Value::Bool(false)),
"content_type" => return Ok(Value::Bool(false)),
"instance" | "initializers" | "symbol" => return Ok(Value::Bool(false)),
"permitted?" | "to_model" | "to_partial_path" | "render_in" => {
return Ok(Value::Bool(false))
}
"to_text" | "to_html" | "to_js" => return Ok(Value::Bool(false)),
"action" => return Ok(Value::Bool(false)),
"call" | "arity" => {
return Ok(Value::Bool(with_host(|h| {
matches!(h.dispatch_class(recv).as_str(), "Proc" | "Method")
})))
}
"to_path" => {
return Ok(Value::Bool(with_host(|h| {
h.is_a(recv, "IO") || h.is_a(recv, "File")
})))
}
_ => {}
}
if matches!(recv, Value::Undef | Value::Bool(_)) {
let q = name_of(&args[0]);
let known = is_universal_object_method(&q)
|| matches!(
q.as_str(),
"to_s"
| "inspect"
| "to_a"
| "to_h"
| "to_r"
| "to_c"
| "&"
| "|"
| "^"
| "!"
| "=="
| "==="
| "!="
| "nil?"
| "class"
| "hash"
| "object_id"
| "dup"
| "clone"
| "to_i"
| "to_f"
| "to_proc"
);
return Ok(Value::Bool(known));
}
let cls = with_host(|h| h.dispatch_class(recv));
if ACCURATE_RESPOND_CLASSES.contains(&cls.as_str())
&& !CORE_EXTENDING_LIBS
.iter()
.any(|l| with_host(|h| h.builtin_lib_loaded(l)))
{
let m = name_of(&args[0]);
let chain = crate::arity_table::ancestry(&cls).unwrap_or(&[]);
let user_defined = std::iter::once(cls.as_str())
.chain(chain.iter().copied())
.any(|c| {
with_host(|h| {
h.find_method_owner(c, &m).is_some()
|| h.find_define_method(c, &m).is_some()
|| h.find_alias(c, &m).is_some()
})
});
return Ok(Value::Bool(user_defined));
}
return Ok(Value::Bool(true));
}
"define_singleton_method" if matches!(recv, Value::Obj(_)) => {
let mname = name_of(&args[0]);
let proc = block
.clone()
.or_else(|| args.get(1).cloned())
.ok_or_else(|| {
raise_exc(
"ArgumentError",
"tried to create Proc object without a block",
)
})?;
if let Some(cls) = with_host(|h| h.classref_name(recv)) {
with_host(|h| h.add_class_define_method(&cls, &mname, proc));
fire_method_hook(recv, "singleton_method_added", &mname)?;
return Ok(with_host(|h| h.new_symbol(&mname)));
}
if let Value::Obj(id) = recv {
with_host(|h| h.add_singleton_define_method(*id, &mname, proc));
}
fire_method_hook(recv, "singleton_method_added", &mname)?;
return Ok(with_host(|h| h.new_symbol(&mname)));
}
"extend"
if matches!(recv, Value::Obj(_)) && with_host(|h| h.classref_name(recv)).is_none() =>
{
unchill(recv)?;
if let Value::Obj(id) = recv {
for a in args.iter().rev() {
if let Some(mname) = with_host(|h| h.classref_name(a)) {
with_host(|h| h.extend_object(*id, &mname));
if with_host(|h| h.find_class_method(&mname, "extended")).is_some() {
dispatch(a, "extended", std::slice::from_ref(recv), None)?;
}
}
}
}
return Ok(recv.clone());
}
"instance_eval" | "instance_exec" => {
let target = eval_target(recv, true);
if let Some(b) = block {
let block_args: Vec<Value> = if name == "instance_exec" {
args.to_vec()
} else {
vec![recv.clone()]
};
return crate::host::eval_block_scoped(&b, recv, target, &block_args);
}
let src = arg_str(&args[0]);
return crate::host::eval_string_scoped(&src, recv, target);
}
"class_eval" | "module_eval" | "class_exec" | "module_exec"
if with_host(|h| h.classref_name(recv)).is_some() =>
{
let target = eval_target(recv, false);
if let Some(b) = block {
let block_args: Vec<Value> = if name.ends_with("_exec") {
args.to_vec()
} else {
vec![recv.clone()]
};
return crate::host::eval_block_scoped(&b, recv, target, &block_args);
}
let src = arg_str(&args[0]);
return crate::host::eval_string_scoped(&src, recv, target);
}
_ => {}
}
if let Some(cls) = with_host(|h| h.classref_name(recv)) {
return dispatch_classref(&cls, name, args, block);
}
if let Some(cls) = with_host(|h| h.object_class(recv)) {
return dispatch_object(recv, &cls, name, args, block);
}
let aliased;
let name = match with_host(|h| h.alias_target(&h.class_of(recv), name)) {
Some(t) => {
aliased = t;
aliased.as_str()
}
None => name,
};
let class = with_host(|h| h.dispatch_class(recv));
let fallback_block = block.clone();
let result = dispatch_by_type(&class, recv, name, args, block);
if let Err(ref e) = result {
if e.starts_with("undefined method") {
let singleton_attr = with_host(|h| {
h.singleton_class_name(recv)
.and_then(|sc| h.attr_access(&sc, name))
});
if let Some((field, writer)) =
singleton_attr.or_else(|| with_host(|h| h.attr_access(&class, name)))
{
with_host(|h| h.take_pending_exc());
if writer {
let val = args.first().cloned().unwrap_or(Value::Undef);
with_host(|h| h.set_ivar_of(recv, &field, val.clone()));
return Ok(val);
}
return Ok(with_host(|h| h.ivar_of(recv, &field)));
}
let object_defines =
class != "Object" && with_host(|h| h.find_method_owner("Object", name)).is_some();
if !object_defines {
if let Some(def) = with_host(|h| h.find_singleton_method(recv, "method_missing")) {
with_host(|h| h.take_pending_exc());
let mut mm_args = vec![with_host(|h| h.new_symbol(name))];
mm_args.extend_from_slice(args);
return crate::host::call_singleton(
recv.clone(),
&def,
"method_missing",
&mm_args,
fallback_block,
);
}
}
let ovr = with_host(|h| h.class_of(recv));
if ovr != class && with_host(|h| h.find_method_owner(&ovr, "method_missing").is_some())
{
with_host(|h| h.take_pending_exc());
let mut mm_args = vec![with_host(|h| h.new_symbol(name))];
mm_args.extend_from_slice(args);
return call_instance_method(
recv.clone(),
&ovr,
"method_missing",
&mm_args,
fallback_block,
);
}
if class != "Object" && with_host(|h| h.find_method_owner("Object", name)).is_some() {
with_host(|h| h.take_pending_exc());
return call_instance_method(recv.clone(), "Object", name, args, fallback_block);
}
if name == "<=>" && args.len() == 1 {
with_host(|h| h.take_pending_exc());
return Ok(if with_host(|h| h.eq_values(recv, &args[0])) {
Value::Int(0)
} else {
Value::Undef
});
}
}
}
result
}
fn dispatch_bool(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
let this = with_host(|h| h.truthy(recv));
let arg = || with_host(|h| h.truthy(&args[0]));
match name {
"&" => Ok(Value::Bool(this && arg())),
"|" => Ok(Value::Bool(this || arg())),
"^" => Ok(Value::Bool(this != arg())),
"!" => Ok(Value::Bool(!this)),
"to_s" => Ok(with_host(|h| {
let s = h.to_s(recv);
let v = h.new_string(s);
h.freeze_value(&v);
v
})),
"inspect" => Ok(new_str(with_host(|h| h.to_s(recv)))),
"to_a" if matches!(recv, Value::Undef) => Ok(new_arr(vec![])),
"to_h" if matches!(recv, Value::Undef) => Ok(with_host(|h| h.new_hash(IndexMap::new()))),
"=~" if matches!(recv, Value::Undef) => Ok(Value::Undef),
"to_i" | "to_int" if matches!(recv, Value::Undef) => Ok(Value::Int(0)),
"to_f" if matches!(recv, Value::Undef) => Ok(Value::Float(0.0)),
"to_r" | "rationalize"
if matches!(recv, Value::Undef) && args.len() <= usize::from(name == "rationalize") =>
{
Ok(with_host(|h| {
h.new_rational(num_rational::BigRational::from_integer(0.into()))
}))
}
"to_c" if matches!(recv, Value::Undef) && args.is_empty() => {
Ok(with_host(|h| h.new_complex(Value::Int(0), Value::Int(0))))
}
_ => match kernel(name, args, None) {
Err(e) if e.starts_with("undefined method") => Err(no_method_error(recv, name)),
other => other,
},
}
}
pub(crate) fn probe_dispatch(recv: &Value, name: &str, args: &[Value]) -> Option<Value> {
match dispatch(recv, name, args, None) {
Ok(v) => Some(v),
Err(_) => {
with_host(|h| {
h.take_pending_exc();
});
None
}
}
}
pub(crate) fn coerce_block_arg(block: Option<Value>) -> Result<Option<Value>, String> {
let Some(v) = &block else {
return Ok(None);
};
let callable = matches!(v, Value::Undef) || with_host(|h| h.is_block_callable(v));
if callable {
return Ok(block);
}
match probe_dispatch(v, "to_proc", &[]) {
Some(p) if with_host(|h| h.is_block_callable(&p)) => Ok(Some(p)),
_ => Err(conv_error(v, "Proc")),
}
}
fn object_space_each_object(args: &[Value], block: Option<Value>) -> Result<Value, String> {
let found: Vec<Value> = with_host(|h| {
let names: Vec<String> = match args.first().and_then(|a| h.classref_name(a)).as_deref() {
Some("Class") => h.defined_class_names(false),
Some("Module") => h.defined_class_names(true),
Some(n) => match crate::host::RubyHost::metaclass_attached(n) {
Some(base) => std::iter::once(base.to_string())
.chain(h.all_descendants(base))
.collect(),
None => Vec::new(),
},
None => h.defined_class_names(true),
};
names.iter().map(|n| h.class_ref(n)).collect()
});
let Some(bl) = block else {
return Ok(with_host(|h| h.new_enumerator(found, "each_object")));
};
let count = found.len() as i64;
for c in found {
call_proc(&bl, &[c])?;
if has_pending_signal() {
break;
}
}
Ok(Value::Int(count))
}
fn process_clock_gettime(args: &[Value]) -> Result<Value, String> {
let einval = || {
let clock = args.first().map(arg_str).unwrap_or_default();
sys_err(
"Invalid argument",
&format!("clock_gettime({clock})"),
&std::io::Error::from_raw_os_error(libc::EINVAL),
)
};
let id = match args.first() {
Some(Value::Int(0)) => libc::CLOCK_REALTIME,
Some(Value::Int(1)) => libc::CLOCK_MONOTONIC,
Some(Value::Int(2)) => libc::CLOCK_PROCESS_CPUTIME_ID,
Some(Value::Int(3)) => libc::CLOCK_THREAD_CPUTIME_ID,
#[cfg(any(target_os = "linux", target_os = "macos"))]
Some(Value::Int(4)) => libc::CLOCK_MONOTONIC_RAW,
_ => return Err(einval()),
};
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
if unsafe { libc::clock_gettime(id, &mut ts) } != 0 {
return Err(einval());
}
let ns = ts.tv_sec as i128 * 1_000_000_000 + ts.tv_nsec as i128;
let unit = match args.get(1) {
None => None,
Some(Value::Undef) => return Err(einval()),
Some(u) => Some(name_of(u)),
};
Ok(match unit.as_deref() {
Some("nanosecond") => Value::Int(ns as i64),
Some("microsecond") => Value::Int((ns / 1_000) as i64),
Some("millisecond") => Value::Int((ns / 1_000_000) as i64),
Some("second") => Value::Int((ns / 1_000_000_000) as i64),
Some("float_millisecond") => Value::Float(ns as f64 / 1e6),
Some("float_microsecond") => Value::Float(ns as f64 / 1e3),
Some("float_second") | None => Value::Float(ns as f64 / 1e9),
Some(_) => return Err(einval()),
})
}
fn dispatch_classref(
cls: &str,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
let (name, native_only) = match name.strip_prefix("\u{1}native:") {
Some(n) => (n, true),
None => (name, false),
};
let explicit_recv = take_explicit_class_call(cls, name);
if !native_only {
if let Some(proc) = with_host(|h| h.own_singleton_define_method(cls, name)) {
let recv = with_host(|h| h.class_ref(cls));
return crate::host::call_proc_self(&proc, args, Some(&recv));
}
}
if !native_only {
if let Some((def, owner)) = with_host(|h| h.find_class_method_owner(cls, name)) {
let recv = with_host(|h| h.class_ref(cls));
return crate::host::call_class_method(recv, &def, name, &owner, args, block);
}
}
if !native_only {
if let Some(proc) = with_host(|h| h.find_class_define_method(cls, name)) {
let recv = with_host(|h| h.class_ref(cls));
return crate::host::call_proc_self(&proc, args, Some(&recv));
}
}
if !native_only {
if let Some(sclass) = with_host(|h| h.find_singleton_class_method(cls, name)) {
let recv = with_host(|h| h.class_ref(cls));
if let Some(proc) = with_host(|h| h.find_define_method(&sclass, name)) {
return crate::host::call_proc_self(&proc, args, Some(&recv));
}
return call_instance_method(recv, &sclass, name, args, block);
}
}
if !native_only {
if let Some(target) = with_host(|h| h.find_class_alias(cls, name)) {
if target == "new" {
let obj = with_host(|h| h.new_object(cls));
if with_host(|h| h.find_method_owner(cls, "initialize")).is_some() {
call_instance_method(obj.clone(), cls, "initialize", args, block)?;
}
return Ok(obj);
}
if target != name {
return dispatch_classref(cls, &target, args, block);
}
}
}
if name == "autoload" && args.len() >= 2 {
let const_name = name_of(&args[0]);
let path = with_host(|h| h.as_str(&args[1])).unwrap_or_default();
let full = format!("{cls}::{const_name}");
with_host(|h| h.set_autoload(&full, &path));
return Ok(Value::Undef);
}
if name == "autoload?" && !args.is_empty() {
let const_name = name_of(&args[0]);
let full = format!("{cls}::{const_name}");
return Ok(with_host(|h| match h.autoload_path(&full) {
Some(p) => h.new_string(p),
None => Value::Undef,
}));
}
if cls == "ENV" {
return dispatch_env(name, args, block);
}
if cls == "Warning" {
return dispatch_warning(name, args);
}
if cls == "GC" {
return match name {
"start"
| "garbage_collect"
| "compact"
| "verify_compaction_references"
| "verify_internal_consistency" => Ok(Value::Undef),
"enable" | "disable" | "stress" => Ok(Value::Bool(false)),
"count" | "total_time" => Ok(Value::Int(0)),
"stat" | "latest_gc_info" => Ok(with_host(|h| h.new_hash(IndexMap::new()))),
_ => Err(raise_exc(
"NoMethodError",
&format!("undefined method '{name}' for module GC"),
)),
};
}
if cls == "ObjectSpace" {
match name {
"garbage_collect" => return Ok(Value::Undef),
"count_objects" => return Ok(with_host(|h| h.new_hash(IndexMap::new()))),
"each_object" => return object_space_each_object(args, block),
"define_finalizer" => return Ok(args.first().cloned().unwrap_or(Value::Undef)),
"undefine_finalizer" => return Ok(args.first().cloned().unwrap_or(Value::Undef)),
"_id2ref" => return id2ref(args),
_ if name.chars().next().is_some_and(|c| c.is_uppercase()) => {}
_ => {
return Err(raise_exc(
"NoMethodError",
&format!("undefined method '{name}' for module ObjectSpace"),
))
}
}
}
if (cls == "Mutex" || cls == "Thread::Mutex" || cls == "Monitor") && name == "new" {
return Ok(with_host(|h| {
let o = h.new_object(cls);
h.set_ivar_of(&o, "__locked", Value::Bool(false));
o
}));
}
if matches!(
cls,
"Queue" | "Thread::Queue" | "SizedQueue" | "Thread::SizedQueue"
) && name == "new"
{
let cap = if cls.ends_with("SizedQueue") {
Some(args.first().map(as_i).unwrap_or(0).max(0) as usize)
} else {
None
};
let qid = crate::host::new_queue(cap);
return Ok(with_host(|h| {
let o = h.new_object(if cls.ends_with("SizedQueue") {
"SizedQueue"
} else {
"Queue"
});
h.set_ivar_of(&o, "__qid", Value::Int(qid as i64));
o
}));
}
if matches!(cls, "ConditionVariable" | "Thread::ConditionVariable") && name == "new" {
let cvid = crate::host::new_condvar();
return Ok(with_host(|h| {
let o = h.new_object("ConditionVariable");
h.set_ivar_of(&o, "__cvid", Value::Int(cvid as i64));
o
}));
}
if cls == "Thread" {
match name {
"new" | "start" | "fork" => {
let b =
block.ok_or_else(|| raise_exc("ThreadError", "must be called with a block"))?;
return Ok(crate::host::spawn_thread(b));
}
"current" | "main" => return Ok(crate::host::current_thread()),
"pass" => return Ok(Value::Undef),
"list" => return Ok(new_arr(vec![crate::host::current_thread()])),
_ => {}
}
}
if cls == "Random" {
return match name {
"new" => {
let seed = match args.first() {
Some(v) => random_int_arg(v)?,
None => crate::random::new_seed(),
};
let o = with_host(|h| h.new_object("Random"));
if let Value::Obj(id) = o {
crate::random::seed_instance(id, &seed);
}
with_host(|h| {
let sv = h.new_bigint(seed);
h.set_ivar_of(&o, "seed", sv);
});
Ok(o)
}
"rand" => random_rand(Gen::Default, args),
"random_number" => random_number(Gen::Default, args),
"bytes" => random_bytes(Gen::Default, args),
"srand" => random_srand(args),
"new_seed" => Ok(with_host(|h| h.new_bigint(crate::random::new_seed()))),
_ if name.starts_with(|c: char| c.is_ascii_uppercase()) => Err(raise_exc(
"NameError",
&format!("uninitialized constant Random::{name}"),
)),
_ => Err(raise_exc(
"NoMethodError",
&format!("undefined method '{name}' for class Random"),
)),
};
}
if cls == "StringIO" && name == "new" {
let init = args.first().map(arg_str).unwrap_or_default();
let append = args
.get(1)
.and_then(|m| with_host(|h| h.as_str(m)))
.is_some_and(|m| m.starts_with('a'));
return Ok(with_host(|h| {
let obj = h.new_object("StringIO");
let sv = h.new_string(init);
h.set_ivar_of(&obj, "buf", sv);
h.set_ivar_of(&obj, "pos", Value::Int(0));
h.set_ivar_of(&obj, "append", Value::Bool(append));
obj
}));
}
if cls == "Struct" && name == "new" {
let (class_name, rest) = match args.split_first() {
Some((first, rest)) => {
let is_option = with_host(|h| h.is_kwargs(first));
if with_host(|h| h.as_symbol(first).is_some()) || is_option {
(None, args)
} else if matches!(first, Value::Undef) {
(None, rest)
} else {
match with_host(|h| h.as_str(first)) {
Some(s) => (Some(s), rest),
None => return Err(conv_error(first, "String")),
}
}
}
None => (None, args),
};
if let Some(n) = &class_name {
if !n.starts_with(|c: char| c.is_ascii_uppercase()) {
return Err(raise_exc(
"NameError",
&format!("identifier {n} needs to be constant"),
));
}
}
let (members, keyword_init) = struct_member_args(rest, false)?;
let struct_name = with_host(|h| h.define_struct(members, keyword_init));
let struct_name = match class_name {
Some(n) => name_struct_class(&struct_name, &format!("Struct::{n}")),
None => struct_name,
};
let cref = with_host(|h| h.class_ref(&struct_name));
if let Some(bl) = block {
crate::host::eval_block_scoped(
&bl,
&cref,
crate::host::DefTarget::Instance(struct_name),
std::slice::from_ref(&cref),
)?;
}
return Ok(cref);
}
if cls == "Data" && name == "define" {
let (members, _) = struct_member_args(args, true)?;
let data_name = with_host(|h| h.define_data(members));
let cref = with_host(|h| h.class_ref(&data_name));
if let Some(bl) = block {
crate::host::eval_block_scoped(
&bl,
&cref,
crate::host::DefTarget::Instance(data_name),
std::slice::from_ref(&cref),
)?;
}
return Ok(cref);
}
if cls == "Data" && matches!(name, "new" | "[]") {
return Err(no_method_error(&with_host(|h| h.class_ref("Data")), name));
}
if let Some((members, keyword_init)) = with_host(|h| h.struct_def(cls)) {
if name == "new" || name == "[]" {
return struct_new(cls, &members, keyword_init, args, block);
}
if name == "members" {
let syms: Vec<Value> = members
.iter()
.map(|m| with_host(|h| h.new_symbol(m)))
.collect();
return Ok(new_arr(syms));
}
if name == "keyword_init?" && !with_host(|h| h.is_data_class(cls)) {
return Ok(match keyword_init {
Some(b) => Value::Bool(b),
None => Value::Undef,
});
}
}
if cls == "Enumerator::Chain" && name == "new" {
return Ok(with_host(|h| h.new_enum_chain(args.to_vec())));
}
if cls == "Enumerator" && name == "produce" {
let b = block.ok_or_else(|| raise_exc("ArgumentError", "no block given"))?;
let init = args.first().cloned();
return Ok(with_host(|h| {
let e = h.new_produce_enumerator(init, b);
let label = format!(
"#<Enumerator: #<Enumerator::Producer:{}>:each>",
h.object_address(&e)
);
h.set_generator_size(&e, GenSize::Fixed(Value::Float(f64::INFINITY)));
h.set_generator_label(&e, label);
e
}));
}
if cls == "Enumerator" && name == "new" {
let b = block.ok_or_else(|| {
raise_exc(
"ArgumentError",
"tried to create Proc object without a block",
)
})?;
let size = match args.first() {
None | Some(Value::Undef) => GenSize::Fixed(Value::Undef),
Some(Value::Float(f)) if *f == f64::INFINITY => GenSize::Fixed(Value::Float(*f)),
Some(v @ Value::Int(_)) => GenSize::Fixed(v.clone()),
Some(v) if with_host(|h| h.as_bigint(v)).is_some() => GenSize::Fixed(v.clone()),
Some(v)
if probe_dispatch(v, "respond_to?", &[with_host(|h| h.new_symbol("call"))])
.is_some_and(|r| with_host(|h| h.truthy(&r))) =>
{
GenSize::Call(v.clone(), Vec::new())
}
Some(v @ Value::Float(_)) => GenSize::Fixed(dispatch(v, "to_i", &[], None)?),
Some(v)
if probe_dispatch(v, "respond_to?", &[with_host(|h| h.new_symbol("to_int"))])
.is_some_and(|r| with_host(|h| h.truthy(&r))) =>
{
GenSize::Fixed(dispatch(v, "to_int", &[], None)?)
}
Some(v) => {
return Err(raise_exc(
"TypeError",
&format!(
"no implicit conversion of {} into Integer",
conv_operand_name(v)
),
))
}
};
return Ok(with_host(|h| {
let e = h.new_generator(b);
h.set_generator_size(&e, size);
e
}));
}
if cls == "Fiber" {
match name {
"new" => {
let b = block.ok_or_else(|| {
raise_exc(
"ArgumentError",
"tried to create Proc object without a block",
)
})?;
return Ok(crate::host::new_fiber(b));
}
"yield" => {
let v = match args {
[] => Value::Undef,
[one] => one.clone(),
many => new_arr(many.to_vec()),
};
return crate::host::fiber_yield(v);
}
"current" => return Ok(crate::host::current_fiber()),
"[]" => {
let store = with_host(fiber_store);
return dispatch(&store, "[]", args, None);
}
"[]=" => {
let store = with_host(fiber_store);
return dispatch(&store, "[]=", args, None);
}
_ => {}
}
}
if cls == "Timeout" && name == "timeout" {
return match block {
Some(b) => {
let arg = args.first().cloned().unwrap_or(Value::Undef);
call_proc(&b, std::slice::from_ref(&arg))
}
None => Ok(Value::Undef),
};
}
if cls == "CGI" {
match name {
"escape" => return Ok(new_str(cgi_escape(&arg_str(&args[0])))),
"unescape" => return Ok(new_str(cgi_unescape(&arg_str(&args[0])))),
"escapeHTML" | "escape_html" => {
return Ok(new_str(cgi_escape_html(&arg_str(&args[0]))))
}
"unescapeHTML" | "unescape_html" => {
return Ok(new_str(cgi_unescape_html(&arg_str(&args[0]))))
}
"escapeURIComponent" | "escapeURI" => {
return Ok(new_str(cgi_escape(&arg_str(&args[0])).replace('+', "%20")))
}
_ => {}
}
}
if cls == "Encoding" {
if let Some(info) = ENCODINGS.iter().find(|e| e.constants.contains(&name)) {
return Ok(encoding_value(info));
}
if matches!(
name,
"CompatibilityError"
| "UndefinedConversionError"
| "InvalidByteSequenceError"
| "ConverterNotFoundError"
) {
return Ok(with_host(|h| h.class_ref(&format!("Encoding::{name}"))));
}
match name {
"default_external" => return Ok(encoding_object("UTF-8")),
"default_internal" => return Ok(Value::Undef),
"default_external=" | "default_internal=" => {
return Ok(args.first().cloned().unwrap_or(Value::Undef));
}
"find" if args.len() == 1 => {
if with_host(|h| h.class_of(&args[0])) == "Encoding" {
return Ok(args[0].clone());
}
let raw = implicit_str(&args[0])?;
if raw.eq_ignore_ascii_case("internal") {
return Ok(Value::Undef);
}
let Some(info) = encoding_info(&raw) else {
return Err(raise_exc(
"ArgumentError",
&format!("unknown encoding name - {raw}"),
));
};
with_host(|h| h.load_encoding(info));
return Ok(encoding_value(info));
}
"compatible?" if args.len() == 2 => return encoding_compatible(&args[0], &args[1]),
"list" => {
let all: Vec<Value> = ENCODINGS.iter().map(encoding_value).collect();
return Ok(new_arr(all));
}
"name_list" => {
let names = NAME_LIST
.iter()
.chain(&["locale", "external", "filesystem", "internal"])
.map(|n| new_str(n.to_string()))
.collect();
return Ok(new_arr(names));
}
"aliases" => {
let mut map = IndexMap::new();
let specials = ["locale", "external", "filesystem"].map(|a| (a, "UTF-8"));
for (a, n) in ALIASES.iter().copied().chain(specials) {
let k = with_host(|h| h.value_to_key(&new_str(a.to_string())));
map.insert(k, new_str(n.to_string()));
}
return Ok(with_host(|h| h.new_hash(map)));
}
_ => {}
}
}
if cls == "Etc" {
match name {
"nprocessors" => {
let n = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
return Ok(Value::Int(n as i64));
}
"sysconfdir" => return Ok(new_str("/etc".to_string())),
"systmpdir" => return Ok(new_str("/tmp".to_string())),
_ => {}
}
}
if cls == "Process" {
match name {
"pid" => return Ok(Value::Int(std::process::id() as i64)),
"ppid" => return Ok(Value::Int(unsafe { libc::getppid() } as i64)),
"clock_gettime" => return process_clock_gettime(args),
"last_status" => return Ok(with_host(|h| h.get_global("?"))),
_ => {}
}
}
if cls == "Ractor" {
match name {
"shareable?" => {
let v = &args[0];
let sharable = matches!(
v,
Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::Undef
) || with_host(|h| h.is_frozen(v));
return Ok(Value::Bool(sharable));
}
"make_shareable" => {
with_host(|h| h.freeze_value(&args[0]));
return Ok(args[0].clone());
}
"current" | "main" => return Ok(Value::Undef),
_ => {}
}
}
if cls == "Complex" && matches!(name, "rectangular" | "rect" | "polar") {
return complex_class_method(name, args);
}
if cls == "Regexp" {
match name {
"new" | "compile" => {
if let Some((_, s)) = with_host(|h| h.as_regex(&args[0])) {
let flags = with_host(|h| h.regex_flags(&args[0])).unwrap_or_default();
return with_host(|h| h.new_regex(&s, &flags));
}
let src = arg_str(&args[0]);
let mut flags = match args.get(1) {
None | Some(Value::Undef) | Some(Value::Bool(false)) => String::new(),
Some(Value::Int(bits)) => [(1, 'i'), (2, 'x'), (4, 'm'), (16, 'u'), (32, 'n')]
.iter()
.filter(|(b, _)| bits & b != 0)
.map(|(_, c)| *c)
.collect(),
Some(o) if with_host(|h| h.as_str(o).is_some()) => {
let s = arg_str(o);
if s.chars().any(|c| !"imx".contains(c)) {
return Err(raise_exc(
"ArgumentError",
&format!("unknown regexp option: {s}"),
));
}
s
}
Some(_) => "i".to_string(),
};
if !src.is_ascii()
&& with_host(|h| h.string_encoding(&args[0])) == Some("ASCII-8BIT")
{
flags.push('n');
}
return with_host(|h| h.new_regex(&src, &flags));
}
"escape" | "quote" => return Ok(new_str(regex_escape(&arg_str(&args[0])))),
"timeout=" => {
let v = args.first().cloned().unwrap_or(Value::Undef);
with_host(|h| h.set_global("__regexp_timeout", v.clone()));
return Ok(v);
}
"timeout" => return Ok(with_host(|h| h.get_global("__regexp_timeout"))),
"union" => {
let items: Vec<Value> = match args {
[one] => with_host(|h| h.as_array(one)).unwrap_or_else(|| vec![one.clone()]),
many => many.to_vec(),
};
let parts: Vec<String> = items
.iter()
.map(|v| match with_host(|h| h.as_regex(v)) {
Some((_, s)) => format!("(?-mix:{s})"),
None => regex_escape(&arg_str(v)),
})
.collect();
return with_host(|h| h.new_regex(&parts.join("|"), ""));
}
"last_match" => {
let m = with_host(|h| h.match_global("~").unwrap_or(Value::Undef));
return match args.first() {
Some(idx) => dispatch(&m, "[]", std::slice::from_ref(idx), None),
None => Ok(m),
};
}
_ => {}
}
}
if cls == "Set" {
match name {
"new" => {
let mut items = match args.first() {
None | Some(Value::Undef) => Vec::new(),
Some(v) => match with_host(|h| h.as_array(v).or_else(|| h.as_set(v))) {
Some(items) => items,
None if probe_dispatch(
v,
"respond_to?",
&[with_host(|h| h.new_symbol("each_entry"))],
)
.is_some_and(|r| with_host(|h| h.truthy(&r))) =>
{
let a = dispatch(v, "to_a", &[], None)?;
with_host(|h| h.as_array(&a)).unwrap_or_default()
}
None => return Err(raise_exc("ArgumentError", "value must be enumerable")),
},
};
if let Some(b) = &block {
items = items
.iter()
.map(|v| call_proc(b, std::slice::from_ref(v)))
.collect::<Result<_, _>>()?;
}
return Ok(with_host(|h| h.new_set(items)));
}
"[]" => return Ok(with_host(|h| h.new_set(args.to_vec()))),
_ => {}
}
}
if cls == "OpenStruct" && name == "new" {
let obj = with_host(|h| h.new_object("OpenStruct"));
if let Some(map) = args.first().and_then(|a| with_host(|h| h.as_hash(a))) {
for (k, v) in map {
let kv = with_host(|h| h.key_value(&k));
let field = name_of(&kv);
with_host(|h| h.set_ivar_of(&obj, &field, v.clone()));
}
}
return Ok(obj);
}
if cls == "Time" {
if let Some(r) = time_class_method(name, args) {
return r;
}
}
if cls == "Date" {
match name {
"new" | "civil" => {
let g = |i: usize, dflt: i64| args.get(i).map(as_i).unwrap_or(dflt);
let (y, mo, d) = (g(0, -4712), g(1, 1), g(2, 1));
return Ok(with_host(|h| {
let days = crate::host::days_from_civil(y, mo, d);
h.new_date(days)
}));
}
"today" => {
let days = (now_epoch_secs() / 86_400.0).floor() as i64;
return Ok(with_host(|h| h.new_date(days)));
}
"jd" => {
let jd = args
.first()
.map(as_i)
.unwrap_or(crate::host::UNIX_EPOCH_JDN);
return Ok(with_host(|h| h.new_date(jd - crate::host::UNIX_EPOCH_JDN)));
}
"parse" => {
let s = with_host(|h| h.as_str(&args[0]).unwrap_or_default());
return match parse_iso_date(&s) {
Some(days) => Ok(with_host(|h| h.new_date(days))),
None => Err(raise_exc("ArgumentError", "invalid date")),
};
}
_ => {}
}
}
if cls == "DateTime" {
match name {
"new" | "civil" => {
let g = |i: usize, dflt: i64| args.get(i).map(as_i).unwrap_or(dflt);
let (y, mo, d) = (g(0, -4712), g(1, 1), g(2, 1));
let (hh, mi) = (g(3, 0), g(4, 0));
let ss = args.get(5).map(as_f).unwrap_or(0.0);
let days = crate::host::days_from_civil(y, mo, d);
let secs = days as f64 * 86_400.0 + (hh * 3600 + mi * 60) as f64 + ss;
return Ok(with_host(|h| h.new_datetime(secs)));
}
"now" => return Ok(with_host(|h| h.new_datetime(now_epoch_secs()))),
"jd" => {
let g = |i: usize, dflt: i64| args.get(i).map(as_i).unwrap_or(dflt);
let jd = args
.first()
.map(as_i)
.unwrap_or(crate::host::UNIX_EPOCH_JDN);
let days = jd - crate::host::UNIX_EPOCH_JDN;
let (hh, mi) = (g(1, 0), g(2, 0));
let ss = args.get(3).map(as_f).unwrap_or(0.0);
let secs = days as f64 * 86_400.0 + (hh * 3600 + mi * 60) as f64 + ss;
return Ok(with_host(|h| h.new_datetime(secs)));
}
"parse" => {
let s = with_host(|h| h.as_str(&args[0]).unwrap_or_default());
return match parse_iso_datetime(&s) {
Some(secs) => Ok(with_host(|h| h.new_datetime(secs))),
None => Err(raise_exc("ArgumentError", "invalid date")),
};
}
_ => {}
}
}
if cls == "ERB" && name == "new" {
let (positional, kw) = match args.split_last() {
Some((last, rest)) if with_host(|h| h.is_kwargs(last)) => (rest, Some(last)),
_ => (args, None),
};
if positional.len() != 1 {
return Err(raise_exc(
"ArgumentError",
&format!(
"wrong number of arguments (given {}, expected 1)",
positional.len()
),
));
}
let template = arg_str(&positional[0]);
let mode = kw
.and_then(|k| with_host(|h| h.as_hash(k)))
.and_then(|m| m.get(&RKey::Sym("trim_mode".into())).cloned())
.unwrap_or(Value::Undef);
let mode = match &mode {
Value::Undef => crate::erb::TrimArg::Nil,
Value::Int(n) => crate::erb::TrimArg::Int(*n),
v => match with_host(|h| h.as_str(v)) {
Some(s) => crate::erb::TrimArg::Str(s),
None => crate::erb::TrimArg::Other(with_host(|h| h.inspect(v))),
},
};
let (spec, warning) = crate::erb::prepare_trim_mode(&mode);
if let Some(warning) = warning {
let mut kw = IndexMap::new();
kw.insert(RKey::Sym("uplevel".into()), Value::Int(0));
let kw = with_host(|h| {
let hash = h.new_hash(kw);
h.mark_kwargs(&hash);
hash
});
kernel_warn(&[new_str(warning), kw])?;
}
let find_encoding = |name: &str| {
encoding_info(name)
.map(|e| e.name.to_string())
.ok_or_else(|| {
raise_exc("ArgumentError", &format!("unknown encoding name - {name}"))
})
};
let src = crate::erb::compile(&template, spec, &find_encoding)?;
let src_val = new_str(src);
let obj = with_host(|h| h.new_object("ERB"));
with_host(|h| h.set_ivar_of(&obj, "src", src_val));
return Ok(obj);
}
if cls == "Math" {
let x = || as_f(&args[0]);
let y = || as_f(&args[1]);
match name {
"frexp" => {
let mut exp: i32 = 0;
let fr = unsafe { libm_frexp(x(), &mut exp) };
return Ok(new_arr(vec![Value::Float(fr), Value::Int(exp as i64)]));
}
"lgamma" => {
let d = x();
if d.is_infinite() {
if d.is_sign_negative() {
return Err(raise_exc(
"Math::DomainError",
"Numerical argument is out of domain - lgamma",
));
}
return Ok(new_arr(vec![Value::Float(f64::INFINITY), Value::Int(1)]));
}
if d == 0.0 {
let sign = if d.is_sign_negative() { -1 } else { 1 };
return Ok(new_arr(vec![Value::Float(f64::INFINITY), Value::Int(sign)]));
}
let mut sign: i32 = 1;
let v = unsafe { libm_lgamma_r(d, &mut sign) };
return Ok(new_arr(vec![Value::Float(v), Value::Int(sign as i64)]));
}
_ => {}
}
let f = match name {
"PI" => Some(std::f64::consts::PI),
"E" => Some(std::f64::consts::E),
"sqrt" => Some(x().sqrt()),
"cbrt" => Some(x().cbrt()),
"sin" => Some(x().sin()),
"cos" => Some(x().cos()),
"tan" => Some(x().tan()),
"asin" => Some(x().asin()),
"acos" => Some(x().acos()),
"atan" => Some(x().atan()),
"atan2" => Some(x().atan2(y())),
"sinh" => Some(x().sinh()),
"cosh" => Some(x().cosh()),
"tanh" => Some(x().tanh()),
"asinh" => Some(x().asinh()),
"acosh" => Some(x().acosh()),
"atanh" => Some(x().atanh()),
"exp" => Some(x().exp()),
"log" if args.len() >= 2 => Some(x().log(y())),
"log" => Some(x().ln()),
"log2" => Some(x().log2()),
"log10" => Some(x().log10()),
"hypot" => Some(x().hypot(y())),
"ldexp" => Some(unsafe { libm_ldexp(x(), as_i(&args[1]) as i32) }),
"log1p" => Some(unsafe { libm_log1p(x()) }),
"expm1" => Some(unsafe { libm_expm1(x()) }),
"gamma" => Some(math_gamma(x())),
"erf" => Some(unsafe { libm_erf(x()) }),
"erfc" => Some(unsafe { libm_erfc(x()) }),
_ => None,
};
if let Some(v) = f {
if v.is_nan()
&& !args
.iter()
.any(|a| matches!(a, Value::Float(f) if f.is_nan()))
{
return Err(raise_exc(
"Math::DomainError",
&format!("Numerical argument is out of domain - {name}"),
));
}
return Ok(Value::Float(v));
}
}
if cls == "Integer" && name == "sqrt" {
let n = match with_host(|h| h.as_bigint(&args[0])) {
Some(b) => b,
None => num_bigint::BigInt::from(to_int(&args[0])?),
};
if n.sign() == num_bigint::Sign::Minus {
return Err(raise_exc(
"Math::DomainError",
"Numerical argument is out of domain - \"isqrt\"",
));
}
return Ok(with_host(|h| h.new_bigint(n.sqrt())));
}
if cls == "JSON" {
match name {
"generate" | "dump" => {
return match with_host(|h| json_encode(h, &args[0])) {
Ok(s) => Ok(new_str(s)),
Err(e) => Err(raise_exc("JSON::GeneratorError", &e)),
};
}
"pretty_generate" => {
return match with_host(|h| json_pretty(h, &args[0], 0)) {
Ok(s) => Ok(new_str(s)),
Err(e) => Err(raise_exc("JSON::GeneratorError", &e)),
};
}
"parse" | "load" => {
let src = with_host(|h| h.as_str(&args[0])).unwrap_or_default();
let symbolize = args
.get(1)
.and_then(|a| with_host(|h| h.as_hash(a)))
.and_then(|m| m.get(&RKey::Sym("symbolize_names".to_string())).cloned())
.map(|v| with_host(|h| h.truthy(&v)))
.unwrap_or(false);
return match with_host(|h| json_parse(h, &src, symbolize)) {
Ok(v) => Ok(v),
Err(e) => Err(raise_exc("JSON::ParserError", &e)),
};
}
_ => {}
}
}
if let Some(r) = dispatch_stdlib_module(cls, name, args) {
return r;
}
if cls == "File" || cls == "IO" {
if let Some(r) = dispatch_file_class(name, args, block.clone()) {
return r;
}
}
if cls == "Dir" {
if let Some(r) = dispatch_dir_class(name, args, block.clone()) {
return r;
}
}
if (cls == "TCPServer" || cls == "TCPSocket") && (name == "new" || name == "open") {
return tcp_class_new(cls, args, block);
}
if cls == "SQLite3" {
match name {
"Database" => return Ok(with_host(|h| h.class_ref("SQLite3::Database"))),
"SQLException"
| "Exception"
| "CantOpenException"
| "BusyException"
| "ConstraintException" => {
return Ok(with_host(|h| h.class_ref(&format!("SQLite3::{name}"))))
}
"SQLITE_VERSION" => return Ok(new_str(rusqlite::version().to_string())),
_ => {}
}
}
if cls == "SQLite3::Database" && (name == "new" || name == "open") {
return sqlite_db_new(args, block);
}
if let Some(r) = dispatch_fiddle_classref(cls, name, args)? {
return Ok(r);
}
match name {
"allocate"
if args.is_empty()
&& !with_host(|h| h.is_module_name(cls))
&& !with_host(|h| h.is_struct_class(cls)) =>
{
Ok(with_host(|h| h.new_object(cls)))
}
"new"
if matches!(
cls,
"Integer"
| "Float"
| "Symbol"
| "NilClass"
| "TrueClass"
| "FalseClass"
| "Process::Status"
) || (cls != "Module" && with_host(|h| h.is_module_name(cls))) =>
{
let recv = with_host(|h| h.class_ref(cls));
Err(no_method_error(&recv, "new"))
}
"new" if cls == "Proc" => {
block.ok_or_else(|| String::from("tried to create Proc object without a block"))
}
"new" => {
if cls == "Class" || cls == "Module" {
let superclass = if cls == "Class" {
args.first()
.and_then(|a| with_host(|h| h.classref_name(a)))
.or_else(|| Some("Object".to_string()))
} else {
None
};
let name = with_host(|h| h.define_anon_class(superclass.clone(), cls == "Module"));
let cref = with_host(|h| h.class_ref(&name));
if let Some(sc) = &superclass {
if let Some(def) = with_host(|h| h.find_class_method(sc, "inherited")) {
let recv = with_host(|h| h.class_ref(sc));
crate::host::call_class_method(
recv,
&def,
"inherited",
sc,
std::slice::from_ref(&cref),
None,
)?;
}
}
if let Some(bl) = block {
crate::host::eval_block_scoped(
&bl,
&cref,
crate::host::DefTarget::Instance(name),
std::slice::from_ref(&cref),
)?;
}
return Ok(cref);
}
if cls == "Array" {
if args.len() == 1 && block.is_none() {
if let Some(items) = with_host(|h| h.as_array(&args[0])) {
return Ok(new_arr(items));
}
}
let n = match args.first() {
Some(a) => checked_size(a, 0, "negative array size")?,
None => 0,
};
let items: Vec<Value> = if let Some(bl) = &block {
(0..n)
.map(|i| call_proc(bl, &[Value::Int(i as i64)]))
.collect::<Result<_, _>>()?
} else {
let fill = args.get(1).cloned().unwrap_or(Value::Undef);
vec![fill; n]
};
return Ok(new_arr(items));
}
if cls == "Range" {
let lo = args.first().cloned().unwrap_or(Value::Undef);
let hi = args.get(1).cloned().unwrap_or(Value::Undef);
let excl = args.get(2).is_some_and(|v| with_host(|h| h.truthy(v)));
return make_range(&lo, &hi, excl);
}
if cls == "String" {
let s = match args.first() {
Some(a) if !with_host(|h| h.as_hash(a).is_some()) => {
match with_host(|h| h.as_str(a)) {
Some(s) => s,
None => return Err(conv_error(a, "String")),
}
}
_ => String::new(),
};
return Ok(with_host(|h| h.new_string(s)));
}
if cls == "Hash" {
let positional = match args.split_last() {
Some((last, rest)) if with_host(|h| h.is_kwargs(last)) => rest,
_ => args,
};
if positional.len() > 1 {
return Err(raise_exc(
"ArgumentError",
&format!(
"wrong number of arguments (given {}, expected 0..1)",
positional.len()
),
));
}
if let Some(bl) = block {
if !positional.is_empty() {
return Err(raise_exc(
"ArgumentError",
"wrong number of arguments (given 1, expected 0)",
));
}
return Ok(with_host(|h| h.new_hash_with_proc(IndexMap::new(), bl)));
}
let default = positional.first().cloned().unwrap_or(Value::Undef);
return Ok(with_host(|h| {
h.new_hash_with_default(IndexMap::new(), default)
}));
}
if let Some(root) = with_host(|h| h.builtin_container_root(cls)) {
let has_init = with_host(|h| h.find_method(cls, "initialize")).is_some();
let obj = if has_init {
with_host(|h| match root {
"Array" => h.new_array(vec![]),
"String" => h.new_string(String::new()),
_ => h.new_hash(IndexMap::new()),
})
} else {
match root {
"String" => with_host(|h| {
let s = args.first().and_then(|a| h.as_str(a)).unwrap_or_default();
h.new_string(s)
}),
"Array"
if args.len() == 1 && with_host(|h| h.as_array(&args[0])).is_some() =>
{
with_host(|h| {
let items = h.as_array(&args[0]).unwrap_or_default();
h.new_array(items)
})
}
"Array" => {
let n =
args.first().map(to_int).transpose()?.unwrap_or(0).max(0) as usize;
let items: Vec<Value> = if let Some(bl) = &block {
(0..n)
.map(|i| call_proc(bl, &[Value::Int(i as i64)]))
.collect::<Result<_, _>>()?
} else {
let fill = args.get(1).cloned().unwrap_or(Value::Undef);
vec![fill; n]
};
with_host(|h| h.new_array(items))
}
_ => with_host(|h| {
let default = args.first().cloned().unwrap_or(Value::Undef);
h.new_hash_with_default(IndexMap::new(), default)
}),
}
};
with_host(|h| h.set_class_override(&obj, cls));
if has_init {
call_instance_method(obj.clone(), cls, "initialize", args, block)?;
}
return Ok(obj);
}
if with_host(|h| h.find_method(cls, "initialize")).is_some() {
let obj = with_host(|h| h.new_object(cls));
call_instance_method(obj.clone(), cls, "initialize", args, block)?;
Ok(obj)
} else if cls == "SystemExit" {
let (status, msg_arg) = match args.first() {
Some(Value::Bool(b)) => (i64::from(!*b), args.get(1)),
Some(v @ Value::Int(_)) => (as_i(v), args.get(1)),
other => (0, other),
};
let msg = match msg_arg {
Some(a) if !matches!(a, Value::Undef) => with_host(|h| h.to_s(a)),
_ => cls.to_string(),
};
let exc = with_host(|h| h.new_exception(cls, &msg));
with_host(|h| h.set_ivar_of(&exc, "status", Value::Int(status)));
Ok(exc)
} else if is_exception_class(cls) {
let exc = with_host(|h| h.new_exception(cls, cls));
exception_initialize(&exc, cls, args)?;
Ok(exc)
} else {
Ok(with_host(|h| h.new_object(cls)))
}
}
"name" if cls.starts_with("#<") => Ok(Value::Undef),
"inspect" if with_host(|h| h.struct_def(cls)).is_some_and(|(_, k)| k == Some(true)) => {
Ok(new_str(format!("{cls}(keyword_init: true)")))
}
"name" | "to_s" | "inspect" => Ok(new_str(cls.to_string())),
"attr" | "attr_accessor" | "attr_reader" | "attr_writer" => {
let reader = name != "attr_writer";
let writer = matches!(name, "attr_accessor" | "attr_writer");
for a in args {
if matches!(a, Value::Bool(_)) {
continue;
}
let field = name_of(a);
with_host(|h| h.add_attr(cls, &field, reader, writer));
}
Ok(Value::Undef)
}
"include" | "prepend" | "extend" if !args.is_empty() => {
for a in args {
if let Some(m) = with_host(|h| h.classref_name(a)) {
let feat = match name {
"include" => Some("append_features"),
"prepend" => Some("prepend_features"),
_ => None,
};
let has_feat = feat
.map(|f| with_host(|h| h.find_class_method(&m, f)).is_some())
.unwrap_or(false);
if let (true, Some(f)) = (has_feat, feat) {
with_host(|h| h.remove_mixin(cls, &m, name));
let target = with_host(|h| h.class_ref(cls));
dispatch(a, f, &[target], None)?;
} else {
with_host(|h| h.class_mixin(cls, &m, name));
}
let hook = match name {
"include" => "included",
"prepend" => "prepended",
_ => "extended",
};
if with_host(|h| h.find_class_method(&m, hook)).is_some() {
let target = with_host(|h| h.class_ref(cls));
dispatch(a, hook, &[target], None)?;
}
}
}
Ok(with_host(|h| h.class_ref(cls)))
}
"superclass" if with_host(|h| h.is_module_name(cls)) => Err(raise_exc(
"NoMethodError",
&format!("undefined method 'superclass' for module {cls}"),
)),
"superclass" => Ok(with_host(|h| match h.class_superclass(cls) {
Some(sc) => h.class_ref(&sc),
None => Value::Undef,
})),
"subclasses" | "descendants" => {
let names = with_host(|h| {
if name == "subclasses" {
h.direct_subclasses(cls)
} else {
h.all_descendants(cls)
}
});
let refs: Vec<Value> = names
.iter()
.map(|n| with_host(|h| h.class_ref(n)))
.collect();
Ok(with_host(|h| h.new_array(refs)))
}
"singleton_class?" => Ok(Value::Bool(
crate::host::RubyHost::metaclass_attached(cls).is_some(),
)),
"nesting" if cls == "Module" => Ok(new_arr(vec![])),
"<=>" if args.len() == 1 => Ok(with_host(|h| {
let Some(other) = h.classref_name(&args[0]) else {
return Value::Undef;
};
if other == cls {
Value::Int(0)
} else if h.class_ancestry(cls).contains(&other) {
Value::Int(-1)
} else if h.class_ancestry(&other).iter().any(|a| a == cls) {
Value::Int(1)
} else {
Value::Undef
}
})),
"ancestors" => Ok(with_host(|h| {
let refs: Vec<Value> = h
.class_ancestry(cls)
.iter()
.map(|n| h.class_ref(n))
.collect();
h.new_array(refs)
})),
"included_modules" if args.is_empty() => Ok(with_host(|h| {
let mods: Vec<String> = h
.class_ancestry(cls)
.into_iter()
.filter(|n| n.as_str() != cls && h.is_module_name(n))
.collect();
let refs: Vec<Value> = mods.iter().map(|n| h.class_ref(n)).collect();
h.new_array(refs)
})),
"include?" if !args.is_empty() => {
let target = with_host(|h| h.classref_name(&args[0]));
Ok(Value::Bool(match target {
Some(t) => {
with_host(|h| h.class_ancestry(cls).iter().any(|n| *n != cls && *n == t))
}
None => false,
}))
}
"instance_methods"
| "public_instance_methods"
| "private_instance_methods"
| "protected_instance_methods" => {
let want: &[crate::host::Visibility] = match name {
"instance_methods" => &[
crate::host::Visibility::Public,
crate::host::Visibility::Protected,
],
"public_instance_methods" => &[crate::host::Visibility::Public],
"private_instance_methods" => &[crate::host::Visibility::Private],
_ => &[crate::host::Visibility::Protected],
};
let inherited = args
.first()
.map(|a| with_host(|h| h.truthy(a)))
.unwrap_or(true);
Ok(with_host(|h| {
let names = h.instance_method_names_vis(cls, inherited, want);
let syms: Vec<Value> = names.iter().map(|n| h.new_symbol(n)).collect();
h.new_array(syms)
}))
}
"method_defined?"
| "public_method_defined?"
| "private_method_defined?"
| "protected_method_defined?" => {
let m = name_of(&args[0]);
if mixin_provides(cls, &m) || struct_provides(cls, &m) {
return Ok(Value::Bool(name != "private_method_defined?"));
}
Ok(Value::Bool(with_host(|h| {
if !h.is_method_defined(cls, &m) {
return false;
}
let vis = h.method_visibility(cls, &m);
match name {
"method_defined?" => vis != crate::host::Visibility::Private,
"public_method_defined?" => vis == crate::host::Visibility::Public,
"private_method_defined?" => vis == crate::host::Visibility::Private,
_ => vis == crate::host::Visibility::Protected,
}
})))
}
"class_variable_get" => {
let raw = name_of(&args[0]);
let key = raw.strip_prefix("@@").unwrap_or(&raw);
let v = with_host(|h| h.get_cvar(cls, key));
if matches!(v, Value::Undef) {
return Err(raise_exc(
"NameError",
&format!("uninitialized class variable {raw} in {cls}"),
));
}
Ok(v)
}
"class_variable_set" => {
let raw = name_of(&args[0]);
let key = raw.strip_prefix("@@").unwrap_or(&raw).to_string();
let val = args[1].clone();
with_host(|h| h.set_cvar(cls, &key, val.clone()));
Ok(val)
}
"class_variable_defined?" => {
let raw = name_of(&args[0]);
let key = raw.strip_prefix("@@").unwrap_or(&raw);
Ok(Value::Bool(with_host(|h| h.cvar_defined(cls, key))))
}
"class_variables" => Ok(with_host(|h| {
let syms: Vec<Value> = h
.class_var_names(cls)
.iter()
.map(|n| h.new_symbol(&format!("@@{n}")))
.collect();
h.new_array(syms)
})),
"singleton_class" => Ok(with_host(|h| h.class_ref(&format!("#<Class:{cls}>")))),
"Errno" if args.is_empty() && errno_of_class(cls).is_some() => {
Ok(Value::Int(i64::from(errno_of_class(cls).unwrap_or(0))))
}
"exception" if is_exception_class(cls) => dispatch_classref(cls, "new", args, block),
"refine" if args.len() == 1 && with_host(|h| h.is_module_name(cls)) => {
let Some(target) = with_host(|h| h.classref_name(&args[0])) else {
let cname = with_host(|h| h.class_of(&args[0]));
return Err(raise_exc(
"TypeError",
&format!("wrong argument type {cname} (expected Class or Module)"),
));
};
let Some(bl) = block else {
return Err(raise_exc("ArgumentError", "no block given"));
};
let refname = with_host(|h| h.define_refinement(cls, &target));
let rref = with_host(|h| h.class_ref(&refname));
crate::host::eval_block_scoped(
&bl,
&rref,
crate::host::DefTarget::Instance(refname),
std::slice::from_ref(&rref),
)?;
Ok(rref)
}
"refinements" if args.is_empty() => Ok(with_host(|h| {
let refs: Vec<Value> = h
.refinements_of(cls)
.iter()
.map(|(_, r)| h.class_ref(r))
.collect();
h.new_array(refs)
})),
"target" | "refined_class" if args.is_empty() && cls.starts_with("#<refinement:") => {
Ok(with_host(|h| {
let t = h.refinement_target(cls).unwrap_or_default();
h.class_ref(&t)
}))
}
"using" if args.len() == 1 && with_host(|h| h.classref_name(&args[0])).is_some() => {
activate_refinements(&args[0])?;
Ok(recv_ref(cls))
}
"used_modules" if cls == "Module" && args.is_empty() => Ok(with_host(|h| {
let mods: Vec<Value> = h.used_modules().iter().map(|m| h.class_ref(m)).collect();
h.new_array(mods)
})),
"import_methods" if cls.starts_with("#<refinement:") => {
for m in args {
let Some(src) = with_host(|h| h.classref_name(m)) else {
continue;
};
let copied = with_host(|h| h.copy_methods_into(&src, cls));
if !copied {
return Err(raise_exc(
"ArgumentError",
&format!("Can't import method which is not defined with Ruby code: {src}"),
));
}
}
Ok(recv_ref(cls))
}
"instance_method" | "public_instance_method" => {
let m = name_of(&args[0]);
let owner = with_host(|h| h.class_ref(cls));
method_object_or_name_error(&owner, &m, true)?;
Ok(with_host(|h| h.new_unbound_method(owner.clone(), &m)))
}
"INFINITY" if cls == "Float" => Ok(Value::Float(f64::INFINITY)),
"NAN" if cls == "Float" => Ok(Value::Float(f64::NAN)),
"MAX" if cls == "Float" => Ok(Value::Float(f64::MAX)),
"MIN" if cls == "Float" => Ok(Value::Float(f64::MIN_POSITIVE)),
"EPSILON" if cls == "Float" => Ok(Value::Float(f64::EPSILON)),
"DIG" if cls == "Float" => Ok(Value::Int(15)),
"MANT_DIG" if cls == "Float" => Ok(Value::Int(53)),
"===" => Ok(Value::Bool(with_host(|h| h.is_a(&args[0], cls)))),
"[]" if cls == "Hash" => {
if args.len() == 1 && with_host(|h| h.as_hash(&args[0]).is_some()) {
let m = with_host(|h| h.as_hash(&args[0]).unwrap());
return Ok(with_host(|h| h.new_hash(m)));
}
let mut map = IndexMap::new();
if args.len() == 1 && with_host(|h| h.as_array(&args[0])).is_some() {
for (i, p) in with_host(|h| h.as_array(&args[0]).unwrap())
.iter()
.enumerate()
{
let Some(pair) = with_host(|h| h.as_array(p)) else {
let cls = with_host(|h| h.class_of(p));
return Err(raise_exc(
"ArgumentError",
&format!("wrong element type {cls} at {i} (expected array)"),
));
};
let Some(k) = pair.first() else { continue };
let k = with_host(|h| h.value_to_key(k));
map.insert(k, pair.get(1).cloned().unwrap_or(Value::Undef));
}
return Ok(with_host(|h| h.new_hash(map)));
}
if args.len() % 2 != 0 {
return Err(raise_exc(
"ArgumentError",
"odd number of arguments for Hash",
));
}
for pair in args.chunks(2) {
let k = with_host(|h| h.value_to_key(&pair[0]));
map.insert(k, pair[1].clone());
}
Ok(with_host(|h| h.new_hash(map)))
}
"[]" if cls == "Array" => Ok(new_arr(args.to_vec())),
"const_get" => {
let cname = name_of(&args[0]);
let segment_ok = |s: &str| s.starts_with(|c: char| c.is_ascii_uppercase());
if !cname.split("::").all(segment_ok) {
return Err(raise_exc_with(
"NameError",
&format!("wrong constant name {cname}"),
&[("name", args[0].clone())],
));
}
match const_lookup_under(cls, &cname) {
Some(v) => Ok(v),
None => {
let key = if cls == "Object" {
cname.clone()
} else {
format!("{cls}::{cname}")
};
const_miss(&key)
}
}
}
"const_set" => {
let cname = name_of(&args[0]);
let val = args.get(1).cloned().unwrap_or(Value::Undef);
let key = const_key_under(cls, &cname);
let val = with_host(|h| match h.classref_name(&val) {
Some(cref) if h.is_anon_class(&cref) => {
h.rename_class(&cref, &key);
h.class_ref(&key)
}
_ => val.clone(),
});
with_host(|h| h.set_const(&key, val.clone()));
Ok(val)
}
"const_defined?" => {
let cname = name_of(&args[0]);
Ok(Value::Bool(const_lookup_under(cls, &cname).is_some()))
}
"remove_const" => {
let cname = name_of(&args[0]);
let key = const_key_under(cls, &cname);
Ok(with_host(|h| h.remove_const(&key)))
}
"undef_method" | "remove_method" => {
for a in args {
let m = name_of(a);
with_host(|h| h.remove_instance_method(cls, &m));
}
Ok(with_host(|h| h.class_ref(cls)))
}
"constants" if cls != "Object" => {
let inherit = !matches!(args.first(), Some(a) if !with_host(|h| h.truthy(a)));
Ok(with_host(|h| {
let syms: Vec<Value> = h
.module_constants(cls, inherit)
.iter()
.map(|n| h.new_symbol(n))
.collect();
h.new_array(syms)
}))
}
"constants" => Ok(with_host(|h| {
let syms: Vec<Value> = h.const_names().iter().map(|n| h.new_symbol(n)).collect();
h.new_array(syms)
})),
"define_method" => {
let mname = name_of(&args[0]);
let proc = block.or_else(|| args.get(1).cloned()).ok_or_else(|| {
raise_exc(
"ArgumentError",
"tried to create Proc object without a block",
)
})?;
with_host(|h| h.add_define_method(cls, &mname, proc));
if let Some(attached) = crate::host::RubyHost::metaclass_attached(cls) {
let attached = attached.to_string();
with_host(|h| h.remove_class_method(&attached, &mname));
}
fire_added_on(cls, &mname)?;
Ok(with_host(|h| h.new_symbol(&mname)))
}
"alias_method" if args.len() >= 2 => {
let (new_name, old_name) = (name_of(&args[0]), name_of(&args[1]));
with_host(|h| h.register_alias(cls, &new_name, &old_name));
fire_added_on(cls, &new_name)?;
Ok(with_host(|h| h.new_symbol(&new_name)))
}
_ => {
if let Some((def, owner)) = with_host(|h| h.find_class_method_owner(cls, name)) {
let recv = with_host(|h| h.class_ref(cls));
return crate::host::call_class_method(recv, &def, name, &owner, args, block);
}
if let Some(target) = with_host(|h| h.find_alias(&format!("#<Class:{cls}>"), name)) {
if target != name {
return dispatch_classref(cls, &target, args, block);
}
}
for base in ["Class", "Module"] {
if let Some((def, owner)) = with_host(|h| h.find_method_owner(base, name)) {
let recv = with_host(|h| h.class_ref(cls));
return crate::host::call_class_method(recv, &def, name, &owner, args, block);
}
}
let sing = format!("#<Class:{cls}>");
if let Some((field, writer)) = with_host(|h| h.attr_access(&sing, name)) {
let recv = with_host(|h| h.class_ref(cls));
if writer {
let val = args[0].clone();
with_host(|h| h.set_ivar_of(&recv, &field, val.clone()));
return Ok(val);
}
return Ok(with_host(|h| h.ivar_of(&recv, &field)));
}
if args.is_empty() && name.chars().next().is_some_and(|c| c.is_uppercase()) {
let qualified = format!("{cls}::{name}");
if with_host(|h| h.has_const(&qualified)) {
return Ok(with_host(|h| h.get_const(&qualified)));
}
if with_host(|h| h.class_exists(&qualified) || h.is_builtin_class(&qualified)) {
return Ok(with_host(|h| h.class_ref(&qualified)));
}
if let Some(path) = with_host(|h| h.take_autoload(&qualified)) {
let pv = with_host(|h| h.new_string(path));
do_require(&[pv], ReqMode::Require)?;
let v = with_host(|h| h.get_const(&qualified));
if !matches!(v, Value::Undef) {
return Ok(v);
}
if with_host(|h| h.class_exists(&qualified)) {
return Ok(with_host(|h| h.class_ref(&qualified)));
}
}
for anc in with_host(|h| h.class_ancestry(cls)) {
if anc == cls {
continue;
}
let inherited = format!("{anc}::{name}");
if let Some(path) = with_host(|h| h.take_autoload(&inherited)) {
let pv = with_host(|h| h.new_string(path));
do_require(&[pv], ReqMode::Require)?;
}
if with_host(|h| h.has_const(&inherited)) {
return Ok(with_host(|h| h.get_const(&inherited)));
}
if with_host(|h| h.class_exists(&inherited)) {
return Ok(with_host(|h| h.class_ref(&inherited)));
}
}
}
if with_host(|h| h.is_module_function_module(cls) && h.is_method_defined(cls, name)) {
let recv = with_host(|h| h.class_ref(cls));
return call_instance_method(recv, cls, name, args, block);
}
if args.is_empty() && name.chars().next().is_some_and(|c| c.is_uppercase()) {
if let Some(def) = with_host(|h| h.find_class_method(cls, "const_missing")) {
let recv = with_host(|h| h.class_ref(cls));
let sym = with_host(|h| h.new_symbol(name));
return crate::host::call_class_method(
recv,
&def,
"const_missing",
cls,
&[sym],
None,
);
}
return Err(raise_exc(
"NameError",
&format!("uninitialized constant {cls}::{name}"),
));
}
let class_method_missing = |block: Option<Value>| {
with_host(|h| h.find_class_method(cls, "method_missing")).map(|def| {
let recv = with_host(|h| h.class_ref(cls));
let sym = with_host(|h| h.new_symbol(name));
let mut mm_args = vec![sym];
mm_args.extend_from_slice(args);
crate::host::call_class_method(
recv,
&def,
"method_missing",
cls,
&mm_args,
block,
)
})
};
if explicit_recv {
return class_method_missing(block).unwrap_or_else(|| {
Err(raise_exc(
"NoMethodError",
&format!(
"private method '{name}' called for {}",
receiver_phrase(&with_host(|h| h.class_ref(cls)))
),
))
});
}
let kernel_block = block.clone();
match kernel(name, args, block) {
Err(e)
if e == format!("undefined method '{name}'")
|| e.starts_with(&format!("undefined method '{name}' ")) =>
{
class_method_missing(kernel_block).unwrap_or_else(|| {
Err(raise_exc(
"NoMethodError",
&format!(
"undefined method '{name}' for {} {cls}",
with_host(|h| h.class_or_module_word(cls))
),
))
})
}
other => other,
}
}
}
}
fn const_key_under(cls: &str, name: &str) -> String {
if matches!(cls, "Object" | "Kernel" | "BasicObject") {
name.to_string()
} else {
format!("{cls}::{name}")
}
}
fn const_lookup_under(cls: &str, name: &str) -> Option<Value> {
let mut cur = Some(cls.to_string());
let mut guard = 0;
while let Some(c) = cur {
if let Some(v) = const_lookup(&const_key_under(&c, name)) {
return Some(v);
}
guard += 1;
if guard > 100 {
break; }
cur = with_host(|h| h.superclass_of(&c));
}
const_lookup(name).or_else(|| {
let leaf = name.rsplit("::").next().unwrap_or(name);
const_lookup(leaf)
})
}
fn const_lookup(name: &str) -> Option<Value> {
with_host(|h| {
if h.has_const(name) {
return Some(h.get_const(name));
}
if h.class_exists(name) || h.is_builtin_class(name) {
return Some(h.class_ref(name));
}
None
})
.or_else(|| {
if builtin_exception_const(name) {
Some(with_host(|h| h.class_ref(name)))
} else {
None
}
})
}
fn struct_method(
recv: &Value,
cls: &str,
members: &[String],
name: &str,
args: &[Value],
block: &Option<Value>,
) -> Result<Option<Value>, String> {
let values = || -> Vec<Value> {
members
.iter()
.map(|m| with_host(|h| h.ivar_of(recv, m)))
.collect()
};
let is_data = with_host(|h| h.is_data_class(cls));
if let Some(m) = name.strip_suffix('=') {
if !is_data && members.iter().any(|mm| mm == m) {
frozen_guard(recv, name, &[name])?;
with_host(|h| h.set_ivar_of(recv, m, args[0].clone()));
return Ok(Some(args[0].clone()));
}
}
if members.iter().any(|m| m == name) {
return Ok(Some(with_host(|h| h.ivar_of(recv, name))));
}
if is_data
&& !matches!(
name,
"members"
| "to_h"
| "deconstruct_keys"
| "with"
| "deconstruct"
| "inspect"
| "to_s"
| "=="
| "eql?"
)
{
return Ok(None);
}
let r = match name {
"to_a" | "values" | "deconstruct" => new_arr(values()),
"members" => new_arr(
members
.iter()
.map(|m| with_host(|h| h.new_symbol(m)))
.collect(),
),
"size" | "length" => Value::Int(members.len() as i64),
"to_h" => {
let mut map = IndexMap::new();
for (m, v) in members.iter().zip(values()) {
map.insert(RKey::Sym(m.clone()), v);
}
let hash = with_host(|h| h.new_hash(map));
match block {
Some(b) => dispatch(&hash, "to_h", &[], Some(b.clone()))?,
None => hash,
}
}
"deconstruct_keys" => {
let mut map = IndexMap::new();
let wanted = match args.first() {
None | Some(Value::Undef) => None,
Some(a) => match with_host(|h| h.as_array(a)) {
Some(req) => Some(req),
None => {
let cname = with_host(|h| h.class_of(a));
return Err(raise_exc(
"TypeError",
&format!("wrong argument type {cname} (expected Array or nil)"),
));
}
},
};
match wanted {
Some(req) => {
if req.len() > members.len() {
return Ok(Some(with_host(|h| h.new_hash(map))));
}
for k in req {
let Some(m) = with_host(|h| h.as_symbol(&k)) else {
break;
};
if !members.contains(&m) {
break;
}
let v = with_host(|h| h.ivar_of(recv, &m));
map.insert(RKey::Sym(m), v);
}
}
None => {
for (m, v) in members.iter().zip(values()) {
map.insert(RKey::Sym(m.clone()), v);
}
}
}
with_host(|h| h.new_hash(map))
}
"[]" if args.len() == 1 => {
let i = struct_pos(members, &args[0])?;
with_host(|h| h.ivar_of(recv, &members[i]))
}
"[]=" if args.len() == 2 => {
let i = struct_pos(members, &args[0])?;
frozen_guard(recv, "[]=", &["[]="])?;
with_host(|h| h.set_ivar_of(recv, &members[i], args[1].clone()));
args[1].clone()
}
"each" if block.is_some() => {
let bl = block.clone().unwrap();
for v in values() {
call_proc(&bl, &[v])?;
}
recv.clone()
}
"each" => with_host(|h| h.new_enumerator(values(), "each")),
"values_at" => {
let vals = values();
let size = vals.len() as i64;
let mut out = Vec::new();
for a in args {
if let Some(rng) = with_host(|h| h.as_range(a)) {
let (beg, len) = range_beg_len(a, rng, size)?;
for j in beg..beg + len {
out.push(vals.get(j as usize).cloned().unwrap_or(Value::Undef));
}
continue;
}
let i = to_int(a)?;
if i >= size {
return Err(raise_exc(
"IndexError",
&format!("offset {i} too large for struct(size:{size})"),
));
}
if i < -size {
return Err(raise_exc(
"IndexError",
&format!("offset {i} too small for struct(size:{size})"),
));
}
out.push(vals[norm_idx(i, vals.len()).unwrap_or(0)].clone());
}
new_arr(out)
}
"each_pair" if block.is_none() => with_host(|h| {
let pairs: Vec<Value> = members
.iter()
.map(|m| {
let sym = h.new_symbol(m);
let v = h.ivar_of(recv, m);
h.new_array(vec![sym, v])
})
.collect();
h.new_enumerator(pairs, "each")
}),
"each_pair" if block.is_some() => {
let bl = block.clone().unwrap();
for (m, v) in members.iter().zip(values()) {
let pair = with_host(|h| {
let sym = h.new_symbol(m);
h.new_array(vec![sym, v])
});
call_proc(&bl, &[pair])?;
}
recv.clone()
}
"==" | "eql?" => {
let strict = name == "eql?";
let same = with_host(|h| h.object_class(&args[0])).as_deref() == Some(cls)
&& members.iter().zip(values()).all(|(m, v)| {
with_host(|h| {
let other = h.ivar_of(&args[0], m);
if strict {
h.eql_values(&other, &v)
} else {
h.eq_values(&other, &v)
}
})
});
Value::Bool(same)
}
"to_s" | "inspect" => {
let parts: Vec<String> = members
.iter()
.zip(values())
.map(|(m, v)| format!("{m}={}", with_host(|h| h.inspect(&v))))
.collect();
new_str(with_host(|h| h.struct_inspect(cls, &parts)))
}
"with" if with_host(|h| h.is_data_class(cls)) => {
let kwargs_only = args.len() == 1 && with_host(|h| h.is_kwargs(&args[0]));
if args.is_empty() {
return Ok(Some(recv.clone()));
}
if !kwargs_only {
return Err(raise_exc(
"ArgumentError",
&format!(
"wrong number of arguments (given {}, expected 0)",
args.len()
),
));
}
let obj = with_host(|h| h.new_object(cls));
for m in members {
let cur = with_host(|h| h.ivar_of(recv, m));
with_host(|h| h.set_ivar_of(&obj, m, cur));
}
if let Some(k) = args.first().and_then(|a| with_host(|h| h.as_hash(a))) {
for (key, v) in &k {
match key {
RKey::Sym(m) if members.iter().any(|mm| mm == m) => {
with_host(|h| h.set_ivar_of(&obj, m, v.clone()));
}
RKey::Sym(m) => {
return Err(raise_exc(
"ArgumentError",
&format!("unknown keyword: :{m}"),
))
}
_ => {
return Err(raise_exc("ArgumentError", "unknown keyword"));
}
}
}
}
with_host(|h| h.freeze_value(&obj));
obj
}
"dig" if !args.is_empty() => {
let vals = values();
let first = match &args[0] {
Value::Int(i) => norm_idx(*i, vals.len()).and_then(|k| vals.get(k)).cloned(),
other => {
let key = with_host(|h| h.as_symbol(other).or_else(|| h.as_str(other)));
key.and_then(|k| members.iter().position(|m| *m == k))
.and_then(|i| vals.get(i))
.cloned()
}
}
.unwrap_or(Value::Undef);
if args.len() == 1 || matches!(first, Value::Undef) {
return Ok(Some(first));
}
return Ok(Some(dispatch(&first, "dig", &args[1..], None)?));
}
_ => {
let delegated = dispatch_array(&new_arr(values()), name, args, block.clone());
return match delegated {
Err(e)
if e.starts_with("undefined method") && e.contains("an instance of Array") =>
{
Ok(None)
}
other => other.map(Some),
};
}
};
Ok(Some(r))
}
fn dispatch_object(
recv: &Value,
cls: &str,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
if with_host(|h| h.has_own_define_method(cls, name) && !h.has_own_method(cls, name)) {
if let Some(proc) = with_host(|h| h.find_define_method(cls, name)) {
return crate::host::call_proc_self_ctx(
&proc,
args,
Some(recv),
Some((name.to_string(), cls.to_string())),
block,
);
}
}
if with_host(|h| h.find_method_owner(cls, name)).is_some() {
return call_instance_method(recv.clone(), cls, name, args, block);
}
if let Some(proc) = with_host(|h| h.find_define_method(cls, name)) {
return crate::host::call_proc_self_ctx(
&proc,
args,
Some(recv),
Some((name.to_string(), cls.to_string())),
block,
);
}
if let Some(target) = with_host(|h| h.find_alias(cls, name)) {
return dispatch(recv, &target, args, block);
}
if let Some(nat) = with_host(|h| h.native_kernel_alias(cls, name)) {
return kernel(&nat, args, block);
}
dispatch_object_native(recv, cls, name, args, block)
}
pub(crate) fn dispatch_object_native(
recv: &Value,
cls: &str,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
if let Some((members, _)) = with_host(|h| h.struct_def(cls)) {
if let Some(r) = struct_method(recv, cls, &members, name, args, &block)? {
return Ok(r);
}
}
if with_host(|h| h.is_a(recv, "Comparable")) {
if let Some(r) = comparable_method(recv, name, args)? {
return Ok(r);
}
}
if with_host(|h| h.is_a(recv, "Enumerable")) {
if let Some(r) = enumerable_method(recv, name, args, block.clone())? {
return Ok(r);
}
}
if cls == "OpenStruct" {
if let Some(r) = openstruct_method(recv, name, args, block.clone())? {
return Ok(r);
}
}
if cls == "ERB" {
if let Some(r) = erb_method(recv, name, args)? {
return Ok(r);
}
}
if cls == "StringIO" {
return stringio_method(recv, name, args, block);
}
if cls == "Encoding" {
if let Some(r) = encoding_method(recv, name)? {
return Ok(r);
}
}
if cls == "Random" {
if let Some(r) = random_method(recv, name, args)? {
return Ok(r);
}
}
if cls == "Mutex" || cls == "Thread::Mutex" || cls == "Monitor" {
if let Some(r) = mutex_method(recv, name, block.clone())? {
return Ok(r);
}
}
if cls == "Queue" || cls == "SizedQueue" {
if let Some(r) = queue_method(recv, name, args)? {
return Ok(r);
}
}
if cls == "ConditionVariable" {
if let Some(r) = condvar_method(recv, name, args)? {
return Ok(r);
}
}
if matches!(cls, "Digest::SHA256" | "Digest::SHA1" | "Digest::MD5") {
if let Some(r) = digest_instance_method(recv, cls, name, args)? {
return Ok(r);
}
}
match name {
"message" | "to_s" => {
if name == "message" && defines_own(recv, "to_s") {
return dispatch(recv, "to_s", &[], None);
}
let m = with_host(|h| h.ivar_of(recv, "message"));
if matches!(m, Value::Undef) {
Ok(new_str(cls.to_string()))
} else {
Ok(m)
}
}
"name"
if matches!(
exception_init_owner(cls),
Some("NameError" | "NoMethodError")
) =>
{
if let Some(stored) = with_host(|h| h.ivar_lookup(recv, "name")) {
return Ok(stored);
}
let msg = with_host(|h| h.as_str(&h.ivar_of(recv, "message"))).unwrap_or_default();
match msg.split('\'').nth(1) {
Some(nm) => Ok(with_host(|h| h.new_symbol(nm))),
None => Ok(Value::Undef),
}
}
"key" | "receiver" | "matchee" if exception_reader_raises(cls, name) => {
match with_host(|h| (h.ivar_lookup(recv, name), h.is_initialized_exception(recv))) {
(Some(v), _) => Ok(v),
(None, true) => Err(raise_exc(
"ArgumentError",
&format!("no {name} is available"),
)),
(None, false) => Ok(Value::Undef),
}
}
"result" | "path" | "reason" | "exit_value" | "errno" | "destination_encoding"
if with_host(|h| h.is_exception_class(cls)) =>
{
Ok(with_host(|h| h.ivar_of(recv, name)))
}
"tag" | "value" if cls == "UncaughtThrowError" => Ok(with_host(|h| h.ivar_of(recv, name))),
"args" if exception_init_owner(cls) == Some("NoMethodError") => {
Ok(with_host(|h| h.ivar_lookup(recv, "args")).unwrap_or_else(|| new_arr(Vec::new())))
}
"private_call?" if exception_init_owner(cls) == Some("NoMethodError") => {
Ok(with_host(|h| h.ivar_lookup(recv, "private_call?")).unwrap_or(Value::Bool(false)))
}
"status" | "success?" if cls == "SystemExit" => {
let code = match with_host(|h| h.ivar_of(recv, "status")) {
Value::Undef => 0,
v => as_i(&v),
};
Ok(if name == "status" {
Value::Int(code)
} else {
Value::Bool(code == 0)
})
}
"backtrace" if is_exception_class(cls) => Ok(match with_host(|h| h.exc_backtrace(recv)) {
Some(frames) => new_arr(frames.into_iter().map(new_str).collect()),
None => Value::Undef,
}),
"backtrace_locations" if is_exception_class(cls) => Ok(exc_backtrace_locations(recv)),
"set_backtrace" if is_exception_class(cls) => {
let arg = args.first().cloned().unwrap_or(Value::Undef);
let raised_locs = exc_backtrace_locations(recv);
let mut from_locations = false;
let frames = match with_host(|h| h.as_array(&arg)) {
Some(items) if !items.is_empty() && items.iter().all(is_backtrace_location) => {
from_locations = true;
Some(items.iter().map(location_frame).collect())
}
Some(items) => {
let strs: Option<Vec<String>> =
items.iter().map(|v| with_host(|h| h.as_str(v))).collect();
Some(strs.ok_or_else(backtrace_type_error)?)
}
None if matches!(arg, Value::Undef) => None,
None => Some(vec![
with_host(|h| h.as_str(&arg)).ok_or_else(backtrace_type_error)?
]),
};
with_host(|h| {
if from_locations {
h.set_exc_backtrace_locations(recv, None);
h.set_string_backtrace(recv, false);
} else if !matches!(raised_locs, Value::Undef) {
h.set_exc_backtrace_locations(recv, Some(raised_locs.clone()));
} else if frames.is_some() {
h.set_string_backtrace(recv, true);
}
});
match frames {
Some(frames) if with_host(|h| h.as_array(&arg)).is_none() => {
with_host(|h| h.set_exc_backtrace(recv, Some(frames.clone())));
Ok(new_arr(frames.into_iter().map(new_str).collect()))
}
Some(frames) => {
with_host(|h| h.set_exc_backtrace(recv, Some(frames)));
Ok(arg)
}
None => {
with_host(|h| h.set_exc_backtrace(recv, None));
Ok(arg)
}
}
}
"cause" if is_exception_class(cls) => Ok(with_host(|h| h.ivar_of(recv, "cause"))),
"exception" if is_exception_class(cls) && args.len() <= 1 => match args.first() {
None => Ok(recv.clone()),
Some(a) if identical(a, recv) => Ok(recv.clone()),
Some(m) => {
let copy = with_host(|h| h.dup_value(recv));
with_host(|h| {
let sv = if matches!(m, Value::Undef) {
Value::Undef
} else {
let s = h.to_s(m);
h.new_string(s)
};
h.set_ivar_of(©, "message", sv);
});
Ok(copy)
}
},
"detailed_message" if is_exception_class(cls) => {
let highlight = exc_highlight_opt(args, false)?;
Ok(new_str(exc_detailed_message(recv, cls, highlight)?))
}
"full_message" if is_exception_class(cls) => {
use std::io::IsTerminal;
let highlight = exc_highlight_opt(args, std::io::stderr().is_terminal())?;
let bottom = match kw_opt(args, "order") {
None | Some(Value::Undef) => false,
Some(v) => match with_host(|h| h.as_symbol(&v)).as_deref() {
Some("top") => false,
Some("bottom") => true,
_ => {
let insp = with_host(|h| h.inspect(&v));
return Err(raise_exc(
"ArgumentError",
&format!("expected :top or :bottom as order: {insp}"),
));
}
},
};
let detailed = if defines_own(recv, "detailed_message") {
let kw = with_host(|h| {
let mut m = IndexMap::new();
m.insert(RKey::Sym("highlight".into()), Value::Bool(highlight));
let v = h.new_hash(m);
h.mark_kwargs(&v);
v
});
let d = dispatch(recv, "detailed_message", &[kw], None)?;
with_host(|h| h.to_s(&d))
} else {
exc_detailed_message(recv, cls, highlight)?
};
let frames = with_host(|h| h.exc_backtrace(recv)).unwrap_or_default();
let mut out = String::new();
let (head, callers) = match frames.split_first() {
Some((first, rest)) => (format!("{first}: "), rest),
None => (
crate::host::live_backtrace()
.first()
.map(|f| format!("{}:{}:in 'full_message': ", f.path, f.line))
.unwrap_or_default(),
&[][..],
),
};
if bottom && !frames.is_empty() {
out.push_str(if highlight {
"\x1b[1mTraceback\x1b[m (most recent call last):\n"
} else {
"Traceback (most recent call last):\n"
});
for (i, f) in callers.iter().enumerate().rev() {
out.push_str(&format!("\t{}: from {f}\n", i + 1));
}
}
out.push_str(&head);
out.push_str(&detailed);
out.push('\n');
if !bottom {
for f in callers {
out.push_str(&format!("\tfrom {f}\n"));
}
}
Ok(new_str(out))
}
_ if with_host(|h| {
h.singleton_class_name(recv)
.and_then(|sc| h.attr_access(&sc, name))
.or_else(|| h.attr_access(cls, name))
})
.is_some() =>
{
let (field, is_writer) = with_host(|h| {
h.singleton_class_name(recv)
.and_then(|sc| h.attr_access(&sc, name))
.or_else(|| h.attr_access(cls, name))
})
.unwrap();
if is_writer {
let v = args.first().cloned().unwrap_or(Value::Undef);
with_host(|h| h.set_ivar_of(recv, &field, v.clone()));
Ok(v)
} else {
Ok(with_host(|h| h.ivar_of(recv, &field)))
}
}
"<=>" if args.len() == 1 => Ok(if with_host(|h| h.eq_values(recv, &args[0])) {
Value::Int(0)
} else {
Value::Undef
}),
_ if with_host(|h| h.find_singleton_method(recv, "method_missing")).is_some() => {
let def = with_host(|h| h.find_singleton_method(recv, "method_missing")).unwrap();
let mut mm_args = Vec::with_capacity(args.len() + 1);
mm_args.push(with_host(|h| h.new_symbol(name)));
mm_args.extend_from_slice(args);
crate::host::call_singleton(recv.clone(), &def, "method_missing", &mm_args, block)
}
_ if with_host(|h| h.find_method_owner(cls, "method_missing")).is_some() => {
let mut mm_args = Vec::with_capacity(args.len() + 1);
mm_args.push(with_host(|h| h.new_symbol(name)));
mm_args.extend_from_slice(args);
call_instance_method(recv.clone(), cls, "method_missing", &mm_args, block)
}
_ if with_host(|h| h.has_method(name)) => {
let this = with_host(|h| h.current_self());
if matches!((recv, &this), (Value::Obj(a), Value::Obj(b)) if a == b) {
crate::host::call_method(name, args, block)
} else {
Err(raise_exc_with(
"NoMethodError",
&format!(
"private method '{name}' called for {}",
receiver_phrase(recv)
),
&[("receiver", recv.clone())],
))
}
}
_ => Err(no_method_error(recv, name)),
}
}
fn comparable_method(recv: &Value, name: &str, args: &[Value]) -> Result<Option<Value>, String> {
let spaceship = |other: &Value| -> Result<Option<i64>, String> {
match dispatch(recv, "<=>", std::slice::from_ref(other), None)? {
Value::Undef => Ok(None),
v => rb_cmpint(&v).map(Some),
}
};
let cmp_err = |other: &Value| -> String { with_host(|h| h.cmp_failed(recv, other)) };
match name {
"<" | "<=" | ">" | ">=" => {
let o = &args[0];
let Some(c) = spaceship(o)? else {
return Err(cmp_err(o));
};
let b = match name {
"<" => c < 0,
"<=" => c <= 0,
">" => c > 0,
_ => c >= 0,
};
Ok(Some(Value::Bool(b)))
}
"between?" => comparable_between(recv, args).map(Some),
"clamp" => comparable_clamp(recv, args).map(Some),
_ => Ok(None),
}
}
fn rb_cmpint(v: &Value) -> Result<i64, String> {
if let Value::Int(n) = v {
return Ok(n.signum());
}
if let Some(b) = with_host(|h| h.as_bigint(v)) {
use num_traits::Signed as _;
return Ok(if b.is_negative() { -1 } else { 1 });
}
let zero = [Value::Int(0)];
let gt = dispatch(v, ">", &zero, None)?;
if with_host(|h| h.truthy(>)) {
return Ok(1);
}
let lt = dispatch(v, "<", &zero, None)?;
Ok(if with_host(|h| h.truthy(<)) { -1 } else { 0 })
}
fn mixin_provides(class: &str, method: &str) -> bool {
let anc = with_host(|h| h.class_ancestry(class));
(anc.iter().any(|a| a == "Comparable") && COMPARABLE_METHODS.contains(&method))
|| (anc.iter().any(|a| a == "Enumerable") && ENUMERABLE_METHODS.contains(&method))
}
pub(crate) const COMPARABLE_METHODS: &[&str] = &["<", "<=", "==", ">", ">=", "between?", "clamp"];
pub(crate) const ENUMERABLE_METHODS: &[&str] = &[
"map",
"collect",
"flat_map",
"collect_concat",
"select",
"filter",
"find_all",
"grep",
"grep_v",
"filter_map",
"reject",
"reduce",
"inject",
"to_a",
"entries",
"find",
"detect",
"find_index",
"count",
"min",
"max",
"minmax",
"min_by",
"max_by",
"sort",
"sort_by",
"sum",
"include?",
"member?",
"first",
"take",
"drop",
"take_while",
"drop_while",
"each_with_index",
"each_with_object",
"group_by",
"partition",
"tally",
"uniq",
"zip",
"any?",
"all?",
"none?",
"one?",
"each_slice",
"each_cons",
"chunk_while",
"chunk",
"slice_when",
"reverse_each",
"to_h",
"to_set",
"each_entry",
"compact",
"minmax_by",
"slice_after",
"slice_before",
"cycle",
"chain",
];
fn enum_to_vec(recv: &Value) -> Result<Vec<Value>, String> {
let sink = with_host(|h| h.new_enum_sink());
dispatch(recv, "each", &[], Some(sink))?;
Ok(with_host(|h| h.take_enum_sink()))
}
fn enumerable_method(
recv: &Value,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Option<Value>, String> {
if !ENUMERABLE_METHODS.contains(&name) {
return Ok(None);
}
if name == "chain" {
return Ok(Some(make_enum_chain(recv, args)));
}
let elems = enum_to_vec(recv)?;
let arr = with_host(|h| h.new_array(elems));
let out = enum_delegate(&arr, name, args, block)?;
if with_host(|h| h.enum_source(&out)).is_some() {
with_host(|h| h.set_enum_source(&out, recv.clone()));
}
Ok(Some(out))
}
fn as_i(v: &Value) -> i64 {
match v {
Value::Int(n) => *n,
Value::Float(f) => *f as i64,
_ => 0,
}
}
fn conv_operand_name(v: &Value) -> String {
match v {
Value::Undef => "nil".to_string(),
Value::Bool(true) => "true".to_string(),
Value::Bool(false) => "false".to_string(),
_ => with_host(|h| h.class_of(v)),
}
}
fn with_index_offset(args: &[Value]) -> Result<i64, String> {
match args.first() {
None | Some(Value::Undef) => Ok(0),
Some(v) => to_int(v),
}
}
fn to_int(v: &Value) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
Value::Float(f) => Ok(*f as i64),
Value::Undef => Err(raise_exc(
"TypeError",
"no implicit conversion from nil to integer",
)),
_ => int_arg(v).ok_or_else(|| {
if with_host(|h| h.as_bigint(v)).is_some() {
return raise_exc("RangeError", "bignum too big to convert into 'long'");
}
raise_exc(
"TypeError",
&format!(
"no implicit conversion of {} into Integer",
conv_operand_name(v)
),
)
}),
}
}
fn str_append_operand(v: &Value) -> Result<String, String> {
if let Some(other) = with_host(|h| h.as_str(v)) {
return Ok(other);
}
match v {
Value::Int(n) => match u32::try_from(*n).ok().and_then(char::from_u32) {
Some(c) => Ok(c.to_string()),
None => Err(raise_exc("RangeError", &format!("{n} out of char range"))),
},
_ => Err(conv_error(v, "String")),
}
}
fn coerce_num(recv: &Value, v: &Value) -> Result<f64, String> {
let numeric = matches!(v, Value::Int(_) | Value::Float(_))
|| with_host(|h| h.as_rational(v).is_some() || h.as_bigint(v).is_some());
if numeric {
return Ok(as_f(v));
}
let (recv_class, named) = with_host(|h| (h.class_of(recv), h.coerce_operand_name(v)));
Err(raise_exc(
"TypeError",
&format!("{named} can't be coerced into {recv_class}"),
))
}
fn int_operand(v: &Value) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ => int_arg(v).ok_or_else(|| raise_exc("TypeError", "not an integer")),
}
}
pub(crate) fn conv_error(v: &Value, target: &str) -> String {
raise_exc(
"TypeError",
&format!(
"no implicit conversion of {} into {target}",
conv_operand_name(v)
),
)
}
fn int_arg(v: &Value) -> Option<i64> {
use num_traits::ToPrimitive;
match v {
Value::Int(n) => Some(*n),
Value::Obj(_) => with_host(|h| h.as_bigint(v)).and_then(|b| b.to_i64()),
_ => None,
}
}
fn as_f(v: &Value) -> f64 {
match v {
Value::Int(n) => *n as f64,
Value::Float(f) => *f,
_ => with_host(|h| {
use num_traits::ToPrimitive as _;
h.as_rational(v).and_then(|r| r.to_f64()).unwrap_or(0.0)
}),
}
}
fn default_rationalize_eps(f: f64) -> f64 {
if f == 0.0 || !f.is_finite() {
return 0.0;
}
let next = f64::from_bits(f.to_bits() + 1);
(next - f).abs() * 0.5
}
fn simplest_rational_within(f: f64, eps: f64) -> num_rational::BigRational {
use num_bigint::BigInt;
let rat = |n: i128, d: i128| num_rational::BigRational::new(BigInt::from(n), BigInt::from(d));
if eps == 0.0 || !f.is_finite() {
return num_rational::BigRational::from_float(f).unwrap_or_else(|| rat(0, 1));
}
if f < 0.0 {
return -simplest_rational_within(-f, eps);
}
fn simplest(lo: f64, hi: f64) -> (i128, i128) {
let fl = lo.floor();
if fl >= lo {
return (fl as i128, 1);
}
if fl < hi.floor() || hi.floor() >= hi {
return (fl as i128 + 1, 1);
}
let (n, d) = simplest(1.0 / (hi - fl), 1.0 / (lo - fl));
(fl as i128 * n + d, n)
}
let (n, d) = simplest(f - eps, f + eps);
rat(n, d)
}
fn simplest_rational_between(
mut a: num_rational::BigRational,
mut b: num_rational::BigRational,
) -> num_rational::BigRational {
use num_bigint::BigInt;
use num_rational::BigRational;
let one = || BigRational::from(BigInt::from(1));
let (mut p0, mut p1) = (BigRational::from(BigInt::from(0)), one());
let (mut q0, mut q1) = (one(), BigRational::from(BigInt::from(0)));
loop {
let c = a.ceil();
if c < b {
let p = &c * &p1 + &p0;
let q = &c * &q1 + &q0;
return p / q;
}
let k = &c - one();
let p2 = &k * &p1 + &p0;
let q2 = &k * &q1 + &q0;
let t = (&b - &k).recip();
b = (&a - &k).recip();
a = t;
p0 = p1;
q0 = q1;
p1 = p2;
q1 = q2;
}
}
fn string_to_rational(s: &str) -> num_rational::BigRational {
use num_bigint::BigInt;
let zero = || num_rational::BigRational::from(BigInt::from(0));
let s = s.trim_start_matches(RUBY_SPACE);
if let Some((n, d)) = s.split_once('/') {
if let (Ok(n), Ok(d)) = (
n.trim_matches(RUBY_SPACE).parse::<BigInt>(),
d.trim_matches(RUBY_SPACE).parse::<BigInt>(),
) {
if d != BigInt::from(0) {
return num_rational::BigRational::new(n, d);
}
}
}
let mut end = 0;
let bytes = s.as_bytes();
if end < bytes.len() && (bytes[end] == b'-' || bytes[end] == b'+') {
end += 1;
}
let int_start = end;
while end < bytes.len() && bytes[end].is_ascii_digit() {
end += 1;
}
let mut frac_digits = 0usize;
if end < bytes.len() && bytes[end] == b'.' {
let dot = end;
end += 1;
while end < bytes.len() && bytes[end].is_ascii_digit() {
end += 1;
}
frac_digits = end - dot - 1;
}
if end == int_start && frac_digits == 0 {
return zero();
}
let digits: String = s[..end].chars().filter(|c| *c != '.').collect();
match digits.parse::<BigInt>() {
Ok(num) => {
let den = BigInt::from(10).pow(frac_digits as u32);
num_rational::BigRational::new(num, den)
}
Err(_) => zero(),
}
}
pub(crate) const RUBY_STRIP: &[char] = &['\0', ' ', '\t', '\n', '\x0b', '\x0c', '\r'];
pub(crate) const RUBY_SPACE: &[char] = &[' ', '\t', '\n', '\x0b', '\x0c', '\r'];
pub(crate) fn is_ruby_space(b: u8) -> bool {
matches!(b, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
}
enum RatParse {
Ok(num_rational::BigRational),
Invalid,
DivZero,
}
fn parse_rational_strict(s: &str) -> RatParse {
use num_bigint::BigInt;
use num_traits::Zero as _;
let body = s.trim_matches(RUBY_SPACE);
let mut parts = body.splitn(2, '/');
let num_src = parts.next().unwrap_or("");
let den_src = parts.next();
if den_src.is_some_and(|d| d.contains('/')) {
return RatParse::Invalid;
}
let Some(num) = parse_decimal_exact(num_src, true) else {
return RatParse::Invalid;
};
let den = match den_src {
Some(d) => match parse_decimal_exact(d, false) {
Some(v) => v,
None => return RatParse::Invalid,
},
None => num_rational::BigRational::from(BigInt::from(1)),
};
if den.is_zero() {
return RatParse::DivZero;
}
RatParse::Ok(num / den)
}
fn parse_decimal_exact(s: &str, allow_sign: bool) -> Option<num_rational::BigRational> {
use num_bigint::BigInt;
let b = s.as_bytes();
let mut i = 0;
let mut neg = false;
if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
if !allow_sign {
return None;
}
neg = b[i] == b'-';
i += 1;
}
let mut digits = String::new();
let mut scale = 0i64;
let take_digits = |i: &mut usize, into: &mut String| -> usize {
let start = *i;
while *i < b.len() {
if b[*i].is_ascii_digit() {
into.push(b[*i] as char);
*i += 1;
} else if b[*i] == b'_' {
let ok = *i > start
&& b[*i - 1].is_ascii_digit()
&& b.get(*i + 1).is_some_and(u8::is_ascii_digit);
if !ok {
break;
}
*i += 1;
} else {
break;
}
}
into.len()
};
let int_len = take_digits(&mut i, &mut digits);
if i < b.len() && b[i] == b'.' {
i += 1;
let before = digits.len();
take_digits(&mut i, &mut digits);
scale = (digits.len() - before) as i64;
}
if digits.is_empty() {
return None;
}
let _ = int_len;
if i < b.len() && (b[i] | 0x20) == b'e' {
i += 1;
let mut eneg = false;
if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
eneg = b[i] == b'-';
i += 1;
}
let mut exp_digits = String::new();
take_digits(&mut i, &mut exp_digits);
let exp: i64 = exp_digits.parse().ok()?;
scale += if eneg { exp } else { -exp };
}
if i != b.len() {
return None;
}
let mut num: BigInt = digits.parse().ok()?;
if neg {
num = -num;
}
let pow = |n: i64| BigInt::from(10).pow(n.unsigned_abs() as u32);
Some(if scale > 0 {
num_rational::BigRational::new(num, pow(scale))
} else {
num_rational::BigRational::from(num * pow(scale))
})
}
fn parse_complex_str(raw: &str) -> Option<(Value, Value)> {
let t: String = raw.chars().filter(|c| *c != '_').collect();
let t = t.trim();
if t.is_empty() {
return None;
}
let num = |part: &str| -> Option<Value> {
let part = part.trim();
if part.is_empty() || part == "+" {
return Some(Value::Int(1));
}
if part == "-" {
return Some(Value::Int(-1));
}
if let Ok(n) = part.parse::<i64>() {
return Some(Value::Int(n));
}
if part.contains('/') {
return match parse_rational_strict(part) {
RatParse::Ok(r) => Some(with_host(|h| h.new_rational(r))),
_ => None,
};
}
part.parse::<f64>().ok().map(Value::Float)
};
let b = t.as_bytes();
let is_imag = |c: u8| c == b'i' || c == b'j' || c == b'I' || c == b'J';
let split = (1..b.len())
.rev()
.find(|&k| (b[k] == b'+' || b[k] == b'-') && !matches!(b[k - 1], b'e' | b'E'));
match split {
Some(k) if is_imag(*b.last()?) => {
let re = num(&t[..k])?;
let im = num(&t[k..t.len() - 1])?;
Some((re, im))
}
Some(_) => None,
None if is_imag(*b.last()?) => Some((Value::Int(0), num(&t[..t.len() - 1])?)),
None => Some((num(t)?, Value::Int(0))),
}
}
fn rational_arg(v: &Value) -> Result<num_rational::BigRational, String> {
if let Some(r) = with_host(|h| h.as_rational(v)) {
return Ok(r);
}
match v {
Value::Float(f) => {
if f.is_nan() {
return Err(raise_exc("FloatDomainError", "NaN"));
}
if f.is_infinite() {
let s = if *f > 0.0 { "Infinity" } else { "-Infinity" };
return Err(raise_exc("FloatDomainError", s));
}
num_rational::BigRational::from_float(*f)
.ok_or_else(|| raise_exc("FloatDomainError", "NaN"))
}
_ => {
if let Some(s) = with_host(|h| h.as_str(v)) {
return match parse_rational_strict(&s) {
RatParse::Ok(r) => Ok(r),
RatParse::DivZero => Err(raise_exc("ZeroDivisionError", "divided by 0")),
RatParse::Invalid => Err(raise_exc(
"ArgumentError",
&format!(
"invalid value for convert(): {}",
crate::host::inspect_string(&s)
),
)),
};
}
if let Some((re, im)) = with_host(|h| h.complex_parts(v)) {
if as_f(&im) == 0.0 {
return rational_arg(&re);
}
let shown = with_host(|h| h.to_s(v));
return Err(raise_exc(
"RangeError",
&format!("can't convert {shown} into Rational"),
));
}
Err(raise_exc(
"TypeError",
&format!("can't convert {} into Rational", type_name_for(v)),
))
}
}
}
fn now_epoch_secs() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0)
}
fn clamp_bounds(args: &[Value]) -> Result<(Option<Value>, Option<Value>), String> {
if args.len() == 1 {
let parts = with_host(|h| {
h.as_range(&args[0])
.map(|(lo, hi, ex)| {
(
(lo != crate::host::RANGE_BEGINLESS).then_some(Value::Int(lo)),
(hi != crate::host::RANGE_ENDLESS).then_some(Value::Int(hi)),
ex,
)
})
.or_else(|| {
h.as_float_range(&args[0])
.map(|(lo, hi, ex)| (Some(Value::Float(lo)), Some(Value::Float(hi)), ex))
})
.or_else(|| {
h.as_str_range(&args[0])
.map(|(lo, hi, ex)| (Some(new_str(lo)), Some(new_str(hi)), ex))
})
.or_else(|| {
h.as_obj_range(&args[0]).map(|(lo, hi, ex)| {
(
(!matches!(lo, Value::Undef)).then_some(lo),
(!matches!(hi, Value::Undef)).then_some(hi),
ex,
)
})
})
});
let Some((lo, hi, exclusive)) = parts else {
let kind = match &args[0] {
Value::Undef => "nil".to_string(),
Value::Bool(b) => b.to_string(),
v => with_host(|h| h.class_of(v)),
};
return Err(raise_exc(
"TypeError",
&format!("wrong argument type {kind} (expected Range)"),
));
};
if exclusive && hi.is_some() {
return Err(raise_exc(
"ArgumentError",
"cannot clamp with an exclusive range",
));
}
return Ok((lo, hi));
}
let opt = |v: &Value| (!matches!(v, Value::Undef)).then(|| v.clone());
Ok((opt(&args[0]), opt(&args[1])))
}
fn cmp_int(a: &Value, b: &Value) -> Result<Option<std::cmp::Ordering>, String> {
Ok(match dispatch(a, "<=>", std::slice::from_ref(b), None)? {
Value::Undef => None,
v => Some(rb_cmpint(&v)?.cmp(&0)),
})
}
fn comparable_between(recv: &Value, args: &[Value]) -> Result<Value, String> {
let (lo, hi) = (&args[0], &args[1]);
if cmp_int(recv, lo)?
.ok_or_else(|| cmp_error(recv, lo))?
.is_lt()
{
return Ok(Value::Bool(false));
}
Ok(Value::Bool(
!cmp_int(recv, hi)?
.ok_or_else(|| cmp_error(recv, hi))?
.is_gt(),
))
}
fn comparable_clamp(recv: &Value, args: &[Value]) -> Result<Value, String> {
let (lo, hi) = clamp_bounds(args)?;
if let (Some(l), Some(h)) = (&lo, &hi) {
if cmp_int(l, h)?.ok_or_else(|| cmp_error(l, h))?.is_gt() {
return Err(raise_exc(
"ArgumentError",
"min argument must be less than or equal to max argument",
));
}
}
if let Some(l) = &lo {
if cmp_int(recv, l)?.ok_or_else(|| cmp_error(recv, l))?.is_lt() {
return Ok(l.clone());
}
}
if let Some(h) = &hi {
if cmp_int(recv, h)?.ok_or_else(|| cmp_error(recv, h))?.is_gt() {
return Ok(h.clone());
}
}
Ok(recv.clone())
}
fn dispatch_bigint(
b: &num_bigint::BigInt,
name: &str,
args: &[Value],
) -> Result<Option<Value>, String> {
use num_integer::Integer as _;
use num_traits::{Signed as _, ToPrimitive as _, Zero as _};
let big = |v: num_bigint::BigInt| with_host(|h| h.new_bigint(v));
let r = match name {
"to_s" | "inspect" => {
let radix = match args.first() {
Some(v) => {
let base = to_int(v)?;
check_radix(base)?;
base
}
None => 10,
};
new_str(b.to_str_radix(radix as u32))
}
"to_i" | "to_int" => big(b.clone()),
"floor" | "ceil" | "round" | "truncate" => {
let kind = match name {
"floor" => RoundKind::Floor,
"ceil" => RoundKind::Ceil,
"round" => RoundKind::Round,
_ => RoundKind::Truncate,
};
let (nd, half) = round_args(args)?;
match nd.filter(|_| args.first().and_then(int_arg).is_some()) {
Some(d) if d < 0 => {
bigint_to_value(int_round_negative(b, clamp_ndigits(d), kind, half))
}
_ => big(b.clone()),
}
}
"to_f" => Value::Float(b.to_f64().unwrap_or(f64::INFINITY)),
"abs" | "magnitude" => big(b.abs()),
"-@" => big(-b.clone()),
"~" => big(-b.clone() - 1),
"bit_length" => Value::Int(if b.is_negative() {
(-b - 1u8).bits() as i64
} else {
b.bits() as i64
}),
"size" => Value::Int((b.bits().div_ceil(8) as i64).max(8)),
"to_r" if args.is_empty() => {
with_host(|h| h.new_rational(num_rational::BigRational::from(b.clone())))
}
"rationalize" if args.len() <= 1 => {
with_host(|h| h.new_rational(num_rational::BigRational::from(b.clone())))
}
"abs2" => big(b.abs() * b.abs()),
"numerator" => big(b.clone()),
"denominator" => Value::Int(1),
"even?" => Value::Bool(b.is_even()),
"odd?" => Value::Bool(b.is_odd()),
"zero?" => Value::Bool(b.is_zero()),
"positive?" => Value::Bool(b.is_positive()),
"negative?" => Value::Bool(b.is_negative()),
"integer?" => Value::Bool(true),
"hash" => Value::Int(b.to_i64().unwrap_or(b.bits() as i64)),
"succ" | "next" => big(b + 1),
"pred" => big(b - 1),
"digits" => {
if b.is_negative() {
return Err(raise_exc("Math::DomainError", "out of domain"));
}
let base = digits_radix(args)?;
let mut n = b.clone();
let mut out = Vec::new();
if n.is_zero() {
out.push(Value::Int(0));
}
while n > num_bigint::BigInt::zero() {
let (q, rem) = n.div_rem(&base);
out.push(with_host(|h| h.new_bigint(rem)));
n = q;
}
new_arr(out)
}
"/" | "div" => match with_host(|h| h.as_bigint(&args[0])) {
Some(d) if !d.is_zero() => big(b.div_floor(&d)),
Some(_) => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
None => return Ok(None),
},
"%" | "modulo" => match with_host(|h| h.as_bigint(&args[0])) {
Some(d) if !d.is_zero() => big(b.mod_floor(&d)),
Some(_) => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
None => return Ok(None),
},
"divmod" => match with_host(|h| h.as_bigint(&args[0])) {
Some(d) if !d.is_zero() => {
let (q, m) = b.div_mod_floor(&d);
new_arr(vec![big(q), big(m)])
}
_ => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
},
"gcd" | "lcm" | "gcdlcm" => match with_host(|h| h.as_bigint(&args[0])) {
Some(d) => {
let g = b.gcd(&d);
let l = if b.is_zero() || d.is_zero() {
num_bigint::BigInt::from(0)
} else {
b.lcm(&d).abs()
};
match name {
"gcd" => big(g),
"lcm" => big(l),
_ => new_arr(vec![big(g), big(l)]),
}
}
None => return Ok(None),
},
"remainder" => match with_host(|h| h.as_bigint(&args[0])) {
Some(d) if !d.is_zero() => big(b % d),
Some(_) => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
None => return Ok(None),
},
"<=>" => match with_host(|h| h.as_bigint(&args[0])) {
Some(o) => Value::Int(ord_to_i(b.cmp(&o))),
None => match &args[0] {
Value::Float(f) if f.is_nan() => Value::Undef,
Value::Float(f) if f.is_infinite() => Value::Int(if *f > 0.0 { -1 } else { 1 }),
Value::Float(f) => Value::Int(ord_to_i(cmp_bigint_float(b, *f))),
other => match with_host(|h| h.as_rational(other)) {
Some(o) => {
Value::Int(ord_to_i(num_rational::BigRational::from(b.clone()).cmp(&o)))
}
None => Value::Undef,
},
},
},
"coerce" => match &args[0] {
Value::Float(_) => new_arr(vec![args[0].clone(), Value::Float(bigint_to_f64(b))]),
_ => new_arr(vec![args[0].clone(), big(b.clone())]),
},
_ => return Ok(None),
};
Ok(Some(r))
}
fn dispatch_number(
recv: &Value,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
if matches!(recv, Value::Float(_)) && integer_only_method(name) {
return Err(no_method_error(recv, name));
}
if !matches!(recv, Value::Float(_))
&& matches!(name, "%" | "modulo" | "div" | "divmod" | "remainder")
&& args
.first()
.is_some_and(|a| with_host(|h| h.class_of(a)) == "Rational")
{
let r = with_host(|h| h.as_rational(recv).map(|r| h.new_rational(r)));
if let Some(r) = r {
return dispatch(&r, name, args, None);
}
}
if name == "/"
&& args
.first()
.is_some_and(|a| with_host(|h| h.complex_parts(a)).is_some())
{
return with_host(|h| h.num_op(fusevm::NumOp::Div, recv, &args[0]));
}
if matches!(name, "**" | "pow")
&& args.len() == 1
&& with_host(|h| h.complex_parts(&args[0])).is_some()
{
let c = with_host(|h| h.new_complex(recv.clone(), Value::Int(0)));
return complex_pow(&c, &args[0]);
}
if let Some(b) = with_host(|h| h.as_promoted_bigint(recv)) {
if let Some(r) = dispatch_bigint(&b, name, args)? {
return Ok(r);
}
}
match name {
"times" => {
let n = as_i(recv);
if let Some(b) = &block {
let mut i = 0;
while i < n {
call_proc(b, &[Value::Int(i)])?;
if has_pending_signal() {
break;
}
i += 1;
}
Ok(recv.clone())
} else {
Ok(with_host(|h| {
let items: Vec<Value> = (0..n.max(0)).map(Value::Int).collect();
h.new_enumerator_of(items, "times", recv.clone())
}))
}
}
"**" | "pow" => {
if name == "pow" && args.len() >= 2 {
let is_int = |v: &Value| with_host(|h| h.as_bigint(v).is_some());
if !is_int(&args[0]) {
return Err(raise_exc(
"TypeError",
"Integer#pow() 2nd argument not allowed unless a 1st argument is integer",
));
}
if !is_int(&args[1]) {
return Err(raise_exc(
"TypeError",
"Integer#pow() 2nd argument not allowed unless all arguments are integers",
));
}
if let (Value::Int(base), Value::Int(exp), Value::Int(m)) =
(recv, &args[0], &args[1])
{
if *m == 0 {
return Err(raise_exc("ZeroDivisionError", "divided by 0"));
}
if *exp >= 0 {
return Ok(Value::Int(mod_pow(*base, *exp, *m)));
}
return Err(raise_exc(
"RangeError",
"Integer#pow() 1st argument cannot be negative when 2nd argument specified",
));
}
if let (Some(base), Some(exp), Some(m)) = with_host(|h| {
(
h.as_bigint(recv),
h.as_bigint(&args[0]),
h.as_bigint(&args[1]),
)
}) {
use num_traits::{Signed as _, Zero as _};
if m.is_zero() {
return Err(raise_exc("ZeroDivisionError", "divided by 0"));
}
if exp.is_negative() {
return Err(raise_exc(
"RangeError",
"Integer#pow() 1st argument cannot be negative when 2nd argument specified",
));
}
return Ok(bigint_to_value(big_mod_pow(&base, &exp, &m)));
}
}
if let Some(base) = with_host(|h| h.as_bigint(recv)) {
use num_integer::Integer as _;
use num_traits::{Signed as _, Zero as _};
let one = || num_bigint::BigInt::from(1);
if base.is_zero() {
if let Some(e) = with_host(|h| h.as_bigint(&args[0])) {
if e.is_zero() {
return Ok(Value::Int(1));
}
if e.is_positive() {
return Ok(Value::Int(0));
}
return Err(raise_exc("ZeroDivisionError", "divided by 0"));
}
if let Some(r) = with_host(|h| h.as_rational(&args[0])) {
if r.is_negative() {
return Err(raise_exc("ZeroDivisionError", "divided by 0"));
}
let zero =
num_rational::BigRational::new(num_bigint::BigInt::from(0), one());
return Ok(with_host(|h| h.new_rational(zero)));
}
}
if base == one() {
if with_host(|h| h.as_bigint(&args[0]).is_some()) {
return Ok(Value::Int(1));
}
if with_host(|h| h.as_rational(&args[0]).is_some()) {
let r = num_rational::BigRational::new(one(), one());
return Ok(with_host(|h| h.new_rational(r)));
}
}
if base == num_bigint::BigInt::from(-1) {
if let Some(e) = with_host(|h| h.as_bigint(&args[0])) {
return Ok(Value::Int(if e.is_even() { 1 } else { -1 }));
}
}
if (base > one() || base < num_bigint::BigInt::from(-1))
&& int_arg(&args[0]).is_none()
&& with_host(|h| {
h.as_bigint(&args[0])
.map(|e| e.abs() > one())
.unwrap_or(false)
})
{
return Err(raise_exc("ArgumentError", "exponent is too large"));
}
}
if let (Some(base), Some(exp)) = (with_host(|h| h.as_bigint(recv)), int_arg(&args[0])) {
if exp.unsigned_abs() > u32::MAX as u64 {
return Err(raise_exc("ArgumentError", "exponent is too large"));
}
if exp >= 0 {
let r = base.pow(exp as u32);
return Ok(with_host(|h| h.new_bigint(r)));
}
if base == num_bigint::BigInt::from(0) {
return Err(raise_exc("ZeroDivisionError", "divided by 0"));
}
if base == num_bigint::BigInt::from(1) {
return Ok(Value::Int(1));
}
if base == num_bigint::BigInt::from(-1) {
return Ok(Value::Int(if exp % 2 == 0 { 1 } else { -1 }));
}
let denom = base.pow((-exp) as u32);
let r = num_rational::BigRational::new(num_bigint::BigInt::from(1), denom);
return Ok(with_host(|h| h.new_rational(r)));
}
let (x, y) = (as_f(recv), coerce_num(recv, &args[0])?);
if x < 0.0 && y != y.round() {
return Ok(dbl_complex_new_polar_pi((-x).powf(y), y));
}
Ok(Value::Float(x.powf(y)))
}
"/" => match (recv, &args[0]) {
(Value::Int(_), Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
(Value::Int(a), Value::Int(b)) => Ok(int_wide(floor_div(*a as i128, *b as i128))),
_ if with_host(|h| h.as_rational(&args[0])).is_some()
&& matches!(recv, Value::Int(_)) =>
{
with_host(|h| h.num_op(fusevm::NumOp::Div, recv, &args[0]))
}
_ => Ok(Value::Float(as_f(recv) / coerce_num(recv, &args[0])?)),
},
"div" => match (recv, &args[0]) {
(_, Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
(Value::Int(a), Value::Int(b)) => Ok(int_wide(floor_div(*a as i128, *b as i128))),
_ => {
let d = coerce_num(recv, &args[0])?;
if d == 0.0 {
return Err(raise_exc("ZeroDivisionError", "divided by 0"));
}
Ok(float_to_int_value((as_f(recv) / d).floor()))
}
},
"remainder" => match (recv, &args[0]) {
(_, Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
(Value::Int(a), Value::Int(b)) => Ok(int_wide(*a as i128 % *b as i128)),
_ => {
let d = coerce_num(recv, &args[0])?;
if d == 0.0 {
return Err(raise_exc("ZeroDivisionError", "divided by 0"));
}
Ok(Value::Float(as_f(recv) % d))
}
},
"%" | "modulo" => match (recv, &args[0]) {
(Value::Int(_), Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
(Value::Int(a), Value::Int(b)) => Ok(int_wide(floor_mod(*a as i128, *b as i128))),
_ if with_host(|h| h.as_rational(&args[0])).is_some()
&& matches!(recv, Value::Int(_)) =>
{
with_host(|h| h.num_op(fusevm::NumOp::Mod, recv, &args[0]))
}
_ => {
let (x, y) = (as_f(recv), coerce_num(recv, &args[0])?);
match flodivmod(x, y) {
Some((_, m)) => Ok(Value::Float(m)),
None => Err(raise_exc("ZeroDivisionError", "divided by 0")),
}
}
},
"step" => {
let mut pos: Vec<Value> = args.to_vec();
let (mut kw_to, mut kw_by) = (None, None);
if let Some(kw) = pos.last().and_then(|a| with_host(|h| h.as_hash(a))) {
let t = kw.get(&RKey::Sym("to".into())).cloned();
let b = kw.get(&RKey::Sym("by".into())).cloned();
if t.is_some() || b.is_some() {
pos.pop();
if t.is_some() && !pos.is_empty() {
return Err(raise_exc("ArgumentError", "to is given twice"));
}
if b.is_some() && pos.len() > 1 {
return Err(raise_exc("ArgumentError", "step is given twice"));
}
kw_to = t;
kw_by = b;
}
}
let to = kw_to.or_else(|| pos.first().cloned());
let by_val = kw_by.or_else(|| pos.get(1).cloned());
if let Some(by) = &by_val {
if with_host(|h| h.eq_values(by, &Value::Int(0))) {
return Err(raise_exc("ArgumentError", "step can't be 0"));
}
}
let Some(to) = to else {
let by_val = by_val.unwrap_or(Value::Int(1));
let float = matches!(recv, Value::Float(_)) || matches!(by_val, Value::Float(_));
let Some(bl) = &block else {
let desc = arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
return Ok(make_endless_arith_seq(desc, recv.clone(), by_val, float));
};
if float {
let (base, unit) = (as_f(recv), as_f(&by_val));
let mut i = 0.0f64;
loop {
call_proc(bl, &[Value::Float(i * unit + base)])?;
if has_pending_signal() {
return Ok(recv.clone());
}
i += 1.0;
}
}
let mut cur = recv.clone();
loop {
call_proc(bl, std::slice::from_ref(&cur))?;
if has_pending_signal() {
return Ok(recv.clone());
}
cur = dispatch(&cur, "+", std::slice::from_ref(&by_val), None)?;
}
};
let all_int = matches!(recv, Value::Int(_))
&& matches!(&to, Value::Int(_))
&& by_val
.as_ref()
.map(|v| matches!(v, Value::Int(_)))
.unwrap_or(true);
if all_int {
let limit = as_i(&to);
let by = by_val.as_ref().map(as_i).unwrap_or(1);
if by != 0 {
if let Some(bl) = &block {
let mut i = as_i(recv);
while (by > 0 && i <= limit) || (by < 0 && i >= limit) {
call_proc(bl, &[Value::Int(i)])?;
if has_pending_signal() {
break;
}
i += by;
}
return Ok(recv.clone());
}
let mut vals = Vec::new();
let mut i = as_i(recv);
while (by > 0 && i <= limit) || (by < 0 && i >= limit) {
vals.push(Value::Int(i));
i += by;
}
let desc = arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
return Ok(make_arith_seq(
desc,
recv.clone(),
to.clone(),
Value::Int(by),
false,
vals,
));
}
} else {
let from = as_f(recv);
let to = as_f(&to);
let by = by_val.as_ref().map(as_f).unwrap_or(1.0);
if to.is_infinite() && by != 0.0 && by.is_finite() {
if (by > 0.0) != (to > 0.0) {
return match &block {
Some(_) => Ok(recv.clone()),
None => {
let desc =
arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
Ok(make_arith_seq(
desc,
recv.clone(),
Value::Float(to),
Value::Float(by),
false,
Vec::new(),
))
}
};
}
let Some(bl) = &block else {
let desc = arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
return Ok(make_endless_arith_seq(
desc,
Value::Float(from),
Value::Float(by),
true,
));
};
let mut i = 0.0f64;
loop {
call_proc(bl, &[Value::Float(i * by + from)])?;
if has_pending_signal() {
return Ok(recv.clone());
}
i += 1.0;
}
}
if by != 0.0 && by.is_finite() {
let n = float_step_size(from, to, by, false);
let clamp = |i: f64| float_step_value(i, from, by, to);
if let Some(bl) = &block {
let mut i = 0.0f64;
while i < n {
call_proc(bl, &[Value::Float(clamp(i))])?;
if has_pending_signal() {
break;
}
i += 1.0;
}
return Ok(recv.clone());
}
let mut vals = Vec::new();
let mut i = 0.0f64;
while i < n {
vals.push(Value::Float(clamp(i)));
i += 1.0;
}
let desc = arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
return Ok(make_arith_seq(
desc,
Value::Float(from),
Value::Float(to),
Value::Float(by),
false,
vals,
));
}
}
Ok(recv.clone())
}
"upto" => own_enum(
iter_int_range(recv, as_i(&args[0]), 1, &block),
recv,
name,
args,
),
"downto" => own_enum(
iter_int_range(recv, as_i(&args[0]), -1, &block),
recv,
name,
args,
),
"to_s" => {
let base_arg = args.first().map(to_int).transpose()?;
if let Some(base) = base_arg {
check_radix(base)?;
if let Value::Int(n) = recv {
return Ok(new_str(to_radix(*n, base as u32)));
}
}
Ok(with_host(|h| {
let s = h.to_s(recv);
h.new_string(s)
}))
}
"to_i" | "to_int" | "floor" if name != "floor" => {
if let Value::Float(f) = recv {
if !f.is_finite() {
let name = if f.is_nan() {
"NaN"
} else if *f > 0.0 {
"Infinity"
} else {
"-Infinity"
};
return Err(raise_exc("FloatDomainError", name));
}
return Ok(float_to_int_value(f.trunc()));
}
Ok(Value::Int(as_i(recv)))
}
"to_f" => Ok(Value::Float(as_f(recv))),
"to_r" => match recv {
Value::Int(n) => Ok(with_host(|h| {
h.new_rational(num_rational::BigRational::from(num_bigint::BigInt::from(
*n,
)))
})),
Value::Float(f) => match num_rational::BigRational::from_float(*f) {
Some(r) => Ok(with_host(|h| h.new_rational(r))),
None => Err(raise_exc(
"FloatDomainError",
if f.is_nan() {
"NaN"
} else if *f > 0.0 {
"Infinity"
} else {
"-Infinity"
},
)),
},
_ => Ok(recv.clone()),
},
"rationalize" if matches!(recv, Value::Int(_)) && args.len() <= 1 => Ok(with_host(|h| {
h.new_rational(num_rational::BigRational::from(num_bigint::BigInt::from(
as_i(recv),
)))
})),
"rationalize" => {
let f = as_f(recv);
let eps = match args.first() {
Some(v) => as_f(v).abs(),
None => default_rationalize_eps(f),
};
let r = simplest_rational_within(f, eps);
Ok(with_host(|h| h.new_rational(r)))
}
"numerator" | "denominator" => {
let want_num = name == "numerator";
match recv {
Value::Int(n) => Ok(if want_num {
Value::Int(*n)
} else {
Value::Int(1)
}),
_ => {
let r = dispatch_number(recv, "to_r", &[], None)?;
dispatch(&r, name, &[], None)
}
}
}
"real?" | "real" | "conj" | "conjugate" | "imag" | "imaginary" | "rect" | "rectangular"
| "i"
if args.is_empty() =>
{
Ok(real_number_complex_view(recv, name))
}
"to_c" => Ok(with_host(|h| h.new_complex(recv.clone(), Value::Int(0)))),
"coerce" => match (recv, &args[0]) {
(Value::Int(a), Value::Int(b)) => Ok(new_arr(vec![Value::Int(*b), Value::Int(*a)])),
_ => Ok(new_arr(vec![
Value::Float(coerce_float_operand(&args[0])?),
Value::Float(as_f(recv)),
])),
},
"abs" | "magnitude" => Ok(match recv {
Value::Int(n) => int_wide((*n as i128).abs()),
Value::Float(f) => Value::Float(f.abs()),
_ => recv.clone(),
}),
"polar" => {
let abs = dispatch(recv, "abs", &[], None)?;
let arg = dispatch(recv, "arg", &[], None)?;
Ok(new_arr(vec![abs, arg]))
}
"abs2" => Ok(match recv {
Value::Int(n) => int_wide(*n as i128 * *n as i128),
Value::Float(f) => Value::Float(f * f),
_ => recv.clone(),
}),
"even?" => Ok(Value::Bool(as_i(recv) % 2 == 0)),
"odd?" => Ok(Value::Bool(as_i(recv) % 2 != 0)),
"zero?" => Ok(Value::Bool(as_f(recv) == 0.0)),
"nonzero?" => Ok(if as_f(recv) != 0.0 {
recv.clone()
} else {
Value::Undef
}),
"positive?" => Ok(Value::Bool(as_f(recv) > 0.0)),
"negative?" => Ok(Value::Bool(as_f(recv) < 0.0)),
"integer?" => Ok(Value::Bool(matches!(recv, Value::Int(_)))),
"succ" | "next" => Ok(int_wide(as_i(recv) as i128 + 1)),
"pred" => Ok(int_wide(as_i(recv) as i128 - 1)),
"floor" | "ceil" | "truncate" => {
let nd = args.first().map(to_int).transpose()?;
let kind = match name {
"floor" => RoundKind::Floor,
"ceil" => RoundKind::Ceil,
_ => RoundKind::Truncate,
};
round_like(recv, nd, kind, RoundHalf::Up)
}
"round" => {
let (nd, half) = round_args(args)?;
round_like(recv, nd, RoundKind::Round, half)
}
"allbits?" | "anybits?" | "nobits?" => {
let n = as_i(recv);
let m = to_int(&args[0])?;
Ok(Value::Bool(match name {
"allbits?" => n & m == m,
"anybits?" => n & m != 0,
_ => n & m == 0,
}))
}
"next_float" | "prev_float" => {
if !matches!(recv, Value::Float(_)) {
return Err(no_method_error(recv, name));
}
let x = as_f(recv);
if x.is_nan() {
return Ok(Value::Float(x));
}
let up = name == "next_float";
if x.is_infinite() && (x > 0.0) == up {
return Ok(Value::Float(x));
}
let bits = x.to_bits();
let next = if x == 0.0 {
if up {
1
} else {
(1u64 << 63) | 1
}
} else if (x > 0.0) == up {
bits + 1
} else {
bits - 1
};
Ok(Value::Float(f64::from_bits(next)))
}
"quo" => match recv {
Value::Float(_) => dispatch(recv, "/", args, None),
_ if matches!(args[0], Value::Float(_)) => dispatch(recv, "fdiv", args, None),
_ => {
let r = with_host(|h| h.as_rational(recv).map(|r| h.new_rational(r)))
.ok_or_else(|| no_method_error(recv, name))?;
dispatch(&r, "/", args, None)
}
},
"arg" | "angle" | "phase" => {
let x = as_f(recv);
Ok(if x.is_sign_negative() && !x.is_nan() {
Value::Float(std::f64::consts::PI)
} else {
Value::Int(0)
})
}
"nan?" if matches!(recv, Value::Float(_)) => {
Ok(Value::Bool(matches!(recv, Value::Float(f) if f.is_nan())))
}
"infinite?" => Ok(match recv {
Value::Float(f) if f.is_infinite() => Value::Int(if *f > 0.0 { 1 } else { -1 }),
_ => Value::Undef,
}),
"finite?" => Ok(Value::Bool(match recv {
Value::Float(f) => f.is_finite(),
_ => true,
})),
"divmod" => match (recv, &args[0]) {
(Value::Int(_), Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
(Value::Int(a), Value::Int(b)) => Ok(new_arr(vec![
int_wide(floor_div(*a as i128, *b as i128)),
int_wide(floor_mod(*a as i128, *b as i128)),
])),
_ => {
let (x, y) = (as_f(recv), as_f(&args[0]));
let Some((q, m)) = flodivmod(x, y) else {
return Err(raise_exc("ZeroDivisionError", "divided by 0"));
};
Ok(new_arr(vec![dbl2ival(q)?, Value::Float(m)]))
}
},