use fusevm::{Chunk, NumOp, VMResult, Value, VM};
use indexmap::IndexMap;
use std::cell::RefCell;
use std::collections::HashSet;
use std::rc::Rc;
pub struct EnvData {
vars: IndexMap<String, Value>,
parent: Option<Env>,
}
pub type Env = Rc<RefCell<EnvData>>;
fn new_env() -> Env {
Rc::new(RefCell::new(EnvData {
vars: IndexMap::new(),
parent: None,
}))
}
fn env_with(vars: IndexMap<String, Value>) -> Env {
Rc::new(RefCell::new(EnvData { vars, parent: None }))
}
fn child_env(parent: Env) -> Env {
Rc::new(RefCell::new(EnvData {
vars: IndexMap::new(),
parent: Some(parent),
}))
}
#[derive(Clone)]
pub struct Scope {
locals: Env,
self_obj: Value,
block: Option<Value>,
method_name: Option<String>,
def_class: Option<String>,
}
impl std::fmt::Debug for Scope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "<scope>")
}
}
pub mod ops {
pub const GETLOCAL: u16 = 1; pub const SETLOCAL: u16 = 2; pub const GETIVAR: u16 = 3;
pub const SETIVAR: u16 = 4;
pub const GETGVAR: u16 = 5;
pub const SETGVAR: u16 = 6;
pub const GETCONST: u16 = 7;
pub const SETCONST: u16 = 8;
pub const CALL: u16 = 9; pub const CALL_BLK: u16 = 10; pub const CALL_METHOD: u16 = 11; pub const CALL_METHOD_BLK: u16 = 12; pub const MKSTR: u16 = 13; pub const MKSYM: u16 = 14; pub const MKARRAY: u16 = 15; pub const MKHASH: u16 = 16; pub const MKRANGE: u16 = 17; pub const MKPROC: u16 = 18; pub const YIELD: u16 = 19; pub const TRUTHY: u16 = 20; pub const INDEX_GET: u16 = 21; pub const INDEX_SET: u16 = 22; pub const TOSTR: u16 = 23; pub const DEFINED: u16 = 24; pub const SIG_BREAK: u16 = 25; pub const SIG_NEXT: u16 = 26; pub const SIG_RETURN: u16 = 27; pub const GETSELF: u16 = 28; pub const BEGIN: u16 = 29; pub const SUPER: u16 = 30; pub const SUPER_FWD: u16 = 31; pub const MKARGS: u16 = 32; pub const CALL_ARR: u16 = 33; pub const CALL_METHOD_ARR: u16 = 34; pub const MKREGEX: u16 = 35; pub const MKLAMBDA: u16 = 36; pub const SIG_RETRY: u16 = 37; }
#[derive(Debug, Clone)]
pub enum RObj {
Str(String),
Array(Vec<Value>),
Hash {
map: IndexMap<RKey, Value>,
default: Value,
default_proc: Option<Value>,
},
Symbol(String),
Range {
lo: i64,
hi: i64,
exclusive: bool,
},
StrRange {
lo: String,
hi: String,
exclusive: bool,
},
Proc {
template: usize,
scope: Scope,
is_lambda: bool,
kind: ProcKind,
},
SymProc(String),
Method {
recv: Value,
name: String,
},
Object {
class: String,
ivars: IndexMap<String, Value>,
},
ClassRef(String),
Regexp {
source: String,
re: regex::Regex,
},
MatchData {
groups: Vec<Option<String>>,
pre: String,
post: String,
},
}
#[derive(Debug, Clone)]
pub enum ProcKind {
Normal,
Curried { arity: usize, collected: Vec<Value> },
Composed {
first: Box<Value>,
second: Box<Value>,
},
Collect(usize),
}
#[derive(Clone, Default)]
pub struct ClassDef {
pub superclass: Option<String>,
pub methods: IndexMap<String, MethodDef>,
pub includes: Vec<String>,
pub class_methods: IndexMap<String, MethodDef>,
}
#[derive(Clone)]
pub struct BeginDef {
pub body: usize,
pub rescues: Vec<RescueDef>,
pub ensure: Option<usize>,
}
#[derive(Clone)]
pub struct RescueDef {
pub classes: Vec<String>,
pub binding: Option<String>,
pub body: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RKey {
Int(i64),
Str(String),
Sym(String),
Bool(bool),
Nil,
FloatBits(u64),
}
#[derive(Clone)]
pub struct MethodDef {
pub params: Vec<String>,
pub splat: Option<usize>,
pub kwparams: Vec<String>,
pub kwsplat: Option<String>,
pub blockparam: Option<String>,
pub chunk: Chunk,
}
#[derive(Clone)]
pub struct ProcDef {
pub params: Vec<String>,
pub chunk: Chunk,
}
struct Frame {
scope: Scope,
args: Vec<Value>,
}
#[derive(Clone)]
enum Signal {
Break(Value),
Next(Value),
Return(Value),
Retry,
Throw(Value, Value),
}
pub struct RubyHost {
heap: Vec<RObj>,
frames: Vec<Frame>,
globals: IndexMap<String, Value>,
consts: IndexMap<String, Value>,
methods: IndexMap<String, MethodDef>,
classes: IndexMap<String, ClassDef>,
begins: Vec<BeginDef>,
procs: Vec<ProcDef>,
symbols: IndexMap<String, u32>,
pub error: Option<String>,
pending_exc: Option<Value>,
signal: Option<Signal>,
active_scope: Option<Scope>,
frozen: HashSet<u32>,
enum_sinks: Vec<Vec<Value>>,
}
thread_local! {
static HOST: RefCell<RubyHost> = RefCell::new(RubyHost::new());
}
pub fn with_host<R>(f: impl FnOnce(&mut RubyHost) -> R) -> R {
HOST.with(|h| f(&mut h.borrow_mut()))
}
pub fn reset_host() {
with_host(|h| *h = RubyHost::new());
}
impl Default for RubyHost {
fn default() -> Self {
Self::new()
}
}
impl RubyHost {
pub fn new() -> Self {
RubyHost {
heap: Vec::new(),
frames: vec![Frame {
scope: Scope {
locals: new_env(),
block: None,
self_obj: Value::Undef,
method_name: None,
def_class: None,
},
args: Vec::new(),
}],
globals: IndexMap::new(),
consts: IndexMap::new(),
methods: IndexMap::new(),
classes: IndexMap::new(),
begins: Vec::new(),
procs: Vec::new(),
symbols: IndexMap::new(),
error: None,
pending_exc: None,
signal: None,
active_scope: None,
frozen: HashSet::new(),
enum_sinks: Vec::new(),
}
}
pub fn freeze_value(&mut self, v: &Value) {
if let Value::Obj(id) = v {
self.frozen.insert(*id);
}
}
pub fn is_frozen(&self, v: &Value) -> bool {
match v {
Value::Obj(id) => self.as_symbol(v).is_some() || self.frozen.contains(id),
_ => true,
}
}
pub fn load_program(
&mut self,
methods: Vec<(String, MethodDef)>,
classes: Vec<(String, ClassDef)>,
begins: Vec<BeginDef>,
procs: Vec<ProcDef>,
) {
for (name, def) in methods {
self.methods.insert(name, def);
}
for (name, def) in classes {
self.classes.insert(name, def);
}
self.begins = begins;
self.procs = procs;
}
pub fn take_error(&mut self) -> Option<String> {
self.error.take()
}
fn alloc(&mut self, obj: RObj) -> Value {
let id = self.heap.len() as u32;
self.heap.push(obj);
Value::Obj(id)
}
fn obj(&self, v: &Value) -> Option<&RObj> {
match v {
Value::Obj(i) => self.heap.get(*i as usize),
_ => None,
}
}
fn obj_mut(&mut self, v: &Value) -> Option<&mut RObj> {
match v {
Value::Obj(i) => self.heap.get_mut(*i as usize),
_ => None,
}
}
pub fn dup_value(&mut self, v: &Value) -> Value {
match self.obj(v) {
Some(RObj::Symbol(_)) | Some(RObj::ClassRef(_)) => v.clone(),
Some(obj) => {
let copy = obj.clone();
self.alloc(copy)
}
None => v.clone(),
}
}
pub fn new_string(&mut self, s: String) -> Value {
self.alloc(RObj::Str(s))
}
pub fn new_array(&mut self, items: Vec<Value>) -> Value {
self.alloc(RObj::Array(items))
}
pub fn new_hash(&mut self, map: IndexMap<RKey, Value>) -> Value {
self.alloc(RObj::Hash {
map,
default: Value::Undef,
default_proc: None,
})
}
pub fn new_hash_with_default(&mut self, map: IndexMap<RKey, Value>, default: Value) -> Value {
self.alloc(RObj::Hash {
map,
default,
default_proc: None,
})
}
pub fn new_hash_with_proc(&mut self, map: IndexMap<RKey, Value>, proc: Value) -> Value {
self.alloc(RObj::Hash {
map,
default: Value::Undef,
default_proc: Some(proc),
})
}
pub fn hash_default(&self, v: &Value) -> Value {
match self.obj(v) {
Some(RObj::Hash { default, .. }) => default.clone(),
_ => Value::Undef,
}
}
pub fn hash_default_proc(&self, v: &Value) -> Option<Value> {
match self.obj(v) {
Some(RObj::Hash { default_proc, .. }) => default_proc.clone(),
_ => None,
}
}
pub fn new_range(&mut self, lo: i64, hi: i64, exclusive: bool) -> Value {
self.alloc(RObj::Range { lo, hi, exclusive })
}
pub fn new_str_range(&mut self, lo: String, hi: String, exclusive: bool) -> Value {
self.alloc(RObj::StrRange { lo, hi, exclusive })
}
pub fn as_str_range(&self, v: &Value) -> Option<(String, String, bool)> {
match self.obj(v) {
Some(RObj::StrRange { lo, hi, exclusive }) => {
Some((lo.clone(), hi.clone(), *exclusive))
}
_ => None,
}
}
pub fn new_regex(&mut self, source: &str, flags: &str) -> Result<Value, String> {
let mut inline = String::new();
if flags.contains('i') {
inline.push('i');
}
if flags.contains('m') {
inline.push('s'); }
if flags.contains('x') {
inline.push('x');
}
let full = if inline.is_empty() {
source.to_string()
} else {
format!("(?{inline}){source}")
};
match regex::Regex::new(&full) {
Ok(re) => Ok(self.alloc(RObj::Regexp {
source: source.to_string(),
re,
})),
Err(e) => Err(format!("invalid regex /{source}/: {e}")),
}
}
#[allow(clippy::type_complexity)]
pub fn as_matchdata(&self, v: &Value) -> Option<(Vec<Option<String>>, String, String)> {
match self.obj(v) {
Some(RObj::MatchData { groups, pre, post }) => {
Some((groups.clone(), pre.clone(), post.clone()))
}
_ => None,
}
}
pub fn as_regex(&self, v: &Value) -> Option<(regex::Regex, String)> {
match self.obj(v) {
Some(RObj::Regexp { re, source }) => Some((re.clone(), source.clone())),
_ => None,
}
}
pub fn new_matchdata(
&mut self,
groups: Vec<Option<String>>,
pre: String,
post: String,
) -> Value {
self.alloc(RObj::MatchData { groups, pre, post })
}
pub fn new_proc(&mut self, template: usize) -> Value {
let scope = self.cur_scope().clone();
self.alloc(RObj::Proc {
template,
scope,
is_lambda: false,
kind: ProcKind::Normal,
})
}
pub fn new_lambda(&mut self, template: usize) -> Value {
let scope = self.cur_scope().clone();
self.alloc(RObj::Proc {
template,
scope,
is_lambda: true,
kind: ProcKind::Normal,
})
}
pub fn proc_is_lambda(&self, v: &Value) -> bool {
matches!(
self.obj(v),
Some(RObj::Proc {
is_lambda: true,
..
})
)
}
pub fn set_proc_lambda(&mut self, v: &Value) {
if let Some(RObj::Proc { is_lambda, .. }) = self.obj_mut(v) {
*is_lambda = true;
}
}
pub fn proc_arity(&self, v: &Value) -> Option<i64> {
match self.obj(v) {
Some(RObj::Proc { kind, template, .. }) => match kind {
ProcKind::Curried { .. } | ProcKind::Composed { .. } => Some(-1),
ProcKind::Collect(_) => Some(1),
ProcKind::Normal => Some(self.procs[*template].params.len() as i64),
},
_ => None,
}
}
pub fn proc_curry(&mut self, v: &Value) -> Option<Value> {
match self.obj(v).cloned() {
Some(RObj::Proc {
template,
scope,
is_lambda,
kind,
}) => {
let arity = match kind {
ProcKind::Curried { arity, .. } => arity,
ProcKind::Composed { .. } | ProcKind::Collect(_) => return Some(v.clone()),
ProcKind::Normal => self.procs[template].params.len(),
};
Some(self.alloc(RObj::Proc {
template,
scope,
is_lambda,
kind: ProcKind::Curried {
arity,
collected: Vec::new(),
},
}))
}
_ => None,
}
}
pub fn new_composed(&mut self, first: Value, second: Value, is_lambda: bool) -> Value {
let scope = self.cur_scope().clone();
self.alloc(RObj::Proc {
template: 0,
scope,
is_lambda,
kind: ProcKind::Composed {
first: Box::new(first),
second: Box::new(second),
},
})
}
pub fn new_symbol(&mut self, name: &str) -> Value {
self.intern(name)
}
pub fn new_enum_sink(&mut self) -> Value {
let idx = self.enum_sinks.len();
self.enum_sinks.push(Vec::new());
let scope = self.cur_scope().clone();
self.alloc(RObj::Proc {
template: 0,
scope,
is_lambda: false,
kind: ProcKind::Collect(idx),
})
}
pub fn take_enum_sink(&mut self) -> Vec<Value> {
self.enum_sinks.pop().unwrap_or_default()
}
pub fn new_sym_proc(&mut self, sym: &str) -> Value {
self.alloc(RObj::SymProc(sym.to_string()))
}
pub fn as_sym_proc(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::SymProc(s)) => Some(s.clone()),
_ => None,
}
}
pub fn new_method(&mut self, recv: Value, name: &str) -> Value {
self.alloc(RObj::Method {
recv,
name: name.to_string(),
})
}
pub fn as_method(&self, v: &Value) -> Option<(Value, String)> {
match self.obj(v) {
Some(RObj::Method { recv, name }) => Some((recv.clone(), name.clone())),
_ => None,
}
}
pub fn method_arity(&self, recv: &Value, name: &str) -> i64 {
let def = if let Some(cls) = self.object_class(recv) {
self.find_method_owner(&cls, name).map(|(d, _)| d)
} else if let Some(cls) = self.classref_name(recv) {
self.find_class_method(&cls, name)
} else {
self.methods.get(name).cloned()
};
match def {
Some(d) => {
if d.splat.is_some() {
-((d.params.len().saturating_sub(1)) as i64 + 1)
} else {
d.params.len() as i64
}
}
None => -1,
}
}
pub fn as_array(&self, v: &Value) -> Option<Vec<Value>> {
match self.obj(v) {
Some(RObj::Array(xs)) => Some(xs.clone()),
_ => None,
}
}
pub fn set_array(&mut self, v: &Value, xs: Vec<Value>) {
if let Some(RObj::Array(slot)) = self.obj_mut(v) {
*slot = xs;
}
}
pub fn as_str(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::Str(s)) => Some(s.clone()),
_ => match v {
Value::Str(s) => Some(s.to_string()),
_ => None,
},
}
}
pub fn set_str(&mut self, v: &Value, s: String) {
if let Some(RObj::Str(slot)) = self.obj_mut(v) {
*slot = s;
}
}
pub fn as_hash(&self, v: &Value) -> Option<IndexMap<RKey, Value>> {
match self.obj(v) {
Some(RObj::Hash { map, .. }) => Some(map.clone()),
_ => None,
}
}
pub fn set_hash(&mut self, v: &Value, m: IndexMap<RKey, Value>) {
if let Some(RObj::Hash { map, .. }) = self.obj_mut(v) {
*map = m;
}
}
pub fn as_range(&self, v: &Value) -> Option<(i64, i64, bool)> {
match self.obj(v) {
Some(RObj::Range { lo, hi, exclusive }) => Some((*lo, *hi, *exclusive)),
_ => None,
}
}
pub fn as_symbol(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::Symbol(s)) => Some(s.clone()),
_ => None,
}
}
pub fn is_proc(&self, v: &Value) -> bool {
matches!(
self.obj(v),
Some(RObj::Proc { .. }) | Some(RObj::SymProc(_))
)
}
pub fn has_method(&self, name: &str) -> bool {
self.methods.contains_key(name)
}
pub fn repl_completion_names(&self) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
out.extend(self.methods.keys().cloned());
out.extend(self.classes.keys().cloned());
out.extend(self.consts.keys().cloned());
out.extend(self.globals.keys().map(|g| format!("${g}")));
out
}
pub fn responds_to(&self, name: &str) -> bool {
let this = self.current_self();
if let Some(cls) = self.classref_name(&this) {
return name == "new" || self.find_class_method(&cls, name).is_some();
}
if let Some(cls) = self.object_class(&this) {
if self.find_method(&cls, name).is_some() {
return true;
}
}
self.methods.contains_key(name)
}
pub fn class_of(&self, v: &Value) -> String {
match self.obj(v) {
Some(RObj::Object { class, .. }) => class.clone(),
Some(RObj::ClassRef(_)) => "Class".to_string(),
_ => self.class_name(v).to_string(),
}
}
pub fn value_to_key(&self, v: &Value) -> RKey {
self.to_key(v)
}
pub fn key_value(&mut self, k: &RKey) -> Value {
self.key_to_value(k)
}
fn intern(&mut self, name: &str) -> Value {
if let Some(id) = self.symbols.get(name) {
return Value::Obj(*id);
}
let v = self.alloc(RObj::Symbol(name.to_string()));
if let Value::Obj(id) = v {
self.symbols.insert(name.to_string(), id);
}
v
}
fn cur_scope(&self) -> &Scope {
self.active_scope
.as_ref()
.unwrap_or(&self.frames.last().unwrap().scope)
}
fn cur_env(&self) -> Env {
self.cur_scope().locals.clone()
}
pub fn get_local(&self, name: &str) -> Value {
let mut env = self.cur_env();
loop {
if let Some(v) = env.borrow().vars.get(name).cloned() {
return v;
}
let parent = env.borrow().parent.clone();
match parent {
Some(p) => env = p,
None => return Value::Undef,
}
}
}
pub fn set_local(&self, name: &str, v: Value) {
let mut env = self.cur_env();
loop {
if env.borrow().vars.contains_key(name) {
env.borrow_mut().vars.insert(name.to_string(), v);
return;
}
let parent = env.borrow().parent.clone();
match parent {
Some(p) => env = p,
None => break,
}
}
self.cur_env().borrow_mut().vars.insert(name.to_string(), v);
}
pub fn local_defined(&self, name: &str) -> bool {
let mut env = self.cur_env();
loop {
if env.borrow().vars.contains_key(name) {
return true;
}
let parent = env.borrow().parent.clone();
match parent {
Some(p) => env = p,
None => return false,
}
}
}
pub fn get_global(&self, name: &str) -> Value {
self.globals.get(name).cloned().unwrap_or(Value::Undef)
}
pub fn set_global(&mut self, name: &str, v: Value) {
self.globals.insert(name.to_string(), v);
}
pub fn get_const(&self, name: &str) -> Value {
self.consts.get(name).cloned().unwrap_or(Value::Undef)
}
pub fn set_const(&mut self, name: &str, v: Value) {
self.consts.insert(name.to_string(), v);
}
pub fn get_ivar(&self, name: &str) -> Value {
match self.current_self() {
Value::Obj(_) => {
if let Some(RObj::Object { ivars, .. }) = self.obj(&self.current_self()) {
return ivars.get(name).cloned().unwrap_or(Value::Undef);
}
Value::Undef
}
_ => self
.globals
.get(&format!("@{name}"))
.cloned()
.unwrap_or(Value::Undef),
}
}
pub fn set_ivar(&mut self, name: &str, v: Value) {
let this = self.current_self();
match this {
Value::Obj(i) => {
if let Some(RObj::Object { ivars, .. }) = self.heap.get_mut(i as usize) {
ivars.insert(name.to_string(), v);
}
}
_ => {
self.globals.insert(format!("@{name}"), v);
}
}
}
pub fn current_self(&self) -> Value {
self.cur_scope().self_obj.clone()
}
pub fn add_class(&mut self, name: String, def: ClassDef) {
self.classes.insert(name, def);
}
pub fn class_exists(&self, name: &str) -> bool {
self.classes.contains_key(name)
}
pub fn new_object(&mut self, class: &str) -> Value {
self.alloc(RObj::Object {
class: class.to_string(),
ivars: IndexMap::new(),
})
}
pub fn class_ref(&mut self, name: &str) -> Value {
self.alloc(RObj::ClassRef(name.to_string()))
}
pub fn object_class(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::Object { class, .. }) => Some(class.clone()),
_ => None,
}
}
pub fn superclass_of(&self, name: &str) -> Option<String> {
self.classes.get(name).and_then(|d| d.superclass.clone())
}
fn class_is_ancestor(&self, start: &str, class: &str) -> bool {
let mut cur = Some(start.to_string());
while let Some(name) = cur {
if name == class {
return true;
}
let Some(def) = self.classes.get(&name) else {
break;
};
if def.includes.iter().any(|m| m == class) {
return true;
}
cur = def.superclass.clone();
}
false
}
pub fn is_a(&self, v: &Value, class: &str) -> bool {
let actual = self.class_of(v);
if actual == class || class == "Object" || class == "BasicObject" {
return true;
}
if class == "Numeric" && (actual == "Integer" || actual == "Float") {
return true;
}
if class == "Comparable" && matches!(actual.as_str(), "Integer" | "Float" | "String") {
return true;
}
if class == "Enumerable" && matches!(actual.as_str(), "Array" | "Hash" | "Range") {
return true;
}
if let Some(oc) = self.object_class(v) {
return self.class_is_ancestor(&oc, class);
}
false
}
pub fn is_builtin_class(&self, name: &str) -> bool {
matches!(
name,
"Integer"
| "Float"
| "Numeric"
| "String"
| "Symbol"
| "Array"
| "Hash"
| "Range"
| "Proc"
| "Method"
| "Object"
| "BasicObject"
| "Comparable"
| "Enumerable"
| "NilClass"
| "TrueClass"
| "FalseClass"
)
}
pub fn classref_name(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::ClassRef(n)) => Some(n.clone()),
_ => None,
}
}
pub fn find_method_owner(&self, class: &str, method: &str) -> Option<(MethodDef, String)> {
let mut cur = Some(class.to_string());
while let Some(name) = cur {
let def = self.classes.get(&name)?;
if let Some(m) = def.methods.get(method) {
return Some((m.clone(), name.clone()));
}
for module in def.includes.iter().rev() {
if let Some(md) = self.classes.get(module) {
if let Some(m) = md.methods.get(method) {
return Some((m.clone(), module.clone()));
}
}
}
cur = def.superclass.clone();
}
None
}
pub fn find_method(&self, class: &str, method: &str) -> Option<MethodDef> {
self.find_method_owner(class, method).map(|(m, _)| m)
}
pub fn find_super(&self, def_class: &str, method: &str) -> Option<(MethodDef, String)> {
let sup = self.classes.get(def_class)?.superclass.clone()?;
self.find_method_owner(&sup, method)
}
pub fn find_class_method(&self, class: &str, method: &str) -> Option<MethodDef> {
let mut cur = Some(class.to_string());
while let Some(name) = cur {
let def = self.classes.get(&name)?;
if let Some(m) = def.class_methods.get(method) {
return Some(m.clone());
}
cur = def.superclass.clone();
}
None
}
fn method_for_self(
&self,
self_obj: &Value,
method: &str,
) -> Option<(MethodDef, String, Value)> {
let class = self.object_class(self_obj)?;
self.find_method_owner(&class, method)
.map(|(m, owner)| (m, owner, self_obj.clone()))
}
pub fn ivar_of(&self, obj: &Value, name: &str) -> Value {
match self.obj(obj) {
Some(RObj::Object { ivars, .. }) => ivars.get(name).cloned().unwrap_or(Value::Undef),
_ => Value::Undef,
}
}
pub fn set_ivar_of(&mut self, obj: &Value, name: &str, v: Value) {
if let Value::Obj(i) = obj {
if let Some(RObj::Object { ivars, .. }) = self.heap.get_mut(*i as usize) {
ivars.insert(name.to_string(), v);
}
}
}
pub fn ivar_names(&self, obj: &Value) -> Vec<String> {
match self.obj(obj) {
Some(RObj::Object { ivars, .. }) => ivars.keys().map(|k| format!("@{k}")).collect(),
_ => Vec::new(),
}
}
pub fn bind_params(
&mut self,
params: &[String],
splat: Option<usize>,
kwparams: &[String],
kwsplat: Option<&str>,
args: &[Value],
) -> IndexMap<String, Value> {
let wants_kw = !kwparams.is_empty() || kwsplat.is_some();
let (positional, kwhash): (&[Value], Option<IndexMap<RKey, Value>>) = if wants_kw {
match args.last() {
Some(v) if matches!(self.obj(v), Some(RObj::Hash { .. })) => {
(&args[..args.len() - 1], self.as_hash(v))
}
_ => (args, None),
}
} else {
(args, None)
};
let mut locals = IndexMap::new();
match splat {
None => {
for (i, p) in params.iter().enumerate() {
if let Some(v) = positional.get(i) {
locals.insert(p.clone(), v.clone());
}
}
}
Some(si) => {
let after = params.len() - si - 1;
for (i, p) in params.iter().take(si).enumerate() {
if let Some(v) = positional.get(i) {
locals.insert(p.clone(), v.clone());
}
}
let splat_end = positional.len().saturating_sub(after).max(si);
let rest: Vec<Value> = positional
.get(si..splat_end)
.map(|s| s.to_vec())
.unwrap_or_default();
let arr = self.new_array(rest);
locals.insert(params[si].clone(), arr);
for (j, p) in params.iter().skip(si + 1).enumerate() {
if let Some(v) = positional.get(splat_end + j) {
locals.insert(p.clone(), v.clone());
}
}
}
}
for kw in kwparams {
let key = RKey::Sym(kw.clone());
if let Some(v) = kwhash.as_ref().and_then(|m| m.get(&key)) {
locals.insert(kw.clone(), v.clone());
}
}
if let Some(name) = kwsplat {
let mut rest = IndexMap::new();
if let Some(m) = &kwhash {
for (k, v) in m {
let claimed = matches!(k, RKey::Sym(s) if kwparams.iter().any(|p| p == s));
if !claimed {
rest.insert(k.clone(), v.clone());
}
}
}
let h = self.new_hash(rest);
locals.insert(name.to_string(), h);
}
locals
}
pub fn super_context(&self) -> (Value, Option<String>, Option<String>, Vec<Value>) {
let s = self.cur_scope();
(
s.self_obj.clone(),
s.method_name.clone(),
s.def_class.clone(),
self.frames.last().unwrap().args.clone(),
)
}
pub fn set_pending_exc(&mut self, v: Value) {
self.pending_exc = Some(v);
}
pub fn take_pending_exc(&mut self) -> Option<Value> {
self.pending_exc.take()
}
pub fn new_exception(&mut self, class: &str, message: &str) -> Value {
let msg = self.new_string(message.to_string());
let mut ivars = IndexMap::new();
ivars.insert("message".to_string(), msg);
self.alloc(RObj::Object {
class: class.to_string(),
ivars,
})
}
pub fn exc_matches(&self, exc_class: &str, rescued: &str) -> bool {
if exc_class == rescued || rescued == "Exception" || rescued == "StandardError" {
return true;
}
let mut cur = Some(exc_class.to_string());
while let Some(name) = cur {
if name == rescued {
return true;
}
cur = self.classes.get(&name).and_then(|d| d.superclass.clone());
}
false
}
pub fn begin_def(&self, id: usize) -> Option<BeginDef> {
self.begins.get(id).cloned()
}
pub fn proc_def(&self, id: usize) -> ProcDef {
self.procs[id].clone()
}
pub fn truthy(&self, v: &Value) -> bool {
!matches!(v, Value::Undef | Value::Bool(false))
}
pub fn to_s(&mut self, v: &Value) -> String {
match v {
Value::Undef => String::new(),
Value::Bool(b) => b.to_string(),
Value::Int(n) => n.to_string(),
Value::Float(f) => fmt_float(*f),
Value::Str(s) => s.to_string(),
Value::Obj(_) => match self.obj(v).cloned() {
Some(RObj::Str(s)) => s,
Some(RObj::Symbol(s)) => s,
Some(RObj::Range { lo, hi, exclusive }) => {
format!("{lo}{}{hi}", if exclusive { "..." } else { ".." })
}
Some(RObj::StrRange { lo, hi, exclusive }) => {
format!("{lo}{}{hi}", if exclusive { "..." } else { ".." })
}
Some(RObj::Array(items)) => self.inspect_array(&items),
Some(RObj::Hash { map, .. }) => self.inspect_hash(&map),
Some(RObj::Proc { .. }) | Some(RObj::SymProc(_)) => "#<Proc>".to_string(),
Some(RObj::Method { recv, name }) => {
format!("#<Method: {}#{name}>", self.class_of(&recv))
}
Some(RObj::Regexp { source, .. }) => format!("(?-mix:{source})"),
Some(RObj::MatchData { groups, .. }) => {
groups.first().and_then(|g| g.clone()).unwrap_or_default()
}
Some(RObj::ClassRef(n)) => n,
Some(RObj::Object { class, ivars }) => {
match ivars.get("message") {
Some(m) => self.to_s(&m.clone()),
None => format!("#<{class}>"),
}
}
None => "nil".to_string(),
},
_ => String::new(),
}
}
pub fn inspect(&mut self, v: &Value) -> String {
match v {
Value::Undef => "nil".to_string(),
Value::Str(s) => format!("{s:?}"),
Value::Obj(_) => match self.obj(v).cloned() {
Some(RObj::Str(s)) => format!("{s:?}"),
Some(RObj::Symbol(s)) => format!(":{s}"),
Some(RObj::Array(items)) => self.inspect_array(&items),
Some(RObj::Hash { map, .. }) => self.inspect_hash(&map),
Some(RObj::Regexp { source, .. }) => format!("/{source}/"),
Some(RObj::StrRange { lo, hi, exclusive }) => {
format!("{lo:?}{}{hi:?}", if exclusive { "..." } else { ".." })
}
Some(RObj::MatchData { groups, .. }) => {
let whole = groups.first().and_then(|g| g.clone()).unwrap_or_default();
let mut out = format!("#<MatchData {whole:?}");
for (i, g) in groups.iter().enumerate().skip(1) {
match g {
Some(s) => out.push_str(&format!(" {i}:{s:?}")),
None => out.push_str(&format!(" {i}:nil")),
}
}
out.push('>');
out
}
_ => self.to_s(v),
},
_ => self.to_s(v),
}
}
fn inspect_array(&mut self, items: &[Value]) -> String {
let parts: Vec<String> = items.iter().map(|it| self.inspect(it)).collect();
format!("[{}]", parts.join(", "))
}
fn inspect_hash(&mut self, map: &IndexMap<RKey, Value>) -> String {
let parts: Vec<String> = map
.iter()
.map(|(k, v)| {
let vs = self.inspect(v);
match k {
RKey::Sym(s) => format!("{s}: {vs}"),
_ => format!("{} => {vs}", self.key_inspect(k)),
}
})
.collect();
format!("{{{}}}", parts.join(", "))
}
fn key_inspect(&mut self, k: &RKey) -> String {
match k {
RKey::Int(n) => n.to_string(),
RKey::Str(s) => format!("{s:?}"),
RKey::Sym(s) => format!(":{s}"),
RKey::Bool(b) => b.to_string(),
RKey::Nil => "nil".to_string(),
RKey::FloatBits(b) => fmt_float(f64::from_bits(*b)),
}
}
fn class_name(&self, v: &Value) -> &'static str {
match v {
Value::Undef => "NilClass",
Value::Bool(true) => "TrueClass",
Value::Bool(false) => "FalseClass",
Value::Int(_) => "Integer",
Value::Float(_) => "Float",
Value::Str(_) => "String",
Value::Obj(_) => match self.obj(v) {
Some(RObj::Str(_)) => "String",
Some(RObj::Array(_)) => "Array",
Some(RObj::Hash { .. }) => "Hash",
Some(RObj::Symbol(_)) => "Symbol",
Some(RObj::Range { .. }) => "Range",
Some(RObj::StrRange { .. }) => "Range",
Some(RObj::Proc { .. }) | Some(RObj::SymProc(_)) => "Proc",
Some(RObj::Method { .. }) => "Method",
Some(RObj::Regexp { .. }) => "Regexp",
Some(RObj::MatchData { .. }) => "MatchData",
Some(RObj::ClassRef(_)) => "Class",
Some(RObj::Object { .. }) => "Object",
None => "Object",
},
_ => "Object",
}
}
fn to_key(&self, v: &Value) -> RKey {
match v {
Value::Int(n) => RKey::Int(*n),
Value::Float(f) => RKey::FloatBits(f.to_bits()),
Value::Bool(b) => RKey::Bool(*b),
Value::Undef => RKey::Nil,
Value::Str(s) => RKey::Str(s.to_string()),
Value::Obj(_) => match self.obj(v) {
Some(RObj::Str(s)) => RKey::Str(s.clone()),
Some(RObj::Symbol(s)) => RKey::Sym(s.clone()),
_ => RKey::Str(format!("{v:?}")),
},
_ => RKey::Nil,
}
}
fn key_to_value(&mut self, k: &RKey) -> Value {
match k {
RKey::Int(n) => Value::Int(*n),
RKey::Str(s) => self.new_string(s.clone()),
RKey::Sym(s) => self.intern(s),
RKey::Bool(b) => Value::Bool(*b),
RKey::Nil => Value::Undef,
RKey::FloatBits(b) => Value::Float(f64::from_bits(*b)),
}
}
pub fn num_op(&mut self, op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
use NumOp::*;
match op {
Eq => return Ok(Value::Bool(self.eq_values(a, b))),
Ne => return Ok(Value::Bool(!self.eq_values(a, b))),
_ => {}
}
match (self.obj(a).cloned(), op) {
(Some(RObj::Str(s)), Add) => {
let bs = self.to_s(b);
return Ok(self.new_string(format!("{s}{bs}")));
}
(Some(RObj::Str(s)), Mul) => {
let n = as_int(b).unwrap_or(0).max(0) as usize;
return Ok(self.new_string(s.repeat(n)));
}
(Some(RObj::Str(s)), Lt | Gt | Le | Ge) => {
if let Some(RObj::Str(bs)) = self.obj(b) {
return Ok(Value::Bool(cmp_ord(op, s.cmp(bs))));
}
}
(Some(RObj::Array(mut xs)), Add) => {
if let Some(RObj::Array(ys)) = self.obj(b).cloned() {
xs.extend(ys);
return Ok(self.new_array(xs));
}
}
(Some(RObj::Array(xs)), Mul) => {
let n = as_int(b).unwrap_or(0).max(0) as usize;
let mut out = Vec::with_capacity(xs.len() * n);
for _ in 0..n {
out.extend(xs.iter().cloned());
}
return Ok(self.new_array(out));
}
_ => {}
}
Err(format!(
"undefined method '{}' for {}",
num_op_name(op),
self.class_name(a)
))
}
pub fn eq_values(&self, a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Int(x), Value::Int(y)) => x == y,
(Value::Float(x), Value::Float(y)) => x == y,
(Value::Int(x), Value::Float(y)) | (Value::Float(y), Value::Int(x)) => *x as f64 == *y,
(Value::Bool(x), Value::Bool(y)) => x == y,
(Value::Undef, Value::Undef) => true,
_ => {
let (oa, ob) = (self.obj(a), self.obj(b));
match (oa, ob) {
(Some(RObj::Str(x)), Some(RObj::Str(y))) => x == y,
(Some(RObj::Symbol(x)), Some(RObj::Symbol(y))) => x == y,
(Some(RObj::Array(x)), Some(RObj::Array(y))) => {
x.len() == y.len() && x.iter().zip(y).all(|(p, q)| self.eq_values(p, q))
}
(Some(RObj::Hash { map: x, .. }), Some(RObj::Hash { map: y, .. })) => {
x.len() == y.len()
&& x.iter()
.all(|(k, v)| y.get(k).is_some_and(|w| self.eq_values(v, w)))
}
_ => matches!((a, b), (Value::Obj(i), Value::Obj(j)) if i == j),
}
}
}
}
}
fn fmt_float(f: f64) -> String {
if f == f.trunc() && f.is_finite() && f.abs() < 1e16 {
format!("{f:.1}")
} else {
format!("{f}")
}
}
fn as_int(v: &Value) -> Option<i64> {
match v {
Value::Int(n) => Some(*n),
Value::Float(f) => Some(*f as i64),
_ => None,
}
}
fn cmp_ord(op: NumOp, o: std::cmp::Ordering) -> bool {
use std::cmp::Ordering::*;
match op {
NumOp::Lt => o == Less,
NumOp::Gt => o == Greater,
NumOp::Le => o != Greater,
NumOp::Ge => o != Less,
_ => false,
}
}
fn num_op_name(op: NumOp) -> &'static str {
match op {
NumOp::Add => "+",
NumOp::Sub => "-",
NumOp::Mul => "*",
NumOp::Div => "/",
NumOp::Mod => "%",
NumOp::Pow => "**",
NumOp::Lt => "<",
NumOp::Gt => ">",
NumOp::Le => "<=",
NumOp::Ge => ">=",
_ => "<op>",
}
}
fn run_chunk_on(chunk: Chunk) -> Result<Value, String> {
let mut vm = VM::new(chunk);
crate::builtins::install(&mut vm);
vm.set_numeric_hook(std::sync::Arc::new(|op, a, b| {
crate::builtins::numeric_hook(op, a, b)
}));
vm.enable_tracing_jit();
let outcome = vm.run();
if let Some(e) = with_host(|h| h.take_error()) {
return Err(e);
}
match outcome {
VMResult::Ok(v) => Ok(v),
VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
VMResult::Error(e) => Err(e),
}
}
pub fn run_main(chunk: Chunk) -> Result<Value, String> {
let r = run_chunk_on(chunk);
let uncaught = with_host(|h| match h.signal.take() {
Some(Signal::Throw(tag, _)) => Some(h.inspect(&tag)),
_ => None,
});
if let Some(tag) = uncaught {
return Err(format!("uncaught throw {tag} (UncaughtThrowError)"));
}
r
}
#[allow(clippy::too_many_arguments)]
fn run_method(
def: &MethodDef,
self_obj: Value,
args: &[Value],
block: Option<Value>,
method_name: Option<String>,
def_class: Option<String>,
) -> Result<Value, String> {
let saved_active = with_host(|h| {
let mut binding = h.bind_params(
&def.params,
def.splat,
&def.kwparams,
def.kwsplat.as_deref(),
args,
);
if let Some(bp) = &def.blockparam {
binding.insert(bp.clone(), block.clone().unwrap_or(Value::Undef));
}
h.frames.push(Frame {
scope: Scope {
locals: env_with(binding),
block,
self_obj,
method_name,
def_class,
},
args: args.to_vec(),
});
h.active_scope.take()
});
let r = run_chunk_on(def.chunk.clone());
let sig = with_host(|h| {
h.frames.pop();
h.active_scope = saved_active;
h.signal.take()
});
match sig {
Some(Signal::Return(v)) => Ok(v),
Some(other @ Signal::Throw(..)) => {
with_host(|h| h.signal = Some(other));
r
}
_ => r,
}
}
pub fn call_method(name: &str, args: &[Value], block: Option<Value>) -> Result<Value, String> {
let self_obj = with_host(|h| h.current_self());
if let Some((def, owner, recv)) = with_host(|h| h.method_for_self(&self_obj, name)) {
return run_method(&def, recv, args, block, Some(name.into()), Some(owner));
}
let def = with_host(|h| h.methods.get(name).cloned());
let Some(def) = def else {
return Err(format!("undefined method '{name}'"));
};
run_method(&def, self_obj, args, block, Some(name.into()), None)
}
pub fn call_instance_method(
recv: Value,
class: &str,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
let (def, owner) = with_host(|h| h.find_method_owner(class, name))
.ok_or_else(|| format!("undefined method '{name}' for {class}"))?;
run_method(&def, recv, args, block, Some(name.into()), Some(owner))
}
pub fn call_class_method(
recv: Value,
def: &MethodDef,
name: &str,
def_class: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
run_method(
def,
recv,
args,
block,
Some(name.into()),
Some(def_class.into()),
)
}
pub fn call_super(explicit_args: Option<Vec<Value>>) -> Result<Value, String> {
let (self_obj, method, def_class, cur_args) = with_host(|h| h.super_context());
let (Some(method), Some(def_class)) = (method, def_class) else {
return Err("super called outside of a method".to_string());
};
let Some((def, owner)) = with_host(|h| h.find_super(&def_class, &method)) else {
return Err(format!("super: no superclass method '{method}'"));
};
let args = explicit_args.unwrap_or(cur_args);
let block = with_host(|h| h.cur_scope().block.clone());
run_method(&def, self_obj, &args, block, Some(method), Some(owner))
}
fn run_template(id: usize, args: &[Value]) -> Result<Value, String> {
let def = with_host(|h| h.proc_def(id));
let saved: Vec<(String, Option<Value>)> = with_host(|h| {
def.params
.iter()
.enumerate()
.map(|(i, p)| {
let prev = h.get_local(p);
let had = h.local_defined(p);
h.set_local(p, args.get(i).cloned().unwrap_or(Value::Undef));
(p.clone(), had.then_some(prev))
})
.collect()
});
let r = run_chunk_on(def.chunk.clone());
with_host(|h| {
let env = h.cur_env();
for (p, prev) in saved {
match prev {
Some(v) => {
env.borrow_mut().vars.insert(p, v);
}
None => {
env.borrow_mut().vars.shift_remove(&p);
}
}
}
});
r
}
pub fn run_begin(begin_id: usize) -> Result<Value, String> {
let Some(bd) = with_host(|h| h.begin_def(begin_id)) else {
return Err("bad begin id".to_string());
};
let result = loop {
let mut result = run_template(bd.body, &[]);
let err = result.as_ref().err().cloned();
let Some(e) = err else {
break result;
};
let has_signal = with_host(|h| h.signal.is_some());
if has_signal {
break result;
}
let exc = with_host(|h| h.take_pending_exc());
let exc_class = exc
.as_ref()
.and_then(|v| with_host(|h| h.object_class(v)))
.unwrap_or_else(|| "StandardError".to_string());
let excv = exc.clone().unwrap_or(Value::Undef);
let mut handled = false;
let mut retrying = false;
for rd in &bd.rescues {
let matches = rd.classes.is_empty()
|| rd
.classes
.iter()
.any(|c| with_host(|h| h.exc_matches(&exc_class, c)));
if matches {
let args = if rd.binding.is_some() {
vec![excv.clone()]
} else {
vec![]
};
result = run_template(rd.body, &args);
handled = true;
retrying = take_retry_signal();
break;
}
}
if retrying {
continue;
}
if !handled {
with_host(|h| h.pending_exc = exc);
result = Err(e);
}
break result;
};
if let Some(eid) = bd.ensure {
run_template(eid, &[])?;
}
result
}
pub fn call_proc(proc_val: &Value, args: &[Value]) -> Result<Value, String> {
let (template, scope, kind) = match with_host(|h| h.obj(proc_val).cloned()) {
Some(RObj::Proc {
template,
scope,
kind,
..
}) => (template, scope, kind),
Some(RObj::Method { recv, name }) => {
return crate::builtins::dispatch(&recv, &name, args, None);
}
Some(RObj::SymProc(s)) => {
return match args.split_first() {
Some((recv, rest)) => crate::builtins::dispatch(recv, &s, rest, None),
None => Err("no receiver is available".to_string()),
};
}
_ => return Err("not a proc".to_string()),
};
match kind {
ProcKind::Composed { first, second } => {
let mid = call_proc(&first, args)?;
return call_proc(&second, std::slice::from_ref(&mid));
}
ProcKind::Curried { arity, collected } => {
let mut all = collected.clone();
all.extend_from_slice(args);
if all.len() >= arity {
let base = with_host(|h| {
h.alloc(RObj::Proc {
template,
scope: scope.clone(),
is_lambda: false,
kind: ProcKind::Normal,
})
});
return call_proc(&base, &all);
}
return Ok(with_host(|h| {
h.alloc(RObj::Proc {
template,
scope: scope.clone(),
is_lambda: false,
kind: ProcKind::Curried {
arity,
collected: all,
},
})
}));
}
ProcKind::Collect(idx) => {
let elem = match args {
[single] => single.clone(),
many => with_host(|h| h.new_array(many.to_vec())),
};
with_host(|h| h.enum_sinks[idx].push(elem));
return Ok(Value::Undef);
}
ProcKind::Normal => {}
}
let def = with_host(|h| h.procs[template].clone());
let bound: Vec<Value> = if def.params.len() > 1 && args.len() == 1 {
match with_host(|h| h.as_array(&args[0])) {
Some(items) => items,
None => args.to_vec(),
}
} else {
args.to_vec()
};
let child = child_env(scope.locals.clone());
for (i, p) in def.params.iter().enumerate() {
child
.borrow_mut()
.vars
.insert(p.clone(), bound.get(i).cloned().unwrap_or(Value::Undef));
}
let block_scope = Scope {
locals: child,
..scope
};
let prev_active = with_host(|h| h.active_scope.replace(block_scope));
let r = run_chunk_on(def.chunk.clone());
with_host(|h| {
h.active_scope = prev_active;
});
let sig = with_host(|h| h.signal.take());
match sig {
Some(Signal::Next(v)) => Ok(v),
Some(other) => {
with_host(|h| h.signal = Some(other));
r
}
None => r,
}
}
pub fn current_block() -> Option<Value> {
with_host(|h| h.cur_scope().block.clone())
}
pub fn raise_signal_break(v: Value) {
with_host(|h| h.signal = Some(Signal::Break(v)));
}
pub fn raise_signal_next(v: Value) {
with_host(|h| h.signal = Some(Signal::Next(v)));
}
pub fn raise_signal_return(v: Value) {
with_host(|h| h.signal = Some(Signal::Return(v)));
}
pub fn raise_signal_retry() {
with_host(|h| h.signal = Some(Signal::Retry));
}
pub fn raise_signal_throw(tag: Value, value: Value) {
with_host(|h| h.signal = Some(Signal::Throw(tag, value)));
}
pub fn take_throw(tag: &Value) -> Option<Value> {
with_host(|h| {
if let Some(Signal::Throw(t, _)) = &h.signal {
if t == tag {
if let Some(Signal::Throw(_, v)) = h.signal.take() {
return Some(v);
}
}
}
None
})
}
pub fn take_retry_signal() -> bool {
with_host(|h| {
if matches!(h.signal, Some(Signal::Retry)) {
h.signal = None;
true
} else {
false
}
})
}
pub fn take_break() -> Option<Value> {
with_host(|h| match &h.signal {
Some(Signal::Break(_)) => {
if let Some(Signal::Break(v)) = h.signal.take() {
Some(v)
} else {
None
}
}
_ => None,
})
}
pub fn has_pending_signal() -> bool {
with_host(|h| h.signal.is_some())
}