use fusevm::{Chunk, NumOp, VMResult, Value, VM};
use indexmap::IndexMap;
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
pub use crate::rstr::{RStr, BROKEN_UTF8};
use crate::intercepts::{self, Advice};
pub struct EnvData {
vars: IndexMap<String, Value>,
parent: Option<Env>,
}
pub type Env = Arc<Mutex<EnvData>>;
fn new_env() -> Env {
Arc::new(Mutex::new(EnvData {
vars: IndexMap::new(),
parent: None,
}))
}
fn env_with(vars: IndexMap<String, Value>) -> Env {
Arc::new(Mutex::new(EnvData { vars, parent: None }))
}
fn child_env(parent: Env) -> Env {
Arc::new(Mutex::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>,
frame_id: u64,
}
thread_local! {
static NEXT_FRAME_ID: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
}
fn next_frame_id() -> u64 {
NEXT_FRAME_ID.with(|c| {
let v = c.get();
c.set(v.wrapping_add(1));
v
})
}
impl std::fmt::Debug for Scope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "<scope>")
}
}
pub mod ext {
pub const DBG_LINE: u16 = 1;
}
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; pub const NO_MATCH: u16 = 38; pub const CALL_ARR_BLK: u16 = 39; pub const CALL_METHOD_ARR_BLK: u16 = 40; pub const GETCVAR: u16 = 41; pub const SETCVAR: u16 = 42; pub const DEFINED_DESC: u16 = 43; pub const MKSTRC: u16 = 64; pub const DEFINE_SINGLETON: u16 = 44; pub const DEFINE_METHOD_DYN: u16 = 45; pub const FIRE_HOOK: u16 = 46; pub const SUPER_BLK: u16 = 47; pub const SUPER_FWD_BLK: u16 = 48; pub const MKSTRF: u16 = 49; pub const MKHASH_MERGE: u16 = 50; pub const TAKE_LOOP_NEXT: u16 = 51; pub const PEEK_LOOP_BREAK: u16 = 52; pub const TAKE_LOOP_BREAK: u16 = 53; pub const BEGIN_IN_LOOP: u16 = 54; pub const SIG_REDO: u16 = 55; pub const TAKE_LOOP_REDO: u16 = 56; pub const GETLOCAL_DECLARED: u16 = 57; pub const MARK_KWARGS: u16 = 58; pub const KWSPLAT_ARGS: u16 = 59; pub const BITNOT: u16 = 60; pub const METHOD_HOOK: u16 = 61; pub const MKBSTR: u16 = 62; pub const REGEX_ONCE: u16 = 63; }
pub const RANGE_BEGINLESS: i64 = i64::MIN;
pub const RANGE_ENDLESS: i64 = i64::MAX;
#[derive(Debug, Clone)]
pub enum LazyOp {
Map(Value),
Select(Value),
Reject(Value),
FilterMap(Value),
FlatMap(Value),
TakeWhile(Value),
DropWhile(Value),
Take(i64),
Drop(i64),
Zip(Vec<Vec<Value>>),
Uniq(Option<Value>),
Compact,
Grep(Value, bool),
WithIndex(Option<i64>),
WithObject(Value, bool),
EachSlice(usize),
EachCons(usize),
ChunkWhile(Value, bool),
}
#[derive(Debug, Clone)]
pub enum Derive {
Each,
Slice(usize),
Cons(usize),
WithIndex(i64),
WithObject(Value),
}
#[derive(Debug, Clone)]
pub enum GenSize {
Fixed(Value),
Call(Value, Vec<Value>),
Of(Value, Derive),
}
#[derive(Debug, Clone)]
pub struct GenExt {
pub fiber: Value,
pub peeked: Option<Value>,
pub result: Value,
}
#[derive(Debug, Clone)]
pub struct ArithSeq {
pub desc: String,
pub begin: Value,
pub end: Value,
pub step: Value,
pub exclude_end: bool,
pub inner: Value,
}
#[derive(Default)]
struct AncestryCache {
gen: u64,
chains: std::collections::HashMap<(String, bool), Arc<Vec<String>>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatchPart {
Pre,
Post,
Subject,
}
#[derive(Debug, Clone)]
pub enum RObj {
Str(RStr),
Array(Vec<Value>),
Hash {
map: IndexMap<RKey, Value>,
default: Value,
default_proc: Option<Value>,
by_identity: bool,
},
Symbol(String),
Set(IndexMap<RKey, Value>),
BigInt(num_bigint::BigInt),
Rational(num_rational::BigRational),
Complex {
re: Value,
im: Value,
},
Lazy {
source: Value,
ops: Vec<LazyOp>,
origin: Value,
},
Range {
lo: i64,
hi: i64,
exclusive: bool,
},
FloatRange {
lo: f64,
hi: f64,
exclusive: bool,
},
StrRange {
lo: String,
hi: String,
exclusive: bool,
},
ObjRange {
lo: Value,
hi: Value,
exclusive: bool,
},
Proc {
template: usize,
scope: Scope,
is_lambda: bool,
kind: ProcKind,
home: Option<u64>,
},
SymProc(String),
CycleProc(Vec<Value>),
RaiseProc {
class: String,
message: String,
},
SeqProc(i64),
ProduceProc {
init: Option<Value>,
block: Value,
},
StepProc {
from: Value,
by: Value,
float: bool,
},
DeriveProc {
src: Box<Value>,
kind: Derive,
},
Method {
recv: Value,
name: String,
unbound: bool,
via: Option<String>,
},
Object {
class: String,
ivars: IndexMap<String, Value>,
},
ClassRef(String),
Regexp {
source: String,
re: std::sync::Arc<fancy_regex::Regex>,
flags: String,
},
MatchData {
groups: Vec<Option<String>>,
names: Vec<(String, usize)>,
offsets: Vec<Option<(usize, usize)>>,
pre: String,
post: String,
regexp: Value,
subject: Option<Vec<u8>>,
},
Enumerator {
buf: Vec<Value>,
cursor: usize,
method: String,
source: Option<Value>,
},
ArithSeq(Box<ArithSeq>),
EnumChain(Vec<Value>),
Generator {
block: Value,
materialized: Option<(Vec<Value>, usize)>,
ext: Option<GenExt>,
size: GenSize,
label: Option<String>,
},
Yielder {
sink: usize,
limit: usize,
},
FiberYielder,
Fiber {
id: u32,
},
Binding {
id: u32,
},
Thread {
id: u32,
},
IoHandle {
id: u32,
},
Time(crate::rtime::RTime),
Date {
days: i64,
},
DateTime {
secs: f64,
},
Db {
id: u32,
},
FiddleHandle {
id: u32,
},
FiddleFunc {
addr: u64,
args: Vec<i32>,
ret: i32,
},
FiddlePtr {
addr: u64,
size: i64,
owned: Option<u32>,
},
}
pub const UNIX_EPOCH_JDN: i64 = 2_440_588;
pub fn days_in_month(y: i64, m: i64) -> i64 {
match m {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if is_leap_year(y) => 29,
2 => 28,
_ => 30,
}
}
pub fn is_leap_year(y: i64) -> bool {
(y % 4 == 0 && y % 100 != 0) || y % 400 == 0
}
pub fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400; let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146097 + doe - 719468
}
pub fn civil_from_days(z: i64) -> (i64, i64, i64) {
let z = z + 719468;
let era = if z >= 0 { z } else { z - 146096 } / 146097;
let doe = z - era * 146097; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; (if m <= 2 { y + 1 } else { y }, m, d)
}
#[derive(Debug, Clone)]
pub enum ProcKind {
Normal,
Curried { arity: usize, collected: Vec<Value> },
MethodCurried {
target: Box<Value>,
arity: usize,
collected: Vec<Value>,
},
Composed {
first: Box<Value>,
second: Box<Value>,
},
Collect(usize),
Around(usize),
SetsMatch {
inner: Box<Value>,
matches: Vec<Value>,
next: usize,
},
}
#[derive(Clone, Default)]
pub struct ClassDef {
pub superclass: Option<String>,
pub methods: IndexMap<String, MethodDef>,
pub includes: Vec<String>,
pub prepends: Vec<String>,
pub extends: Vec<String>,
pub class_methods: IndexMap<String, MethodDef>,
pub visibility: IndexMap<String, Visibility>,
pub class_visibility: IndexMap<String, Visibility>,
pub is_module: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Visibility {
#[default]
Public,
Private,
Protected,
}
impl Visibility {
pub fn as_u8(self) -> u8 {
match self {
Visibility::Public => 0,
Visibility::Private => 1,
Visibility::Protected => 2,
}
}
pub fn from_u8(b: u8) -> Self {
match b {
1 => Visibility::Private,
2 => Visibility::Protected,
_ => Visibility::Public,
}
}
pub fn word(self) -> &'static str {
match self {
Visibility::Public => "public",
Visibility::Private => "private",
Visibility::Protected => "protected",
}
}
}
#[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 splat: Option<usize>,
pub body: usize,
}
fn compiled_regex(
source: &str,
flags: &str,
inline: &str,
) -> Result<std::sync::Arc<fancy_regex::Regex>, String> {
const MAX_CACHED: usize = 1024;
type Entry = Result<std::sync::Arc<fancy_regex::Regex>, String>;
thread_local! {
static CACHE: std::cell::RefCell<rustc_hash::FxHashMap<u64, (String, String, Entry)>> =
std::cell::RefCell::new(rustc_hash::FxHashMap::default());
}
let key = {
use std::hash::{Hash, Hasher};
let mut h = rustc_hash::FxHasher::default();
source.hash(&mut h);
flags.hash(&mut h);
h.finish()
};
if let Some(hit) = CACHE.with(|c| {
c.borrow()
.get(&key)
.filter(|(s, f, _)| s == source && f == flags)
.map(|(_, _, e)| e.clone())
}) {
return hit;
}
let body = ruby_regex_to_fancy(source, flags.contains('x'));
let full = format!("(?{inline}){body}");
let entry: Entry = fancy_regex::Regex::new(&full)
.map(std::sync::Arc::new)
.map_err(|e| format!("invalid regex /{source}/: {e}"));
CACHE.with(|c| {
let mut m = c.borrow_mut();
if m.len() >= MAX_CACHED {
m.clear();
}
m.insert(key, (source.to_string(), flags.to_string(), entry.clone()));
});
entry
}
pub fn regex_group_names(source: &str, flags: &str) -> Vec<String> {
fancy_regex::Regex::new(&ruby_regex_to_fancy(source, flags.contains('x')))
.map(|re| re.capture_names().flatten().map(str::to_string).collect())
.unwrap_or_default()
}
fn ruby_regex_to_fancy(source: &str, extended: bool) -> String {
let decoded = decode_regex_byte_escapes(source);
let source = decoded.as_ref();
let scan = scan_regex_groups(source, extended, None, false);
if !scan.named && !scan.inline_flags {
return source.to_string();
}
let mut out = String::with_capacity(source.len() + 16);
scan_regex_groups(source, extended, Some(&mut out), scan.named);
out
}
fn decode_regex_byte_escapes(source: &str) -> std::borrow::Cow<'_, str> {
if !source.contains("\\x") {
return std::borrow::Cow::Borrowed(source);
}
let b = source.as_bytes();
let hex = |c: u8| (c as char).to_digit(16);
let escape_at = |i: usize| -> Option<(u8, usize)> {
if b.get(i) != Some(&b'\\') || b.get(i + 1) != Some(&b'x') {
return None;
}
let d1 = hex(*b.get(i + 2)?)?;
match b.get(i + 3).and_then(|&c| hex(c)) {
Some(d2) => Some(((d1 * 16 + d2) as u8, 4)),
None => Some((d1 as u8, 3)),
}
};
let mut out = String::with_capacity(source.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'\\' {
if escape_at(i).is_none() {
let len = 1 + source[i + 1..].chars().next().map_or(0, char::len_utf8);
out.push_str(&source[i..i + len]);
i += len;
continue;
}
let start = i;
let mut run = Vec::new();
let mut ends = Vec::new();
while let Some((byte, len)) = escape_at(i) {
run.push(byte);
i += len;
ends.push(i);
}
let mut at = start;
let mut k = 0;
for chunk in run.utf8_chunks() {
for c in chunk.valid().chars() {
let n = c.len_utf8();
if c.is_ascii() {
out.push_str(&source[at..ends[k]]);
} else {
out.push(c);
}
at = ends[k + n - 1];
k += n;
}
for _ in chunk.invalid() {
out.push_str(&source[at..ends[k]]);
at = ends[k];
k += 1;
}
}
continue;
}
let len = source[i..].chars().next().map_or(1, char::len_utf8);
out.push_str(&source[i..i + len]);
i += len;
}
std::borrow::Cow::Owned(out)
}
#[derive(Default)]
struct RegexScan {
named: bool,
inline_flags: bool,
}
fn inline_flag_group_end(c: &[char], i: usize) -> Option<usize> {
let mut j = i;
while matches!(c.get(j), Some('i') | Some('m') | Some('x') | Some('-')) {
j += 1;
}
match c.get(j) {
Some(')') | Some(':') if j > i => Some(j),
_ => None,
}
}
fn scan_regex_groups(
source: &str,
extended: bool,
mut out: Option<&mut String>,
suppress_unnamed: bool,
) -> RegexScan {
let c: Vec<char> = source.chars().collect();
let mut i = 0;
let mut scan = RegexScan::default();
let mut in_class = false;
macro_rules! push {
($ch:expr) => {
if let Some(o) = out.as_deref_mut() {
o.push($ch);
}
};
}
while i < c.len() {
let ch = c[i];
if ch == '\\' {
push!(ch);
i += 1;
if i < c.len() {
push!(c[i]);
i += 1;
}
continue;
}
if in_class {
if ch == '[' && c.get(i + 1) == Some(&':') {
if let Some(end) =
(i + 2..c.len()).find(|&j| c[j] == ':' && c.get(j + 1) == Some(&']'))
{
for &x in &c[i..=end + 1] {
push!(x);
}
i = end + 2;
continue;
}
}
if ch == ']' {
in_class = false;
}
push!(ch);
i += 1;
continue;
}
if extended && ch == '#' {
while i < c.len() && c[i] != '\n' {
push!(c[i]);
i += 1;
}
continue;
}
if ch == '[' {
in_class = true;
push!(ch);
i += 1;
continue;
}
if ch == '(' {
if c.get(i + 1) == Some(&'?') {
if c.get(i + 2) == Some(&'#') {
while i < c.len() && c[i] != ')' {
push!(c[i]);
i += 1;
}
continue;
}
if let Some(end) = inline_flag_group_end(&c, i + 2) {
scan.inline_flags = true;
push!('(');
push!('?');
for &f in &c[i + 2..end] {
push!(if f == 'm' { 's' } else { f });
}
push!(c[end]);
i = end + 1;
continue;
}
let named_here = match c.get(i + 2) {
Some('<') => !matches!(c.get(i + 3), Some('=') | Some('!')),
Some('\'') => true,
_ => false,
};
scan.named |= named_here;
push!('(');
push!('?');
i += 2;
continue;
}
if suppress_unnamed {
push!('(');
push!('?');
push!(':');
} else {
push!('(');
}
i += 1;
continue;
}
push!(ch);
i += 1;
}
scan
}
pub fn regex_option_bits(flags: &str) -> u8 {
let mut bits = 0u8;
if flags.contains('i') {
bits |= 1;
}
if flags.contains('x') {
bits |= 2;
}
if flags.contains('m') {
bits |= 4;
}
bits
}
thread_local! {
static EQ_PAIRS: std::cell::RefCell<Vec<(u32, u32)>> =
const { std::cell::RefCell::new(Vec::new()) };
static EQL_PAIRS: std::cell::RefCell<Vec<(u32, u32)>> =
const { std::cell::RefCell::new(Vec::new()) };
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum RKey {
Int(i64),
Str(String),
ByteStr(String, &'static str),
Sym(String),
Bool(bool),
Nil,
FloatBits(u64),
Class(String),
Array(Vec<RKey>),
Hash(Vec<(RKey, RKey)>),
Set(Vec<RKey>),
Big(num_bigint::BigInt),
Rational(num_rational::BigRational),
Complex(Box<RKey>, Box<RKey>),
Range(i64, i64, bool),
StrRange(String, String, bool),
FloatRange(u64, u64, bool),
ObjRange(Box<RKey>, Box<RKey>, bool),
Regexp(String, u8),
ArithSeq(Vec<RKey>),
Identity(u32),
Recursive,
}
#[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 req: u16,
pub opt: u16,
pub post: u16,
pub kwreq: Vec<String>,
pub chunk: Arc<Chunk>,
pub chunk_id: u64,
pub slot_params: u16,
pub line: u32,
pub file: Option<Arc<SourceFile>>,
}
#[derive(Clone, Copy)]
pub struct PositionalShape {
pub splat: Option<usize>,
pub opt: usize,
pub post: usize,
}
impl MethodDef {
pub fn positional_shape(&self) -> PositionalShape {
PositionalShape {
splat: self.splat,
opt: self.opt as usize,
post: self.post as usize,
}
}
}
pub enum MethodShape {
Def { def: Box<MethodDef>, owner: String },
Block { template: usize, owner: String },
Builtin {
owner: &'static str,
arity: i16,
params: &'static str,
},
}
#[derive(Clone)]
pub struct ProcSig {
pub params: Vec<String>,
pub splat: Option<usize>,
pub arity: crate::ast::BlockArity,
}
#[derive(Clone)]
pub struct ProcDef {
pub params: Vec<String>,
pub splat: Option<usize>,
pub chunk: Chunk,
pub arity: crate::ast::BlockArity,
pub block_depth: u32,
pub line: u32,
pub file: Option<Arc<SourceFile>>,
}
struct Frame {
scope: Scope,
args: Vec<Value>,
line: u32,
}
#[derive(Clone)]
enum Signal {
Break(Value),
Next(Value),
Return(Value, Option<u64>),
Retry,
Redo,
Throw(Value, Value),
}
#[derive(Clone)]
struct AroundCall {
handlers: Vec<String>,
def: MethodDef,
self_obj: Value,
args: Vec<Value>,
block: Option<Value>,
method_name: Option<String>,
def_class: Option<String>,
}
pub struct RubyHost {
heap: Vec<RObj>,
frames: Vec<Frame>,
globals: IndexMap<String, Value>,
last_match: Value,
match_owner: u64,
parked_matches: HashMap<u64, Value>,
shadowed_defs: HashMap<(String, String), MethodDef>,
method_snapshots: HashMap<u32, (MethodDef, String)>,
binary_regexps: bool,
binary_regexp_encodings: HashMap<u32, &'static str>,
regex_sites: HashMap<i64, Value>,
required_tops: HashSet<u64>,
enum_feeds: HashMap<u32, (Option<Value>, Vec<Value>)>,
enum_matches: HashMap<u32, Vec<Value>>,
consts: IndexMap<String, Value>,
autoloads: IndexMap<String, String>,
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>,
at_exit_procs: Vec<Value>,
exc_backtraces: IndexMap<u32, Vec<String>>,
sealed_backtraces: HashSet<u32>,
exc_backtrace_locations: HashMap<u32, Value>,
string_backtraces: HashSet<u32>,
byte_strings: bool,
encoding_objects: HashMap<&'static str, Value>,
loaded_encodings: HashSet<&'static str>,
signal: Option<Signal>,
catch_tags: Vec<Value>,
active_scope: Option<Scope>,
frozen: HashSet<u32>,
enum_sinks: Vec<Vec<Value>>,
multi_yield_packs: HashSet<u32>,
class_gen: u64,
ancestry_cache: std::cell::RefCell<AncestryCache>,
kwargs_hashes: HashSet<u32>,
initialized_exceptions: HashSet<u32>,
hash_iter_lev: HashMap<u32, u32>,
user_key_canon: HashMap<u32, u32>,
user_key_reps: HashMap<i64, Vec<u32>>,
around_stack: Vec<AroundCall>,
struct_defs: IndexMap<String, (Vec<String>, Option<bool>)>,
data_classes: std::collections::HashSet<String>,
embedded_stdlib_loaded: std::collections::HashSet<String>,
builtin_libs_loaded: std::collections::HashSet<String>,
enum_size_fns: std::collections::HashMap<u32, (Option<Value>, Vec<Value>)>,
enum_labels: std::collections::HashMap<u32, String>,
io_linenos: std::collections::HashMap<u32, i64>,
io_syncs: std::collections::HashMap<u32, bool>,
struct_counter: u32,
refinement_defs: IndexMap<String, Vec<(String, String)>>,
active_refinements: Vec<(String, String)>,
used_modules: Vec<String>,
skip_refined: Option<String>,
class_vars: IndexMap<String, IndexMap<String, Value>>,
class_ivars: IndexMap<String, IndexMap<String, Value>>,
class_object_ids: IndexMap<String, ()>,
attr_accessors: IndexMap<String, IndexMap<String, (bool, bool)>>,
attr_aliases: IndexMap<String, IndexMap<String, (String, bool)>>,
hoisted_hooks: HashMap<(String, String), std::collections::VecDeque<MethodDef>>,
define_methods: IndexMap<String, IndexMap<String, Value>>,
singleton_methods: IndexMap<u32, IndexMap<String, MethodDef>>,
object_extends: HashMap<u32, Vec<String>>,
extended_singletons: HashMap<u32, HashSet<String>>,
singleton_define_methods: IndexMap<u32, IndexMap<String, Value>>,
class_define_methods: IndexMap<String, IndexMap<String, Value>>,
obj_ivars: IndexMap<u32, IndexMap<String, Value>>,
pack_associates: HashMap<u32, Vec<Value>>,
chilled: Vec<u64>,
chilled_symbol_strings: HashMap<u32, String>,
symbol_names: HashMap<String, Value>,
method_aliases: IndexMap<String, IndexMap<String, String>>,
alias_originals: IndexMap<String, IndexMap<String, String>>,
module_function_modules: std::collections::HashSet<String>,
class_overrides: IndexMap<u32, String>,
bindings: Vec<Scope>,
threads: Vec<ThreadCell>,
queues: Vec<Arc<QueueSync>>,
condvars: Vec<Arc<CondVarSync>>,
io_handles: Vec<IoCell>,
db_handles: Vec<Option<DbCell>>,
fiddle_libs: Vec<Option<FiddleLib>>,
fiddle_mem: Vec<Option<Box<[u8]>>>,
capture: Option<String>,
pub stdin: StdinSource,
pub exit_status: Option<i32>,
rendering: Vec<u32>,
}
pub struct DbCell {
conn: rusqlite::Connection,
pub results_as_hash: bool,
}
pub struct FiddleLib(libloading::os::unix::Library);
pub type SqlVal = rusqlite::types::Value;
pub enum StdinSource {
Process,
Fed(std::io::Cursor<Vec<u8>>),
}
impl std::io::Read for StdinSource {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self {
StdinSource::Process => std::io::stdin().read(buf),
StdinSource::Fed(c) => c.read(buf),
}
}
}
impl StdinSource {
pub fn read_line(&mut self, line: &mut String) -> std::io::Result<usize> {
use std::io::BufRead;
match self {
StdinSource::Process => std::io::stdin().read_line(line),
StdinSource::Fed(c) => c.read_line(line),
}
}
pub fn is_terminal(&self) -> bool {
use std::io::IsTerminal;
matches!(self, StdinSource::Process) && std::io::stdin().is_terminal()
}
}
pub enum IoCell {
Stdout,
Stderr,
Stdin,
File {
file: Option<std::fs::File>,
path: String,
},
TcpListener {
listener: Option<std::net::TcpListener>,
local: String,
},
TcpStream {
stream: Option<std::net::TcpStream>,
peer: String,
rbuf: std::collections::VecDeque<u8>,
},
}
impl IoCell {
fn class_name(&self) -> &'static str {
match self {
IoCell::File { .. } => "File",
IoCell::TcpListener { .. } => "TCPServer",
IoCell::TcpStream { .. } => "TCPSocket",
_ => "IO",
}
}
}
struct QueueSync {
data: Mutex<QueueData>,
cv: std::sync::Condvar,
}
struct QueueData {
items: std::collections::VecDeque<Value>,
closed: bool,
cap: Option<usize>,
}
struct CondVarSync {
gen: Mutex<u64>,
cv: std::sync::Condvar,
}
struct ThreadCell {
handle: Option<std::thread::JoinHandle<()>>,
result: Arc<Mutex<Option<Result<Value, String>>>>,
exc: Arc<Mutex<Option<Value>>>,
done: Arc<std::sync::atomic::AtomicBool>,
}
struct FiberCell {
coro: Option<corosensei::Coroutine<Value, Value, Result<Value, String>>>,
yielder: *const (),
ctx: FiberContext,
done: bool,
}
#[derive(Default)]
struct FiberContext {
active_scope: Option<Scope>,
signal: Option<Signal>,
catch_tags: Vec<Value>,
pending_exc: Option<Value>,
error: Option<String>,
frames: Vec<Frame>,
enum_sinks: Vec<Vec<Value>>,
around_stack: Vec<AroundCall>,
call_sites: Vec<CallSite>,
}
type Vm = Arc<Mutex<RubyHost>>;
thread_local! {
static CURRENT_VM: RefCell<Option<Vm>> = const { RefCell::new(None) };
static HOST_PTR: std::cell::Cell<*mut RubyHost> =
const { std::cell::Cell::new(std::ptr::null_mut()) };
static GVL_GUARD: RefCell<Option<GvlHold>> = const { RefCell::new(None) };
}
struct GvlHold {
_guard: std::sync::MutexGuard<'static, RubyHost>,
_vm: Vm,
}
fn current_vm() -> Vm {
CURRENT_VM.with(|c| {
c.borrow_mut()
.get_or_insert_with(|| Arc::new(Mutex::new(RubyHost::new())))
.clone()
})
}
fn install_current_vm(vm: Vm) {
CURRENT_VM.with(|c| *c.borrow_mut() = Some(vm));
}
fn gvl_enter() {
let vm = current_vm();
let mut guard = vm.lock().unwrap_or_else(|p| p.into_inner());
let ptr: *mut RubyHost = &mut *guard;
let guard: std::sync::MutexGuard<'static, RubyHost> = unsafe { std::mem::transmute(guard) };
HOST_PTR.with(|p| p.set(ptr));
GVL_GUARD.with(|g| {
*g.borrow_mut() = Some(GvlHold {
_guard: guard,
_vm: vm,
})
});
}
fn gvl_leave() {
HOST_PTR.with(|p| p.set(std::ptr::null_mut()));
GVL_GUARD.with(|g| *g.borrow_mut() = None);
}
pub fn with_gvl<R>(f: impl FnOnce() -> R) -> R {
if HOST_PTR.with(|p| !p.get().is_null()) {
return f();
}
gvl_enter();
let r = f();
gvl_leave();
r
}
pub fn gvl_blocking<R>(blocking: impl FnOnce() -> R) -> R {
if HOST_PTR.with(|p| p.get().is_null()) {
return blocking();
}
gvl_leave();
let r = blocking();
gvl_enter();
r
}
pub fn with_host<R>(f: impl FnOnce(&mut RubyHost) -> R) -> R {
let ptr = HOST_PTR.with(|p| p.get());
if !ptr.is_null() {
return f(unsafe { &mut *ptr });
}
let vm = current_vm();
let mut guard = vm.lock().unwrap_or_else(|p| p.into_inner());
f(&mut guard)
}
pub fn reset_host() {
debug_assert!(
GVL_GUARD.with(|g| g.borrow().is_none()),
"reset_host must run with the GVL released"
);
CURRENT_VM.with(|c| *c.borrow_mut() = Some(Arc::new(Mutex::new(RubyHost::new()))));
crate::intercepts::clear();
FILE_DIR_STACK.with(|s| s.borrow_mut().clear());
FILE_PATH_STACK.with(|s| s.borrow_mut().clear());
DEF_TARGET.with(|t| t.borrow_mut().clear());
VM_POOL.with(|p| p.borrow_mut().clear());
BLOCK_HOMES.with(|s| s.borrow_mut().clear());
BLOCK_CTX.with(|s| s.borrow_mut().clear());
CALL_SITES.with(|s| s.borrow_mut().clear());
LEXICAL_BREAK.with(|c| c.set(false));
FIBERS.with(|f| f.borrow_mut().clear());
CUR_FIBER.with(|c| c.set(None));
CURRENT_THREAD.with(|c| *c.borrow_mut() = None);
}
thread_local! {
static FILE_DIR_STACK: RefCell<Vec<std::path::PathBuf>> = const { RefCell::new(Vec::new()) };
static FILE_PATH_STACK: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
pub fn push_file_dir(dir: std::path::PathBuf) {
FILE_DIR_STACK.with(|s| s.borrow_mut().push(dir));
}
pub fn push_file_path(path: String) {
FILE_PATH_STACK.with(|s| s.borrow_mut().push(path));
}
pub fn pop_file_dir() {
FILE_DIR_STACK.with(|s| {
s.borrow_mut().pop();
});
FILE_PATH_STACK.with(|s| {
s.borrow_mut().pop();
});
}
pub fn current_file_dir() -> Option<std::path::PathBuf> {
FILE_DIR_STACK.with(|s| s.borrow().last().cloned())
}
pub fn current_file_path() -> Option<String> {
FILE_PATH_STACK.with(|s| s.borrow().last().cloned())
}
pub struct SourceFile {
pub path: String,
pub dir: std::path::PathBuf,
}
fn enter_code_file(file: Option<&SourceFile>) -> bool {
let Some(f) = file else {
return false;
};
if FILE_PATH_STACK.with(|s| s.borrow().last().is_some_and(|top| *top == f.path)) {
return false;
}
push_file_dir(f.dir.clone());
push_file_path(f.path.clone());
true
}
fn leave_code_file(pushed: bool) {
if pushed {
pop_file_dir();
}
}
#[derive(Clone)]
pub enum DefTarget {
Instance(String),
ClassMethod(String),
Singleton(u32),
None,
}
thread_local! {
static DEF_TARGET: RefCell<Vec<DefTarget>> = const { RefCell::new(Vec::new()) };
}
pub fn apply_def_target(real: &str, synth: &str) -> Option<DefTarget> {
let target = DEF_TARGET.with(|t| t.borrow().last().cloned())?;
let def = with_host(|h| h.method_def(synth))?;
with_host(|h| match &target {
DefTarget::Instance(c) => h.add_instance_method(c, real, def),
DefTarget::ClassMethod(c) => h.add_class_method(c, real, def),
DefTarget::Singleton(id) => h.add_singleton_method(*id, real, def),
DefTarget::None => {}
});
Some(target)
}
pub fn eval_block_scoped(
block: &Value,
self_val: &Value,
target: DefTarget,
args: &[Value],
) -> Result<Value, String> {
DEF_TARGET.with(|t| t.borrow_mut().push(target));
let r = call_proc_self(block, args, Some(self_val));
DEF_TARGET.with(|t| t.borrow_mut().pop());
r
}
pub fn eval_string_scoped(src: &str, self_val: &Value, target: DefTarget) -> Result<Value, String> {
DEF_TARGET.with(|t| t.borrow_mut().push(target));
with_host(|h| {
h.frames.push(Frame {
scope: Scope {
locals: new_env(),
block: None,
self_obj: self_val.clone(),
method_name: None,
def_class: None,
frame_id: next_frame_id(),
},
args: Vec::new(),
line: 0,
});
});
let saved_active = with_host(|h| h.active_scope.take());
let r = eval_in_place(src);
with_host(|h| {
h.frames.pop();
h.active_scope = saved_active;
});
DEF_TARGET.with(|t| t.borrow_mut().pop());
r
}
pub fn eval_erb_with_locals(src: &str, locals: Vec<(String, Value)>) -> Result<Value, String> {
let self_obj = with_host(|h| h.new_object("Object"));
let env = new_env();
{
let mut e = env.lock().unwrap();
for (k, v) in locals {
e.vars.insert(k, v);
}
}
with_host(|h| {
h.frames.push(Frame {
scope: Scope {
locals: env,
block: None,
self_obj,
method_name: None,
def_class: None,
frame_id: next_frame_id(),
},
args: Vec::new(),
line: 0,
});
});
let saved_active = with_host(|h| h.active_scope.take());
let r = eval_in_place(src);
with_host(|h| {
h.frames.pop();
h.active_scope = saved_active;
});
r
}
fn is_stop_iteration(_e: &str) -> bool {
with_host(|h| {
let Some(exc) = h.pending_exc.clone() else {
return false;
};
if !h.is_a(&exc, "StopIteration") {
return false;
}
h.pending_exc = None;
true
})
}
pub fn in_binding<R>(binding: &Value, f: impl FnOnce() -> R) -> R {
let scope = with_host(|h| h.binding_scope(binding));
let saved = with_host(|h| std::mem::replace(&mut h.active_scope, scope));
let r = f();
with_host(|h| h.active_scope = saved);
r
}
pub fn eval_in_place(src: &str) -> Result<Value, String> {
let syntax = |e: String| crate::builtins::raise_exc("SyntaxError", &e);
let stmts = crate::parser::parse(src).map_err(syntax)?;
let (proc_base, begin_base) = with_host(|h| (h.procs.len(), h.begins.len()));
let mut prog = crate::compiler::compile_at(&stmts, proc_base, begin_base).map_err(syntax)?;
crate::compiler::assign_regex_sites(&mut prog);
let main = prog.main;
let target = DEF_TARGET.with(|t| t.borrow().last().cloned());
with_host(|h| {
for (name, def) in prog.methods {
let synthetic = name.starts_with("__");
match &target {
Some(DefTarget::Instance(c)) if !synthetic => h.add_instance_method(c, &name, def),
Some(DefTarget::ClassMethod(c)) if !synthetic => h.add_class_method(c, &name, def),
Some(DefTarget::Singleton(id)) if !synthetic => {
h.add_singleton_method(*id, &name, def)
}
_ => {
h.methods.insert(name, def);
}
}
}
for (name, mut def) in prog.classes {
h.note_hoisted_hooks(&name, &mut def);
merge_class(&mut h.classes, name, def);
}
h.begins.extend(prog.begins);
h.procs.extend(prog.procs);
});
run_chunk_on(main)
}
pub fn call_singleton(
recv: Value,
def: &MethodDef,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
let def_class = with_host(|h| h.class_of(&recv));
run_method(def, recv, args, block, Some(name.into()), Some(def_class))
}
fn merge_class(classes: &mut IndexMap<String, ClassDef>, name: String, def: ClassDef) {
let Some(existing) = classes.get_mut(&name) else {
classes.insert(name, def);
return;
};
if def.superclass.is_some() {
existing.superclass = def.superclass;
}
existing.is_module |= def.is_module;
for (k, v) in def.visibility {
existing.visibility.insert(k, v);
}
for (k, v) in def.class_visibility {
existing.class_visibility.insert(k, v);
}
for (k, v) in def.methods {
existing.methods.insert(k, v);
}
for (k, v) in def.class_methods {
existing.class_methods.insert(k, v);
}
for m in def.includes {
if !existing.includes.contains(&m) {
existing.includes.push(m);
}
}
for m in def.prepends {
if !existing.prepends.contains(&m) {
existing.prepends.push(m);
}
}
for m in def.extends {
if !existing.extends.contains(&m) {
existing.extends.push(m);
}
}
}
impl Default for RubyHost {
fn default() -> Self {
Self::new()
}
}
pub const MAIN_OBJ_ID: u32 = 0;
pub fn is_main(v: &Value) -> bool {
matches!(v, Value::Obj(id) if *id == MAIN_OBJ_ID)
}
impl RubyHost {
pub fn new() -> Self {
let main = RObj::Object {
class: "Object".to_string(),
ivars: IndexMap::new(),
};
let mut h = RubyHost {
heap: vec![main],
frames: vec![Frame {
scope: Scope {
locals: new_env(),
block: None,
self_obj: Value::Obj(0),
method_name: None,
def_class: None,
frame_id: next_frame_id(),
},
args: Vec::new(),
line: 0,
}],
globals: IndexMap::new(),
last_match: Value::Undef,
match_owner: u64::MAX,
parked_matches: HashMap::new(),
enum_matches: HashMap::new(),
shadowed_defs: HashMap::new(),
method_snapshots: HashMap::new(),
enum_feeds: HashMap::new(),
binary_regexps: false,
binary_regexp_encodings: HashMap::new(),
regex_sites: HashMap::new(),
required_tops: HashSet::new(),
consts: IndexMap::new(),
autoloads: IndexMap::new(),
methods: IndexMap::new(),
classes: IndexMap::new(),
begins: Vec::new(),
procs: Vec::new(),
symbols: IndexMap::new(),
error: None,
pending_exc: None,
at_exit_procs: Vec::new(),
exc_backtraces: IndexMap::new(),
sealed_backtraces: HashSet::new(),
exc_backtrace_locations: HashMap::new(),
string_backtraces: HashSet::new(),
byte_strings: false,
encoding_objects: HashMap::new(),
loaded_encodings: HashSet::new(),
signal: None,
catch_tags: Vec::new(),
active_scope: None,
frozen: HashSet::new(),
enum_sinks: Vec::new(),
rendering: Vec::new(),
multi_yield_packs: HashSet::new(),
class_gen: 0,
ancestry_cache: std::cell::RefCell::new(AncestryCache::default()),
kwargs_hashes: HashSet::new(),
initialized_exceptions: HashSet::new(),
hash_iter_lev: HashMap::new(),
user_key_canon: HashMap::new(),
user_key_reps: HashMap::new(),
around_stack: Vec::new(),
bindings: Vec::new(),
threads: Vec::new(),
queues: Vec::new(),
condvars: Vec::new(),
io_handles: vec![IoCell::Stdout, IoCell::Stderr, IoCell::Stdin],
db_handles: Vec::new(),
fiddle_libs: Vec::new(),
fiddle_mem: Vec::new(),
capture: None,
stdin: StdinSource::Process,
exit_status: None,
struct_defs: IndexMap::new(),
data_classes: std::collections::HashSet::new(),
embedded_stdlib_loaded: std::collections::HashSet::new(),
builtin_libs_loaded: std::collections::HashSet::new(),
enum_size_fns: std::collections::HashMap::new(),
enum_labels: std::collections::HashMap::new(),
io_linenos: std::collections::HashMap::new(),
io_syncs: std::collections::HashMap::new(),
struct_counter: 0,
refinement_defs: IndexMap::new(),
active_refinements: Vec::new(),
used_modules: Vec::new(),
skip_refined: None,
class_vars: IndexMap::new(),
class_ivars: IndexMap::new(),
class_object_ids: IndexMap::new(),
attr_accessors: IndexMap::new(),
attr_aliases: IndexMap::new(),
hoisted_hooks: HashMap::new(),
define_methods: IndexMap::new(),
singleton_methods: IndexMap::new(),
object_extends: HashMap::new(),
extended_singletons: HashMap::new(),
singleton_define_methods: IndexMap::new(),
class_define_methods: IndexMap::new(),
obj_ivars: IndexMap::new(),
pack_associates: HashMap::new(),
chilled: Vec::new(),
chilled_symbol_strings: HashMap::new(),
symbol_names: HashMap::new(),
method_aliases: IndexMap::new(),
alias_originals: IndexMap::new(),
module_function_modules: std::collections::HashSet::new(),
class_overrides: IndexMap::new(),
};
let stdout = h.alloc(RObj::IoHandle { id: 0 });
let stderr = h.alloc(RObj::IoHandle { id: 1 });
let stdin = h.alloc(RObj::IoHandle { id: 2 });
h.set_const("STDOUT", stdout.clone());
h.set_const("STDERR", stderr.clone());
h.set_const("STDIN", stdin.clone());
h.set_global("stdout", stdout);
h.set_global("stderr", stderr);
h.set_global("stdin", stdin);
let ver = h.new_string(crate::RUBY_COMPAT_VERSION.to_string());
h.set_const("RUBY_VERSION", ver);
let engine = h.new_string(crate::RUBY_ENGINE.to_string());
h.set_const("RUBY_ENGINE", engine);
let engine_ver = h.new_string(crate::RUBY_ENGINE_VERSION.to_string());
h.set_const("RUBY_ENGINE_VERSION", engine_ver);
let platform = h.new_string(crate::ruby_platform());
h.set_const("RUBY_PLATFORM", platform);
let desc = h.new_string(crate::version_banner());
h.set_const("RUBY_DESCRIPTION", desc);
h.set_const("RUBY_PATCHLEVEL", Value::Int(-1));
h
}
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()
|| matches!(
self.obj(v),
Some(
RObj::Range { .. }
| RObj::FloatRange { .. }
| RObj::StrRange { .. }
| RObj::ObjRange { .. }
| RObj::Rational(_)
| RObj::Complex { .. }
| RObj::BigInt(_)
)
)
|| self.frozen.contains(id)
}
_ => true,
}
}
fn note_hoisted_hooks(&mut self, class: &str, def: &mut ClassDef) {
for hook in ["method_added", "singleton_method_added"] {
if let Some(m) = def.class_methods.shift_remove(hook) {
self.hoisted_hooks
.entry((class.to_string(), hook.to_string()))
.or_default()
.push_back(m);
}
}
}
pub fn activate_hoisted_hook(&mut self, class: &str, name: &str) {
if self.hoisted_hooks.is_empty() {
return;
}
let key = (class.to_string(), name.to_string());
if let Some(m) = self.hoisted_hooks.get_mut(&key).and_then(|q| q.pop_front()) {
self.classes
.entry(class.to_string())
.or_default()
.class_methods
.insert(name.to_string(), m);
}
}
pub fn load_program(
&mut self,
mut methods: Vec<(String, MethodDef)>,
mut classes: Vec<(String, ClassDef)>,
begins: Vec<BeginDef>,
mut procs: Vec<ProcDef>,
) {
let file = Some(Arc::new(SourceFile {
path: current_file_path().unwrap_or_else(|| "-e".into()),
dir: current_file_dir().unwrap_or_default(),
}));
let defs = methods.iter_mut().map(|(_, d)| d).chain(
classes
.iter_mut()
.flat_map(|(_, c)| c.methods.values_mut().chain(c.class_methods.values_mut())),
);
for def in defs {
def.file = file.clone();
}
for p in &mut procs {
p.file = file.clone();
}
for (name, def) in methods {
self.methods.insert(name, def);
}
for (name, mut def) in classes {
self.note_hoisted_hooks(&name, &mut def);
merge_class(&mut self.classes, name, def);
}
self.begins.extend(begins);
self.procs.extend(procs);
}
pub fn program_offsets(&self) -> (usize, usize) {
(self.procs.len(), self.begins.len())
}
pub fn init_load_path(&mut self, dir: &str) {
let mut entries = vec![self.new_string(dir.to_string())];
for gd in gem_lib_dirs() {
entries.push(self.new_string(gd));
}
let load_path = self.new_array(entries);
self.set_global("LOAD_PATH", load_path.clone());
self.set_global(":", load_path);
let features = self.new_array(Vec::new());
self.set_global("LOADED_FEATURES", features.clone());
self.set_global("\"", features);
}
pub fn set_program_args(&mut self, argv: &[String], script_name: &str) {
let items: Vec<Value> = argv.iter().map(|a| self.new_string(a.clone())).collect();
let arr = self.new_array(items);
self.set_const("ARGV", arr.clone());
self.set_global("*", arr);
let name = self.new_string(script_name.to_string());
self.set_global("0", name.clone());
self.set_global("PROGRAM_NAME", name);
}
pub fn prepend_load_path(&mut self, dirs: &[String]) {
if dirs.is_empty() {
return;
}
let lp = self.get_global("LOAD_PATH");
let news: Vec<Value> = dirs.iter().map(|d| self.new_string(d.clone())).collect();
if let Some(RObj::Array(items)) = self.obj_mut(&lp) {
for (i, v) in news.into_iter().enumerate() {
items.insert(i, v);
}
}
}
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 copy_singleton(&mut self, from: &Value, to: &Value) {
let (Value::Obj(src), Value::Obj(dst)) = (from, to) else {
return;
};
let (src, dst) = (*src, *dst);
if let Some(m) = self.singleton_methods.get(&src).cloned() {
self.singleton_methods.insert(dst, m);
}
if let Some(m) = self.singleton_define_methods.get(&src).cloned() {
self.singleton_define_methods.insert(dst, m);
}
if let Some(e) = self.object_extends.get(&src).cloned() {
self.object_extends.insert(dst, e);
}
if let Some(e) = self.extended_singletons.get(&src).cloned() {
self.extended_singletons.insert(dst, e);
}
}
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();
let new = self.alloc(copy);
if let (Value::Obj(src), Value::Obj(dst)) = (v, &new) {
if let Some(iv) = self.obj_ivars.get(src).cloned() {
self.obj_ivars.insert(*dst, iv);
}
if let Some(a) = self.pack_associates.get(src).cloned() {
self.pack_associates.insert(*dst, a);
}
}
if let Value::Obj(oid) = v {
if let Some(cls) = self.class_overrides.get(oid).cloned() {
self.set_class_override(&new, &cls);
}
}
new
}
None => v.clone(),
}
}
pub fn new_string(&mut self, s: String) -> Value {
self.alloc(RObj::Str(RStr::Text(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,
by_identity: false,
})
}
pub fn new_hash_with_default(&mut self, map: IndexMap<RKey, Value>, default: Value) -> Value {
self.alloc(RObj::Hash {
map,
default,
default_proc: None,
by_identity: false,
})
}
pub fn hash_replace(&mut self, dst: &Value, src: &Value) {
let Some(RObj::Hash {
map,
default,
default_proc,
by_identity,
}) = self.obj(src).cloned()
else {
return;
};
if let Some(RObj::Hash {
map: m,
default: d,
default_proc: p,
by_identity: b,
}) = self.obj_mut(dst)
{
(*m, *d, *p, *b) = (map, default, default_proc, by_identity);
}
}
pub fn new_hash_like(
&mut self,
src: &Value,
map: IndexMap<RKey, Value>,
defaults: bool,
) -> Value {
let Some(RObj::Hash {
default,
default_proc,
by_identity,
..
}) = self.obj(src).cloned()
else {
return self.new_hash(map);
};
self.alloc(RObj::Hash {
map,
default: if defaults { default } else { Value::Undef },
default_proc: if defaults { default_proc } else { None },
by_identity,
})
}
pub fn set_hash_default(&mut self, v: &Value, default: Value) {
if let Some(RObj::Hash {
default: d,
default_proc: p,
..
}) = self.obj_mut(v)
{
*d = default;
*p = None;
}
}
pub fn set_hash_default_proc(&mut self, v: &Value, proc: Value) {
if let Some(RObj::Hash {
default: d,
default_proc: p,
..
}) = self.obj_mut(v)
{
*d = Value::Undef;
*p = if matches!(proc, Value::Undef) {
None
} else {
Some(proc)
};
}
}
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),
by_identity: false,
})
}
pub fn set_hash_by_identity(&mut self, v: &Value) {
let Some(RObj::Hash { map, .. }) = self.obj(v).cloned() else {
return;
};
let mut rekeyed = IndexMap::new();
for (k, val) in map {
let key_obj = self.key_to_value(&k);
rekeyed.insert(self.identity_key(&key_obj), val);
}
if let Some(RObj::Hash {
map, by_identity, ..
}) = self.obj_mut(v)
{
*map = rekeyed;
*by_identity = true;
}
}
fn identity_key(&self, v: &Value) -> RKey {
match (v, self.obj(v)) {
(_, Some(RObj::Symbol(_))) => self.to_key(v),
(Value::Obj(i), _) => RKey::Identity(*i),
_ => self.to_key(v),
}
}
pub fn hash_is_by_identity(&self, v: &Value) -> bool {
matches!(
self.obj(v),
Some(RObj::Hash {
by_identity: true,
..
})
)
}
pub fn user_hash_candidate(&self, v: &Value) -> bool {
match self.obj(v) {
Some(RObj::Time(_)) => true,
Some(RObj::Object { class, .. }) if !self.is_struct_class(class) => {
self.find_method_owner(class, "hash").is_some()
|| self.find_define_method(class, "hash").is_some()
}
_ => false,
}
}
pub fn user_keyed_operands(&self, recv: &Value, name: &str, args: &[Value]) -> Vec<Value> {
let elems = |v: &Value| -> Vec<Value> {
match self.obj(v) {
Some(RObj::Array(xs)) => xs.clone(),
_ => Vec::new(),
}
};
let mut out: Vec<Value> = match self.obj(recv) {
Some(RObj::Hash {
by_identity: false, ..
}) => match name {
"[]" | "[]=" | "store" | "key?" | "has_key?" | "include?" | "member?" | "fetch"
| "delete" | "dig" | "assoc" | "fetch_values" | "values_at" => args.to_vec(),
_ => return Vec::new(),
},
Some(RObj::Set(_)) => match name {
"add" | "<<" | "add?" | "include?" | "member?" | "===" | "delete" | "delete?"
| "contain?" => args.to_vec(),
"merge" | "|" | "union" | "+" | "&" | "intersection" | "-" | "difference"
| "subtract" | "^" => args.iter().flat_map(elems).collect(),
_ => return Vec::new(),
},
Some(RObj::Array(xs)) => match name {
"uniq" | "uniq!" | "tally" | "to_set" => xs.clone(),
"-" | "&" | "|" | "difference" | "union" | "intersection" | "intersect?" => {
let mut all = xs.clone();
all.extend(args.iter().flat_map(elems));
all
}
_ => return Vec::new(),
},
Some(RObj::ClassRef(c)) if c == "Set" && matches!(name, "new" | "[]") => {
if name == "new" {
args.iter().flat_map(elems).collect()
} else {
args.to_vec()
}
}
_ => return Vec::new(),
};
out.retain(|v| self.user_hash_candidate(v));
out
}
pub fn user_key_reps(&self, h: i64) -> Vec<u32> {
self.user_key_reps.get(&h).cloned().unwrap_or_default()
}
pub fn set_user_key_canon(&mut self, id: u32, rep: u32, h: i64) {
if id == rep {
let reps = self.user_key_reps.entry(h).or_default();
if !reps.contains(&id) {
reps.push(id);
}
}
self.user_key_canon.insert(id, rep);
}
pub fn hash_key(&self, recv: &Value, v: &Value) -> RKey {
if self.hash_is_by_identity(recv) {
return self.identity_key(v);
}
self.to_key(v)
}
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_set(&mut self, items: Vec<Value>) -> Value {
let mut map = IndexMap::new();
for v in items {
let k = self.value_to_key(&v);
map.entry(k).or_insert(v);
}
self.alloc(RObj::Set(map))
}
pub fn as_set(&self, v: &Value) -> Option<Vec<Value>> {
match self.obj(v) {
Some(RObj::Set(map)) => Some(map.values().cloned().collect()),
_ => None,
}
}
pub fn set_contains(&self, set: &Value, item: &Value) -> bool {
let k = self.value_to_key(item);
matches!(self.obj(set), Some(RObj::Set(map)) if map.contains_key(&k))
}
pub fn set_add(&mut self, set: &Value, item: Value) -> bool {
let k = self.value_to_key(&item);
if let Some(RObj::Set(map)) = self.obj_mut(set) {
if map.contains_key(&k) {
false
} else {
map.insert(k, item);
true
}
} else {
false
}
}
pub fn set_replace(&mut self, set: &Value, items: Vec<Value>) {
let mut fresh = IndexMap::new();
for v in items {
let k = self.value_to_key(&v);
fresh.entry(k).or_insert(v);
}
if let Some(RObj::Set(map)) = self.obj_mut(set) {
*map = fresh;
}
}
pub fn set_remove(&mut self, set: &Value, item: &Value) -> bool {
let k = self.value_to_key(item);
if let Some(RObj::Set(map)) = self.obj_mut(set) {
map.shift_remove(&k).is_some()
} else {
false
}
}
pub fn new_bigint(&mut self, b: num_bigint::BigInt) -> Value {
use num_traits::ToPrimitive;
match b.to_i64() {
Some(n) => Value::Int(n),
None => self.alloc(RObj::BigInt(b)),
}
}
pub fn as_promoted_bigint(&self, v: &Value) -> Option<num_bigint::BigInt> {
match self.obj(v) {
Some(RObj::BigInt(b)) => Some(b.clone()),
_ => None,
}
}
pub fn new_rational(&mut self, r: num_rational::BigRational) -> Value {
self.alloc(RObj::Rational(r))
}
pub fn new_complex(&mut self, re: Value, im: Value) -> Value {
self.alloc(RObj::Complex { re, im })
}
pub fn new_lazy(&mut self, source: Value, ops: Vec<LazyOp>) -> Value {
let origin = source.clone();
self.alloc(RObj::Lazy {
source,
ops,
origin,
})
}
pub fn new_lazy_of(&mut self, source: Value, ops: Vec<LazyOp>, origin: Value) -> Value {
self.alloc(RObj::Lazy {
source,
ops,
origin,
})
}
pub fn lazy_origin(&self, v: &Value) -> Option<Value> {
match self.obj(v) {
Some(RObj::Lazy { origin, .. }) => Some(origin.clone()),
_ => None,
}
}
fn lazy_op_tag(&mut self, op: &LazyOp) -> String {
match op {
LazyOp::Map(_) => "map".to_string(),
LazyOp::Select(_) => "select".to_string(),
LazyOp::Reject(_) => "reject".to_string(),
LazyOp::FilterMap(_) => "filter_map".to_string(),
LazyOp::FlatMap(_) => "flat_map".to_string(),
LazyOp::TakeWhile(_) => "take_while".to_string(),
LazyOp::DropWhile(_) => "drop_while".to_string(),
LazyOp::Take(n) => format!("take({n})"),
LazyOp::Drop(n) => format!("drop({n})"),
LazyOp::Zip(others) => {
let args: Vec<String> = others.iter().map(|xs| self.inspect_array(xs)).collect();
format!("zip({})", args.join(", "))
}
LazyOp::Uniq(_) => "uniq".to_string(),
LazyOp::Compact => "compact".to_string(),
LazyOp::Grep(pat, inverted) => {
let pat = self.inspect(&pat.clone());
format!("{}({pat})", if *inverted { "grep_v" } else { "grep" })
}
LazyOp::WithIndex(n) => match n {
None => "each_with_index".to_string(),
Some(n) => format!("with_index({n})"),
},
LazyOp::WithObject(obj, spelled_each) => {
let obj = self.inspect(&obj.clone());
format!(
"{}({obj})",
if *spelled_each {
"each_with_object"
} else {
"with_object"
}
)
}
LazyOp::EachSlice(n) => format!("each_slice({n})"),
LazyOp::EachCons(n) => format!("each_cons({n})"),
LazyOp::ChunkWhile(_, sliced) => {
if *sliced { "slice_when" } else { "chunk_while" }.to_string()
}
}
}
pub fn lazy_parts(&self, v: &Value) -> Option<(Value, Vec<LazyOp>)> {
match self.obj(v) {
Some(RObj::Lazy { source, ops, .. }) => Some((source.clone(), ops.clone())),
_ => None,
}
}
pub fn new_enumerator(&mut self, buf: Vec<Value>, method: &str) -> Value {
self.alloc(RObj::Enumerator {
buf,
cursor: 0,
method: method.to_string(),
source: None,
})
}
pub fn new_arith_seq(&mut self, seq: ArithSeq) -> Value {
self.alloc(RObj::ArithSeq(Box::new(seq)))
}
pub fn arith_seq_from_parts(
&mut self,
begin: Value,
end: Value,
step: Value,
exclude_end: bool,
) -> Value {
let dots = if exclude_end { "..." } else { ".." };
let e_txt = match end {
Value::Undef => String::new(),
ref v => self.inspect(&v.clone()),
};
let desc = format!(
"(({}{dots}{e_txt}).step({}))",
self.inspect(&begin.clone()),
self.inspect(&step.clone())
);
let vals = Self::arith_seq_values(&begin, &end, &step, exclude_end);
let inner = self.new_enumerator(vals, "each");
self.new_arith_seq(ArithSeq {
desc,
begin,
end,
step,
exclude_end,
inner,
})
}
fn arith_seq_values(begin: &Value, end: &Value, step: &Value, exclude_end: bool) -> Vec<Value> {
let float = matches!(begin, Value::Float(_))
|| matches!(end, Value::Float(_))
|| matches!(step, Value::Float(_));
let num = |v: &Value| match v {
Value::Int(n) => Some(*n as f64),
Value::Float(f) => Some(*f),
_ => None,
};
let (Some(b), Some(e), Some(st)) = (num(begin), num(end), num(step)) else {
return Vec::new();
};
if st <= 0.0 {
return Vec::new();
}
let mut out = Vec::new();
let mut i = 0.0f64;
loop {
let v = b + i * st;
if v > e || (exclude_end && v == e) {
break;
}
out.push(if float {
Value::Float(v)
} else {
Value::Int(v as i64)
});
i += 1.0;
}
out
}
pub fn arith_seq(&self, v: &Value) -> Option<ArithSeq> {
match self.obj(v) {
Some(RObj::ArithSeq(s)) => Some((**s).clone()),
_ => None,
}
}
pub fn new_enum_chain(&mut self, parts: Vec<Value>) -> Value {
self.alloc(RObj::EnumChain(parts))
}
pub fn enum_chain_parts(&self, v: &Value) -> Option<Vec<Value>> {
match self.obj(v) {
Some(RObj::EnumChain(p)) => Some(p.clone()),
_ => None,
}
}
pub fn new_enumerator_of(&mut self, buf: Vec<Value>, method: &str, source: Value) -> Value {
self.alloc(RObj::Enumerator {
buf,
cursor: 0,
method: method.to_string(),
source: Some(source),
})
}
pub fn set_enum_source(&mut self, v: &Value, src: Value) {
if let Some(RObj::Enumerator { source, .. }) = self.obj_mut(v) {
*source = Some(src);
}
}
pub fn set_enum_buf(&mut self, v: &Value, elems: Vec<Value>) {
if let Some(RObj::Enumerator { buf, .. }) = self.obj_mut(v) {
*buf = elems;
}
}
pub fn enum_source(&self, v: &Value) -> Option<Value> {
match self.obj(v) {
Some(RObj::Enumerator { source, .. }) => source.clone(),
_ => None,
}
}
pub fn new_generator(&mut self, block: Value) -> Value {
self.alloc(RObj::Generator {
block,
materialized: None,
ext: None,
size: GenSize::Fixed(Value::Undef),
label: None,
})
}
pub fn set_generator_size(&mut self, v: &Value, s: GenSize) {
if let Some(RObj::Generator { size, .. }) = self.obj_mut(v) {
*size = s;
}
}
pub fn generator_size(&self, v: &Value) -> Option<GenSize> {
match self.obj(v) {
Some(RObj::Generator { size, .. }) => Some(size.clone()),
_ => None,
}
}
pub fn set_generator_label(&mut self, v: &Value, s: String) {
if let Some(RObj::Generator { label, .. }) = self.obj_mut(v) {
*label = Some(s);
}
}
pub fn new_fiber_yielder(&mut self) -> Value {
self.alloc(RObj::FiberYielder)
}
pub fn is_fiber_yielder(&self, v: &Value) -> bool {
matches!(self.obj(v), Some(RObj::FiberYielder))
}
pub fn generator_ext_fiber(&self, v: &Value) -> Option<Value> {
match self.obj(v) {
Some(RObj::Generator { ext: Some(e), .. }) => Some(e.fiber.clone()),
_ => None,
}
}
pub fn generator_ext_start(&mut self, v: &Value, fiber: Value) {
if let Some(RObj::Generator { ext, .. }) = self.obj_mut(v) {
*ext = Some(GenExt {
fiber,
peeked: None,
result: Value::Undef,
});
}
}
pub fn generator_peeked(&self, v: &Value) -> Option<Value> {
match self.obj(v) {
Some(RObj::Generator { ext: Some(e), .. }) => e.peeked.clone(),
_ => None,
}
}
pub fn generator_set_peeked(&mut self, v: &Value, val: Option<Value>) {
if let Some(RObj::Generator { ext: Some(e), .. }) = self.obj_mut(v) {
e.peeked = val;
}
}
pub fn generator_set_result(&mut self, v: &Value, result: Value) {
if let Some(RObj::Generator { ext: Some(e), .. }) = self.obj_mut(v) {
e.result = result;
}
}
pub fn generator_result(&self, v: &Value) -> Value {
match self.obj(v) {
Some(RObj::Generator { ext: Some(e), .. }) => e.result.clone(),
_ => Value::Undef,
}
}
pub fn new_raising_enumerator(&mut self, class: &str, message: &str) -> Value {
let block = self.alloc(RObj::RaiseProc {
class: class.to_string(),
message: message.to_string(),
});
self.new_generator(block)
}
pub fn new_cycle_enumerator(&mut self, buf: Vec<Value>) -> Value {
let block = self.alloc(RObj::CycleProc(buf));
self.new_generator(block)
}
pub fn new_derived_enumerator(&mut self, src_block: Value, kind: Derive) -> Value {
let block = match kind {
Derive::Each => src_block,
kind => self.alloc(RObj::DeriveProc {
src: Box::new(src_block),
kind,
}),
};
self.new_generator(block)
}
pub fn new_endless_range_enumerator(&mut self, lo: i64, kind: Derive) -> Value {
let seq = self.alloc(RObj::SeqProc(lo));
self.new_derived_enumerator(seq, kind)
}
pub fn new_produce_enumerator(&mut self, init: Option<Value>, block: Value) -> Value {
let seq = self.alloc(RObj::ProduceProc { init, block });
self.new_generator(seq)
}
pub fn new_step_enumerator(&mut self, from: Value, by: Value, float: bool) -> Value {
let seq = self.alloc(RObj::StepProc { from, by, float });
self.new_generator(seq)
}
pub fn generator_block(&self, v: &Value) -> Option<Value> {
match self.obj(v) {
Some(RObj::Generator { block, .. }) => Some(block.clone()),
_ => None,
}
}
pub fn generator_unmaterialized(&self, v: &Value) -> bool {
matches!(
self.obj(v),
Some(RObj::Generator {
materialized: None,
..
})
)
}
pub fn new_yielder(&mut self, limit: usize) -> Value {
let sink = self.enum_sinks.len();
self.enum_sinks.push(Vec::new());
self.alloc(RObj::Yielder { sink, limit })
}
pub fn yielder_push(&mut self, v: &Value, val: Value) -> bool {
if let Some(RObj::Yielder { sink, limit }) = self.obj(v).cloned() {
let len = self.enum_sinks.get(sink).map(|s| s.len()).unwrap_or(0);
if len >= limit {
return true;
}
if let Some(s) = self.enum_sinks.get_mut(sink) {
s.push(val);
}
return len + 1 >= limit;
}
false
}
pub fn set_generator_materialized(&mut self, v: &Value, buf: Vec<Value>) {
if let Some(RObj::Generator { materialized, .. }) = self.obj_mut(v) {
*materialized = Some((buf, 0));
}
}
pub fn cycle_proc_len(&self, block: &Value) -> Option<usize> {
match self.obj(block) {
Some(RObj::CycleProc(buf)) => Some(buf.len()),
_ => None,
}
}
pub fn generator_next(&mut self, v: &Value, advance: bool) -> Option<Value> {
let is_cycle = match self.generator_block(v) {
Some(b) => matches!(self.obj(&b), Some(RObj::CycleProc(_))),
None => false,
};
if let Some(RObj::Generator {
materialized: Some((buf, cursor)),
..
}) = self.obj_mut(v)
{
if buf.is_empty() {
return None;
}
if *cursor >= buf.len() {
if is_cycle {
*cursor = 0;
} else {
return None;
}
}
let out = buf[*cursor].clone();
if advance {
*cursor += 1;
}
Some(out)
} else {
None
}
}
pub fn generator_rewind(&mut self, v: &Value) {
if let Value::Obj(id) = v {
self.enum_feeds.remove(id);
}
if let Some(RObj::Generator {
materialized, ext, ..
}) = self.obj_mut(v)
{
if let Some((_, cursor)) = materialized {
*cursor = 0;
}
*ext = None;
}
}
pub fn enum_buf(&self, v: &Value) -> Option<Vec<Value>> {
match self.obj(v) {
Some(RObj::Enumerator { buf, .. }) => Some(buf.clone()),
_ => None,
}
}
pub fn enum_method(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::Enumerator { method, .. }) => Some(method.clone()),
_ => None,
}
}
pub fn enum_next(&mut self, v: &Value, advance: bool) -> Option<Value> {
if let Some(RObj::Enumerator { buf, cursor, .. }) = self.obj_mut(v) {
if *cursor >= buf.len() {
return None;
}
let out = buf[*cursor].clone();
if advance {
*cursor += 1;
}
Some(out)
} else {
None
}
}
pub fn enum_cursor(&self, v: &Value) -> usize {
match self.obj(v) {
Some(RObj::Enumerator { cursor, .. }) => *cursor,
_ => 0,
}
}
pub fn enum_feed(&mut self, v: &Value, value: Value) -> bool {
let Value::Obj(id) = v else { return false };
let slot = &mut self.enum_feeds.entry(*id).or_default().0;
if slot.is_some() {
return false;
}
*slot = Some(value);
true
}
pub fn enum_take_feed(&mut self, v: &Value) -> Option<Value> {
match v {
Value::Obj(id) if !self.enum_feeds.is_empty() => {
self.enum_feeds.get_mut(id).and_then(|f| f.0.take())
}
_ => None,
}
}
pub fn enum_record_feed(&mut self, v: &Value, idx: usize, value: Value) {
if let Value::Obj(id) = v {
let fed = &mut self.enum_feeds.entry(*id).or_default().1;
if fed.len() <= idx {
fed.resize(idx + 1, Value::Undef);
}
fed[idx] = value;
}
}
pub fn enum_fed_values(&self, v: &Value) -> Vec<Value> {
match v {
Value::Obj(id) => self
.enum_feeds
.get(id)
.map(|f| f.1.clone())
.unwrap_or_default(),
_ => Vec::new(),
}
}
pub fn enum_rewind(&mut self, v: &Value) {
if let Some(RObj::Enumerator { cursor, .. }) = self.obj_mut(v) {
*cursor = 0;
}
if let Value::Obj(id) = v {
self.enum_feeds.remove(id);
}
}
pub fn new_rtime(&mut self, t: crate::rtime::RTime) -> Value {
self.alloc(RObj::Time(t))
}
pub fn as_time(&self, v: &Value) -> Option<crate::rtime::RTime> {
match self.obj(v) {
Some(RObj::Time(t)) => Some(t.clone()),
_ => None,
}
}
pub fn set_time_zone(&mut self, v: &Value, zone: crate::rtime::Zone) {
if let Some(RObj::Time(t)) = self.obj_mut(v) {
t.zone = zone;
}
}
pub fn time_secs(&self, v: &Value) -> Option<f64> {
use num_traits::ToPrimitive as _;
match self.obj(v) {
Some(RObj::Time(t)) => t.secs.to_f64(),
_ => None,
}
}
pub fn exact_num(&self, v: &Value) -> Option<num_rational::BigRational> {
match v {
Value::Float(f) => num_rational::BigRational::from_float(*f),
_ => self.as_rational(v),
}
}
pub fn time_fields(&self, secs: f64) -> (i64, i64, i64, i64, i64, i64, i64, i64, f64) {
let whole = secs.floor() as i64;
let subsec = secs - whole as f64;
let days = whole.div_euclid(86_400);
let rem = whole.rem_euclid(86_400);
let (y, m, d) = civil_from_days(days);
let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
let wday = (days.rem_euclid(7) + 4) % 7;
let yday = days - days_from_civil(y, 1, 1) + 1;
(y, m, d, hh, mm, ss, wday, yday, subsec)
}
pub fn new_date(&mut self, days: i64) -> Value {
self.alloc(RObj::Date { days })
}
pub fn date_days(&self, v: &Value) -> Option<i64> {
match self.obj(v) {
Some(RObj::Date { days }) => Some(*days),
_ => None,
}
}
pub fn date_to_s(&self, days: i64) -> String {
let (y, m, d) = civil_from_days(days);
format!("{y:04}-{m:02}-{d:02}")
}
pub fn date_inspect(&self, days: i64) -> String {
format!(
"#<Date: {} (({}j,0s,0n),+0s,2299161j)>",
self.date_to_s(days),
days + UNIX_EPOCH_JDN
)
}
pub fn new_datetime(&mut self, secs: f64) -> Value {
self.alloc(RObj::DateTime { secs })
}
pub fn datetime_secs(&self, v: &Value) -> Option<f64> {
match self.obj(v) {
Some(RObj::DateTime { secs }) => Some(*secs),
_ => None,
}
}
pub fn datetime_to_s(&self, secs: f64) -> String {
let (y, mo, d, hh, mi, ss, _, _, _) = self.time_fields(secs);
format!("{y:04}-{mo:02}-{d:02}T{hh:02}:{mi:02}:{ss:02}+00:00")
}
pub fn datetime_inspect(&self, secs: f64) -> String {
let (_, _, _, hh, mi, ss, _, _, frac) = self.time_fields(secs);
let day = (secs / 86_400.0).floor() as i64;
let sod = hh * 3600 + mi * 60 + ss;
let nsec = (frac * 1e9).round() as i64;
format!(
"#<DateTime: {} (({}j,{}s,{}n),+0s,2299161j)>",
self.datetime_to_s(secs),
day + UNIX_EPOCH_JDN,
sod,
nsec
)
}
pub fn complex_parts(&self, v: &Value) -> Option<(Value, Value)> {
match self.obj(v) {
Some(RObj::Complex { re, im }) => Some((re.clone(), im.clone())),
_ => None,
}
}
pub fn complex_to_s(&mut self, re: &Value, im: &Value) -> String {
let re_s = self.to_s(re);
let im_s = self.to_s(im);
let sign = if im_s.starts_with('-') { "-" } else { "+" };
format!("{re_s}{sign}{}i", im_s.trim_start_matches('-'))
}
pub fn as_f64(&self, v: &Value) -> Option<f64> {
use num_traits::ToPrimitive as _;
match v {
Value::Int(n) => Some(*n as f64),
Value::Float(f) => Some(*f),
Value::Obj(_) => match self.obj(v) {
Some(RObj::BigInt(b)) => b.to_f64(),
Some(RObj::Rational(r)) => r.to_f64(),
_ => None,
},
_ => None,
}
}
pub fn as_rational(&self, v: &Value) -> Option<num_rational::BigRational> {
match self.obj(v) {
Some(RObj::Rational(r)) => Some(r.clone()),
_ => self.as_bigint(v).map(num_rational::BigRational::from),
}
}
pub fn as_bigint(&self, v: &Value) -> Option<num_bigint::BigInt> {
match v {
Value::Int(n) => Some(num_bigint::BigInt::from(*n)),
Value::Obj(_) => match self.obj(v) {
Some(RObj::BigInt(b)) => Some(b.clone()),
_ => None,
},
_ => 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 new_obj_range(&mut self, lo: Value, hi: Value, exclusive: bool) -> Value {
self.alloc(RObj::ObjRange { lo, hi, exclusive })
}
pub fn new_float_range(&mut self, lo: f64, hi: f64, exclusive: bool) -> Value {
self.alloc(RObj::FloatRange { lo, hi, exclusive })
}
pub fn as_float_range(&self, v: &Value) -> Option<(f64, f64, bool)> {
match self.obj(v) {
Some(RObj::FloatRange { lo, hi, exclusive }) => Some((*lo, *hi, *exclusive)),
_ => None,
}
}
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 as_obj_range(&self, v: &Value) -> Option<(Value, Value, bool)> {
match self.obj(v) {
Some(RObj::ObjRange { lo, hi, exclusive }) => {
Some((lo.clone(), hi.clone(), *exclusive))
}
_ => None,
}
}
pub fn new_regex(&mut self, source: &str, flags: &str) -> Result<Value, String> {
if flags.contains('n') {
self.binary_regexps = true;
}
let mut inline = String::from("m");
if flags.contains('i') {
inline.push('i');
}
if flags.contains('m') {
inline.push('s'); }
if flags.contains('x') {
inline.push('x');
}
match compiled_regex(source, flags, &inline) {
Ok(re) => Ok(self.alloc(RObj::Regexp {
source: source.to_string(),
re,
flags: flags.chars().filter(|c| "imxun".contains(*c)).collect(),
})),
Err(e) => Err(e),
}
}
#[allow(clippy::type_complexity)]
pub fn as_matchdata(
&self,
v: &Value,
) -> Option<(Vec<Option<String>>, Vec<(String, usize)>, String, String)> {
match self.obj(v) {
Some(RObj::MatchData {
groups,
names,
pre,
post,
..
}) => Some((groups.clone(), names.clone(), pre.clone(), post.clone())),
_ => None,
}
}
pub fn matchdata_offsets(&self, v: &Value) -> Option<Vec<Option<(usize, usize)>>> {
match self.obj(v) {
Some(RObj::MatchData { offsets, .. }) => Some(offsets.clone()),
_ => None,
}
}
pub fn matchdata_regexp(&self, v: &Value) -> Option<Value> {
match self.obj(v) {
Some(RObj::MatchData { regexp, .. }) => Some(regexp.clone()),
_ => None,
}
}
pub fn set_matchdata_regexp(&mut self, v: &Value, re: Value) {
if let Some(RObj::MatchData { regexp, .. }) = self.obj_mut(v) {
*regexp = re;
}
}
pub fn as_regex(&self, v: &Value) -> Option<(std::sync::Arc<fancy_regex::Regex>, String)> {
match self.obj(v) {
Some(RObj::Regexp { re, source, .. }) => Some((re.clone(), source.clone())),
_ => None,
}
}
pub fn regex_flags(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::Regexp { flags, .. }) => Some(flags.clone()),
_ => None,
}
}
#[allow(clippy::too_many_arguments)]
pub fn new_matchdata(
&mut self,
groups: Vec<Option<String>>,
names: Vec<(String, usize)>,
offsets: Vec<Option<(usize, usize)>>,
pre: String,
post: String,
regexp: Value,
) -> Value {
self.alloc(RObj::MatchData {
groups,
names,
offsets,
pre,
post,
regexp,
subject: None,
})
}
pub fn new_string_matchdata_bytes(
&mut self,
subject: &[u8],
(beg, end): (usize, usize),
pattern: Value,
) -> Value {
let lossy = |b: &[u8]| String::from_utf8_lossy(b).into_owned();
self.alloc(RObj::MatchData {
groups: vec![Some(lossy(&subject[beg..end]))],
names: Vec::new(),
offsets: vec![Some((beg, end))],
pre: lossy(&subject[..beg]),
post: lossy(&subject[end..]),
regexp: pattern,
subject: Some(subject.to_vec()),
})
}
pub fn matchdata_text(&mut self, v: &Value, part: MatchPart) -> Option<Value> {
let Some(RObj::MatchData {
groups,
offsets,
pre,
post,
subject,
..
}) = self.obj(v)
else {
return None;
};
let bytes = match subject {
Some(b) => {
let (beg, end) = offsets.first().copied().flatten().unwrap_or((0, 0));
match part {
MatchPart::Pre => b[..beg].to_vec(),
MatchPart::Post => b[end..].to_vec(),
MatchPart::Subject => b.clone(),
}
}
None => match part {
MatchPart::Pre => pre.clone().into_bytes(),
MatchPart::Post => post.clone().into_bytes(),
MatchPart::Subject => {
let whole = groups.first().cloned().flatten().unwrap_or_default();
format!("{pre}{whole}{post}").into_bytes()
}
},
};
Some(self.new_utf8_from_bytes(bytes))
}
pub fn regex_site(&self, site: i64) -> Option<Value> {
self.regex_sites.get(&site).cloned()
}
pub fn set_regex_site(&mut self, site: i64, re: Value) {
self.regex_sites.insert(site, re);
}
pub fn matchdata_subject(&self, v: &Value) -> Option<Vec<u8>> {
match self.obj(v) {
Some(RObj::MatchData { subject, .. }) => subject.clone(),
_ => None,
}
}
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,
home: None,
})
}
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,
home: None,
})
}
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,
is_lambda,
..
}) => match kind {
ProcKind::Curried { .. }
| ProcKind::MethodCurried { .. }
| ProcKind::Composed { .. } => Some(-1),
ProcKind::Collect(_) | ProcKind::Around(_) => Some(1),
ProcKind::SetsMatch { inner, .. } => self.proc_arity(inner),
ProcKind::Normal => Some(
ArityFacts::of_block(
&self.procs[*template].arity,
self.procs[*template].splat.is_some(),
)
.arity_value(*is_lambda),
),
},
Some(RObj::SymProc(_)) => Some(-2),
Some(RObj::Method {
recv,
name,
unbound,
..
}) => Some(self.method_arity(recv, name, *unbound)),
_ => None,
}
}
pub fn proc_min_max(&self, v: &Value) -> Option<(i64, Option<i64>)> {
match self.obj(v) {
Some(RObj::Proc {
kind: ProcKind::Normal,
template,
..
}) => {
let def = &self.procs[*template];
Some(ArityFacts::of_block(&def.arity, def.splat.is_some()).min_max())
}
_ => None,
}
}
pub fn proc_curry(&mut self, v: &Value, requested: Option<usize>) -> Option<Value> {
match self.obj(v).cloned() {
Some(RObj::Proc {
template,
scope,
is_lambda,
kind,
home,
}) => {
let arity = match kind {
ProcKind::Curried { arity, .. } => arity,
ProcKind::MethodCurried { .. }
| ProcKind::Composed { .. }
| ProcKind::Collect(_)
| ProcKind::Around(_)
| ProcKind::SetsMatch { .. } => return Some(v.clone()),
ProcKind::Normal => match requested {
Some(n) => n,
None => self.proc_min_max(v).map_or(0, |(min, _)| min as usize),
},
};
Some(self.alloc(RObj::Proc {
template,
scope,
is_lambda,
kind: ProcKind::Curried {
arity,
collected: Vec::new(),
},
home,
}))
}
_ => None,
}
}
pub fn new_method_curry(&mut self, target: Value, arity: usize) -> Value {
let scope = self.cur_scope().clone();
self.alloc(RObj::Proc {
template: 0,
scope,
is_lambda: true,
kind: ProcKind::MethodCurried {
target: Box::new(target),
arity,
collected: Vec::new(),
},
home: 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),
},
home: None,
})
}
pub fn new_symbol(&mut self, name: &str) -> Value {
self.intern(name)
}
pub fn mark_multi_yield(&mut self, v: &Value) {
if let Value::Obj(id) = v {
self.multi_yield_packs.insert(*id);
}
}
pub fn is_multi_yield(&self, v: &Value) -> bool {
matches!(v, Value::Obj(id) if self.multi_yield_packs.contains(id))
}
pub fn mark_kwargs(&mut self, v: &Value) {
if let Value::Obj(id) = v {
self.kwargs_hashes.insert(*id);
}
}
pub fn mark_initialized_exception(&mut self, v: &Value) {
if let Value::Obj(id) = v {
self.initialized_exceptions.insert(*id);
}
}
pub fn is_initialized_exception(&self, v: &Value) -> bool {
matches!(v, Value::Obj(id) if self.initialized_exceptions.contains(id))
}
pub fn hash_iter_step(&mut self, v: &Value, delta: i32) {
let Value::Obj(id) = v else {
return;
};
let lev = self.hash_iter_lev.entry(*id).or_insert(0);
*lev = lev.saturating_add_signed(delta);
if *lev == 0 {
self.hash_iter_lev.remove(id);
}
}
pub fn hash_iterating(&self, v: &Value) -> bool {
matches!(v, Value::Obj(id) if self.hash_iter_lev.contains_key(id))
}
pub fn is_kwargs(&self, v: &Value) -> bool {
matches!(v, Value::Obj(id) if self.kwargs_hashes.contains(id))
}
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),
home: None,
})
}
pub fn new_match_setting_block(&mut self, block: Value, matches: Vec<Value>) -> Value {
let is_lambda = matches!(
self.obj(&block),
Some(RObj::Proc {
is_lambda: true,
..
})
);
let scope = self.cur_scope().clone();
self.alloc(RObj::Proc {
template: 0,
scope,
is_lambda,
kind: ProcKind::SetsMatch {
inner: Box::new(block),
matches,
next: 0,
},
home: None,
})
}
pub fn set_enum_matches(&mut self, e: &Value, matches: Vec<Value>) {
if let Value::Obj(id) = e {
self.enum_matches.insert(*id, matches);
}
}
pub fn enum_matches(&self, e: &Value) -> Option<Vec<Value>> {
match e {
Value::Obj(id) if !self.enum_matches.is_empty() => self.enum_matches.get(id).cloned(),
_ => None,
}
}
pub fn take_enum_sink(&mut self) -> Vec<Value> {
self.enum_sinks.pop().unwrap_or_default()
}
#[allow(clippy::too_many_arguments)]
fn push_around(
&mut self,
handlers: Vec<String>,
def: MethodDef,
self_obj: Value,
args: Vec<Value>,
block: Option<Value>,
method_name: Option<String>,
def_class: Option<String>,
) -> usize {
let idx = self.around_stack.len();
self.around_stack.push(AroundCall {
handlers,
def,
self_obj,
args,
block,
method_name,
def_class,
});
idx
}
fn around_call(&self, idx: usize) -> AroundCall {
self.around_stack[idx].clone()
}
fn around_len(&self) -> usize {
self.around_stack.len()
}
fn truncate_around(&mut self, n: usize) {
self.around_stack.truncate(n);
}
fn new_around_block(&mut self, idx: usize) -> Value {
let scope = self.cur_scope().clone();
self.alloc(RObj::Proc {
template: 0,
scope,
is_lambda: false,
kind: ProcKind::Around(idx),
home: None,
})
}
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(),
unbound: false,
via: None,
})
}
pub fn new_method_via(&mut self, recv: Value, name: &str, via: Option<String>) -> Value {
self.alloc(RObj::Method {
recv,
name: name.to_string(),
unbound: false,
via,
})
}
pub fn method_via(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::Method { via, .. }) => via.clone(),
_ => None,
}
}
pub fn new_unbound_method(&mut self, owner: Value, name: &str) -> Value {
let snapshot = self
.classref_name(&owner)
.and_then(|c| self.find_method_owner(&c, name));
let m = self.alloc(RObj::Method {
recv: owner,
name: name.to_string(),
unbound: true,
via: None,
});
if let (Some(s), Value::Obj(id)) = (snapshot, &m) {
self.method_snapshots.insert(*id, s);
}
m
}
pub fn method_snapshot(&self, m: &Value) -> Option<(MethodDef, String)> {
match m {
Value::Obj(id) if !self.method_snapshots.is_empty() => {
self.method_snapshots.get(id).cloned()
}
_ => None,
}
}
pub fn copy_method_snapshot(&mut self, from: &Value, to: &Value) {
if let (Some(s), Value::Obj(id)) = (self.method_snapshot(from), to) {
self.method_snapshots.insert(*id, s);
}
}
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 is_unbound_method(&self, v: &Value) -> bool {
matches!(self.obj(v), Some(RObj::Method { unbound: true, .. }))
}
pub fn class_or_module_word(&self, name: &str) -> &'static str {
if self.is_module_name(name) {
"module"
} else {
"class"
}
}
pub fn method_lookup_class(&self, recv: &Value, unbound: bool) -> String {
match self.classref_name(recv) {
Some(cls) if unbound => cls,
Some(cls) if self.is_module_name(&cls) && !self.has_singleton_class(recv, &cls) => {
"Module".to_string()
}
Some(cls) => format!("#<Class:{cls}>"),
None => self.class_of(recv),
}
}
pub fn has_singleton_class(&self, recv: &Value, cls: &str) -> bool {
if let Some(def) = self.classes.get(cls) {
if !def.class_methods.is_empty() || !def.extends.is_empty() {
return true;
}
}
if self
.class_define_methods
.get(cls)
.is_some_and(|m| !m.is_empty())
{
return true;
}
if let Value::Obj(id) = recv {
if self
.singleton_methods
.get(id)
.is_some_and(|m| !m.is_empty())
|| self
.singleton_define_methods
.get(id)
.is_some_and(|m| !m.is_empty())
{
return true;
}
}
self.classes.contains_key(&format!("#<Class:{cls}>"))
}
pub fn method_defined_on(&self, recv: &Value, name: &str, unbound: bool) -> bool {
if !unbound
&& (self.find_singleton_method(recv, name).is_some()
|| self.find_singleton_define_method(recv, name).is_some())
{
return true;
}
match self.resolve_method_shape(recv, name, unbound) {
Some(_) if !unbound && self.classref_name(recv).is_some() => {
let cls = self.classref_name(recv).unwrap_or_default();
if self.find_class_method_owner(&cls, name).is_some()
|| self.methods.contains_key(name)
|| self.find_method_owner("Object", name).is_some()
|| self
.singleton_lookup_chain(&cls)
.iter()
.any(|o| crate::arity_table::lookup(o, name).is_some())
{
return true;
}
}
Some(_) => return true,
None => {}
}
if !unbound {
if let Some(cls) = self.classref_name(recv) {
let generated: &[&str] = if self.is_data_class(&cls) {
&["[]", "new", "members"]
} else {
&["[]", "members", "keyword_init?"]
};
if self.struct_def(&cls).is_some() && generated.contains(&name) {
return true;
}
}
}
let mut chain: Vec<String> = Vec::new();
if let Some(cls) = self.classref_name(recv) {
chain.push(if unbound {
cls
} else {
format!("#<Class:{cls}>")
});
} else {
chain.push(self.class_of(recv));
}
chain.iter().any(|cls| {
self.find_method_owner(cls, name).is_some()
|| self.find_define_method(cls, name).is_some()
|| self.attr_access(cls, name).is_some()
|| self.find_alias(cls, name).is_some()
|| self.native_kernel_alias(cls, name).is_some()
|| self.struct_def(cls).is_some_and(|(members, _)| {
let member = name.strip_suffix('=').unwrap_or(name);
members.iter().any(|m| m == member)
|| matches!(name, "deconstruct" | "deconstruct_keys")
})
})
}
pub fn resolve_method_shape(
&self,
recv: &Value,
name: &str,
unbound: bool,
) -> Option<MethodShape> {
if let (false, Value::Obj(id), Some(def)) =
(unbound, recv, self.find_singleton_method(recv, name))
{
let owner = if self.is_extended_singleton(*id, name) {
self.object_extends
.get(id)
.and_then(|mods| {
mods.iter().find(|m| {
self.classes
.get(*m)
.is_some_and(|d| d.methods.contains_key(name))
})
})
.cloned()
} else {
self.singleton_class_name(recv)
};
if let Some(owner) = owner {
return Some(MethodShape::Def {
def: Box::new(def),
owner,
});
}
}
if let (false, Some(p)) = (unbound, self.find_singleton_define_method(recv, name)) {
if let (
Some(RObj::Proc {
template,
kind: ProcKind::Normal,
..
}),
Some(owner),
) = (self.obj(&p), self.singleton_class_name(recv))
{
return Some(MethodShape::Block {
template: *template,
owner,
});
}
}
if let Some(cls) = self.object_class(recv) {
if let Some((def, owner)) = self.find_method_owner(&cls, name) {
return Some(MethodShape::Def {
def: Box::new(def),
owner,
});
}
} else if let Some(cls) = self.classref_name(recv) {
if unbound {
if let Some((def, owner)) = self.find_method_owner(&cls, name) {
return Some(MethodShape::Def {
def: Box::new(def),
owner,
});
}
} else if let Some((def, owner)) = self.find_class_method_owner(&cls, name) {
let owner = if self
.classes
.get(&owner)
.is_some_and(|d| d.class_methods.contains_key(name))
{
format!("#<Class:{owner}>")
} else {
owner
};
return Some(MethodShape::Def {
def: Box::new(def),
owner,
});
}
if let Some((def, owner)) = self.find_method_owner(&cls, name) {
return Some(MethodShape::Def {
def: Box::new(def),
owner,
});
}
}
if let Some(def) = self.methods.get(name) {
return Some(MethodShape::Def {
def: Box::new(def.clone()),
owner: "Object".to_string(),
});
}
if let Some(cls) = self.object_class(recv).or_else(|| self.classref_name(recv)) {
if let Some(owner) = self.class_ancestry(&cls).into_iter().find(|c| {
self.define_methods
.get(c)
.is_some_and(|m| m.contains_key(name))
}) {
let p = self.define_methods[&owner][name].clone();
if let Some(RObj::Proc {
template,
kind: ProcKind::Normal,
..
}) = self.obj(&p)
{
return Some(MethodShape::Block {
template: *template,
owner,
});
}
if let Some(RObj::Method {
recv: target,
name: target_name,
unbound: target_unbound,
..
}) = self.obj(&p)
{
let shape = self.resolve_method_shape(target, target_name, *target_unbound);
return match shape {
Some(MethodShape::Def { def, .. }) => Some(MethodShape::Def { def, owner }),
Some(MethodShape::Block { template, .. }) => {
Some(MethodShape::Block { template, owner })
}
other => other,
};
}
}
}
self.builtin_shape(recv, name, unbound)
}
pub fn builtin_owner(&self, recv: &Value, name: &str) -> Option<&'static str> {
self.builtin_chain_cached(recv, false)
.iter()
.find_map(|owner| crate::arity_table::lookup(owner, name).map(|(owner, _, _)| owner))
}
fn builtin_shape(&self, recv: &Value, name: &str, unbound: bool) -> Option<MethodShape> {
let chain = self.builtin_chain_cached(recv, unbound);
chain.iter().find_map(|owner| {
crate::arity_table::lookup(owner, name).map(|(owner, arity, params)| {
MethodShape::Builtin {
owner,
arity,
params,
}
})
})
}
fn classes_mut(&mut self) -> &mut IndexMap<String, ClassDef> {
self.class_gen += 1;
&mut self.classes
}
fn builtin_chain_cached(&self, recv: &Value, unbound: bool) -> Arc<Vec<String>> {
if let (false, Value::Obj(id)) = (unbound, recv) {
if self.object_extends.get(id).is_some_and(|e| !e.is_empty()) {
return Arc::new(self.builtin_chain(recv, unbound));
}
}
let key = match self.classref_name(recv) {
Some(cls) => (format!("c\u{1}{cls}"), unbound),
None => (self.dispatch_class(recv), unbound),
};
{
let cache = self.ancestry_cache.borrow();
if cache.gen == self.class_gen {
if let Some(hit) = cache.chains.get(&key) {
return hit.clone();
}
}
}
let chain = Arc::new(self.builtin_chain(recv, unbound));
let mut cache = self.ancestry_cache.borrow_mut();
if cache.gen != self.class_gen {
cache.chains.clear();
cache.gen = self.class_gen;
}
cache.chains.insert(key, chain.clone());
chain
}
fn builtin_chain(&self, recv: &Value, unbound: bool) -> Vec<String> {
match self.classref_name(recv) {
Some(cls) if unbound => self.expanded_ancestry(&cls),
Some(cls) => {
let mut c = self.singleton_lookup_chain(&cls);
c.extend(self.expanded_ancestry(&cls));
c
}
None => {
let mut out = Vec::new();
if let Value::Obj(id) = recv {
for m in self.object_extends.get(id).into_iter().flatten() {
match crate::arity_table::ancestry(m) {
Some(chain) => out.extend(chain.iter().map(|s| s.to_string())),
None => out.push(m.clone()),
}
}
}
out.extend(self.expanded_ancestry(&self.dispatch_class(recv)));
dedup_keep_first(out)
}
}
}
pub fn expanded_ancestry(&self, class: &str) -> Vec<String> {
let mut out = Vec::new();
for a in self.class_ancestry(class) {
match crate::arity_table::ancestry(&a) {
Some(chain) => out.extend(chain.iter().map(|s| s.to_string())),
None => out.push(a),
}
}
dedup_keep_first(out)
}
fn singleton_lookup_chain(&self, class: &str) -> Vec<String> {
let mut out = vec![format!("#<Class:{class}>")];
if !self.is_module_name(class) {
out.extend(
self.expanded_ancestry(class)
.into_iter()
.skip(1)
.filter(|a| !self.is_module_name(a))
.map(|a| format!("#<Class:{a}>")),
);
out.push("Class".to_string());
}
out.extend(["Module", "Object", "Kernel", "BasicObject"].map(String::from));
out
}
pub fn method_owner(&self, recv: &Value, name: &str, unbound: bool) -> String {
match self.resolve_method_shape(recv, name, unbound) {
Some(MethodShape::Def { owner, .. }) | Some(MethodShape::Block { owner, .. }) => owner,
Some(MethodShape::Builtin { owner, .. }) => owner.to_string(),
None if !unbound && !self.singleton_method_names(recv, true).is_empty() => self
.singleton_class_name(recv)
.unwrap_or_else(|| self.dispatch_class(recv)),
None => self
.runtime_attr_owner(recv, name, unbound)
.unwrap_or_else(|| {
self.classref_name(recv)
.map(|c| format!("#<Class:{c}>"))
.unwrap_or_else(|| self.dispatch_class(recv))
}),
}
}
fn runtime_attr_owner(&self, recv: &Value, name: &str, unbound: bool) -> Option<String> {
let class = match self.object_class(recv) {
Some(c) => c,
None if unbound => self.classref_name(recv)?,
None => return None,
};
let (field, writer) = match name.strip_suffix('=') {
Some(f) => (f, true),
None => (name, false),
};
self.class_ancestry(&class).into_iter().find(|c| {
self.attr_accessors
.get(c)
.and_then(|m| m.get(field))
.is_some_and(|(r, w)| if writer { *w } else { *r })
})
}
pub fn method_parameters(
&self,
recv: &Value,
name: &str,
unbound: bool,
) -> Vec<(&'static str, Option<String>)> {
match self.resolve_method_shape(recv, name, unbound) {
Some(MethodShape::Def { def, .. }) => written_params(
&def.params,
def.positional_shape(),
&def.kwparams,
&def.kwreq,
def.kwsplat.as_deref(),
def.blockparam.as_deref(),
),
Some(MethodShape::Block { template, .. }) => {
let p = &self.procs[template];
let positional = match p.params.last().map(String::as_str) {
Some("__blockkw") => &p.params[..p.params.len() - 1],
_ => &p.params[..],
};
written_params(
positional,
PositionalShape {
splat: p.splat,
opt: p.arity.opt as usize,
post: 0,
},
&p.arity.kwnames,
&p.arity.kwreq,
p.arity.kwsplat.as_deref(),
p.arity.blockparam.as_deref(),
)
}
Some(MethodShape::Builtin { arity, params, .. }) => {
crate::arity_table::params_for(arity, params)
}
None => Vec::new(),
}
}
pub fn method_original_name(&self, recv: &Value, name: &str, unbound: bool) -> String {
let owner = self.method_owner(recv, name, unbound);
let mut current = name.to_string();
for _ in 0..64 {
match self.alias_original(&owner, ¤t) {
Some(orig) if orig != current => current = orig,
_ => break,
}
}
current
}
pub fn method_inspect(&mut self, recv: &Value, name: &str, unbound: bool) -> String {
let tag = if unbound { "UnboundMethod" } else { "Method" };
let owner = self.method_owner(recv, name, unbound);
let mut out = format!("#<{tag}: ");
let mut sharp = "#";
if unbound {
out.push_str(&owner);
} else if let Some(cls) = self.classref_name(recv) {
let singleton = format!("#<Class:{cls}>");
if owner == singleton {
out.push_str(&cls);
sharp = ".";
} else if let Some(attached) = RubyHost::metaclass_attached(&owner) {
out.push_str(&format!("{cls}({attached})"));
sharp = ".";
} else {
out.push_str(&singleton);
out.push_str(&format!("({owner})"));
}
} else if self.singleton_class_name(recv).as_deref() == Some(owner.as_str()) {
let shown = self.inspect(recv);
out.push_str(&shown);
sharp = ".";
} else {
let mklass = self.class_of(recv).to_string();
out.push_str(&mklass);
if owner != mklass {
out.push_str(&format!("({owner})"));
}
}
out.push_str(sharp);
out.push_str(name);
let original = self.method_original_name(recv, name, unbound);
if original != name {
out.push_str(&format!("({original})"));
}
out.push('(');
out.push_str(&method_params_signature(
&self.method_parameters(recv, name, unbound),
));
out.push(')');
if let Some((file, line)) = self.method_source_location(recv, name, unbound) {
out.push_str(&format!(" {file}:{line}"));
}
out.push('>');
out
}
pub fn method_source_location(
&self,
recv: &Value,
name: &str,
unbound: bool,
) -> Option<(String, u32)> {
match self.resolve_method_shape(recv, name, unbound)? {
MethodShape::Def { def, .. } => {
let file = def.file.as_ref()?;
Some((file.path.clone(), def.line))
}
MethodShape::Block { template, .. } => self.template_source_location(template),
_ => None,
}
}
pub fn proc_source_location(&self, v: &Value) -> Option<(String, u32)> {
match self.obj(v)? {
RObj::Proc {
template,
kind: ProcKind::Normal,
..
} => self.template_source_location(*template),
RObj::Proc {
kind: ProcKind::SetsMatch { inner, .. },
..
} => self.proc_source_location(inner),
_ => None,
}
}
fn template_source_location(&self, template: usize) -> Option<(String, u32)> {
let def = self.procs.get(template)?;
let file = def.file.as_ref()?;
(def.line > 0).then(|| (file.path.clone(), def.line))
}
pub fn proc_parameters(
&self,
v: &Value,
lambda: Option<bool>,
) -> Vec<(&'static str, Option<String>)> {
match self.obj(v) {
Some(RObj::Proc {
template,
is_lambda,
kind,
..
}) => {
if matches!(
kind,
ProcKind::Curried { .. }
| ProcKind::MethodCurried { .. }
| ProcKind::Composed { .. }
) {
return vec![("rest", None)];
}
let p = &self.procs[*template];
let positional = match p.params.last().map(String::as_str) {
Some("__blockkw") => &p.params[..p.params.len() - 1],
_ => &p.params[..],
};
let mut out = written_params(
positional,
PositionalShape {
splat: p.splat,
opt: p.arity.opt as usize,
post: 0,
},
&p.arity.kwnames,
&p.arity.kwreq,
p.arity.kwsplat.as_deref(),
p.arity.blockparam.as_deref(),
);
if !lambda.unwrap_or(*is_lambda) {
for e in out.iter_mut() {
if e.0 == "req" {
e.0 = "opt";
}
}
}
out
}
Some(RObj::SymProc(_)) => vec![("req", None), ("rest", None)],
Some(RObj::Method {
recv,
name,
unbound,
..
}) => self.method_parameters(recv, name, *unbound),
_ => Vec::new(),
}
}
pub fn method_arity(&self, recv: &Value, name: &str, unbound: bool) -> i64 {
match self.resolve_method_shape(recv, name, unbound) {
Some(MethodShape::Def { def, .. }) => ArityFacts::of_method(&def).arity_value(true),
Some(MethodShape::Block { template, .. }) => ArityFacts::of_block(
&self.procs[template].arity,
self.procs[template].splat.is_some(),
)
.arity_value(true),
Some(MethodShape::Builtin { arity, .. }) => arity as i64,
None => -1,
}
}
pub fn method_min_max(&self, recv: &Value, name: &str, unbound: bool) -> (i64, Option<i64>) {
match self.resolve_method_shape(recv, name, unbound) {
Some(MethodShape::Def { def, .. }) => ArityFacts::of_method(&def).min_max(),
Some(MethodShape::Block { template, .. }) => ArityFacts::of_block(
&self.procs[template].arity,
self.procs[template].splat.is_some(),
)
.min_max(),
Some(MethodShape::Builtin { arity, .. }) if arity >= 0 => {
(arity as i64, Some(arity as i64))
}
Some(MethodShape::Builtin { arity, .. }) => (-(arity as i64) - 1, None),
None => (0, None),
}
}
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 array_push(&mut self, v: &Value, items: &[Value]) -> Option<()> {
match self.obj_mut(v) {
Some(RObj::Array(xs)) => {
xs.extend_from_slice(items);
Some(())
}
_ => None,
}
}
pub fn hash_at(&self, v: &Value, k: &RKey) -> Option<Option<Value>> {
match self.obj(v) {
Some(RObj::Hash { map, .. }) => Some(map.get(k).cloned()),
_ => None,
}
}
pub fn hash_has_key(&self, v: &Value, k: &RKey) -> Option<bool> {
match self.obj(v) {
Some(RObj::Hash { map, .. }) => Some(map.contains_key(k)),
_ => None,
}
}
pub fn hash_len(&self, v: &Value) -> Option<usize> {
match self.obj(v) {
Some(RObj::Hash { map, .. }) => Some(map.len()),
_ => None,
}
}
pub fn hash_insert(&mut self, v: &Value, k: RKey, val: Value) -> Option<()> {
match self.obj_mut(v) {
Some(RObj::Hash { map, .. }) => {
map.insert(k, val);
Some(())
}
_ => None,
}
}
pub fn hash_remove(&mut self, v: &Value, k: &RKey) -> Option<Option<Value>> {
match self.obj_mut(v) {
Some(RObj::Hash { map, .. }) => Some(map.shift_remove(k)),
_ => None,
}
}
pub fn array_len(&self, v: &Value) -> Option<usize> {
match self.obj(v) {
Some(RObj::Array(xs)) => Some(xs.len()),
_ => None,
}
}
pub fn array_set(&mut self, v: &Value, i: usize, val: Value) -> Option<()> {
match self.obj_mut(v) {
Some(RObj::Array(xs)) if i < xs.len() => {
xs[i] = val;
Some(())
}
_ => None,
}
}
pub fn array_at(&self, v: &Value, i: usize) -> Option<Option<Value>> {
match self.obj(v) {
Some(RObj::Array(xs)) => Some(xs.get(i).cloned()),
_ => None,
}
}
pub fn str_ref<'a>(&'a self, v: &'a Value) -> Option<Cow<'a, str>> {
match self.obj(v) {
Some(RObj::Str(s)) => Some(s.view()),
_ => match v {
Value::Str(s) => Some(Cow::Borrowed(s)),
_ => None,
},
}
}
pub fn rstr(&self, v: &Value) -> Option<&RStr> {
match self.obj(v) {
Some(RObj::Str(s)) => Some(s),
_ => None,
}
}
pub fn rstr_mut(&mut self, v: &Value) -> Option<&mut RStr> {
match self.obj_mut(v) {
Some(RObj::Str(s)) => Some(s),
_ => None,
}
}
pub fn str_bytes<'a>(&'a self, v: &'a Value) -> Option<&'a [u8]> {
match self.obj(v) {
Some(RObj::Str(s)) => Some(s.bytes()),
_ => match v {
Value::Str(s) => Some(s.as_bytes()),
_ => None,
},
}
}
pub fn as_str(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::Str(s)) => Some(s.view().into_owned()),
_ => 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.set_view(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 is_str_or_obj_range(&self, v: &Value) -> bool {
matches!(
self.obj(v),
Some(RObj::StrRange { .. } | RObj::ObjRange { .. })
)
}
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_block_callable(&self, v: &Value) -> bool {
self.is_proc(v) || matches!(self.obj(v), Some(RObj::Method { .. }))
}
pub fn is_proc(&self, v: &Value) -> bool {
matches!(
self.obj(v),
Some(RObj::Proc { .. })
| Some(RObj::SymProc(_))
| Some(RObj::CycleProc(_))
| Some(RObj::RaiseProc { .. })
| Some(RObj::SeqProc(_))
| Some(RObj::StepProc { .. })
| Some(RObj::ProduceProc { .. })
| Some(RObj::DeriveProc { .. })
)
}
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 class_responds_to(&self, cls: &str, name: &str) -> bool {
name == "new"
|| matches!(
name,
"name"
| "to_s"
| "inspect"
| "singleton_class"
| "instance_methods"
| "public_instance_methods"
| "private_instance_methods"
| "class_variables"
| "constants"
| "ancestors"
| "superclass"
)
|| self.find_class_method(cls, name).is_some()
|| self.find_class_define_method(cls, name).is_some()
|| self.find_singleton_class_method(cls, name).is_some()
|| self.find_class_alias(cls, name).is_some()
|| self.find_method("Class", name).is_some()
|| self.find_method("Module", name).is_some()
}
pub fn responds_to(&self, name: &str) -> bool {
let this = self.current_self();
if let Some(cls) = self.classref_name(&this) {
return self.class_responds_to(&cls, name);
}
if let Some(cls) = self.object_class(&this) {
if self.find_method(&cls, name).is_some()
|| self.find_define_method(&cls, name).is_some()
|| self.attr_access(&cls, name).is_some()
{
return true;
}
if let Some((members, _)) = self.struct_def(&cls) {
let member = name.strip_suffix('=').unwrap_or(name);
if members.iter().any(|m| m == member) {
return true;
}
}
}
if self.find_singleton_method(&this, name).is_some()
|| self.find_singleton_define_method(&this, name).is_some()
{
return true;
}
self.methods.contains_key(name)
}
pub fn receiver_phrase(&self, v: &Value) -> String {
match v {
_ if is_main(v) => "main".to_string(),
Value::Undef => "nil".to_string(),
Value::Bool(true) => "true".to_string(),
Value::Bool(false) => "false".to_string(),
_ => match self.classref_name(v) {
Some(c) => format!("{} {c}", self.class_or_module_word(&c)),
None => format!("an instance of {}", self.class_of(v)),
},
}
}
pub fn class_of(&self, v: &Value) -> String {
if let Value::Obj(id) = v {
if let Some(cls) = self.class_overrides.get(id) {
return cls.clone();
}
}
match self.obj(v) {
Some(RObj::Object { class, .. }) => class.clone(),
Some(RObj::ClassRef(n)) => if Self::is_refinement_class(n) {
"Refinement"
} else if self.is_module_name(n) {
"Module"
} else {
"Class"
}
.to_string(),
_ => self.class_name(v).to_string(),
}
}
pub fn dispatch_class(&self, v: &Value) -> String {
if let Value::Obj(id) = v {
if self.class_overrides.contains_key(id) {
return self.class_name(v).to_string();
}
}
self.class_of(v)
}
pub fn alias_target(&self, class: &str, name: &str) -> Option<String> {
let anc = self.class_ancestry(class);
let mut cur = name.to_string();
let mut changed = false;
for _ in 0..50 {
let next = anc
.iter()
.find_map(|a| self.method_aliases.get(a).and_then(|m| m.get(&cur)));
match next {
Some(t) if *t != cur => {
cur = t.clone();
changed = true;
}
_ => break,
}
}
if let Some(native) = Self::native_alias_target(&cur) {
return Some(native.to_string());
}
changed.then_some(cur)
}
pub fn set_class_override(&mut self, v: &Value, class: &str) {
if let Value::Obj(id) = v {
self.class_overrides.insert(*id, class.to_string());
}
}
pub fn builtin_container_root(&self, class: &str) -> Option<&'static str> {
if !self.classes.contains_key(class) {
return None;
}
let mut cur = Some(class.to_string());
let mut guard = 0;
while let Some(n) = cur {
guard += 1;
if guard > 100 {
break;
}
match n.as_str() {
"Hash" => return Some("Hash"),
"Array" => return Some("Array"),
"String" => return Some("String"),
_ => {}
}
cur = self
.classes
.get(&n)
.and_then(|d| d.superclass.clone())
.map(|s| self.resolve_class_alias(&s, &n));
}
None
}
pub fn value_to_key(&self, v: &Value) -> RKey {
self.to_key(v)
}
pub fn key_value(&mut self, k: &RKey) -> Value {
let v = self.key_to_value(k);
if matches!(k, RKey::Str(_) | RKey::ByteStr(..)) {
self.freeze_value(&v);
}
v
}
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 frame_depth(&self) -> usize {
self.frames.len()
}
pub fn frame_method_tail(&self, n: usize) -> Vec<String> {
self.frames
.iter()
.rev()
.take(n)
.filter_map(|f| f.scope.method_name.clone())
.collect()
}
pub fn set_cur_line(&mut self, line: u32) {
if let Some(f) = self.frames.last_mut() {
f.line = line;
}
}
pub fn dbg_stack(&self) -> Vec<(String, u32)> {
self.frames
.iter()
.rev()
.map(|f| {
(
f.scope.method_name.clone().unwrap_or_else(|| "main".into()),
f.line,
)
})
.collect()
}
pub fn dbg_locals(&mut self) -> Vec<(String, String)> {
let env = self.cur_env();
let names: Vec<String> = env
.lock()
.unwrap()
.vars
.keys()
.filter(|k| !k.starts_with("__"))
.cloned()
.collect();
names
.into_iter()
.map(|n| {
let v = self.get_local(&n);
(n, self.inspect(&v))
})
.collect()
}
pub fn capture_binding(&mut self) -> Value {
let scope = self.cur_scope().clone();
self.bindings.push(scope);
let id = (self.bindings.len() - 1) as u32;
self.alloc(RObj::Binding { id })
}
pub fn binding_scope(&self, v: &Value) -> Option<Scope> {
match self.obj(v) {
Some(RObj::Binding { id }) => self.bindings.get(*id as usize).cloned(),
_ => None,
}
}
pub fn binding_receiver(&self, v: &Value) -> Value {
self.binding_scope(v)
.map(|s| s.self_obj)
.unwrap_or(Value::Undef)
}
pub fn local_names(&self) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut env = Some(self.cur_env());
while let Some(e) = env {
let data = e.lock().unwrap();
for name in data.vars.keys() {
let user = name
.chars()
.next()
.is_some_and(|c| c.is_ascii_lowercase() || c == '_')
&& !name.starts_with("__")
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if user && !out.contains(name) {
out.push(name.clone());
}
}
env = data.parent.clone();
}
out
}
pub fn get_local(&self, name: &str) -> Value {
let mut env = self.cur_env();
loop {
if let Some(v) = env.lock().unwrap().vars.get(name).cloned() {
return v;
}
let parent = env.lock().unwrap().parent.clone();
match parent {
Some(p) => env = p,
None => break,
}
}
if name == "it" {
return self.get_local("__it__");
}
Value::Undef
}
pub fn set_local(&self, name: &str, v: Value) {
let mut env = self.cur_env();
loop {
if env.lock().unwrap().vars.contains_key(name) {
env.lock().unwrap().vars.insert(name.to_string(), v);
return;
}
let parent = env.lock().unwrap().parent.clone();
match parent {
Some(p) => env = p,
None => break,
}
}
self.cur_env()
.lock()
.unwrap()
.vars
.insert(name.to_string(), v);
}
pub fn local_defined(&self, name: &str) -> bool {
let mut env = self.cur_env();
loop {
if env.lock().unwrap().vars.contains_key(name) {
return true;
}
let parent = env.lock().unwrap().parent.clone();
match parent {
Some(p) => env = p,
None => break,
}
}
if name == "it" {
return self.local_defined("__it__");
}
false
}
pub fn get_global(&self, name: &str) -> Value {
if name == "~" {
return self.last_match.clone();
}
self.globals.get(name).cloned().unwrap_or(Value::Undef)
}
pub fn match_global(&mut self, name: &str) -> Option<Value> {
let digits = !name.is_empty() && name.bytes().all(|b| b.is_ascii_digit()) && name != "0";
if !(digits || matches!(name, "~" | "&" | "`" | "'" | "+")) {
return None;
}
self.sync_match_owner();
let md = self.last_match.clone();
if name == "~" {
return Some(md);
}
let part = match name {
"`" => Some(MatchPart::Pre),
"'" => Some(MatchPart::Post),
_ => None,
};
if let Some(part) = part {
return Some(self.matchdata_text(&md, part).unwrap_or(Value::Undef));
}
let Some((groups, ..)) = self.as_matchdata(&md) else {
return Some(Value::Undef);
};
let text = match name {
"&" => groups.first().cloned().flatten(),
"+" => groups.iter().skip(1).rev().find_map(|g| g.clone()),
_ => name
.parse::<usize>()
.ok()
.and_then(|i| groups.get(i).cloned().flatten()),
};
Some(text.map_or(Value::Undef, |t| self.new_string(t)))
}
fn sync_match_owner(&mut self) {
let owner = match self
.active_scope
.as_ref()
.or(self.frames.last().map(|f| &f.scope))
{
Some(s) => s.frame_id,
None => return,
};
if owner == self.match_owner {
return;
}
let live = std::mem::replace(&mut self.last_match, Value::Undef);
if self.match_owner != u64::MAX && !matches!(live, Value::Undef) {
self.parked_matches.insert(self.match_owner, live);
}
self.last_match = self.parked_matches.remove(&owner).unwrap_or(Value::Undef);
self.match_owner = owner;
}
pub fn drop_frame_match(&mut self, frame_id: u64) {
if self.match_owner == frame_id {
self.last_match = Value::Undef;
self.match_owner = u64::MAX;
}
if !self.parked_matches.is_empty() {
self.parked_matches.remove(&frame_id);
}
}
pub fn set_global(&mut self, name: &str, v: Value) {
if name == "~" {
self.sync_match_owner();
self.last_match = v;
return;
}
self.globals.insert(name.to_string(), v);
}
pub fn begin_capture(&mut self) {
self.capture = Some(String::new());
}
pub fn end_capture(&mut self) -> String {
self.capture.take().unwrap_or_default()
}
pub fn capturing(&self) -> bool {
self.capture.is_some()
}
pub fn write_out(&mut self, s: &[u8], stderr: bool) {
if let Some(buf) = &mut self.capture {
buf.push_str(&String::from_utf8_lossy(s));
return;
}
use std::io::Write;
if stderr {
let mut o = std::io::stderr();
let _ = o.write_all(s);
let _ = o.flush();
} else {
let mut o = std::io::stdout();
let _ = o.write_all(s);
let _ = o.flush();
}
}
pub fn get_const(&self, name: &str) -> Value {
self.consts.get(name).cloned().unwrap_or(Value::Undef)
}
pub fn has_const(&self, name: &str) -> bool {
self.consts.contains_key(name)
}
pub fn set_const(&mut self, name: &str, v: Value) {
self.consts.insert(name.to_string(), v);
}
pub fn remove_const(&mut self, name: &str) -> Value {
let old = self.consts.shift_remove(name).unwrap_or(Value::Undef);
self.classes_mut().shift_remove(name);
old
}
pub fn const_names(&self) -> Vec<String> {
self.consts.keys().cloned().collect()
}
pub fn module_constants(&self, module: &str, inherit: bool) -> Vec<String> {
let mut owners = vec![module.to_string()];
if inherit {
owners.extend(self.class_ancestry(module).into_iter().filter(|a| {
a != module && !matches!(a.as_str(), "Object" | "Kernel" | "BasicObject")
}));
}
let mut out: Vec<String> = Vec::new();
for owner in owners {
let prefix = format!("{owner}::");
let direct = |k: &String| -> Option<String> {
k.strip_prefix(&prefix)
.filter(|rest| {
!rest.is_empty() && !rest.contains("::") && !rest.starts_with('#')
})
.map(str::to_string)
};
for name in self
.consts
.keys()
.filter_map(direct)
.chain(self.classes.keys().filter_map(direct))
{
if !out.contains(&name) {
out.push(name);
}
}
}
out
}
pub fn set_autoload(&mut self, name: &str, path: &str) {
self.autoloads.insert(name.to_string(), path.to_string());
}
pub fn autoload_path(&self, name: &str) -> Option<String> {
self.autoloads.get(name).cloned()
}
pub fn take_autoload(&mut self, name: &str) -> Option<String> {
self.autoloads.shift_remove(name)
}
pub fn get_ivar(&self, name: &str) -> Value {
match self.current_self() {
Value::Obj(id) => {
match self.obj(&self.current_self()) {
Some(RObj::Object { ivars, .. }) => {
ivars.get(name).cloned().unwrap_or(Value::Undef)
}
Some(RObj::ClassRef(cls)) => self
.class_ivars
.get(cls)
.and_then(|m| m.get(name))
.cloned()
.unwrap_or(Value::Undef),
_ => self
.obj_ivars
.get(&id)
.and_then(|m| m.get(name))
.cloned()
.unwrap_or(Value::Undef),
}
}
_ => self
.globals
.get(&format!("@{name}"))
.cloned()
.unwrap_or(Value::Undef),
}
}
pub fn ivar_defined(&self, name: &str) -> bool {
let this = self.current_self();
match &this {
Value::Obj(id) => match self.obj(&this) {
Some(RObj::Object { ivars, .. }) => ivars.contains_key(name),
Some(RObj::ClassRef(cls)) => self
.class_ivars
.get(cls)
.is_some_and(|m| m.contains_key(name)),
_ => self.obj_ivars.get(id).is_some_and(|m| m.contains_key(name)),
},
_ => self.globals.contains_key(&format!("@{name}")),
}
}
pub fn global_names(&self) -> Vec<String> {
self.globals.keys().cloned().collect()
}
pub fn global_defined(&self, name: &str) -> bool {
self.globals.contains_key(name)
}
pub fn set_ivar(&mut self, name: &str, v: Value) {
let this = self.current_self();
match this {
Value::Obj(i) => match self.heap.get_mut(i as usize) {
Some(RObj::Object { ivars, .. }) => {
ivars.insert(name.to_string(), v);
}
Some(RObj::ClassRef(cls)) => {
let cls = cls.clone();
self.class_ivars
.entry(cls)
.or_default()
.insert(name.to_string(), v);
}
_ => {
self.obj_ivars
.entry(i)
.or_default()
.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_mut().insert(name, def);
}
pub fn add_attr(&mut self, class: &str, field: &str, reader: bool, writer: bool) {
let e = self
.attr_accessors
.entry(class.to_string())
.or_default()
.entry(field.to_string())
.or_insert((false, false));
e.0 |= reader;
e.1 |= writer;
}
pub fn attr_access(&self, class: &str, method: &str) -> Option<(String, bool)> {
let (field, writer) = match method.strip_suffix('=') {
Some(f) => (f, true),
None => (method, false),
};
for c in self.class_ancestry(class) {
if let Some((r, w)) = self.attr_accessors.get(&c).and_then(|m| m.get(field)) {
if (writer && *w) || (!writer && *r) {
return Some((field.to_string(), writer));
}
}
if let Some((f, w)) = self.attr_aliases.get(&c).and_then(|m| m.get(method)) {
return Some((f.clone(), *w));
}
}
None
}
pub fn class_mixin(&mut self, class: &str, module: &str, kind: &str) {
let def = self.classes_mut().entry(class.to_string()).or_default();
let list = match kind {
"prepend" => &mut def.prepends,
"extend" => &mut def.extends,
_ => &mut def.includes,
};
let m = module.to_string();
if !list.contains(&m) {
list.push(m);
}
}
pub fn remove_mixin(&mut self, class: &str, module: &str, kind: &str) {
let target = self.resolve_module_name(module, class);
let list_names: Vec<String> = match self.classes.get(class) {
Some(def) => match kind {
"prepend" => def.prepends.clone(),
"extend" => def.extends.clone(),
_ => def.includes.clone(),
},
None => return,
};
let keep: Vec<bool> = list_names
.iter()
.map(|e| e != module && self.resolve_module_name(e, class) != target)
.collect();
if let Some(def) = self.classes_mut().get_mut(class) {
let list = match kind {
"prepend" => &mut def.prepends,
"extend" => &mut def.extends,
_ => &mut def.includes,
};
let mut i = 0;
list.retain(|_| {
let k = keep[i];
i += 1;
k
});
}
}
pub fn class_exists(&self, name: &str) -> bool {
self.classes.contains_key(name)
}
pub fn remove_instance_method(&mut self, cls: &str, name: &str) {
if let Some(def) = self.classes_mut().get_mut(cls) {
def.methods.shift_remove(name);
}
}
pub fn remove_class_method(&mut self, cls: &str, name: &str) {
if let Some(def) = self.classes_mut().get_mut(cls) {
def.class_methods.shift_remove(name);
}
}
pub fn metaclass_attached(name: &str) -> Option<&str> {
name.strip_prefix("#<Class:")
.and_then(|r| r.strip_suffix('>'))
.filter(|inner| {
let anon = inner
.strip_prefix("0x")
.is_some_and(|h| !h.is_empty() && h.bytes().all(|b| b.is_ascii_hexdigit()));
!inner.is_empty() && !anon
})
}
pub fn heap_address(id: u32) -> u64 {
0x1_0000_0000u64 + id as u64 * 0x28
}
pub fn object_singleton_class_name(cls: &str, id: u32) -> String {
format!("#<Class:#<{cls}:0x{:016x}>>", Self::heap_address(id))
}
fn next_anon_name(&mut self, kind: &str) -> String {
self.struct_counter += 1;
format!(
"#<{kind}:0x{:016x}>",
0x2_0000_0000u64 + u64::from(self.struct_counter) * 0x28
)
}
fn next_anon_class_name(&mut self) -> String {
self.next_anon_name("Class")
}
pub fn define_anon_class(&mut self, superclass: Option<String>, is_module: bool) -> String {
let name = self.next_anon_name(if is_module { "Module" } else { "Class" });
self.classes_mut().insert(
name.clone(),
ClassDef {
superclass,
is_module,
..ClassDef::default()
},
);
name
}
pub fn define_struct(&mut self, members: Vec<String>, keyword_init: Option<bool>) -> String {
let name = self.next_anon_class_name();
self.struct_defs
.insert(name.clone(), (members, keyword_init));
name
}
pub fn define_refinement(&mut self, module_name: &str, target: &str) -> String {
if let Some((_, existing)) = self
.refinement_defs
.get(module_name)
.and_then(|v| v.iter().find(|(t, _)| t == target))
{
return existing.clone();
}
let name = format!("#<refinement:{target}@{module_name}>");
self.classes_mut().insert(
name.clone(),
ClassDef {
superclass: None,
is_module: true,
..ClassDef::default()
},
);
self.refinement_defs
.entry(module_name.to_string())
.or_default()
.push((target.to_string(), name.clone()));
name
}
pub fn refinements_of(&self, module_name: &str) -> Vec<(String, String)> {
self.refinement_defs
.get(module_name)
.cloned()
.unwrap_or_default()
}
pub fn copy_methods_into(&mut self, src: &str, dst: &str) -> bool {
let Some(methods) = self.classes.get(src).map(|c| c.methods.clone()) else {
return false;
};
if methods.is_empty() {
return false;
}
if let Some(d) = self.classes_mut().get_mut(dst) {
d.methods.extend(methods);
}
true
}
pub fn refinement_target(&self, refinement: &str) -> Option<String> {
self.refinement_defs
.values()
.flatten()
.find(|(_, r)| r == refinement)
.map(|(t, _)| t.clone())
}
pub fn is_refinement_class(name: &str) -> bool {
name.starts_with("#<refinement:")
}
pub fn activate_refinements(&mut self, module_name: &str) {
for pair in self.refinements_of(module_name) {
self.active_refinements.retain(|p| *p != pair);
self.active_refinements.push(pair);
}
self.used_modules.retain(|m| m != module_name);
self.used_modules.push(module_name.to_string());
}
pub fn alias_top_level_method(&mut self, new_name: &str, old_name: &str) -> bool {
match self.methods.get(old_name).cloned() {
Some(def) => {
self.methods.insert(new_name.to_string(), def);
true
}
None => false,
}
}
pub fn top_level_method_names(&self) -> Vec<String> {
self.methods
.keys()
.filter(|n| !n.starts_with("__"))
.cloned()
.collect()
}
pub fn used_modules(&self) -> Vec<String> {
self.used_modules.iter().rev().cloned().collect()
}
pub fn refinements_active(&self) -> bool {
!self.active_refinements.is_empty()
}
pub fn skip_refined_once(&mut self, name: &str) {
self.skip_refined = Some(name.to_string());
}
pub fn find_refined_method(&mut self, recv: &Value, name: &str) -> Option<(MethodDef, String)> {
if self.skip_refined.as_deref() == Some(name) {
self.skip_refined = None;
return None;
}
let class = match self.classref_name(recv) {
Some(_) => "Class".to_string(),
None => self
.object_class(recv)
.unwrap_or_else(|| self.class_of(recv)),
};
let ancestry = self.class_ancestry(&class);
for (target, refname) in self.active_refinements.iter().rev() {
if !ancestry.iter().any(|a| a == target) && !(class == "Class" && target == "Module") {
continue;
}
if let Some(def) = self.classes.get(refname).and_then(|c| c.methods.get(name)) {
return Some((def.clone(), refname.clone()));
}
}
None
}
pub fn struct_def(&self, name: &str) -> Option<(Vec<String>, Option<bool>)> {
let owner = self.struct_owner(name)?;
self.struct_defs.get(&owner).cloned()
}
pub fn struct_owner(&self, name: &str) -> Option<String> {
if self.struct_defs.is_empty() {
return None;
}
let mut cur = name.to_string();
for _ in 0..64 {
if self.struct_defs.contains_key(&cur) {
return Some(cur);
}
cur = self.superclass_of(&cur)?;
}
None
}
pub fn struct_defs_contain(&self, name: &str) -> bool {
self.struct_defs.contains_key(name)
}
pub fn is_struct_class(&self, name: &str) -> bool {
self.struct_owner(name).is_some()
}
pub fn define_data(&mut self, members: Vec<String>) -> String {
let name = self.next_anon_class_name();
self.struct_defs.insert(name.clone(), (members, None));
self.data_classes.insert(name.clone());
name
}
pub fn struct_inspect(&self, class: &str, parts: &[String]) -> String {
let head = self.struct_inspect_head(class);
let named = !class.starts_with("#<");
match (parts.is_empty(), named) {
(true, true) => format!("{head}>"),
_ => format!("{head} {}>", parts.join(", ")),
}
}
pub fn struct_inspect_head(&self, class: &str) -> String {
let kind = if self.is_data_class(class) {
"data"
} else {
"struct"
};
if class.starts_with("#<") {
format!("#<{kind}")
} else {
format!("#<{kind} {class}")
}
}
pub fn is_data_class(&self, name: &str) -> bool {
self.struct_owner(name)
.is_some_and(|o| self.data_classes.contains(&o))
}
pub fn embedded_stdlib_loaded(&self, name: &str) -> bool {
self.embedded_stdlib_loaded.contains(name)
}
pub fn mark_embedded_stdlib_loaded(&mut self, name: &str) {
self.embedded_stdlib_loaded.insert(name.to_string());
}
pub fn require_builtin_lib(&mut self, name: &str) -> bool {
const PRELOADED: &[&str] = &["thread", "fiber", "monitor", "did_you_mean", "rbconfig"];
const DEPS: &[(&str, &[&str])] = &[
("time", &["date"]),
("digest/md5", &["digest"]),
("digest/sha1", &["digest"]),
("digest/sha2", &["digest"]),
("bigdecimal/util", &["bigdecimal"]),
("pp", &["prettyprint"]),
("tmpdir", &["fileutils", "etc"]),
("tempfile", &["fileutils", "tmpdir", "etc"]),
("cgi", &["cgi/escape"]),
("cgi/util", &["cgi/escape"]),
("erb", &["cgi/escape"]),
];
let name = name.strip_suffix(".rb").unwrap_or(name);
if PRELOADED.contains(&name) || !self.builtin_libs_loaded.insert(name.to_string()) {
return false;
}
if let Some((_, deps)) = DEPS.iter().find(|(n, _)| *n == name) {
for d in *deps {
self.builtin_libs_loaded.insert(d.to_string());
}
}
true
}
pub fn set_enum_label(&mut self, e: &Value, label: String) {
if let Value::Obj(id) = e {
self.enum_labels.insert(*id, label);
}
}
pub fn new_chunk_enumerator(&mut self, chunks: Vec<Value>) -> Value {
let e = self.new_enumerator(chunks, "each");
self.set_enum_size_fn(&e, None, vec![]);
let label = format!(
"#<Enumerator: #<Enumerator::Generator:{}>:each>",
self.object_address(&e)
);
if let Value::Obj(id) = e {
self.enum_labels.insert(id, label);
}
e
}
pub fn set_enum_size_fn(&mut self, e: &Value, size_fn: Option<Value>, args: Vec<Value>) {
if let Value::Obj(id) = e {
self.enum_size_fns.insert(*id, (size_fn, args));
}
}
pub fn enum_size_fn(&self, e: &Value) -> Option<(Option<Value>, Vec<Value>)> {
match e {
Value::Obj(id) => self.enum_size_fns.get(id).cloned(),
_ => None,
}
}
pub fn builtin_lib_loaded(&self, name: &str) -> bool {
self.builtin_libs_loaded.contains(name)
}
pub fn cvar_owner(&self, this: &Value) -> Option<String> {
self.object_class(this).or_else(|| self.classref_name(this))
}
pub fn cvar_class(&self) -> Option<String> {
let s = self.cur_scope();
match &s.def_class {
Some(dc) => Some(dc.clone()),
None => self.cvar_owner(&s.self_obj),
}
}
pub fn method_def(&self, name: &str) -> Option<MethodDef> {
self.methods.get(name).cloned()
}
pub fn extend_object(&mut self, id: u32, module: &str) {
let class_chain = self.class_ancestry(&self.class_of(&Value::Obj(id)));
let recorded = self.object_extends.get(&id).cloned().unwrap_or_default();
let mut chain: Vec<String> = self
.class_ancestry(module)
.into_iter()
.filter(|m| !recorded.contains(m) && !class_chain.contains(m))
.collect();
chain.extend(recorded);
self.object_extends.insert(id, chain.clone());
let previous = self.extended_singletons.remove(&id).unwrap_or_default();
for n in &previous {
if let Some(m) = self.singleton_methods.get_mut(&id) {
m.shift_remove(n);
}
if let Some(m) = self.singleton_define_methods.get_mut(&id) {
m.shift_remove(n);
}
}
let own: HashSet<String> = self
.singleton_methods
.get(&id)
.into_iter()
.flat_map(|m| m.keys().cloned())
.chain(
self.singleton_define_methods
.get(&id)
.into_iter()
.flat_map(|m| m.keys().cloned()),
)
.collect();
let mut copied = HashSet::new();
for mname in chain.iter().rev() {
if let Some(cd) = self.classes.get(mname).cloned() {
for (n, def) in cd.methods {
if own.contains(&n) {
continue;
}
if let Some(m) = self.singleton_define_methods.get_mut(&id) {
m.shift_remove(&n);
}
self.singleton_methods
.entry(id)
.or_default()
.insert(n.clone(), def);
copied.insert(n);
}
}
if let Some(dm) = self.define_methods.get(mname).cloned() {
for (n, proc) in dm {
if own.contains(&n) {
continue;
}
if let Some(m) = self.singleton_methods.get_mut(&id) {
m.shift_remove(&n);
}
self.singleton_define_methods
.entry(id)
.or_default()
.insert(n.clone(), proc);
copied.insert(n);
}
}
}
self.extended_singletons.insert(id, copied);
}
fn claim_singleton(&mut self, id: u32, name: &str) {
if self
.extended_singletons
.get_mut(&id)
.is_some_and(|s| s.remove(name))
{
if let Some(m) = self.singleton_methods.get_mut(&id) {
m.shift_remove(name);
}
if let Some(m) = self.singleton_define_methods.get_mut(&id) {
m.shift_remove(name);
}
}
}
pub fn is_extended_singleton(&self, id: u32, name: &str) -> bool {
self.extended_singletons
.get(&id)
.is_some_and(|s| s.contains(name))
}
pub fn object_singleton_parts(name: &str) -> Option<(&str, u32)> {
let inner = Self::metaclass_attached(name)?;
let body = inner.strip_prefix("#<")?.strip_suffix('>')?;
let (cls, hex) = body.rsplit_once(":0x")?;
let addr = u64::from_str_radix(hex, 16).ok()?;
let id = addr.checked_sub(0x1_0000_0000)?;
(id % 0x28 == 0).then_some(())?;
Some((cls, u32::try_from(id / 0x28).ok()?))
}
pub fn add_singleton_method(&mut self, id: u32, name: &str, def: MethodDef) {
self.claim_singleton(id, name);
self.singleton_methods
.entry(id)
.or_default()
.insert(name.to_string(), def);
}
pub fn find_singleton_method(&self, v: &Value, name: &str) -> Option<MethodDef> {
if self.singleton_methods.is_empty() {
return None;
}
match v {
Value::Obj(id) => self
.singleton_methods
.get(id)
.and_then(|m| m.get(name))
.cloned(),
_ => None,
}
}
pub fn singleton_method_names(&self, v: &Value, all: bool) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
if let Value::Obj(id) = v {
if let Some(m) = self.singleton_methods.get(id) {
names.extend(m.keys().cloned());
}
if let Some(m) = self.singleton_define_methods.get(id) {
names.extend(m.keys().cloned());
}
if let Some(sc) = self.singleton_class_name(v) {
if let Some(attrs) = self.attr_accessors.get(&sc) {
for (field, (r, w)) in attrs {
if *r {
names.push(field.clone());
}
if *w {
names.push(format!("{field}="));
}
}
}
if let Some(m) = self.define_methods.get(&sc) {
names.extend(m.keys().cloned());
}
}
}
if let Some(cls) = self.classref_name(v) {
self.class_singleton_method_names(&cls, all, &mut names);
}
names.retain(|n| !n.starts_with("__"));
names.sort();
names.dedup();
names
}
fn class_singleton_method_names(&self, cls: &str, all: bool, names: &mut Vec<String>) {
let mut cur = Some(cls.to_string());
while let Some(c) = cur {
if let Some(def) = self.classes.get(&c) {
names.extend(
def.class_methods
.keys()
.filter(|k| def.class_visibility.get(*k) != Some(&Visibility::Private))
.cloned(),
);
}
if let Some(m) = self.class_define_methods.get(&c) {
names.extend(m.keys().cloned());
}
if !all {
break;
}
let Some(def) = self.classes.get(&c) else {
break;
};
for m in &def.extends {
let module = self.resolve_module_name(m, &c);
names.extend(self.instance_method_names_vis(
&module,
true,
&[Visibility::Public, Visibility::Protected],
));
}
cur = self.superclass_of(&c).filter(|s| s != &c);
}
}
pub fn has_own_class_method(&self, cls: &str, name: &str) -> bool {
let defines = |c: &str| {
self.classes
.get(c)
.is_some_and(|d| d.methods.contains_key(name))
|| self
.define_methods
.get(c)
.is_some_and(|m| m.contains_key(name))
};
self.classes.get(cls).is_some_and(|d| {
d.class_methods.contains_key(name)
|| d.extends
.iter()
.any(|m| defines(&self.resolve_module_name(m, cls)))
}) || self
.class_define_methods
.get(cls)
.is_some_and(|m| m.contains_key(name))
}
pub fn add_singleton_define_method(&mut self, id: u32, name: &str, proc: Value) {
self.claim_singleton(id, name);
self.singleton_define_methods
.entry(id)
.or_default()
.insert(name.to_string(), proc);
}
pub fn singleton_class_name(&self, v: &Value) -> Option<String> {
let Value::Obj(id) = v else {
return None;
};
if self.classref_name(v).is_some() {
return None;
}
let cls = self.class_of(v);
if matches!(cls.as_str(), "Symbol" | "Integer" | "Float") {
return None;
}
Some(Self::object_singleton_class_name(&cls, *id))
}
pub fn find_singleton_define_method(&self, v: &Value, name: &str) -> Option<Value> {
if let Some(sc) = self.singleton_class_name(v) {
if let Some(p) = self.define_methods.get(&sc).and_then(|m| m.get(name)) {
return Some(p.clone());
}
}
if self.singleton_define_methods.is_empty() {
return None;
}
match v {
Value::Obj(id) => self
.singleton_define_methods
.get(id)
.and_then(|m| m.get(name))
.cloned(),
_ => None,
}
}
pub fn add_class_define_method(&mut self, class: &str, name: &str, proc: Value) {
self.class_define_methods
.entry(class.to_string())
.or_default()
.insert(name.to_string(), proc);
}
pub fn own_singleton_define_method(&self, class: &str, name: &str) -> Option<Value> {
let sclass = format!("#<Class:{class}>");
self.define_methods
.get(&sclass)
.and_then(|m| m.get(name))
.cloned()
}
pub fn find_singleton_class_method(&self, class: &str, name: &str) -> Option<String> {
let mut cur = Some(class.to_string());
let mut guard = 0;
while let Some(c) = cur {
let sclass = format!("#<Class:{c}>");
let has = self
.define_methods
.get(&sclass)
.is_some_and(|m| m.contains_key(name))
|| self
.classes
.get(&sclass)
.is_some_and(|d| d.methods.contains_key(name));
if has {
return Some(sclass);
}
guard += 1;
if guard > 100 {
break;
}
cur = self.superclass_of(&c);
}
None
}
pub fn find_class_define_method(&self, class: &str, name: &str) -> Option<Value> {
let mut cur = Some(class.to_string());
let mut guard = 0;
while let Some(c) = cur {
if let Some(p) = self.class_define_methods.get(&c).and_then(|m| m.get(name)) {
return Some(p.clone());
}
if let Some(def) = self.classes.get(&c) {
let extends = def.extends.clone();
for module in extends.iter().rev() {
let resolved = self.resolve_module_name(module, &c);
for anc in self.module_self_ancestry(&resolved) {
if let Some(p) = self.define_methods.get(&anc).and_then(|m| m.get(name)) {
return Some(p.clone());
}
}
}
}
guard += 1;
if guard > 100 {
break;
}
cur = self.superclass_of(&c);
}
None
}
pub fn add_class_method(&mut self, class: &str, name: &str, def: MethodDef) {
self.classes
.entry(class.to_string())
.or_default()
.class_methods
.insert(name.to_string(), def);
}
pub fn add_instance_method(&mut self, class: &str, name: &str, def: MethodDef) {
self.drop_define_method(class, name);
self.shadowed_defs
.remove(&(class.to_string(), name.to_string()));
self.classes
.entry(class.to_string())
.or_default()
.methods
.insert(name.to_string(), def);
}
fn drop_define_method(&mut self, class: &str, name: &str) {
if let Some(m) = self.define_methods.get_mut(class) {
m.shift_remove(name);
}
}
pub fn reassert_hoisted_def(&mut self, class: &str, name: &str) {
let key = (class.to_string(), name.to_string());
if let Some(def) = self.shadowed_defs.remove(&key) {
self.drop_define_method(class, name);
if let Some(c) = self.classes.get_mut(class) {
c.methods.insert(name.to_string(), def);
}
} else if self.has_own_define_method(class, name) {
self.drop_define_method(class, name);
}
}
pub fn add_define_method(&mut self, class: &str, name: &str, proc: Value) {
if let Some(def) = self
.classes
.get_mut(class)
.and_then(|c| c.methods.shift_remove(name))
{
self.shadowed_defs
.insert((class.to_string(), name.to_string()), def);
}
self.define_methods
.entry(class.to_string())
.or_default()
.insert(name.to_string(), proc);
}
pub fn has_own_define_method(&self, class: &str, name: &str) -> bool {
self.define_methods
.get(class)
.is_some_and(|m| m.contains_key(name))
}
pub fn has_own_method(&self, class: &str, name: &str) -> bool {
self.classes
.get(class)
.is_some_and(|d| d.methods.contains_key(name))
}
pub fn find_define_method(&self, class: &str, name: &str) -> Option<Value> {
for c in self.class_ancestry(class) {
if let Some(p) = self.define_methods.get(&c).and_then(|m| m.get(name)) {
return Some(p.clone());
}
}
None
}
pub fn add_alias(&mut self, class: &str, alias_name: &str, target: &str) {
self.method_aliases
.entry(class.to_string())
.or_default()
.insert(alias_name.to_string(), target.to_string());
}
fn is_native_builtin_method(base: &str, method: &str) -> bool {
match base {
"Hash" => matches!(
method,
"[]" | "[]="
| "store"
| "fetch"
| "delete"
| "update"
| "merge"
| "merge!"
| "each"
| "each_pair"
| "keys"
| "values"
| "key?"
| "has_key?"
| "include?"
| "dig"
| "to_hash"
| "to_a"
| "size"
| "length"
| "default"
| "default="
| "default_proc"
| "default_proc="
| "replace"
| "clear"
| "assoc"
| "rassoc"
| "select"
| "reject"
| "invert"
| "key"
| "values_at"
| "slice"
),
"Array" => matches!(
method,
"[]" | "[]="
| "push"
| "<<"
| "pop"
| "shift"
| "unshift"
| "each"
| "map"
| "size"
| "length"
| "first"
| "last"
| "to_a"
| "to_ary"
| "concat"
| "replace"
| "insert"
| "delete"
| "index"
| "include?"
),
"String" => matches!(
method,
"[]" | "[]="
| "<<"
| "concat"
| "replace"
| "length"
| "size"
| "to_s"
| "to_str"
| "each_char"
| "gsub"
| "sub"
),
_ => false,
}
}
pub fn register_alias(&mut self, class: &str, alias_name: &str, target: &str) {
if let Some(base) = self.builtin_container_root(class) {
if Self::is_native_builtin_method(base, target) {
self.method_aliases
.entry(class.to_string())
.or_default()
.insert(alias_name.to_string(), format!("\u{1}native:{target}"));
return;
}
}
if crate::builtins::is_kernel_function(target) {
self.method_aliases
.entry(class.to_string())
.or_default()
.insert(alias_name.to_string(), format!("\u{1}native:{target}"));
return;
}
if let Some((def, _)) = self.find_method_owner(class, target) {
self.add_instance_method(class, alias_name, def);
let original = self
.alias_originals
.get(class)
.and_then(|m| m.get(target))
.cloned()
.unwrap_or_else(|| target.to_string());
self.alias_originals
.entry(class.to_string())
.or_default()
.insert(alias_name.to_string(), original);
} else if let Some(proc) = self.find_define_method(class, target) {
self.define_methods
.entry(class.to_string())
.or_default()
.insert(alias_name.to_string(), proc);
} else if let Some((field, writer)) = self.attr_access(class, target) {
self.attr_aliases
.entry(class.to_string())
.or_default()
.insert(alias_name.to_string(), (field, writer));
} else {
self.method_aliases
.entry(class.to_string())
.or_default()
.insert(alias_name.to_string(), format!("\u{1}native:{target}"));
}
}
pub fn native_kernel_alias(&self, class: &str, name: &str) -> Option<String> {
let anc = self.class_ancestry(class);
let mut cur = name.to_string();
for _ in 0..50 {
let next = anc
.iter()
.find_map(|a| self.method_aliases.get(a).and_then(|m| m.get(&cur)));
match next {
Some(t) if *t != cur => cur = t.clone(),
_ => break,
}
}
Self::native_alias_target(&cur)
.filter(|n| crate::builtins::is_kernel_function(n))
.map(|n| n.to_string())
}
pub fn native_alias_target(target: &str) -> Option<&str> {
target.strip_prefix("\u{1}native:")
}
pub fn find_alias(&self, class: &str, name: &str) -> Option<String> {
let mut cur = Some(class.to_string());
while let Some(c) = cur {
if let Some(t) = self.method_aliases.get(&c).and_then(|m| m.get(name)) {
return Some(t.clone());
}
cur = self.superclass_of(&c);
}
None
}
pub fn find_class_alias(&self, class: &str, name: &str) -> Option<String> {
let mut cur = Some(class.to_string());
let mut guard = 0;
while let Some(c) = cur {
let sclass = format!("#<Class:{c}>");
if let Some(t) = self.method_aliases.get(&sclass).and_then(|m| m.get(name)) {
return Some(t.clone());
}
guard += 1;
if guard > 100 {
break;
}
cur = self.superclass_of(&c);
}
None
}
pub fn get_cvar(&self, class_name: &str, var: &str) -> Value {
let mut cur = Some(class_name.to_string());
while let Some(c) = cur {
if let Some(v) = self.class_vars.get(&c).and_then(|m| m.get(var)) {
return v.clone();
}
cur = self.superclass_of(&c);
}
Value::Undef
}
pub fn class_var_names(&self, class_name: &str) -> Vec<String> {
let mut names = Vec::new();
let mut cur = Some(class_name.to_string());
while let Some(c) = cur {
if let Some(m) = self.class_vars.get(&c) {
for k in m.keys() {
if !names.contains(k) {
names.push(k.clone());
}
}
}
cur = self.superclass_of(&c);
}
names
}
pub fn cvar_defined(&self, class_name: &str, var: &str) -> bool {
let mut cur = Some(class_name.to_string());
while let Some(c) = cur {
if self.class_vars.get(&c).is_some_and(|m| m.contains_key(var)) {
return true;
}
cur = self.superclass_of(&c);
}
false
}
pub fn set_cvar(&mut self, class_name: &str, var: &str, val: Value) {
let mut owner = class_name.to_string();
let mut cur = Some(class_name.to_string());
while let Some(c) = cur {
if self.class_vars.get(&c).is_some_and(|m| m.contains_key(var)) {
owner = c;
break;
}
cur = self.superclass_of(&c);
}
self.class_vars
.entry(owner)
.or_default()
.insert(var.to_string(), val);
}
pub fn rename_struct(&mut self, old: &str, new: &str) {
if let Some(def) = self.struct_defs.shift_remove(old) {
self.struct_defs.insert(new.to_string(), def);
}
if self.data_classes.remove(old) {
self.data_classes.insert(new.to_string());
}
}
pub fn is_anon_class(&self, name: &str) -> bool {
(name.starts_with("#<Class:") || name.starts_with("#<Module:"))
&& self.classes.contains_key(name)
}
pub fn rename_class(&mut self, old: &str, new: &str) {
if let Some(def) = self.classes_mut().shift_remove(old) {
self.classes_mut().insert(new.to_string(), def);
}
if let Some(v) = self.class_vars.shift_remove(old) {
self.class_vars.insert(new.to_string(), v);
}
if let Some(v) = self.class_ivars.shift_remove(old) {
self.class_ivars.insert(new.to_string(), v);
}
if let Some(v) = self.define_methods.shift_remove(old) {
self.define_methods.insert(new.to_string(), v);
}
if let Some(v) = self.class_define_methods.shift_remove(old) {
self.class_define_methods.insert(new.to_string(), v);
}
if let Some(v) = self.attr_accessors.shift_remove(old) {
self.attr_accessors.insert(new.to_string(), v);
}
if let Some(v) = self.method_aliases.shift_remove(old) {
self.method_aliases.insert(new.to_string(), v);
}
self.rewrite_class_name(old, new);
}
fn rewrite_class_name(&mut self, old: &str, new: &str) {
for obj in &mut self.heap {
match obj {
RObj::Object { class, .. } | RObj::ClassRef(class) if class == old => {
*class = new.to_string();
}
RObj::Hash { map, .. } if map.contains_key(&RKey::Class(old.to_string())) => {
*map = std::mem::take(map)
.into_iter()
.map(|(k, v)| match k {
RKey::Class(n) if n == old => (RKey::Class(new.to_string()), v),
k => (k, v),
})
.collect();
}
_ => {}
}
}
let rename = |n: &mut String| {
if n == old {
*n = new.to_string();
}
};
for def in self.classes_mut().values_mut() {
def.superclass.iter_mut().for_each(rename);
for list in [&mut def.includes, &mut def.prepends, &mut def.extends] {
list.iter_mut().for_each(rename);
}
}
}
pub fn class_object_id(&mut self, name: &str) -> i64 {
let (index, _) = self.class_object_ids.insert_full(name.to_string(), ());
(1 << 40) + (index as i64) * 8
}
pub fn object_for_id(&mut self, id: i64) -> Option<Value> {
if id >= 1 << 40 && id % 8 == 0 {
let index = ((id - (1 << 40)) / 8) as usize;
let name = self
.class_object_ids
.get_index(index)
.map(|(n, _)| n.clone())?;
return Some(self.class_ref(&name));
}
let slot = (id / 8).checked_sub(1)?;
(id % 8 == 0 && (slot as usize) < self.heap.len()).then_some(Value::Obj(slot as u32))
}
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 mark_module_function(&mut self, class: &str) {
self.module_function_modules.insert(class.to_string());
}
pub fn is_module_function_module(&self, class: &str) -> bool {
self.module_function_modules.contains(class)
}
pub fn is_module_name(&self, name: &str) -> bool {
crate::arity_table::is_module(name) || self.classes.get(name).is_some_and(|d| d.is_module)
}
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())
.map(|s| self.resolve_class_alias(&s, name))
}
pub fn resolve_class_alias(&self, name: &str, from: &str) -> String {
if self.classes.contains_key(name) {
return name.to_string();
}
if self.is_builtin_class(name) || is_builtin_exception_name(name) {
return name.to_string();
}
if !name.contains("::") {
let mut prefix = from;
while let Some(idx) = prefix.rfind("::") {
prefix = &prefix[..idx];
let cand = format!("{prefix}::{name}");
if cand != from && self.classes.contains_key(&cand) {
return cand;
}
}
}
let suffix = format!("::{name}");
if let Some(full) = self
.classes
.keys()
.find(|k| k.as_str() != from && k.ends_with(&suffix))
{
return full.clone();
}
let mut const_candidates = vec![name.to_string()];
let mut cprefix = from;
while let Some(idx) = cprefix.rfind("::") {
cprefix = &cprefix[..idx];
const_candidates.push(format!("{cprefix}::{name}"));
}
for cand in &const_candidates {
let c = self.get_const(cand);
if let Some(RObj::ClassRef(real)) = self.obj(&c) {
if real != name && real != from {
return self.resolve_class_alias(real, from);
}
}
}
if !name.contains("::") {
for (k, v) in &self.consts {
if k.ends_with(&suffix) {
if let Some(RObj::ClassRef(real)) = self.obj(v) {
if real != name && real != from {
return self.resolve_class_alias(real, from);
}
}
}
}
}
name.to_string()
}
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()
.map(|s| self.resolve_class_alias(&s, &name));
}
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"
&& matches!(
actual.as_str(),
"Integer" | "Float" | "Rational" | "Complex"
)
{
return true;
}
if class == "Module" && actual == "Class" {
return true;
}
if class == "Comparable"
&& matches!(
actual.as_str(),
"Integer" | "Float" | "String" | "Symbol" | "Rational" | "Complex" | "Time"
)
{
return true;
}
if class == "Enumerable"
&& matches!(
actual.as_str(),
"Array"
| "Hash"
| "Range"
| "Set"
| "Enumerator"
| "Enumerator::Lazy"
| "Enumerator::ArithmeticSequence"
| "Enumerator::Chain"
)
{
return true;
}
if class == "Enumerator"
&& matches!(
actual.as_str(),
"Enumerator::Lazy" | "Enumerator::ArithmeticSequence" | "Enumerator::Chain"
)
{
return true;
}
if actual == "DateTime" && matches!(class, "Date" | "Comparable") {
return true;
}
if let Value::Obj(id) = v {
if self
.object_extends
.get(id)
.is_some_and(|m| m.iter().any(|n| n == class))
{
return true;
}
}
if self.classes.contains_key(&actual) && self.class_is_ancestor(&actual, class) {
return true;
}
if is_builtin_exception_name(&actual)
|| self.classes.contains_key(&actual)
|| self.is_struct_class(&actual)
{
return self.class_ancestry(&actual).iter().any(|a| a == class);
}
false
}
pub fn resolve_module_name(&self, module: &str, enclosing: &str) -> String {
let nested = format!("{enclosing}::{module}");
if self.classes.contains_key(&nested) {
return nested;
}
let mut prefix = enclosing;
while let Some(idx) = prefix.rfind("::") {
prefix = &prefix[..idx];
let cand = format!("{prefix}::{module}");
if self.classes.contains_key(&cand) {
return cand;
}
}
if self.classes.contains_key(module) {
return module.to_string();
}
let alias = self.resolve_class_alias(module, enclosing);
if self.classes.contains_key(&alias) {
return alias;
}
module.to_string()
}
fn ancestry_tail(&self, name: &str) -> Vec<String> {
let mut out = Vec::new();
if self.is_struct_class(name) {
out.push(
if self.is_data_class(name) {
"Data"
} else {
"Struct"
}
.to_string(),
);
if !self.is_data_class(name) {
out.push("Enumerable".to_string());
}
}
out.extend(["Object", "Kernel", "BasicObject"].map(String::from));
out
}
pub fn class_ancestry(&self, name: &str) -> Vec<String> {
let own = |mods: &[&str]| {
let mut v = vec![name.to_string()];
v.extend(mods.iter().map(|s| s.to_string()));
v.extend(self.ancestry_tail(name));
v
};
if let Some((cls, id)) = Self::object_singleton_parts(name) {
let mut out = vec![name.to_string()];
out.extend(self.object_extends.get(&id).cloned().unwrap_or_default());
out.extend(self.class_ancestry(cls));
return dedup_keep_first(out);
}
if let Some(inner) = Self::metaclass_attached(name) {
let mut out = vec![name.to_string()];
let mut cur = inner.to_string();
let mut first = true;
for _ in 0..256 {
if !first {
out.push(format!("#<Class:{cur}>"));
}
first = false;
if let Some(def) = self.classes.get(&cur) {
for m in def.extends.iter().rev() {
let r = self.resolve_module_name(m, &cur);
if !out.contains(&r) {
out.push(r);
}
}
if def.is_module {
break;
}
}
if cur == "BasicObject" {
out.push("Class".to_string());
break;
}
let next = self
.classes
.get(&cur)
.and_then(|d| d.superclass.clone())
.map(|s| self.resolve_class_alias(&s, &cur))
.unwrap_or_else(|| {
if cur == "Object" {
"BasicObject".to_string()
} else {
"Object".to_string()
}
});
cur = next;
}
out.extend(
["Module", "Object", "Kernel", "BasicObject"]
.iter()
.map(|s| s.to_string()),
);
return dedup_keep_first(out);
}
let chain = match name {
"BasicObject" => vec!["BasicObject".into()],
"Object" => vec!["Object".into(), "Kernel".into(), "BasicObject".into()],
"Kernel" | "Comparable" | "Enumerable" => vec![name.into()],
"Class" => own(&["Module"]),
"Numeric" => own(&["Comparable"]),
"Integer" | "Float" | "Rational" => own(&["Numeric", "Comparable"]),
"Complex" => own(&["Numeric", "Comparable"]),
"String" | "Symbol" | "Time" | "Date" => own(&["Comparable"]),
"DateTime" => own(&["Date", "Comparable"]),
"Array" | "Hash" | "Range" | "Set" | "Struct" | "Enumerator" => own(&["Enumerable"]),
"Enumerator::Lazy" | "Enumerator::ArithmeticSequence" | "Enumerator::Chain" => {
own(&["Enumerator", "Enumerable"])
}
"IO" => own(&["File::Constants", "Enumerable"]),
"File" => own(&["IO", "File::Constants", "Enumerable"]),
_ if self.classes.get(name).is_some_and(|d| d.is_module) => {
let def = &self.classes[name];
let mut out: Vec<String> = def
.prepends
.iter()
.rev()
.map(|m| self.resolve_module_name(m, name))
.collect();
out.push(name.to_string());
for m in def.includes.iter().rev() {
let inc = self.resolve_module_name(m, name);
out.extend(self.class_ancestry(&inc));
}
dedup_keep_first(out)
}
_ => {
if self.classes.contains_key(name) {
let mut out = Vec::new();
let mut cur = Some(name.to_string());
while let Some(n) = cur {
if let Some(def) = self.classes.get(&n) {
let mods: Vec<String> = def.prepends.clone();
for m in mods.iter().rev() {
out.push(self.resolve_module_name(m, &n));
}
}
out.push(n.clone());
match self.classes.get(&n) {
Some(def) => {
let mods: Vec<String> = def.includes.clone();
for m in mods.iter().rev() {
out.push(self.resolve_module_name(m, &n));
}
cur = def
.superclass
.clone()
.map(|s| self.resolve_class_alias(&s, &n));
}
None => {
out.pop();
out.extend(self.class_ancestry(&n));
return dedup_keep_first(out);
}
}
}
out.extend(self.ancestry_tail(name));
dedup_keep_first(out)
} else if is_builtin_exception_name(name) {
let mut v = vec![name.to_string()];
let mut cur = name;
while let Some(parent) = builtin_exception_parent(cur) {
v.push(parent.to_string());
cur = parent;
}
v.extend(["Object", "Kernel", "BasicObject"].map(String::from));
v
} else {
own(&[])
}
}
};
self.splice_reopened_mixins(chain)
}
fn splice_reopened_mixins(&self, chain: Vec<String>) -> Vec<String> {
let reopened = |c: &String| {
self.classes
.get(c)
.is_some_and(|d| !d.includes.is_empty() || !d.prepends.is_empty())
};
if !chain.iter().any(reopened) {
return chain;
}
let mut out = Vec::with_capacity(chain.len());
for c in chain {
let Some(def) = self.classes.get(&c).filter(|_| reopened(&c)) else {
out.push(c);
continue;
};
for m in def.prepends.iter().rev() {
out.extend(self.class_ancestry(&self.resolve_module_name(m, &c)));
}
out.push(c.clone());
for m in def.includes.iter().rev() {
out.extend(self.class_ancestry(&self.resolve_module_name(m, &c)));
}
}
dedup_keep_first(out)
}
pub fn class_superclass(&self, name: &str) -> Option<String> {
if name == "BasicObject" {
return None;
}
if let Some(inner) = name
.strip_prefix("#<Class:#<")
.and_then(|s| s.strip_suffix(">>"))
.and_then(|s| s.rsplit_once(":0x"))
.map(|(c, _)| c)
{
return Some(inner.to_string());
}
if let Some(sc) = self.superclass_of(name) {
return Some(sc);
}
self.class_ancestry(name)
.into_iter()
.skip(1)
.find(|a| !self.is_module_name(a))
.or_else(|| {
if self.classes.contains_key(name) {
Some("Object".to_string())
} else {
None
}
})
}
pub fn defined_class_names(&self, modules: bool) -> Vec<String> {
self.classes
.iter()
.filter(|(k, d)| !k.starts_with("#<") && (modules || !d.is_module))
.map(|(k, _)| k.clone())
.collect()
}
pub fn direct_subclasses(&self, class: &str) -> Vec<String> {
self.classes
.keys()
.filter(|k| !k.starts_with("#<"))
.filter(|k| self.class_superclass(k).as_deref() == Some(class))
.cloned()
.collect()
}
pub fn all_descendants(&self, class: &str) -> Vec<String> {
let mut out = Vec::new();
let mut queue = self.direct_subclasses(class);
while let Some(c) = queue.pop() {
if out.contains(&c) {
continue;
}
queue.extend(self.direct_subclasses(&c));
out.push(c);
}
out
}
pub fn class_lt(&self, a: &str, b: &str) -> Option<bool> {
if a == b {
return Some(false);
}
if self.class_ancestry(a).iter().any(|c| c == b) {
return Some(true); }
if self.class_ancestry(b).iter().any(|c| c == a) {
return Some(false); }
None
}
pub fn is_builtin_class(&self, name: &str) -> bool {
if is_builtin_exception_name(name) && (!name.contains("::") || name.starts_with("Errno::"))
{
return true;
}
matches!(
name,
"Integer"
| "Float"
| "Numeric"
| "Rational"
| "Complex"
| "BigDecimal"
| "String"
| "Symbol"
| "Array"
| "Hash"
| "Range"
| "Proc"
| "Method"
| "UnboundMethod"
| "Object"
| "BasicObject"
| "Module"
| "Class"
| "Kernel"
| "Comparable"
| "Enumerable"
| "NilClass"
| "TrueClass"
| "FalseClass"
| "Set"
| "Struct"
| "Data"
| "Enumerator"
| "Enumerator::Lazy"
| "Enumerator::ArithmeticSequence"
| "Enumerator::Chain"
| "Enumerator::Yielder"
| "Time"
| "Date"
| "DateTime"
| "Math"
| "Errno"
| "JSON"
| "ERB"
| "Fiber"
| "Thread"
| "Mutex"
| "Thread::Mutex"
| "Monitor"
| "Queue"
| "Thread::Queue"
| "SizedQueue"
| "Thread::SizedQueue"
| "ConditionVariable"
| "Thread::ConditionVariable"
| "File"
| "Dir"
| "IO"
| "TCPServer"
| "TCPSocket"
| "SecureRandom"
| "Base64"
| "Digest"
| "Digest::MD5"
| "Digest::SHA1"
| "Digest::SHA256"
| "OpenStruct"
| "SQLite3"
| "SQLite3::Database"
| "Fiddle"
| "Fiddle::Handle"
| "Fiddle::Function"
| "Fiddle::Pointer"
| "StringIO"
| "Random"
| "Regexp"
| "MatchData"
| "Encoding"
| "Ractor"
| "Etc"
| "CGI"
| "Timeout"
| "GC"
| "ObjectSpace"
| "Warning"
| "Zlib"
| "Zlib::Deflate"
| "Zlib::Inflate"
| "Zlib::GzipWriter"
| "Zlib::GzipReader"
| "ENV"
)
}
pub fn classref_name(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(RObj::ClassRef(n)) => Some(n.clone()),
_ => None,
}
}
fn io_inspect_str(&self, id: u32) -> String {
match self.io_handles.get(id as usize) {
Some(IoCell::Stdout) => "#<IO:<STDOUT>>".to_string(),
Some(IoCell::Stderr) => "#<IO:<STDERR>>".to_string(),
Some(IoCell::Stdin) => "#<IO:<STDIN>>".to_string(),
Some(IoCell::File { file, path }) => {
if file.is_some() {
format!("#<File:{path}>")
} else {
format!("#<File:{path} (closed)>")
}
}
Some(IoCell::TcpListener { listener, local }) => {
if listener.is_some() {
format!("#<TCPServer:{local}>")
} else {
"#<TCPServer: (closed)>".to_string()
}
}
Some(IoCell::TcpStream { stream, peer, .. }) => {
if stream.is_some() {
format!("#<TCPSocket:{peer}>")
} else {
"#<TCPSocket: (closed)>".to_string()
}
}
None => "#<IO:(invalid)>".to_string(),
}
}
fn find_in_module(&self, module: &str, method: &str) -> Option<(MethodDef, String)> {
let name = if self.classes.contains_key(module) {
module.to_string()
} else {
self.resolve_class_alias(module, "")
};
let def = self.classes.get(&name)?;
for p in def.prepends.iter().rev() {
let rp = self.resolve_module_name(p, &name);
if let Some(r) = self.find_in_module(&rp, method) {
return Some(r);
}
}
if let Some(m) = def.methods.get(method) {
return Some((m.clone(), name.clone()));
}
if let Some(target) = self.method_aliases.get(&name).and_then(|a| a.get(method)) {
let target = target.clone();
if target != method {
if let Some(r) = self.find_in_module(&name, &target) {
return Some(r);
}
}
}
for i in def.includes.iter().rev() {
let ri = self.resolve_module_name(i, &name);
if let Some(r) = self.find_in_module(&ri, method) {
return Some(r);
}
}
None
}
fn builtin_superclass(name: &str) -> Option<String> {
match name {
"Integer" | "Float" | "Rational" | "Complex" => Some("Numeric".to_string()),
_ => None,
}
}
fn builtin_modules(name: &str) -> &'static [&'static str] {
match name {
"Array" | "Hash" | "Range" | "Set" | "Struct" | "Enumerator" => &["Enumerable"],
"Integer" | "Float" | "Rational" | "Numeric" | "String" | "Symbol" | "Time"
| "Date" | "DateTime" => &["Comparable"],
"Object" => &["Kernel"],
_ => &[],
}
}
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 {
if let Some(def) = self.classes.get(&name) {
for module in def.prepends.iter().rev() {
let m = self.resolve_module_name(module, &name);
if let Some(r) = self.find_in_module(&m, method) {
return Some(r);
}
}
if let Some(m) = def.methods.get(method) {
return Some((m.clone(), name.clone()));
}
if let Some(target) = self.method_aliases.get(&name).and_then(|m| m.get(method)) {
let target = target.clone();
if let Some(found) = self.find_method_owner(&name, &target) {
return Some(found);
}
}
for module in def.includes.iter().rev() {
let m = self.resolve_module_name(module, &name);
if let Some(r) = self.find_in_module(&m, method) {
return Some(r);
}
}
}
for module_name in Self::builtin_modules(&name) {
if self.classes.contains_key(*module_name) {
if let Some(r) = self.find_in_module(module_name, method) {
return Some(r);
}
}
}
cur = self
.classes
.get(&name)
.and_then(|d| d.superclass.clone())
.map(|s| self.resolve_class_alias(&s, &name))
.or_else(|| Self::builtin_superclass(&name))
.or_else(|| {
if self.classes.contains_key(&name) && name != "Object" && name != "BasicObject"
{
Some("Object".to_string())
} else {
None
}
});
}
None
}
pub fn find_method(&self, class: &str, method: &str) -> Option<MethodDef> {
self.find_method_owner(class, method).map(|(m, _)| m)
}
const PRIVATE_HOOKS: &[&str] = &[
"initialize",
"initialize_copy",
"initialize_clone",
"initialize_dup",
"respond_to_missing?",
];
pub fn instance_method_names(&self, class: &str, inherited: bool) -> Vec<String> {
self.instance_method_names_vis(
class,
inherited,
&[Visibility::Public, Visibility::Protected],
)
}
pub fn instance_method_names_vis(
&self,
class: &str,
inherited: bool,
want: &[Visibility],
) -> Vec<String> {
let chain: Vec<String> = if inherited {
self.class_ancestry(class)
} else {
vec![class.to_string()]
};
let mut out = Vec::new();
for n in &chain {
let vis_of = |k: &str| {
if Self::PRIVATE_HOOKS.contains(&k) {
Visibility::Private
} else {
self.own_visibility(n, k)
}
};
let take = |keys: Box<dyn Iterator<Item = &String> + '_>, out: &mut Vec<String>| {
for k in keys {
if !k.starts_with("__") && want.contains(&vis_of(k)) {
out.push(k.clone());
}
}
};
if let Some(def) = self.classes.get(n) {
take(Box::new(def.methods.keys()), &mut out);
}
if let Some(dm) = self.define_methods.get(n) {
take(Box::new(dm.keys()), &mut out);
}
if let Some((members, _)) = self.struct_defs.get(n) {
let writers = !self.data_classes.contains(n);
for m in members {
out.push(m.clone());
if writers {
out.push(format!("{m}="));
}
}
}
if let Some((_, id)) = Self::object_singleton_parts(n) {
let own = self
.singleton_methods
.get(&id)
.into_iter()
.flat_map(|m| m.keys())
.chain(
self.singleton_define_methods
.get(&id)
.into_iter()
.flat_map(|m| m.keys()),
)
.filter(|k| !self.is_extended_singleton(id, k));
take(Box::new(own), &mut out);
}
if n.starts_with("#<Class:") {
let attrs = self.attr_accessors.get(n).into_iter().flatten();
let accessors = attrs.flat_map(|(field, (r, w))| {
let reader = r.then(|| field.clone());
let writer = w.then(|| format!("{field}="));
reader.into_iter().chain(writer)
});
let mut owned: Vec<String> = accessors.collect();
if let Some(attached) = n.strip_prefix("#<Class:").and_then(|s| s.strip_suffix('>'))
{
if let Some(def) = self.classes.get(attached) {
owned.extend(def.class_methods.keys().cloned());
}
if let Some(m) = self.class_define_methods.get(attached) {
owned.extend(m.keys().cloned());
}
}
if want.contains(&Visibility::Public) {
out.extend(owned.into_iter().filter(|k| !k.starts_with("__")));
}
}
let builtin: &[&str] = match n.as_str() {
"Comparable" => crate::builtins::COMPARABLE_METHODS,
"Enumerable" => crate::builtins::ENUMERABLE_METHODS,
_ => &[],
};
if want.contains(&Visibility::Public) {
out.extend(builtin.iter().map(|k| (*k).to_string()));
}
}
dedup_keep_first(out)
}
pub fn own_visibility(&self, class: &str, method: &str) -> Visibility {
self.classes
.get(class)
.and_then(|d| d.visibility.get(method))
.copied()
.unwrap_or_default()
}
pub fn method_visibility(&self, class: &str, method: &str) -> Visibility {
if Self::PRIVATE_HOOKS.contains(&method) {
return Visibility::Private;
}
for n in self.class_ancestry(class) {
if let Some(def) = self.classes.get(&n) {
if let Some(v) = def.visibility.get(method) {
return *v;
}
if def.methods.contains_key(method) {
return Visibility::Public;
}
}
if self
.define_methods
.get(&n)
.is_some_and(|dm| dm.contains_key(method))
{
return Visibility::Public;
}
}
if method == "method_missing" {
Visibility::Private
} else {
Visibility::Public
}
}
pub fn set_method_visibility(&mut self, class: &str, method: &str, vis: Visibility) {
let def = self.classes_mut().entry(class.to_string()).or_default();
if vis == Visibility::Public {
def.visibility.shift_remove(method);
} else {
def.visibility.insert(method.to_string(), vis);
}
}
pub fn set_class_method_visibility(&mut self, class: &str, method: &str, vis: Visibility) {
let def = self.classes_mut().entry(class.to_string()).or_default();
if vis == Visibility::Public {
def.class_visibility.shift_remove(method);
} else {
def.class_visibility.insert(method.to_string(), vis);
}
}
pub fn class_method_visibility(&self, class: &str, method: &str) -> Visibility {
let mut cur = Some(class.to_string());
while let Some(name) = cur {
let Some(def) = self.classes.get(&name) else {
break;
};
if let Some(v) = def.class_visibility.get(method) {
return *v;
}
if def.class_methods.contains_key(method) {
return Visibility::Public;
}
cur = def.superclass.clone();
}
Visibility::Public
}
pub fn is_method_defined(&self, class: &str, method: &str) -> bool {
self.find_method_owner(class, method).is_some()
|| self.find_define_method(class, method).is_some()
}
pub fn alias_original(&self, class: &str, alias_name: &str) -> Option<String> {
for anc in self.class_ancestry(class) {
if let Some(orig) = self
.alias_originals
.get(&anc)
.and_then(|m| m.get(alias_name))
{
return Some(orig.clone());
}
}
None
}
pub fn find_super(
&self,
recv_class: &str,
def_class: &str,
method: &str,
) -> Option<(MethodDef, String)> {
let anc = self.class_ancestry(recv_class);
let start = anc
.iter()
.position(|c| c == def_class)
.map(|i| i + 1)
.unwrap_or(0);
for name in anc.iter().skip(start) {
if let Some(def) = self.classes.get(name) {
if let Some(m) = def.methods.get(method) {
return Some((m.clone(), name.clone()));
}
}
}
None
}
pub fn find_class_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.class_methods.get(method) {
return Some((m.clone(), name.clone()));
}
for module in def.extends.iter().rev() {
let resolved = self.resolve_module_name(module, &name);
if let Some((m, owner)) = self.find_in_module(&resolved, method) {
return Some((m, owner));
}
}
cur = def
.superclass
.clone()
.map(|s| self.resolve_class_alias(&s, &name));
}
None
}
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());
}
for module in def.extends.iter().rev() {
let resolved = self.resolve_module_name(module, &name);
if let Some((m, _)) = self.find_in_module(&resolved, method) {
return Some(m);
}
}
cur = def
.superclass
.clone()
.map(|s| self.resolve_class_alias(&s, &name));
}
None
}
fn module_self_ancestry(&self, module: &str) -> Vec<String> {
let mut out = Vec::new();
self.collect_module_ancestry(module, &mut out, 0);
out
}
fn collect_module_ancestry(&self, module: &str, out: &mut Vec<String>, depth: usize) {
if depth > 50 || out.iter().any(|m| m == module) {
return;
}
if let Some(def) = self.classes.get(module) {
let prepends = def.prepends.clone();
for p in prepends.iter().rev() {
let rp = self.resolve_module_name(p, module);
self.collect_module_ancestry(&rp, out, depth + 1);
}
out.push(module.to_string());
let includes = def.includes.clone();
for i in includes.iter().rev() {
let ri = self.resolve_module_name(i, module);
self.collect_module_ancestry(&ri, out, depth + 1);
}
} else {
out.push(module.to_string());
}
}
pub fn find_super_class_method(
&self,
recv_class: &str,
def_class: &str,
method: &str,
) -> Option<(MethodDef, String)> {
let mut sources: Vec<(String, bool)> = Vec::new(); let mut cur = Some(recv_class.to_string());
while let Some(name) = cur {
let Some(def) = self.classes.get(&name) else {
break;
};
sources.push((name.clone(), false));
for module in def.extends.iter().rev() {
let resolved = self.resolve_module_name(module, &name);
for anc in self.module_self_ancestry(&resolved) {
sources.push((anc, true));
}
}
cur = def
.superclass
.clone()
.map(|s| self.resolve_class_alias(&s, &name));
}
{
let mut seen = std::collections::HashSet::new();
sources.retain(|(n, _)| seen.insert(n.clone()));
}
let pos = sources.iter().position(|(n, _)| n == def_class)?;
let start = pos + 1;
for (name, is_module) in sources.iter().skip(start) {
if *is_module {
if let Some((m, owner)) = self.find_in_module(name, method) {
return Some((m, owner));
}
} else if let Some(def) = self.classes.get(name) {
if let Some(m) = def.class_methods.get(method) {
return Some((m.clone(), name.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_lookup(&self, obj: &Value, name: &str) -> Option<Value> {
match self.obj(obj) {
Some(RObj::Object { ivars, .. }) => ivars.get(name).cloned(),
_ => None,
}
}
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),
Some(RObj::ClassRef(cls)) => self
.class_ivars
.get(cls)
.and_then(|m| m.get(name))
.cloned()
.unwrap_or(Value::Undef),
_ => match obj {
Value::Obj(i) => self
.obj_ivars
.get(i)
.and_then(|m| m.get(name))
.cloned()
.unwrap_or(Value::Undef),
_ => Value::Undef,
},
}
}
pub fn set_ivar_of(&mut self, obj: &Value, name: &str, v: Value) {
let cls = match self.obj(obj) {
Some(RObj::ClassRef(cls)) => Some(cls.clone()),
_ => None,
};
if let Some(cls) = cls {
self.class_ivars
.entry(cls)
.or_default()
.insert(name.to_string(), v);
return;
}
if let Value::Obj(i) = obj {
match self.heap.get_mut(*i as usize) {
Some(RObj::Object { ivars, .. }) => {
ivars.insert(name.to_string(), v);
}
_ => {
self.obj_ivars
.entry(*i)
.or_default()
.insert(name.to_string(), v);
}
}
}
}
pub fn remove_ivar_of(&mut self, obj: &Value, name: &str) -> Option<Value> {
let Value::Obj(i) = obj else { return None };
match self.heap.get_mut(*i as usize) {
Some(RObj::Object { ivars, .. }) => ivars.shift_remove(name),
Some(RObj::ClassRef(cls)) => {
let cls = cls.clone();
self.class_ivars.get_mut(&cls)?.shift_remove(name)
}
_ => self.obj_ivars.get_mut(i)?.shift_remove(name),
}
}
pub fn ivar_names(&self, obj: &Value) -> Vec<String> {
match self.obj(obj) {
Some(RObj::Object { ivars, .. }) => ivars.keys().map(|k| format!("@{k}")).collect(),
Some(RObj::ClassRef(cls)) => self
.class_ivars
.get(cls)
.map(|m| m.keys().map(|k| format!("@{k}")).collect())
.unwrap_or_default(),
_ => match obj {
Value::Obj(i) => self
.obj_ivars
.get(i)
.map(|m| m.keys().map(|k| format!("@{k}")).collect())
.unwrap_or_default(),
_ => Vec::new(),
},
}
}
pub fn pack_associates(&self, v: &Value) -> Option<Vec<Value>> {
match v {
Value::Obj(id) => self.pack_associates.get(id).cloned(),
_ => None,
}
}
pub fn mark_chilled(&mut self, v: &Value) {
if let Value::Obj(id) = v {
let (word, bit) = (*id as usize / 64, *id % 64);
if self.chilled.len() <= word {
self.chilled.resize(word + 1, 0);
}
self.chilled[word] |= 1 << bit;
}
}
pub fn mark_chilled_symbol(&mut self, v: &Value, sym: &str) {
if let Value::Obj(id) = v {
self.chilled_symbol_strings.insert(*id, sym.to_string());
}
}
pub fn is_chilled(&self, v: &Value) -> bool {
self.chill_of(v).is_some()
}
pub fn chill_of(&self, v: &Value) -> Option<Option<String>> {
let Value::Obj(id) = v else {
return None;
};
if let Some(sym) = self.chilled_symbol_strings.get(id) {
return Some(Some(sym.clone()));
}
self.chilled
.get(*id as usize / 64)
.is_some_and(|w| w & (1 << (id % 64)) != 0)
.then_some(None)
}
pub fn unchill(&mut self, v: &Value) -> Option<Option<String>> {
let was = self.chill_of(v)?;
if let Value::Obj(id) = v {
match was {
Some(_) => {
self.chilled_symbol_strings.remove(id);
}
None => self.chilled[*id as usize / 64] &= !(1 << (id % 64)),
}
}
Some(was)
}
pub fn copy_chill(&mut self, from: &Value, to: &Value) {
match self.chill_of(from) {
Some(Some(sym)) => self.mark_chilled_symbol(to, &sym),
Some(None) => self.mark_chilled(to),
None => {}
}
}
pub fn symbol_name_string(&mut self, sym: &str) -> Value {
if let Some(v) = self.symbol_names.get(sym) {
return v.clone();
}
let v = self.new_string(sym.to_string());
self.freeze_value(&v);
self.symbol_names.insert(sym.to_string(), v.clone());
v
}
pub fn set_pack_associates(&mut self, v: &Value, associates: Vec<Value>) {
if let Value::Obj(id) = v {
self.pack_associates.insert(*id, associates);
}
}
pub fn bind_params(
&mut self,
params: &[String],
shape: PositionalShape,
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 self.is_kwargs(v) && matches!(self.obj(v), Some(RObj::Hash { .. })) => {
(&args[..args.len() - 1], self.as_hash(v))
}
_ => (args, None),
}
} else {
(args, None)
};
let PositionalShape { splat, opt, post } = shape;
let mut locals = IndexMap::new();
let n = positional.len();
let named = params.len() - splat.is_some() as usize;
let post = post.min(named);
let opt = opt.min(named - post);
let pre = named - post - opt;
let opt_given = n.saturating_sub(pre + post).min(opt);
let tail_start = n.saturating_sub(post).max(pre + opt_given);
let positional_params: Vec<&String> = params
.iter()
.enumerate()
.filter(|(i, _)| Some(*i) != splat)
.map(|(_, p)| p)
.collect();
for (i, p) in positional_params.iter().enumerate() {
let arg = if i < pre + opt {
(i < pre + opt_given).then(|| positional.get(i)).flatten()
} else {
positional.get(tail_start + (i - pre - opt))
};
if let Some(v) = arg {
locals.insert((*p).clone(), v.clone());
}
}
if let Some(si) = splat {
let rest: Vec<Value> = positional
.get(pre + opt_given..tail_start)
.map(|s| s.to_vec())
.unwrap_or_default();
let arr = self.new_array(rest);
locals.insert(params[si].clone(), arr);
}
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(&mut self) -> (Value, Option<String>, Option<String>, Vec<Value>) {
let s = self.cur_scope();
let self_obj = s.self_obj.clone();
let method_name = s.method_name.clone();
let def_class = s.def_class.clone();
(self_obj, method_name, def_class, self.zsuper_args())
}
fn zsuper_args(&mut self) -> Vec<Value> {
let s = self.cur_scope();
let (Some(method), Some(def_class)) = (s.method_name.clone(), s.def_class.clone()) else {
return self
.frames
.last()
.map(|f| f.args.clone())
.unwrap_or_default();
};
let Some(def) = self.find_method(&def_class, &method) else {
return self
.frames
.last()
.map(|f| f.args.clone())
.unwrap_or_default();
};
let mut out = Vec::new();
for (i, p) in def.params.iter().enumerate() {
let v = self.get_local(p);
if def.splat == Some(i) {
match self.as_array(&v) {
Some(items) => out.extend(items),
None => out.push(v),
}
} else {
out.push(v);
}
}
if !def.kwparams.is_empty() || def.kwsplat.is_some() {
let mut map: IndexMap<RKey, Value> = IndexMap::new();
for kw in &def.kwparams {
let v = self.get_local(kw);
map.insert(RKey::Sym(kw.clone()), v);
}
if let Some(ks) = &def.kwsplat {
let hv = self.get_local(ks);
if let Some(h) = self.as_hash(&hv) {
for (k, val) in h {
map.insert(k, val);
}
}
}
if !map.is_empty() {
let hash = self.new_hash(map);
out.push(hash);
}
}
out
}
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 has_pending_exc(&self) -> bool {
self.pending_exc.is_some()
}
fn innermost_context(&self) -> String {
let blocks = BLOCK_CTX.with(|s| s.borrow().len());
self.context_at(self.frames.len(), blocks)
}
pub fn context_at(&self, frames: usize, blocks: usize) -> String {
let block = BLOCK_CTX.with(|s| {
let s = s.borrow();
blocks.checked_sub(1).and_then(|i| s.get(i).cloned())
});
if let Some((depth, label)) = block {
if depth >= frames {
return label;
}
}
let frame = frames.checked_sub(1).and_then(|i| self.frames.get(i));
self.scope_context(frame.map(|f| &f.scope))
}
pub fn builtin_frame_label(&self, recv: &Value, name: &str) -> String {
if let Some(RObj::ClassRef(cls)) = self.obj(recv) {
return format!("{cls}.{name}");
}
let owner = self
.builtin_owner(recv, name)
.map(str::to_string)
.unwrap_or_else(|| self.class_of(recv));
format!("{owner}#{name}")
}
fn scope_context(&self, scope: Option<&Scope>) -> String {
match scope.and_then(|s| s.method_name.as_ref().map(|m| (s, m))) {
Some((s, m)) if m.starts_with("__class_body__") => {
let cls = s.def_class.as_deref().unwrap_or("Object");
let short = cls.rsplit("::").next().unwrap_or(cls);
let kind = if self.is_module_name(cls) {
"module"
} else {
"class"
};
format!("<{kind}:{short}>")
}
Some((s, m)) => {
let cls = s.def_class.clone().unwrap_or_else(|| "Object".into());
let sep = if matches!(self.obj(&s.self_obj), Some(RObj::ClassRef(_))) {
'.'
} else {
'#'
};
format!("{cls}{sep}{m}")
}
None if scope.is_some_and(|s| self.required_tops.contains(&s.frame_id)) => {
"<top (required)>".into()
}
None => "<main>".into(),
}
}
fn block_context(&self, scope: &Scope, depth: u32) -> String {
let inner = self.scope_context(Some(scope));
if depth <= 1 {
format!("block in {inner}")
} else {
format!("block ({depth} levels) in {inner}")
}
}
pub fn exc_backtrace(&self, exc: &Value) -> Option<Vec<String>> {
match exc {
Value::Obj(id) => self.exc_backtraces.get(id).cloned(),
_ => None,
}
}
pub fn seal_backtrace(&mut self, exc: &Value) {
if let Value::Obj(id) = exc {
self.sealed_backtraces.insert(*id);
}
}
pub fn backtrace_sealed(&self, exc: &Value) -> bool {
matches!(exc, Value::Obj(id) if self.sealed_backtraces.contains(id))
}
pub fn exc_backtrace_locations(&self, exc: &Value) -> Option<Value> {
match exc {
Value::Obj(id) => self.exc_backtrace_locations.get(id).cloned(),
_ => None,
}
}
pub fn set_exc_backtrace_locations(&mut self, exc: &Value, locs: Option<Value>) {
if let Value::Obj(id) = exc {
match locs {
Some(v) => {
self.exc_backtrace_locations.insert(*id, v);
}
None => {
self.exc_backtrace_locations.remove(id);
}
}
}
}
pub fn is_string_backtrace(&self, exc: &Value) -> bool {
matches!(exc, Value::Obj(id) if self.string_backtraces.contains(id))
}
pub fn set_string_backtrace(&mut self, exc: &Value, strings: bool) {
if let Value::Obj(id) = exc {
if strings {
self.string_backtraces.insert(*id);
} else {
self.string_backtraces.remove(id);
}
}
}
pub fn set_exc_backtrace(&mut self, exc: &Value, frames: Option<Vec<String>>) {
if let Value::Obj(id) = exc {
match frames {
Some(f) => {
self.exc_backtraces.insert(*id, f);
self.sealed_backtraces.insert(*id);
}
None => {
self.exc_backtraces.shift_remove(id);
self.sealed_backtraces.remove(id);
}
}
}
}
pub fn record_backtrace_frame(&mut self, src: &str, line: u32) {
let Some(Value::Obj(id)) = self.pending_exc else {
return;
};
if self.sealed_backtraces.contains(&id) {
return;
}
let ctx = self.innermost_context();
self.exc_backtraces
.entry(id)
.or_default()
.push(format!("{src}:{line}:in '{ctx}'"));
}
pub fn pending_exc_needs_backtrace(&self) -> bool {
match self.pending_exc {
Some(Value::Obj(id)) => {
!self.sealed_backtraces.contains(&id) && !self.exc_backtraces.contains_key(&id)
}
_ => false,
}
}
pub fn record_raise_backtrace(&mut self, stack: Vec<LiveFrame>) {
let Some(Value::Obj(id)) = self.pending_exc else {
return;
};
let frames = stack
.into_iter()
.map(|f| format!("{}:{}:in '{}'", f.path, f.line, f.label))
.collect();
self.exc_backtraces.insert(id, frames);
self.sealed_backtraces.insert(id);
}
pub fn set_string_encoding(&mut self, v: &Value, name: &'static str) {
if let Some(RObj::Str(s)) = self.obj_mut(v) {
s.set_encoding(name);
self.byte_strings = true;
}
}
pub fn clear_string_encoding(&mut self, v: &Value) {
if let Some(RObj::Str(s)) = self.obj_mut(v) {
s.clear_encoding();
}
}
pub fn string_encoding(&self, v: &Value) -> Option<&'static str> {
self.rstr(v).and_then(RStr::encoding)
}
pub fn encoding_value(&mut self, info: &'static crate::encoding_table::EncodingInfo) -> Value {
if let Some(v) = self.encoding_objects.get(info.name) {
return v.clone();
}
let enc = self.new_object("Encoding");
let nm = self.new_string(info.name.to_string());
self.set_ivar_of(&enc, "name", nm);
self.encoding_objects.insert(info.name, enc.clone());
enc
}
pub fn encoding_loaded(&self, info: &crate::encoding_table::EncodingInfo) -> bool {
info.preloaded || self.loaded_encodings.contains(info.name)
}
pub fn load_encoding(&mut self, info: &'static crate::encoding_table::EncodingInfo) {
self.loaded_encodings.insert(info.name);
}
pub fn mark_binary_string(&mut self, v: &Value) {
self.set_string_encoding(v, "ASCII-8BIT");
}
pub fn unmark_binary_string(&mut self, v: &Value) {
self.clear_string_encoding(v);
}
pub fn string_bytes(&self, v: &Value) -> Vec<u8> {
self.str_bytes(v).unwrap_or_default().to_vec()
}
pub fn new_rstr(&mut self, content: RStr) -> Value {
self.byte_strings |= content.encoding().is_some();
self.alloc(RObj::Str(content))
}
pub fn new_byte_string(&mut self, bytes: Vec<u8>, enc: &'static str) -> Value {
if enc == BROKEN_UTF8 {
return self.new_utf8_from_bytes(bytes);
}
self.new_rstr(RStr::Bytes(bytes, enc))
}
pub fn new_utf8_from_bytes(&mut self, bytes: Vec<u8>) -> Value {
self.new_rstr(RStr::from_utf8(bytes))
}
pub fn set_rstr(&mut self, v: &Value, content: RStr) {
let byte_string = content.encoding().is_some();
if let Some(RObj::Str(slot)) = self.obj_mut(v) {
*slot = content;
}
self.byte_strings |= byte_string;
}
pub fn set_str_as(&mut self, v: &Value, view: String, enc: Option<&'static str>) {
let content = match enc {
None => RStr::Text(view),
Some(BROKEN_UTF8) => RStr::from_utf8(crate::rstr::latin1_to_bytes(&view)),
Some(e) => RStr::Bytes(crate::rstr::latin1_to_bytes(&view), e),
};
self.set_rstr(v, content);
}
pub fn set_utf8_bytes(&mut self, v: &Value, bytes: Vec<u8>) {
self.set_rstr(v, RStr::from_utf8(bytes));
}
pub fn any_tagged_strings(&self) -> bool {
self.byte_strings
}
pub fn prepare_binary_regexp(
&mut self,
re: &Value,
str_enc: &'static str,
ascii: bool,
) -> bool {
let Value::Obj(id) = re else {
return false;
};
let cur = self
.binary_regexp_encodings
.get(id)
.copied()
.unwrap_or("US-ASCII");
if cur == str_enc || (ascii && cur == "US-ASCII") {
return false;
}
self.binary_regexp_encodings.insert(*id, str_enc);
str_enc != "ASCII-8BIT" && !ascii
}
pub fn any_binary_regexps(&self) -> bool {
self.binary_regexps
}
pub fn is_broken_utf8(&self, v: &Value) -> bool {
self.string_encoding(v) == Some(BROKEN_UTF8)
}
fn utf8_labelled(&self, v: &Value) -> bool {
matches!(self.string_encoding(v), None | Some(BROKEN_UTF8))
}
pub fn is_binary_string(&self, v: &Value) -> bool {
self.string_encoding(v) == Some("ASCII-8BIT")
}
pub fn inherit_string_encoding(&mut self, out: &Value, src: &Value, src_ascii: bool) {
self.inherit_string_encoding_with(out, src, src_ascii, None)
}
pub fn check_encoding_compatible(&mut self, a: &Value, b: &Value) -> Result<(), String> {
let a_wide = self.as_str(a).map(|s| !s.is_ascii()).unwrap_or(false);
let b_wide = self.as_str(b).map(|s| !s.is_ascii()).unwrap_or(false);
if !(a_wide && b_wide) {
return Ok(());
}
let (ae, be) = (self.string_encoding(a), self.string_encoding(b));
if ae == be {
return Ok(());
}
let name = |e: Option<&'static str>| match e {
Some("ASCII-8BIT") => "BINARY (ASCII-8BIT)".to_string(),
Some(n) => n.to_string(),
None => "UTF-8".to_string(),
};
Err(crate::builtins::raise_exc(
"Encoding::CompatibilityError",
&format!(
"incompatible character encodings: {} and {}",
name(ae),
name(be)
),
))
}
pub fn inherit_string_encoding_with(
&mut self,
out: &Value,
src: &Value,
src_ascii: bool,
other: Option<&Value>,
) {
let out_ascii = self.as_str(out).map(|s| s.is_ascii()).unwrap_or(true);
match self.decide_string_encoding(out_ascii, src, src_ascii, other) {
Some(enc) => self.set_string_encoding(out, enc),
None => self.clear_string_encoding(out),
}
}
pub fn decide_string_encoding(
&self,
out_ascii: bool,
src: &Value,
src_ascii: bool,
other: Option<&Value>,
) -> Option<&'static str> {
if !src_ascii {
self.string_encoding(src)
} else {
let other_decides = match other {
Some(o) => !self.as_str(o).map(|s| s.is_ascii()).unwrap_or(true),
None => !out_ascii,
};
match (other_decides, other) {
(true, Some(o)) => self.string_encoding(o),
(true, None) => None,
(false, _) => self.string_encoding(src),
}
}
}
pub fn pending_system_exit(&self) -> Option<i32> {
let exc = self.pending_exc.clone()?;
(self.class_of(&exc) == "SystemExit").then(|| match self.ivar_of(&exc, "status") {
Value::Int(n) => n as i32,
_ => 0,
})
}
pub fn register_at_exit(&mut self, p: Value) {
self.at_exit_procs.push(p);
}
pub fn format_uncaught(&mut self) -> Option<String> {
self.format_uncaught_as(None)
}
pub fn format_uncaught_as(&mut self, detailed: Option<String>) -> Option<String> {
let exc = self.pending_exc.take()?;
let class = self.class_of(&exc).to_string();
let msg = match self.ivar_of(&exc, "message") {
Value::Undef => class.clone(),
m => self.to_s(&m),
};
let detailed = detailed.unwrap_or_else(|| format!("{msg} ({class})"));
let frames: Vec<String> = match &exc {
Value::Obj(id) => self.exc_backtraces.get(id).cloned().unwrap_or_default(),
_ => Vec::new(),
};
let mut out = match frames.split_first() {
Some((first, _)) => format!("{first}: {detailed}"),
None => detailed,
};
for f in frames.iter().skip(1) {
out.push('\n');
out.push('\t');
out.push_str("from ");
out.push_str(f);
}
Some(out)
}
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 is_exception_class(&self, class: &str) -> bool {
fn builtin(n: &str) -> bool {
n.ends_with("Error")
|| matches!(
n,
"Exception" | "StopIteration" | "SystemExit" | "SignalException" | "Interrupt"
)
|| n.starts_with("Errno::")
}
let mut cur = Some(class.to_string());
while let Some(name) = cur {
if builtin(&name) {
return true;
}
cur = self.superclass_of(&name);
}
false
}
pub fn exc_matches(&self, exc_class: &str, rescued: &str) -> bool {
if exc_class == rescued || rescued == "Exception" {
return true;
}
if !self.classes.contains_key(exc_class) && !is_builtin_exception_name(exc_class) {
return rescued == "StandardError";
}
self.class_ancestry(exc_class).iter().any(|a| a == rescued)
}
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 proc_sig(&self, id: usize) -> ProcSig {
let p = &self.procs[id];
ProcSig {
params: p.params.clone(),
splat: p.splat,
arity: p.arity.clone(),
}
}
pub fn truthy(&self, v: &Value) -> bool {
!matches!(v, Value::Undef | Value::Bool(false))
}
fn cycle_marker(&self, v: &Value) -> Option<(u32, String)> {
let Value::Obj(id) = v else { return None };
let marker = match self.obj(v)? {
RObj::Array(_) => "[...]".to_string(),
RObj::Hash { .. } => "{...}".to_string(),
RObj::Set(_) => "Set[...]".to_string(),
RObj::Object { class, .. } if self.is_struct_class(class) => format!(
"#<{} {class}:...>",
if self.is_data_class(class) {
"data"
} else {
"struct"
}
),
RObj::Object { class, .. } if self.is_plain_object(class) => {
format!("#<{class}:{} ...>", self.object_address(v))
}
_ => return None,
};
Some((*id, marker))
}
pub(crate) fn is_plain_object(&self, class: &str) -> bool {
(class == "Object" || self.classes.contains_key(class))
&& !self.is_struct_class(class)
&& !self.is_exception_class(class)
&& !matches!(class, "Encoding" | "OpenStruct")
}
pub(crate) fn object_address(&self, v: &Value) -> String {
let id = match v {
Value::Obj(id) => *id as u64,
_ => 0,
};
format!("0x{:016x}", Self::heap_address(id as u32))
}
pub fn to_s(&mut self, v: &Value) -> String {
let Some((id, marker)) = self.cycle_marker(v) else {
return self.uncycled_to_s(v);
};
if self.rendering.contains(&id) {
return marker;
}
self.rendering.push(id);
let out = self.uncycled_to_s(v);
self.rendering.pop();
out
}
fn uncycled_to_s(&mut self, v: &Value) -> String {
if is_main(v) {
return "main".to_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.view().into_owned(),
Some(RObj::Symbol(s)) => s,
Some(RObj::BigInt(b)) => b.to_string(),
Some(RObj::Rational(r)) => format!("{}/{}", r.numer(), r.denom()),
Some(RObj::Complex { re, im }) => self.complex_to_s(&re, &im),
Some(RObj::Set(map)) => {
let items: Vec<Value> = map.values().cloned().collect();
let inner: Vec<String> = items.iter().map(|v| self.inspect(v)).collect();
format!("Set[{}]", inner.join(", "))
}
Some(RObj::Time(t)) => t.to_s(),
Some(RObj::ObjRange { lo, hi, exclusive }) => format!(
"{}{}{}",
self.to_s(&lo),
if exclusive { "..." } else { ".." },
self.to_s(&hi)
),
Some(RObj::Date { days }) => self.date_to_s(days),
Some(RObj::DateTime { secs }) => self.datetime_to_s(secs),
Some(RObj::Db { .. }) => "#<SQLite3::Database>".to_string(),
Some(RObj::FiddleHandle { id }) => format!("#<Fiddle::Handle id={id}>"),
Some(RObj::FiddleFunc { addr, .. }) => {
format!("#<Fiddle::Function ptr=0x{addr:x}>")
}
Some(RObj::FiddlePtr { addr, size, .. }) => fiddle_read_cstr_or_len(addr, size),
Some(RObj::Lazy { ops, origin, .. }) => {
let mut s = format!("#<Enumerator::Lazy: {}>", self.inspect(&origin));
for op in &ops {
s = format!("#<Enumerator::Lazy: {s}:{}>", self.lazy_op_tag(op));
}
s
}
Some(RObj::Enumerator {
buf,
method,
source,
..
}) => {
if let Some(l) = match v {
Value::Obj(id) => self.enum_labels.get(id),
_ => None,
} {
return l.clone();
}
let recv = match source {
Some(s) => self.inspect(&s),
None => self.inspect_array(&buf),
};
format!("#<Enumerator: {recv}:{method}>")
}
Some(RObj::ArithSeq(s)) => s.desc.clone(),
Some(RObj::EnumChain(parts)) => {
format!("#<Enumerator::Chain: {}>", self.inspect_array(&parts))
}
Some(RObj::Generator { label: Some(l), .. }) => l,
Some(RObj::Generator { .. }) => format!(
"#<Enumerator: #<Enumerator::Generator:{}>:each>",
self.object_address(v)
),
Some(RObj::Yielder { .. }) | Some(RObj::FiberYielder) => {
"#<Enumerator::Yielder>".to_string()
}
Some(RObj::Fiber { .. }) => "#<Fiber (created)>".to_string(),
Some(RObj::Binding { .. }) => format!("#<Binding:{}>", self.object_address(v)),
Some(RObj::Thread { id }) => {
let alive = self
.threads
.get(id as usize)
.map(|t| !t.done.load(std::sync::atomic::Ordering::SeqCst))
.unwrap_or(false);
format!("#<Thread:{id:#x} {}>", if alive { "run" } else { "dead" })
}
Some(RObj::IoHandle { id }) => self.io_inspect_str(id),
Some(RObj::Range { lo, hi, exclusive }) => {
let lo = if lo == RANGE_BEGINLESS {
String::new()
} else {
lo.to_string()
};
let hi = if hi == RANGE_ENDLESS {
String::new()
} else {
hi.to_string()
};
format!("{lo}{}{hi}", if exclusive { "..." } else { ".." })
}
Some(RObj::FloatRange { lo, hi, exclusive }) => format!(
"{}{}{}",
fmt_float(lo),
if exclusive { "..." } else { ".." },
fmt_float(hi)
),
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 { is_lambda, .. }) => {
let at = match self.proc_source_location(v) {
Some((file, line)) => format!(" {file}:{line}"),
None => String::new(),
};
let lambda = if is_lambda { " (lambda)" } else { "" };
format!("#<Proc:{}{at}{lambda}>", self.object_address(v))
}
Some(RObj::SymProc(s)) => {
let sym = if plain_symbol_name(&s) {
format!(":{s}")
} else {
format!(":{}", inspect_string(&s))
};
format!("#<Proc:{}(&{sym}) (lambda)>", self.object_address(v))
}
Some(RObj::CycleProc(_))
| Some(RObj::RaiseProc { .. })
| Some(RObj::SeqProc(_))
| Some(RObj::StepProc { .. })
| Some(RObj::ProduceProc { .. })
| Some(RObj::DeriveProc { .. }) => format!("#<Proc:{}>", self.object_address(v)),
Some(RObj::Method {
recv,
name,
unbound,
..
}) => self.method_inspect(&recv, &name, unbound),
Some(RObj::Regexp { source, flags, .. }) => {
let on: String = "mix".chars().filter(|c| flags.contains(*c)).collect();
let off: String = "mix".chars().filter(|c| !flags.contains(*c)).collect();
format!("(?{on}-{off}:{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 }) => {
if class == "Encoding" {
return match ivars.get("name") {
Some(n) => self.to_s(&n.clone()),
None => "#<Encoding>".to_string(),
};
}
if class == "OpenStruct" {
let body: Vec<String> = ivars
.iter()
.map(|(k, val)| format!("{k}={}", self.inspect(&val.clone())))
.collect();
return if body.is_empty() {
"#<OpenStruct>".to_string()
} else {
format!("#<OpenStruct {}>", body.join(", "))
};
}
if let Some((members, _)) = self.struct_def(&class) {
let parts: Vec<String> = members
.iter()
.map(|m| {
let v = ivars.get(m).cloned().unwrap_or(Value::Undef);
format!("{m}={}", self.inspect(&v))
})
.collect();
self.struct_inspect(&class, &parts)
} else if self.is_exception_class(&class) {
match ivars.get("message") {
Some(Value::Undef) | None => class,
Some(m) => self.to_s(&m.clone()),
}
} else if self.is_plain_object(&class) {
format!("#<{class}:{}>", self.object_address(v))
} else {
format!("#<{class}>")
}
}
None => "nil".to_string(),
},
_ => String::new(),
}
}
pub fn inspect(&mut self, v: &Value) -> String {
let Some((id, marker)) = self.cycle_marker(v) else {
return self.inspect_uncycled(v);
};
if self.rendering.contains(&id) {
return marker;
}
self.rendering.push(id);
let out = self.inspect_uncycled(v);
self.rendering.pop();
out
}
fn inspect_uncycled(&mut self, v: &Value) -> String {
if is_main(v) {
return "main".to_string();
}
match v {
Value::Undef => "nil".to_string(),
Value::Str(s) => inspect_string(s),
Value::Obj(_) => match self.obj(v).cloned() {
Some(RObj::Str(RStr::Text(s))) => inspect_string(&s),
Some(RObj::Str(RStr::Bytes(b, BROKEN_UTF8))) => inspect_broken_utf8(&b),
Some(RObj::Str(s)) => inspect_string_bytes(&s.view()),
Some(RObj::Symbol(s)) => {
if plain_symbol_name(&s) {
format!(":{s}")
} else {
format!(":{}", inspect_string(&s))
}
}
Some(RObj::BigInt(b)) => b.to_string(),
Some(RObj::Rational(r)) => format!("({}/{})", r.numer(), r.denom()),
Some(RObj::Complex { re, im }) => {
let re_s = self.inspect(&re);
let negative = self.as_f64(&im).is_some_and(|f| f < 0.0);
let mag_v = if negative {
self.num_op(NumOp::Sub, &Value::Int(0), &im)
.unwrap_or_else(|_| im.clone())
} else {
im.clone()
};
let (sign, mag) = (if negative { "-" } else { "+" }, self.inspect(&mag_v));
let unit = if mag.ends_with(|c: char| c.is_ascii_digit()) {
"i"
} else {
"*i"
};
format!("({re_s}{sign}{mag}{unit})")
}
Some(RObj::Set(map)) => {
let inner: Vec<String> = map.values().map(|v| self.inspect(v)).collect();
format!("Set[{}]", inner.join(", "))
}
Some(RObj::Array(items)) => self.inspect_array(&items),
Some(RObj::Hash { map, .. }) => self.inspect_hash(&map),
Some(RObj::Regexp { source, flags, .. }) => {
let f: String = "mixn".chars().filter(|c| flags.contains(*c)).collect();
format!("/{source}/{f}")
}
Some(RObj::Time(t)) => t.inspect(),
Some(RObj::Date { days }) => self.date_inspect(days),
Some(RObj::DateTime { secs }) => self.datetime_inspect(secs),
Some(RObj::Db { .. }) => "#<SQLite3::Database>".to_string(),
Some(RObj::FiddleHandle { id }) => format!("#<Fiddle::Handle id={id}>"),
Some(RObj::FiddleFunc { addr, .. }) => {
format!("#<Fiddle::Function ptr=0x{addr:x}>")
}
Some(RObj::FiddlePtr { addr, size, .. }) => {
format!("#<Fiddle::Pointer ptr=0x{addr:x} size={size}>")
}
Some(RObj::StrRange { lo, hi, exclusive }) => {
format!("{lo:?}{}{hi:?}", if exclusive { "..." } else { ".." })
}
Some(RObj::ObjRange { lo, hi, exclusive }) => {
let both_nil = matches!((&lo, &hi), (Value::Undef, Value::Undef));
let lo_s = match lo {
Value::Undef if !both_nil => String::new(),
_ => self.inspect(&lo),
};
let hi_s = match hi {
Value::Undef if !both_nil => String::new(),
_ => self.inspect(&hi),
};
format!("{lo_s}{}{hi_s}", if exclusive { "..." } else { ".." })
}
Some(RObj::MatchData { groups, regexp, .. }) if self.as_str(®exp).is_some() => {
let whole = groups.first().and_then(|g| g.clone()).unwrap_or_default();
format!("#<MatchData: {whole}>")
}
Some(RObj::MatchData { groups, names, .. }) => {
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) {
let label = names
.iter()
.rev()
.find(|(_, idx)| *idx == i)
.map_or_else(|| i.to_string(), |(n, _)| n.clone());
match g {
Some(s) => out.push_str(&format!(" {label}:{}", inspect_string(s))),
None => out.push_str(&format!(" {label}:nil")),
}
}
out.push('>');
out
}
Some(RObj::Object { class, ivars }) if self.is_exception_class(&class) => {
let msg = match ivars.get("message") {
Some(Value::Undef) | None => class.clone(),
Some(m) => self.to_s(&m.clone()),
};
if msg.is_empty() {
class
} else if msg.contains('\n') {
format!("#<{class}:{}>", inspect_string(&msg))
} else {
format!("#<{class}: {msg}>")
}
}
Some(RObj::Object { class, ivars }) if class == "Encoding" => {
let name = ivars
.get("name")
.map(|n| self.to_s(&n.clone()))
.unwrap_or_default();
let shown = if name == "ASCII-8BIT" {
"BINARY (ASCII-8BIT)"
} else {
&name
};
let (dummy, autoload) = match encoding_info(&name) {
Some(info) => (info.dummy, !self.encoding_loaded(info)),
None => (false, false),
};
format!(
"#<Encoding:{shown}{}{}>",
if dummy { " (dummy)" } else { "" },
if autoload { " (autoload)" } else { "" }
)
}
Some(RObj::Object { class, ivars }) if class == "OpenStruct" => {
let body: Vec<String> = ivars
.iter()
.map(|(k, val)| format!("{k}={}", self.inspect(&val.clone())))
.collect();
if body.is_empty() {
"#<OpenStruct>".to_string()
} else {
format!("#<OpenStruct {}>", body.join(", "))
}
}
Some(RObj::Object { class, ivars }) if self.is_plain_object(&class) => {
let mut out = format!("#<{class}:{}", self.object_address(v));
for (i, (k, val)) in ivars.iter().enumerate() {
out.push_str(if i == 0 { " " } else { ", " });
out.push_str(&format!("@{k}={}", self.inspect(&val.clone())));
}
out.push('>');
out
}
Some(RObj::ClassRef(n))
if self.struct_def(&n).is_some_and(|(_, k)| k == Some(true)) =>
{
format!("{n}(keyword_init: true)")
}
_ => self.uncycled_to_s(v),
},
_ => self.uncycled_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);
format!("{}{vs}", self.hash_entry_prefix(k))
})
.collect();
format!("{{{}}}", parts.join(", "))
}
pub fn hash_entry_prefix(&mut self, k: &RKey) -> String {
match k {
RKey::Sym(s) if !symbol_key_needs_quote(s) => format!("{s}: "),
RKey::Sym(s) => format!("{}: ", inspect_string(s)),
_ => format!("{} => ", self.key_inspect(k)),
}
}
pub fn key_inspect(&mut self, k: &RKey) -> String {
match k {
RKey::Int(n) => n.to_string(),
RKey::Str(s) => inspect_string(s),
RKey::ByteStr(s, enc) => {
let v = self.key_to_value(&RKey::ByteStr(s.clone(), enc));
self.inspect(&v)
}
RKey::Sym(s) if plain_symbol_name(s) => format!(":{s}"),
RKey::Sym(s) => format!(":{}", inspect_string(s)),
RKey::Bool(b) => b.to_string(),
RKey::Nil => "nil".to_string(),
RKey::FloatBits(b) => fmt_float(f64::from_bits(*b)),
RKey::Class(n) => n.clone(),
RKey::Array(ks) => {
let parts: Vec<String> = ks.clone().iter().map(|k| self.key_inspect(k)).collect();
format!("[{}]", parts.join(", "))
}
RKey::ArithSeq(ks) => {
let ks = ks.clone();
let mut part = |i: usize| {
ks.get(i)
.map(|k| self.key_inspect(&k.clone()))
.unwrap_or_default()
};
let (b, e, st) = (part(0), part(1), part(2));
let e = if e == "nil" { String::new() } else { e };
let dots = if matches!(ks.get(3), Some(RKey::Bool(true))) {
"..."
} else {
".."
};
format!("(({b}{dots}{e}).step({st}))")
}
RKey::Regexp(source, bits) => {
let flags: String = [(4, 'm'), (1, 'i'), (2, 'x')]
.iter()
.filter(|(b, _)| bits & b != 0)
.map(|(_, c)| *c)
.collect();
format!("/{source}/{flags}")
}
RKey::Range(lo, hi, excl) => {
let lo = if *lo == RANGE_BEGINLESS {
String::new()
} else {
lo.to_string()
};
let hi = if *hi == RANGE_ENDLESS {
String::new()
} else {
hi.to_string()
};
format!("{lo}{}{hi}", if *excl { "..." } else { ".." })
}
RKey::StrRange(lo, hi, excl) => {
format!("{lo:?}{}{hi:?}", if *excl { "..." } else { ".." })
}
RKey::FloatRange(lo, hi, excl) => format!(
"{}{}{}",
fmt_float(f64::from_bits(*lo)),
if *excl { "..." } else { ".." },
fmt_float(f64::from_bits(*hi))
),
RKey::ObjRange(lo, hi, excl) => format!(
"{}{}{}",
self.key_inspect(lo),
if *excl { "..." } else { ".." },
self.key_inspect(hi)
),
RKey::Identity(i) => self.inspect(&Value::Obj(*i)),
k @ (RKey::Hash(_)
| RKey::Set(_)
| RKey::Big(_)
| RKey::Rational(_)
| RKey::Complex(..)) => {
let v = self.key_to_value(&k.clone());
self.inspect(&v)
}
RKey::Recursive => "[...]".to_string(),
}
}
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::BigInt(_)) => "Integer",
Some(RObj::Rational(_)) => "Rational",
Some(RObj::Complex { .. }) => "Complex",
Some(RObj::Lazy { .. }) => "Enumerator::Lazy",
Some(RObj::Enumerator { .. }) => "Enumerator",
Some(RObj::ArithSeq(_)) => "Enumerator::ArithmeticSequence",
Some(RObj::EnumChain(_)) => "Enumerator::Chain",
Some(RObj::Generator { .. }) => "Enumerator",
Some(RObj::Yielder { .. }) | Some(RObj::FiberYielder) => "Enumerator::Yielder",
Some(RObj::Fiber { .. }) => "Fiber",
Some(RObj::Binding { .. }) => "Binding",
Some(RObj::Thread { .. }) => "Thread",
Some(RObj::IoHandle { id }) => self
.io_handles
.get(*id as usize)
.map(|c| c.class_name())
.unwrap_or("IO"),
Some(RObj::Time { .. }) => "Time",
Some(RObj::Date { .. }) => "Date",
Some(RObj::DateTime { .. }) => "DateTime",
Some(RObj::Db { .. }) => "SQLite3::Database",
Some(RObj::FiddleHandle { .. }) => "Fiddle::Handle",
Some(RObj::FiddleFunc { .. }) => "Fiddle::Function",
Some(RObj::FiddlePtr { .. }) => "Fiddle::Pointer",
Some(RObj::Set(_)) => "Set",
Some(RObj::Array(_)) => "Array",
Some(RObj::Hash { .. }) => "Hash",
Some(RObj::Symbol(_)) => "Symbol",
Some(RObj::Range { .. }) => "Range",
Some(RObj::FloatRange { .. }) => "Range",
Some(RObj::StrRange { .. }) => "Range",
Some(RObj::ObjRange { .. }) => "Range",
Some(RObj::Proc { .. })
| Some(RObj::SymProc(_))
| Some(RObj::CycleProc(_))
| Some(RObj::RaiseProc { .. })
| Some(RObj::SeqProc(_))
| Some(RObj::StepProc { .. })
| Some(RObj::ProduceProc { .. })
| Some(RObj::DeriveProc { .. }) => "Proc",
Some(RObj::Method { unbound: true, .. }) => "UnboundMethod",
Some(RObj::Method { .. }) => "Method",
Some(RObj::Regexp { .. }) => "Regexp",
Some(RObj::MatchData { .. }) => "MatchData",
Some(RObj::ClassRef(n)) => {
if Self::is_refinement_class(n) {
"Refinement"
} else if self.is_module_name(n) {
"Module"
} else {
"Class"
}
}
Some(RObj::Object { .. }) => "Object",
None => "Object",
},
_ => "Object",
}
}
pub fn value_hash(&self, v: &Value) -> i64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
if let Some(RObj::Time(t)) = self.obj(v) {
"Time".hash(&mut hasher);
t.secs.hash(&mut hasher);
return hasher.finish() as i64;
}
self.to_key(v).hash(&mut hasher);
hasher.finish() as i64
}
fn to_key(&self, v: &Value) -> RKey {
self.to_key_seen(v, &mut Vec::new())
}
fn to_key_seen(&self, v: &Value, seen: &mut Vec<u32>) -> RKey {
if let Value::Obj(id) = v {
if seen.contains(id) {
return RKey::Recursive;
}
if matches!(
self.obj(v),
Some(RObj::Array(_) | RObj::Hash { .. } | RObj::Set(_) | RObj::Object { .. })
) {
seen.push(*id);
let k = self.to_key_inner(v, seen);
seen.pop();
return k;
}
}
self.to_key_inner(v, seen)
}
fn to_key_inner(&self, v: &Value, seen: &mut Vec<u32>) -> RKey {
match v {
Value::Int(n) => RKey::Int(*n),
Value::Float(f) => RKey::FloatBits(if *f == 0.0 {
0f64.to_bits()
} else {
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)) => match s.encoding() {
Some(enc) if !s.bytes().is_ascii() => RKey::ByteStr(s.view().into_owned(), enc),
_ => RKey::Str(s.view().into_owned()),
},
Some(RObj::Symbol(s)) => RKey::Sym(s.clone()),
Some(RObj::ClassRef(n)) => RKey::Class(n.clone()),
Some(RObj::Array(items)) => {
RKey::Array(items.iter().map(|e| self.to_key_seen(e, seen)).collect())
}
Some(RObj::Hash { map, .. }) => {
let mut pairs: Vec<(RKey, RKey)> = map
.iter()
.map(|(k, v)| (k.clone(), self.to_key_seen(v, seen)))
.collect();
pairs.sort();
RKey::Hash(pairs)
}
Some(RObj::Set(items)) => {
let mut ks: Vec<RKey> = items.keys().cloned().collect();
ks.sort();
RKey::Set(ks)
}
Some(RObj::BigInt(b)) => RKey::Big(b.clone()),
Some(RObj::Rational(q)) => RKey::Rational(q.clone()),
Some(RObj::Complex { re, im }) => {
let (re, im) = (re.clone(), im.clone());
RKey::Complex(
Box::new(self.to_key_seen(&re, seen)),
Box::new(self.to_key_seen(&im, seen)),
)
}
Some(RObj::ArithSeq(q)) => {
let (b, e, st, x) = (
q.begin.clone(),
q.end.clone(),
q.step.clone(),
q.exclude_end,
);
RKey::ArithSeq(vec![
self.to_key_seen(&b, seen),
self.to_key_seen(&e, seen),
self.to_key_seen(&st, seen),
RKey::Bool(x),
])
}
Some(RObj::Range { lo, hi, exclusive }) => RKey::Range(*lo, *hi, *exclusive),
Some(RObj::StrRange { lo, hi, exclusive }) => {
RKey::StrRange(lo.clone(), hi.clone(), *exclusive)
}
Some(RObj::FloatRange { lo, hi, exclusive }) => {
RKey::FloatRange(lo.to_bits(), hi.to_bits(), *exclusive)
}
Some(RObj::ObjRange { lo, hi, exclusive }) => {
let (lo, hi, exclusive) = (lo.clone(), hi.clone(), *exclusive);
RKey::ObjRange(
Box::new(self.to_key_seen(&lo, seen)),
Box::new(self.to_key_seen(&hi, seen)),
exclusive,
)
}
Some(RObj::Object { class, ivars }) if self.is_struct_class(class) => {
let mut parts = vec![RKey::Class(class.clone())];
parts.extend(ivars.values().map(|m| self.to_key_seen(m, seen)));
RKey::Array(parts)
}
Some(RObj::Regexp { source, flags, .. }) => {
RKey::Regexp(source.clone(), regex_option_bits(flags))
}
Some(RObj::Object { .. } | RObj::Proc { .. } | RObj::Time(_)) => match v {
Value::Obj(id) => {
RKey::Identity(self.user_key_canon.get(id).copied().unwrap_or(*id))
}
_ => RKey::Nil,
},
_ => 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::ByteStr(s, enc) => {
let v = self.new_string(s.clone());
self.set_string_encoding(&v, enc);
v
}
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)),
RKey::Class(n) => self.class_ref(n),
RKey::Array(ks) => {
let items: Vec<Value> = ks.clone().iter().map(|k| self.key_to_value(k)).collect();
self.new_array(items)
}
RKey::ArithSeq(ks) => {
let parts: Vec<Value> = ks.clone().iter().map(|k| self.key_to_value(k)).collect();
let at = |i: usize| parts.get(i).cloned().unwrap_or(Value::Undef);
self.arith_seq_from_parts(
at(0),
at(1),
at(2),
matches!(ks.get(3), Some(RKey::Bool(true))),
)
}
RKey::Hash(pairs) => {
let map: IndexMap<RKey, Value> = pairs
.clone()
.iter()
.map(|(k, v)| (k.clone(), self.key_to_value(v)))
.collect();
self.new_hash(map)
}
RKey::Set(ks) => {
let items: Vec<Value> = ks.clone().iter().map(|k| self.key_to_value(k)).collect();
self.new_set(items)
}
RKey::Big(b) => self.new_bigint(b.clone()),
RKey::Rational(q) => self.new_rational(q.clone()),
RKey::Complex(re, im) => {
let (re, im) = (self.key_to_value(re), self.key_to_value(im));
self.new_complex(re, im)
}
RKey::Range(lo, hi, excl) => self.new_range(*lo, *hi, *excl),
RKey::StrRange(lo, hi, excl) => self.new_str_range(lo.clone(), hi.clone(), *excl),
RKey::ObjRange(lo, hi, excl) => {
let (lo, hi) = (self.key_to_value(lo), self.key_to_value(hi));
self.new_obj_range(lo, hi, *excl)
}
RKey::FloatRange(lo, hi, excl) => {
self.new_float_range(f64::from_bits(*lo), f64::from_bits(*hi), *excl)
}
RKey::Regexp(source, bits) => {
let flags: String = [(4, 'm'), (1, 'i'), (2, 'x')]
.iter()
.filter(|(b, _)| bits & b != 0)
.map(|(_, c)| *c)
.collect();
self.new_regex(source, &flags).unwrap_or(Value::Undef)
}
RKey::Identity(i) => Value::Obj(*i),
RKey::Recursive => Value::Undef,
}
}
pub fn cmp_failed(&mut self, recv: &Value, other: &Value) -> String {
let by_inspect = match other {
Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::Undef => true,
_ => matches!(self.obj(other), Some(RObj::Symbol(_))),
};
let rhs = if by_inspect {
self.inspect(other)
} else {
self.class_of(other)
};
crate::builtins::raise_exc(
"ArgumentError",
&format!("comparison of {} with {rhs} failed", self.class_of(recv)),
)
}
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))),
_ => {}
}
if matches!(op, Neg) {
let rat = match self.obj(a) {
Some(RObj::Rational(r)) => Some(r.clone()),
_ => None,
};
if let Some(r) = rat {
return Ok(self.new_rational(-r));
}
if let Some(x) = self.as_bigint(a) {
return Ok(self.new_bigint(-x));
}
if let Some((re, im)) = self.complex_parts(a) {
let nr = self.num_op(Sub, &Value::Int(0), &re)?;
let ni = self.num_op(Sub, &Value::Int(0), &im)?;
return Ok(self.new_complex(nr, ni));
}
if self.as_str(a).is_some() && matches!(a, Value::Obj(_)) {
let c = if self.is_frozen(a) {
a.clone()
} else {
self.dup_value(a)
};
self.freeze_value(&c);
return Ok(c);
}
return match a {
Value::Int(n) => Ok(Value::Int(n.wrapping_neg())),
Value::Float(f) => Ok(Value::Float(-*f)),
_ => Err(format!(
"undefined method '-@' for {}",
self.receiver_phrase(a)
)),
};
}
if let (Some(x), Some(y)) = (self.as_bigint(a), self.as_bigint(b)) {
use num_integer::Integer as _;
use num_traits::Zero as _;
let arith = match op {
Add => Some(x.clone() + &y),
Sub => Some(x.clone() - &y),
Mul => Some(x.clone() * &y),
Div if !y.is_zero() => Some(x.div_floor(&y)),
Mod if !y.is_zero() => Some(x.mod_floor(&y)),
_ => None,
};
if let Some(v) = arith {
return Ok(self.new_bigint(v));
}
match op {
Div | Mod => return Err("divided by 0".to_string()),
Lt => return Ok(Value::Bool(x < y)),
Gt => return Ok(Value::Bool(x > y)),
Le => return Ok(Value::Bool(x <= y)),
Ge => return Ok(Value::Bool(x >= y)),
_ => {}
}
}
if matches!(op, Lt | Gt | Le | Ge) && matches!(self.obj(a), Some(RObj::Rational(_))) {
let comparable = match b {
Value::Float(f) => !f.is_nan(),
Value::Int(_) => true,
_ => self.as_rational(b).is_some(),
};
if !comparable {
return Err(self.cmp_failed(a, b));
}
}
if matches!(self.obj(a), Some(RObj::Rational(_)))
|| matches!(self.obj(b), Some(RObj::Rational(_)))
{
if matches!(op, Mod) && !matches!(a, Value::Float(_)) {
let ra = match self.obj(a) {
Some(RObj::Rational(_)) => Some(a.clone()),
_ => self.as_rational(a).map(|r| self.new_rational(r)),
};
if let Some(ra) = ra {
return crate::builtins::dispatch(&ra, "modulo", std::slice::from_ref(b), None);
}
}
if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) {
use num_traits::ToPrimitive as _;
let to_f = |this: &Self, v: &Value| -> f64 {
match v {
Value::Float(f) => *f,
Value::Int(n) => *n as f64,
_ => this.as_rational(v).and_then(|r| r.to_f64()).unwrap_or(0.0),
}
};
let (af, bf) = (to_f(self, a), to_f(self, b));
return Ok(match op {
Add => Value::Float(af + bf),
Sub => Value::Float(af - bf),
Mul => Value::Float(af * bf),
Div => Value::Float(af / bf),
Lt => Value::Bool(af < bf),
Gt => Value::Bool(af > bf),
Le => Value::Bool(af <= bf),
Ge => Value::Bool(af >= bf),
_ => Value::Float(af),
});
}
if let (Some(x), Some(y)) = (self.as_rational(a), self.as_rational(b)) {
use num_traits::Zero as _;
let r = match op {
Add => Some(x.clone() + &y),
Sub => Some(x.clone() - &y),
Mul => Some(x.clone() * &y),
Div if !y.is_zero() => Some(x.clone() / &y),
Mod if !y.is_zero() => {
let q = (x.clone() / &y).floor();
Some(x.clone() - &y * q)
}
_ => None,
};
if let Some(v) = r {
return Ok(self.new_rational(v));
}
match op {
Lt => return Ok(Value::Bool(x < y)),
Gt => return Ok(Value::Bool(x > y)),
Le => return Ok(Value::Bool(x <= y)),
Ge => return Ok(Value::Bool(x >= y)),
_ => {}
}
}
}
let complex_side = matches!(self.obj(a), Some(RObj::Complex { .. }))
|| matches!(self.obj(b), Some(RObj::Complex { .. }));
if !complex_side && (matches!(a, Value::Float(_)) || matches!(b, Value::Float(_))) {
if matches!(op, Lt | Gt | Le | Ge) {
if let Some(ord) = self.exact_num_cmp(a, b) {
return Ok(Value::Bool(match op {
Lt => ord.is_lt(),
Gt => ord.is_gt(),
Le => ord.is_le(),
_ => ord.is_ge(),
}));
}
}
if let (Some(x), Some(y)) = (self.as_f64(a), self.as_f64(b)) {
let out = match op {
Add => Some(Value::Float(x + y)),
Sub => Some(Value::Float(x - y)),
Mul => Some(Value::Float(x * y)),
Div => Some(Value::Float(x / y)),
Mod => crate::builtins::flodivmod(x, y).map(|(_, m)| Value::Float(m)),
Pow => Some(Value::Float(x.powf(y))),
Lt => Some(Value::Bool(x < y)),
Gt => Some(Value::Bool(x > y)),
Le => Some(Value::Bool(x <= y)),
Ge => Some(Value::Bool(x >= y)),
_ => None,
};
if let Some(v) = out {
return Ok(v);
}
}
}
if complex_side {
let (ar, ai) = self
.complex_parts(a)
.unwrap_or_else(|| (a.clone(), Value::Int(0)));
let (br, bi) = self
.complex_parts(b)
.unwrap_or_else(|| (b.clone(), Value::Int(0)));
let result = match op {
Add => Some((self.num_op(Add, &ar, &br)?, self.num_op(Add, &ai, &bi)?)),
Sub => Some((self.num_op(Sub, &ar, &br)?, self.num_op(Sub, &ai, &bi)?)),
Mul => {
let rr1 = self.num_op(Mul, &ar, &br)?;
let rr2 = self.num_op(Mul, &ai, &bi)?;
let re = self.num_op(Sub, &rr1, &rr2)?;
let ii1 = self.num_op(Mul, &ar, &bi)?;
let ii2 = self.num_op(Mul, &ai, &br)?;
let im = self.num_op(Add, &ii1, &ii2)?;
Some((re, im))
}
Div if self.complex_parts(a).is_some() => {
return crate::builtins::dispatch(a, "/", std::slice::from_ref(b), None);
}
Div if matches!(a, Value::Int(_) | Value::Float(_))
|| self.as_rational(a).is_some() =>
{
let lhs = self.new_complex(a.clone(), Value::Int(0));
return crate::builtins::dispatch(&lhs, "/", std::slice::from_ref(b), None);
}
_ => None,
};
if let Some((re, im)) = result {
return Ok(self.new_complex(re, im));
}
}
match (self.obj(a).cloned(), op) {
(Some(RObj::Str(s)), Add) => {
let s = s.view().into_owned();
if (self.is_broken_utf8(a) || self.is_broken_utf8(b))
&& self.as_str(b).is_some()
&& self.utf8_labelled(a)
&& self.utf8_labelled(b)
{
let mut bytes = self.string_bytes(a);
bytes.extend(self.string_bytes(b));
return Ok(self.new_utf8_from_bytes(bytes));
}
return match self.as_str(b) {
Some(bs) => {
self.check_encoding_compatible(a, b)?;
let out = self.new_string(format!("{s}{bs}"));
self.inherit_string_encoding_with(&out, a, s.is_ascii(), Some(b));
Ok(out)
}
None => Err(self.no_conversion(b, "String")),
};
}
(Some(RObj::Str(s)), Mul) => {
let s = s.view().into_owned();
let raw = self.to_int_operand(b)?;
if raw < 0 {
return Err(crate::builtins::raise_exc(
"ArgumentError",
"negative argument",
));
}
let n = raw as usize;
let out = self.new_string(s.repeat(n));
self.inherit_string_encoding(&out, a, s.is_ascii());
return Ok(out);
}
(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.view().cmp(&bs.view()))));
}
}
(Some(RObj::Array(mut xs)), Add) => {
let Some(RObj::Array(ys)) = self.obj(b).cloned() else {
return Err(self.no_conversion(b, "Array"));
};
xs.extend(ys);
return Ok(self.new_array(xs));
}
(Some(RObj::Array(xs)), Sub) => {
if let Some(RObj::Array(ys)) = self.obj(b).cloned() {
let kept: Vec<Value> = xs
.iter()
.filter(|v| !ys.iter().any(|w| self.eql_values(v, w)))
.cloned()
.collect();
return Ok(self.new_array(kept));
}
return Err(self.no_conversion(b, "Array"));
}
(Some(RObj::Array(xs)), Mul) => {
if let Some(sep) = self.as_str(b) {
let parts: Vec<String> = xs.iter().map(|v| self.to_s(v)).collect();
return Ok(self.new_string(parts.join(&sep)));
}
let raw = self.to_int_operand(b)?;
if raw < 0 {
return Err(crate::builtins::raise_exc(
"ArgumentError",
"negative argument",
));
}
let n = raw 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));
}
_ => {}
}
if let Some(ta) = self.as_time(a) {
use num_traits::ToPrimitive as _;
match op {
Sub => {
if let Some(tb) = self.as_time(b) {
let d = &ta.secs - &tb.secs;
return Ok(Value::Float(d.to_f64().unwrap_or(0.0)));
}
if let Some(n) = self.exact_num(b) {
return Ok(self.new_rtime(crate::rtime::RTime::new(&ta.secs - n, ta.zone)));
}
}
Add => {
if self.as_time(b).is_some() {
return Err(crate::builtins::raise_exc("TypeError", "time + time?"));
}
if let Some(n) = self.exact_num(b) {
return Ok(self.new_rtime(crate::rtime::RTime::new(&ta.secs + n, ta.zone)));
}
}
Lt | Gt | Le | Ge => {
if let Some(tb) = self.as_time(b) {
return Ok(Value::Bool(cmp_ord(op, ta.secs.cmp(&tb.secs))));
}
}
_ => {}
}
}
if let Some(da) = self.date_days(a) {
match op {
Sub => {
if let Some(db) = self.date_days(b) {
let r = num_rational::BigRational::from(num_bigint::BigInt::from(da - db));
return Ok(self.new_rational(r));
}
if let Some(n) = as_int(b) {
return Ok(self.new_date(da - n));
}
}
Add => {
if let Some(n) = as_int(b) {
return Ok(self.new_date(da + n));
}
}
Lt | Gt | Le | Ge => {
if let Some(db) = self.date_days(b) {
return Ok(Value::Bool(cmp_ord(op, da.cmp(&db))));
}
}
_ => {}
}
}
if let Some(sa) = self.datetime_secs(a) {
let num_f = |v: &Value| match v {
Value::Int(n) => Some(*n as f64),
Value::Float(f) => Some(*f),
_ => None,
};
match op {
Sub => {
if let Some(sb) = self.datetime_secs(b) {
let numer = num_bigint::BigInt::from((sa - sb).round() as i64);
let r =
num_rational::BigRational::new(numer, num_bigint::BigInt::from(86_400));
return Ok(self.new_rational(r));
}
if let Some(n) = num_f(b) {
return Ok(self.new_datetime(sa - n * 86_400.0));
}
}
Add => {
if let Some(n) = num_f(b) {
return Ok(self.new_datetime(sa + n * 86_400.0));
}
}
Lt | Gt | Le | Ge => {
if let Some(sb) = self.datetime_secs(b) {
return Ok(Value::Bool(cmp_ord(op, sa.total_cmp(&sb))));
}
}
_ => {}
}
}
if matches!(op, Lt | Gt | Le | Ge) {
if let (Some(x), Some(y)) = (self.classref_name(a), self.classref_name(b)) {
let res = match op {
Lt => self.class_lt(&x, &y),
Gt => self.class_lt(&y, &x),
Le if x == y => Some(true),
Le => self.class_lt(&x, &y),
Ge if x == y => Some(true),
_ => self.class_lt(&y, &x),
};
return Ok(match res {
Some(b) => Value::Bool(b),
None => Value::Undef,
});
}
}
if matches!(op, Add) && self.class_name(a) == "Enumerator::Lazy" {
return crate::builtins::dispatch(a, "+", std::slice::from_ref(b), None);
}
if matches!(op, Add)
&& matches!(
self.class_name(a),
"Enumerator" | "Enumerator::ArithmeticSequence" | "Enumerator::Chain"
)
{
return Ok(self.new_enum_chain(vec![a.clone(), b.clone()]));
}
if let Some(xs) = self.as_set(a) {
if matches!(op, Add | Sub) {
let ys = self
.as_set(b)
.or_else(|| self.as_array(b))
.unwrap_or_default();
let in_ys = |v: &Value, this: &Self| ys.iter().any(|w| this.eql_values(v, w));
let result: Vec<Value> = match op {
Add => xs.iter().chain(ys.iter()).cloned().collect(),
_ => xs.iter().filter(|v| !in_ys(v, self)).cloned().collect(),
};
return Ok(self.new_set(result));
}
}
if matches!(op, Add | Sub | Mul | Div | Mod | Pow) {
let recv_class = self.class_of(a);
if matches!(
recv_class.as_str(),
"Integer" | "Float" | "Rational" | "Complex"
) {
return Err(format!(
"{} can't be coerced into {recv_class}",
self.coerce_operand_name(b)
));
}
}
if matches!(op, Lt | Gt | Le | Ge) {
let cls = self.class_of(a);
let comparable = crate::arity_table::ancestry(&cls)
.is_some_and(|anc| anc.contains(&"Comparable"))
|| self
.expanded_ancestry(&cls)
.iter()
.any(|c| c == "Comparable");
if comparable {
return Err(self.cmp_failed(a, b));
}
}
Err(format!(
"undefined method '{}' for {}",
num_op_name(op),
self.receiver_phrase(a)
))
}
pub fn coerce_operand_name(&self, v: &Value) -> String {
match v {
Value::Undef => "nil".to_string(),
Value::Bool(true) => "true".to_string(),
Value::Bool(false) => "false".to_string(),
Value::Float(f) => fmt_float(*f),
_ => match self.obj(v) {
Some(RObj::Symbol(s)) => format!(":{s}"),
_ => self.class_of(v),
},
}
}
pub fn no_conversion(&self, v: &Value, target: &str) -> String {
let named = match v {
Value::Undef => "nil".to_string(),
Value::Bool(true) => "true".to_string(),
Value::Bool(false) => "false".to_string(),
_ => self.class_of(v),
};
format!("no implicit conversion of {named} into {target}")
}
pub fn to_int_operand(&self, v: &Value) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
Value::Float(f) => Ok(*f as i64),
Value::Undef => Err("no implicit conversion from nil to integer".to_string()),
_ if as_int(v).is_none() && self.as_bigint(v).is_some() => Err(
crate::builtins::raise_exc("RangeError", "bignum too big to convert into 'long'"),
),
_ => as_int(v).ok_or_else(|| self.no_conversion(v, "Integer")),
}
}
pub fn eql_values(&self, a: &Value, b: &Value) -> bool {
if let (Value::Obj(x), Value::Obj(y)) = (a, b) {
if self.is_container(a) && self.is_container(b) {
let pair = (*x, *y);
if EQL_PAIRS.with(|p| p.borrow().contains(&pair)) {
return true;
}
EQL_PAIRS.with(|p| p.borrow_mut().push(pair));
let out = self.eql_values_uncycled(a, b);
EQL_PAIRS.with(|p| {
p.borrow_mut().pop();
});
return out;
}
}
self.eql_values_uncycled(a, b)
}
fn eql_values_uncycled(&self, a: &Value, b: &Value) -> bool {
let numeric = |c: &str| matches!(c, "Integer" | "Float" | "Rational" | "Complex");
let (ca, cb) = (self.class_of(a), self.class_of(b));
if ca != cb && numeric(&ca) && numeric(&cb) {
return false;
}
if matches!(
(self.obj(a), self.obj(b)),
(Some(RObj::Range { .. }), Some(RObj::FloatRange { .. }))
| (Some(RObj::FloatRange { .. }), Some(RObj::Range { .. }))
) {
return false;
}
if let Some(((l1, h1, e1), (l2, h2, e2))) = self.obj_range_pair(a, b) {
return e1 == e2 && self.eql_values(&l1, &l2) && self.eql_values(&h1, &h2);
}
if let (Value::Obj(x), Value::Obj(y)) = (a, b) {
if let (Some(rx), Some(ry)) = (self.user_key_canon.get(x), self.user_key_canon.get(y)) {
if rx == ry {
return true;
}
}
}
match (self.obj(a), self.obj(b)) {
(Some(RObj::Array(x)), Some(RObj::Array(y))) => {
x.len() == y.len() && x.iter().zip(y).all(|(p, q)| self.eql_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.eql_values(v, w)))
}
(Some(RObj::Complex { re: xr, im: xi }), Some(RObj::Complex { re: yr, im: yi })) => {
self.eql_values(xr, yr) && self.eql_values(xi, yi)
}
(
Some(RObj::Object {
class: sa,
ivars: ia,
}),
Some(RObj::Object {
class: sb,
ivars: ib,
}),
) if self.is_struct_class(sa) => {
sa == sb
&& ia.len() == ib.len()
&& ia
.iter()
.all(|(k, v)| ib.get(k).is_some_and(|w| self.eql_values(v, w)))
}
_ => self.eq_values(a, b),
}
}
fn exact_float_int(v: &Value) -> Option<num_bigint::BigInt> {
use num_traits::FromPrimitive as _;
let f = match v {
Value::Float(f) => *f,
_ => return None,
};
if !f.is_finite() || f.fract() != 0.0 {
return None;
}
num_bigint::BigInt::from_f64(f)
}
pub fn exact_num_cmp(&self, a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
use std::cmp::Ordering::{Greater, Less};
let exact = |v: &Value| match v {
Value::Float(f) if f.is_finite() => num_rational::BigRational::from_float(*f),
Value::Float(_) => None,
_ => self.as_rational(v),
};
match (a, b) {
(Value::Float(x), _) if x.is_infinite() => {
exact(b)?;
return Some(if *x > 0.0 { Greater } else { Less });
}
(_, Value::Float(y)) if y.is_infinite() => {
exact(a)?;
return Some(if *y > 0.0 { Less } else { Greater });
}
_ => {}
}
Some(exact(a)?.cmp(&exact(b)?))
}
pub fn rb_equal(&self, a: &Value, b: &Value) -> bool {
if let (Value::Float(x), Value::Float(y)) = (a, b) {
if x.to_bits() == y.to_bits() {
return true;
}
}
self.eq_values(a, b)
}
pub fn eq_values(&self, a: &Value, b: &Value) -> bool {
if let (Value::Obj(x), Value::Obj(y)) = (a, b) {
if self.is_container(a) && self.is_container(b) {
let pair = (*x, *y);
if EQ_PAIRS.with(|p| p.borrow().contains(&pair)) {
return true;
}
EQ_PAIRS.with(|p| p.borrow_mut().push(pair));
let out = self.eq_values_uncycled(a, b);
EQ_PAIRS.with(|p| {
p.borrow_mut().pop();
});
return out;
}
}
self.eq_values_uncycled(a, b)
}
fn is_container(&self, v: &Value) -> bool {
match self.obj(v) {
Some(RObj::Array(_) | RObj::Hash { .. } | RObj::Set(_)) => true,
Some(RObj::Object { class, .. }) => self.is_struct_class(class),
_ => false,
}
}
fn obj_range_pair(&self, a: &Value, b: &Value) -> Option<(RangeEnds, RangeEnds)> {
let is_obj = |v: &Value| matches!(self.obj(v), Some(RObj::ObjRange { .. }));
if !is_obj(a) && !is_obj(b) {
return None;
}
let parts = |v: &Value| match self.obj(v) {
Some(RObj::ObjRange { lo, hi, exclusive }) => {
Some((lo.clone(), hi.clone(), *exclusive))
}
Some(RObj::FloatRange { lo, hi, exclusive }) => {
Some((Value::Float(*lo), Value::Float(*hi), *exclusive))
}
Some(RObj::Range { lo, hi, exclusive }) => {
Some((Value::Int(*lo), Value::Int(*hi), *exclusive))
}
_ => None,
};
Some((parts(a)?, parts(b)?))
}
fn numeric_range_parts(&self, v: &Value) -> (f64, f64, bool) {
match self.obj(v) {
Some(RObj::Range { lo, hi, exclusive }) => (
if *lo == RANGE_BEGINLESS {
f64::NEG_INFINITY
} else {
*lo as f64
},
if *hi == RANGE_ENDLESS {
f64::INFINITY
} else {
*hi as f64
},
*exclusive,
),
Some(RObj::FloatRange { lo, hi, exclusive }) => (*lo, *hi, *exclusive),
_ => (f64::NAN, f64::NAN, false),
}
}
fn eq_values_uncycled(&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)) => {
if x.unsigned_abs() <= (1u64 << 53) {
*x as f64 == *y
} else {
Self::exact_float_int(&Value::Float(*y))
.is_some_and(|f| f == num_bigint::BigInt::from(*x))
}
}
(Value::Bool(x), Value::Bool(y)) => x == y,
(Value::Undef, Value::Undef) => true,
(Value::Obj(_), Value::Obj(_))
if matches!(
(self.obj(a), self.obj(b)),
(Some(RObj::Range { .. }), Some(RObj::FloatRange { .. }))
| (Some(RObj::FloatRange { .. }), Some(RObj::Range { .. }))
) =>
{
let (l1, h1, e1) = self.numeric_range_parts(a);
let (l2, h2, e2) = self.numeric_range_parts(b);
e1 == e2 && l1 == l2 && h1 == h2
}
(Value::Obj(_), Value::Obj(_)) if self.obj_range_pair(a, b).is_some() => {
let ((l1, h1, e1), (l2, h2, e2)) = self.obj_range_pair(a, b).unwrap();
e1 == e2 && self.eq_values(&l1, &l2) && self.eq_values(&h1, &h2)
}
_ if matches!(self.obj(a), Some(RObj::Rational(_)))
|| matches!(self.obj(b), Some(RObj::Rational(_))) =>
{
match (self.as_rational(a), self.as_rational(b)) {
(Some(x), Some(y)) => x == y,
_ => match (self.as_f64(a), self.as_f64(b)) {
(Some(x), Some(y)) => x == y,
_ => false,
},
}
}
_ if matches!(self.obj(a), Some(RObj::BigInt(_)))
|| matches!(self.obj(b), Some(RObj::BigInt(_))) =>
{
match (self.as_bigint(a), self.as_bigint(b)) {
(Some(x), Some(y)) => x == y,
(Some(x), None) => Self::exact_float_int(b).is_some_and(|y| x == y),
(None, Some(y)) => Self::exact_float_int(a).is_some_and(|x| x == y),
(None, None) => false,
}
}
_ if matches!(self.obj(a), Some(RObj::Complex { .. }))
!= matches!(self.obj(b), Some(RObj::Complex { .. })) =>
{
let (cx, real) = match self.obj(a) {
Some(RObj::Complex { .. }) => (a, b),
_ => (b, a),
};
match self.complex_parts(cx) {
Some((re, im)) => {
self.eq_values(&im, &Value::Int(0)) && self.eq_values(&re, real)
}
None => false,
}
}
_ => {
let (oa, ob) = (self.obj(a), self.obj(b));
match (oa, ob) {
(Some(RObj::Str(x)), Some(RObj::Str(y))) => {
x.bytes() == y.bytes()
&& (x.bytes().is_ascii() || x.encoding() == y.encoding())
}
(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.rb_equal(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)))
}
(
Some(RObj::Complex { re: xr, im: xi }),
Some(RObj::Complex { re: yr, im: yi }),
) => {
let (xr, xi, yr, yi) = (xr.clone(), xi.clone(), yr.clone(), yi.clone());
self.eq_values(&xr, &yr) && self.eq_values(&xi, &yi)
}
(Some(RObj::Set(x)), Some(RObj::Set(y))) => {
x.len() == y.len() && x.keys().all(|k| y.contains_key(k))
}
(
Some(RObj::Regexp {
source: xs,
flags: xf,
..
}),
Some(RObj::Regexp {
source: ys,
flags: yf,
..
}),
) => {
xs == ys
&& regex_option_bits(xf) == regex_option_bits(yf)
&& xf.contains('u') == yf.contains('u')
}
(
Some(RObj::Object {
class: ca,
ivars: ia,
}),
Some(RObj::Object {
class: cb,
ivars: ib,
}),
) if ca == "Encoding" && cb == "Encoding" => {
match (ia.get("name"), ib.get("name")) {
(Some(x), Some(y)) => self.eq_values(x, y),
_ => false,
}
}
(Some(RObj::ArithSeq(x)), Some(RObj::ArithSeq(y))) => {
self.eq_values(&x.begin, &y.begin)
&& self.eq_values(&x.end, &y.end)
&& self.eq_values(&x.step, &y.step)
&& x.exclude_end == y.exclude_end
}
(
Some(RObj::Range {
lo: al,
hi: ah,
exclusive: ax,
}),
Some(RObj::Range {
lo: bl,
hi: bh,
exclusive: bx,
}),
) => al == bl && ah == bh && ax == bx,
(
Some(RObj::FloatRange {
lo: al,
hi: ah,
exclusive: ax,
}),
Some(RObj::FloatRange {
lo: bl,
hi: bh,
exclusive: bx,
}),
) => al == bl && ah == bh && ax == bx,
(
Some(RObj::StrRange {
lo: al,
hi: ah,
exclusive: ax,
}),
Some(RObj::StrRange {
lo: bl,
hi: bh,
exclusive: bx,
}),
) => al == bl && ah == bh && ax == bx,
(Some(RObj::ClassRef(x)), Some(RObj::ClassRef(y))) => x == y,
(Some(RObj::Time(x)), Some(RObj::Time(y))) => x.secs == y.secs,
(Some(RObj::Date { days: x }), Some(RObj::Date { days: y })) => x == y,
(Some(RObj::DateTime { secs: x }), Some(RObj::DateTime { secs: y })) => x == y,
(
Some(RObj::Object {
class: cx,
ivars: ix,
}),
Some(RObj::Object { class: cy, .. }),
) if cx == cy && self.struct_def(cx).is_some() => {
let members = self.struct_def(cx).unwrap().0;
let ix = ix.clone();
members.iter().all(|m| {
let bv = self.ivar_of(b, m);
self.eq_values(ix.get(m).unwrap_or(&Value::Undef), &bv)
})
}
(
Some(RObj::Object {
class: cx,
ivars: ix,
}),
Some(RObj::Object {
class: cy,
ivars: iy,
}),
) if cx == "OpenStruct" && cy == "OpenStruct" => {
ix.len() == iy.len()
&& ix
.iter()
.all(|(k, v)| iy.get(k).is_some_and(|w| self.eq_values(v, w)))
}
_ => matches!((a, b), (Value::Obj(i), Value::Obj(j)) if i == j),
}
}
}
}
}
pub fn plain_symbol_name(s: &str) -> bool {
const OPS: &[&str] = &[
"+", "-", "*", "/", "%", "**", "==", "!=", "<", "<=", ">", ">=", "<=>", "===", "=~", "!~",
"!", "~", "[]", "[]=", "<<", ">>", "&", "|", "^", "+@", "-@", "`",
];
if OPS.contains(&s) {
return true;
}
if let Some(rest) = s.strip_prefix('$') {
let mut cs = rest.chars();
let special = match cs.next() {
Some(c) if "~*$?!@/\\;,.=:<>\"&`'+0".contains(c) => cs.next().is_none(),
Some('-') => {
matches!(cs.next(), Some(c) if c == '_' || c.is_alphanumeric())
&& cs.next().is_none()
}
Some(c) if c.is_ascii_digit() => rest.chars().all(|c| c.is_ascii_digit()),
_ => false,
};
if special {
return true;
}
}
let (sigil, body) = match s.strip_prefix("@@") {
Some(rest) => (true, rest),
None => match s.strip_prefix('@').or_else(|| s.strip_prefix('$')) {
Some(rest) => (true, rest),
None => (false, s),
},
};
let core = match body.chars().last() {
Some('?' | '!' | '=') if !sigil && body.chars().count() > 1 => &body[..body.len() - 1],
_ => body,
};
let mut cs = core.chars();
match cs.next() {
Some(c) if c == '_' || c.is_alphabetic() => {}
_ => return false,
}
cs.all(|c| c == '_' || c.is_alphanumeric())
}
pub fn symbol_key_needs_quote(s: &str) -> bool {
if s.is_empty() || !plain_symbol_name(s) || s.starts_with(['@', '$', '!']) {
return true;
}
s.ends_with([
'+', '-', '*', '/', '`', '%', '^', '&', '|', ']', '<', '=', '>', '~', '@',
])
}
pub fn encoding_info(name: &str) -> Option<&'static crate::encoding_table::EncodingInfo> {
use crate::encoding_table::ENCODINGS;
let name = match name.to_ascii_lowercase().as_str() {
"locale" | "external" | "filesystem" => "UTF-8",
_ => name,
};
ENCODINGS
.iter()
.find(|e| e.names.iter().any(|n| n.eq_ignore_ascii_case(name)))
}
pub fn inspect_string(s: &str) -> String {
inspect_units(s.chars().map(Ok))
}
pub fn inspect_broken_utf8(bytes: &[u8]) -> String {
inspect_units(bytes.utf8_chunks().flat_map(|chunk| {
let chars = chunk.valid().chars().map(Ok);
chars.chain(chunk.invalid().iter().map(|&b| Err(b)))
}))
}
fn inspect_units(units: impl Iterator<Item = Result<char, u8>>) -> String {
let mut out = String::from('"');
let mut units = units.peekable();
while let Some(unit) = units.next() {
let c = match unit {
Ok(c) => c,
Err(b) => {
out.push_str(&format!("\\x{b:02X}"));
continue;
}
};
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'#' => {
if matches!(units.peek(), Some(Ok('{' | '@' | '$'))) {
out.push_str("\\#");
} else {
out.push('#');
}
}
'\u{07}' => out.push_str("\\a"),
'\u{08}' => out.push_str("\\b"),
'\t' => out.push_str("\\t"),
'\n' => out.push_str("\\n"),
'\u{0b}' => out.push_str("\\v"),
'\u{0c}' => out.push_str("\\f"),
'\r' => out.push_str("\\r"),
'\u{1b}' => out.push_str("\\e"),
c if !crate::unicode_tables::is_print(u32::from(c)) => {
if u32::from(c) <= 0xFFFF {
out.push_str(&format!("\\u{:04X}", u32::from(c)));
} else {
out.push_str(&format!("\\u{{{:X}}}", u32::from(c)));
}
}
c => out.push(c),
}
}
out.push('"');
out
}
pub fn inspect_string_bytes(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'#' => {
if matches!(chars.peek(), Some('{') | Some('@') | Some('$')) {
out.push_str("\\#");
} else {
out.push('#');
}
}
'\u{07}' => out.push_str("\\a"),
'\u{08}' => out.push_str("\\b"),
'\t' => out.push_str("\\t"),
'\n' => out.push_str("\\n"),
'\u{0b}' => out.push_str("\\v"),
'\u{0c}' => out.push_str("\\f"),
'\r' => out.push_str("\\r"),
'\u{1b}' => out.push_str("\\e"),
' '..='~' => out.push(c),
c if (c as u32) <= 0xff => out.push_str(&format!("\\x{:02X}", c as u32)),
c => {
let mut buf = [0u8; 4];
for b in c.encode_utf8(&mut buf).as_bytes() {
out.push_str(&format!("\\x{b:02X}"));
}
}
}
}
out.push('"');
out
}
fn dtoa_shortest(f: f64) -> (String, i32) {
let s = format!("{:e}", f.abs());
let (mant, exp) = s.split_once('e').unwrap_or((s.as_str(), "0"));
let decpt = exp.parse::<i32>().unwrap_or(0) + 1;
(mant.chars().filter(|c| *c != '.').collect(), decpt)
}
fn fmt_float(f: f64) -> String {
if !f.is_finite() {
return if f.is_nan() {
"NaN".to_string()
} else if f > 0.0 {
"Infinity".to_string()
} else {
"-Infinity".to_string()
};
}
const DBL_DIG: i32 = 15;
let (digits, decpt) = dtoa_shortest(f);
let digs = digits.len() as i32;
let mut out = if f.is_sign_negative() {
"-".to_string()
} else {
String::new()
};
if decpt > 0 {
if decpt < digs {
let (int, frac) = digits.split_at(decpt as usize);
out.push_str(int);
out.push('.');
out.push_str(frac);
return out;
}
if decpt <= DBL_DIG {
out.push_str(&digits);
out.extend(std::iter::repeat('0').take((decpt - digs) as usize));
out.push_str(".0");
return out;
}
} else if decpt > -4 {
out.push_str("0.");
out.extend(std::iter::repeat('0').take((-decpt) as usize));
out.push_str(&digits);
return out;
}
out.push_str(&digits[..1]);
out.push('.');
if digs > 1 {
out.push_str(&digits[1..]);
} else {
out.push('0');
}
out.push_str(&format!("e{:+03}", decpt - 1));
out
}
fn as_int(v: &Value) -> Option<i64> {
match v {
Value::Int(n) => Some(*n),
Value::Float(f) => Some(*f as i64),
_ => None,
}
}
fn method_params_signature(params: &[(&'static str, Option<String>)]) -> String {
let is = |i: usize, kind: &str, name: &str| {
params
.get(i)
.is_some_and(|(k, n)| *k == kind && n.as_deref() == Some(name))
};
let forwarding =
params.len() == 3 && is(0, "rest", "*") && is(1, "keyrest", "**") && is(2, "block", "&");
let mut out = String::new();
for (i, (kind, name)) in params.iter().enumerate() {
let name = name.clone().unwrap_or_else(|| {
match *kind {
"req" | "opt" => "_",
"block" => "block",
"nokey" => "nil",
_ => "",
}
.to_string()
});
let cut_separator = |out: &mut String| {
let keep = out.len().saturating_sub(2);
out.truncate(keep);
};
match *kind {
"req" => out.push_str(&name),
"opt" => out.push_str(&format!("{name}=...")),
"keyreq" => out.push_str(&format!("{name}:")),
"key" => out.push_str(&format!("{name}: ...")),
"rest" if name == "*" => out.push_str(if forwarding { "..." } else { "*" }),
"rest" => out.push_str(&format!("*{name}")),
"keyrest" if name != "**" => out.push_str(&format!("**{name}")),
"keyrest" if i > 0 => cut_separator(&mut out),
"keyrest" => out.push_str("**"),
"block" if name == "&" && forwarding => cut_separator(&mut out),
"block" if name == "&" => out.push_str("..."),
"block" => out.push_str(&format!("&{name}")),
"nokey" => out.push_str("**nil"),
_ => {}
}
if i + 1 < params.len() {
out.push_str(", ");
}
}
out
}
fn written_params(
params: &[String],
shape: PositionalShape,
kwnames: &[String],
kwreq: &[String],
kwsplat: Option<&str>,
blockparam: Option<&str>,
) -> Vec<(&'static str, Option<String>)> {
let PositionalShape { splat, opt, post } = shape;
let mut out: Vec<(&'static str, Option<String>)> = Vec::new();
let opt_end = splat.unwrap_or(params.len().saturating_sub(post));
let opt_start = opt_end.saturating_sub(opt);
for (i, p) in params.iter().enumerate() {
let mut name = p.trim_start_matches('*').to_string();
let kind = if Some(i) == splat {
"rest"
} else if (opt_start..opt_end).contains(&i) {
"opt"
} else {
"req"
};
if name == "__excess" {
continue;
}
if kind == "rest" && (name.is_empty() || name == crate::parser::FWD_REST) {
name = "*".to_string();
}
let written =
!name.starts_with("__destructure_") && name != crate::compiler::ATTR_WRITER_PARAM;
out.push((kind, written.then_some(name)));
}
for k in kwnames {
let kind = if kwreq.contains(k) { "keyreq" } else { "key" };
out.push((kind, Some(k.clone())));
}
if let Some(ks) = kwsplat {
if ks == crate::parser::NO_KEYWORDS_PARAM {
out.push(("nokey", None));
} else {
let name = ks.trim_start_matches('*');
let anon = name.is_empty()
|| name == crate::parser::FWD_KW
|| name == crate::parser::ANON_KWREST_PARAM
|| name == "__kwrest";
out.push(("keyrest", Some(if anon { "**" } else { name }.to_string())));
}
}
if let Some(bp) = blockparam {
let name = bp.trim_start_matches('&');
let anon = name.is_empty()
|| name == crate::parser::FWD_BLK
|| name == crate::parser::ANON_BLOCK_PARAM;
out.push(("block", Some(if anon { "&" } else { name }.to_string())));
}
out
}
fn dedup_keep_first(items: Vec<String>) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
items
.into_iter()
.filter(|x| seen.insert(x.clone()))
.collect()
}
fn gem_lib_dirs() -> Vec<String> {
use std::path::PathBuf;
let mut roots: Vec<PathBuf> = Vec::new();
for var in ["GEM_HOME", "GEM_PATH"] {
if let Ok(v) = std::env::var(var) {
for p in v.split(':').filter(|s| !s.is_empty()) {
roots.push(PathBuf::from(p));
}
}
}
if roots.is_empty() {
if let Some(home) = dirs::home_dir() {
roots.push(home.join(".rubylang"));
}
}
let mut libs = Vec::new();
for root in roots {
let spec_dir = root.join("specifications");
if let Ok(rd) = std::fs::read_dir(root.join("gems")) {
for e in rd.flatten() {
let gem_dir = e.path();
let spec = spec_dir.join(format!("{}.gemspec", e.file_name().to_string_lossy()));
let paths = gemspec_require_paths(&spec).unwrap_or_else(|| vec!["lib".into()]);
for p in paths {
let lib = gem_dir.join(&p);
if lib.is_dir() {
libs.push(lib.to_string_lossy().into_owned());
}
}
}
}
}
libs
}
fn gemspec_require_paths(spec: &std::path::Path) -> Option<Vec<String>> {
let text = std::fs::read_to_string(spec).ok()?;
let line = text.lines().find(|l| l.contains("require_paths"))?;
let open = line.find('[')?;
let close = line[open..].find(']')? + open;
let inner = &line[open + 1..close];
let paths: Vec<String> = inner
.split(',')
.filter_map(|part| {
let p = part.trim().trim_end_matches(".freeze").trim();
let p = p.trim_matches(|c| c == '"' || c == '\'');
(!p.is_empty()).then(|| p.to_string())
})
.collect();
(!paths.is_empty()).then_some(paths)
}
fn is_builtin_exception_name(name: &str) -> bool {
name.ends_with("Error")
|| name.starts_with("Errno::")
|| matches!(
name,
"Exception" | "StopIteration" | "SystemExit" | "SignalException" | "Interrupt"
)
}
fn builtin_exception_parent(name: &str) -> Option<&'static str> {
Some(match name {
"Exception" => return None,
"NoMemoryError" | "ScriptError" | "SecurityError" | "SignalException" | "StandardError"
| "SystemExit" | "SystemStackError" => "Exception",
"LoadError" | "NotImplementedError" | "SyntaxError" => "ScriptError",
"Interrupt" => "SignalException",
n if n.starts_with("Errno::") => "SystemCallError",
"UncaughtThrowError" => "ArgumentError",
"EOFError" => "IOError",
"KeyError" | "StopIteration" => "IndexError",
"ClosedQueueError" => "StopIteration",
"NoMethodError" => "NameError",
"FloatDomainError" => "RangeError",
"FrozenError" => "RuntimeError",
"NoMatchingPatternKeyError" => "NoMatchingPatternError",
n if n.starts_with("Encoding::") => "EncodingError",
_ => "StandardError",
})
}
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>",
}
}
thread_local! {
static DEBUG_MODE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
const VM_POOL_MAX: usize = 64;
#[derive(Clone, Copy, PartialEq, Eq)]
enum ChunkId {
None,
Proc(usize),
Method(u64),
}
impl ChunkId {
fn same(self, other: ChunkId) -> bool {
!matches!(self, ChunkId::None) && self == other
}
}
thread_local! {
static VM_POOL: std::cell::RefCell<Vec<(ChunkId, VM)>> =
const { std::cell::RefCell::new(Vec::new()) };
}
pub fn next_method_chunk_id() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
pub fn set_debug_mode(on: bool) {
DEBUG_MODE.with(|d| d.set(on));
}
fn run_chunk_on(chunk: Chunk) -> Result<Value, String> {
run_chunk_pooled(ChunkId::None, &[], || chunk)
}
pub fn run_proc_chunk(id: usize) -> Result<Value, String> {
let file = with_host(|h| h.procs[id].file.clone());
let pushed = enter_code_file(file.as_deref());
let r = run_chunk_pooled(ChunkId::Proc(id), &[], || {
with_host(|h| h.procs[id].chunk.clone())
});
leave_code_file(pushed);
r
}
fn run_method_chunk(def: &MethodDef, args: &[Value]) -> Result<Value, String> {
let n = def.slot_params as usize;
let seed: Vec<Value> = (0..n)
.map(|i| args.get(i).cloned().unwrap_or(Value::Undef))
.collect();
let pushed = enter_code_file(def.file.as_deref());
let r = run_chunk_pooled(ChunkId::Method(def.chunk_id), &seed, || {
(*def.chunk).clone()
});
leave_code_file(pushed);
r
}
fn run_chunk_pooled(
id: ChunkId,
slot_seed: &[Value],
fetch: impl FnOnce() -> Chunk,
) -> Result<Value, String> {
let mut vm = match VM_POOL.with(|p| {
let mut pool = p.borrow_mut();
pool.iter()
.rposition(|(k, _)| id.same(*k))
.map(|i| pool.swap_remove(i).1)
}) {
Some(mut vm) => {
let own = std::mem::take(&mut vm.chunk);
vm.reset(own);
vm
}
None => match VM_POOL.with(|p| p.borrow_mut().pop()) {
Some((_, mut vm)) => {
vm.reset(fetch());
vm
}
None => {
let mut vm = VM::new(fetch());
crate::builtins::install(&mut vm);
vm.set_numeric_hook(std::sync::Arc::new(|op, a, b| {
crate::builtins::numeric_hook(op, a, b)
}));
vm
}
},
};
let native = crate::aot::native_entry(vm.chunk.native_id);
for (i, v) in slot_seed.iter().enumerate() {
vm.set_slot(i as u16, v.clone());
}
let outcome = if let Some(entry) = native {
let _ = entry(&mut vm as *mut VM);
vm.take_aot_result()
} else if DEBUG_MODE.with(|d| d.get()) {
vm.set_extension_handler(Box::new(|vm, id, _| {
if id == ext::DBG_LINE {
crate::dap::on_debug_line(vm);
}
}));
vm.run()
} else {
vm.enable_tracing_jit();
vm.run()
};
let result = match with_host(|h| h.take_error()) {
Some(e) => Err(e),
None => match outcome {
VMResult::Ok(v) => Ok(v),
VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
VMResult::Error(e) => {
let native = take_native_raise_frame();
if with_host(|h| h.has_pending_exc()) {
let line = vm
.chunk
.lines
.get(vm.ip.wrapping_sub(1))
.copied()
.unwrap_or(0);
let src = current_file_path().unwrap_or_else(|| "-e".into());
if with_host(|h| h.pending_exc_needs_backtrace()) {
let mut stack = raise_backtrace(line);
if let (Some(label), Some(top)) = (native, stack.first()) {
let frame = LiveFrame {
path: top.path.clone(),
line: top.line,
label,
};
stack.insert(0, frame);
}
with_host(|h| h.record_raise_backtrace(stack));
} else {
with_host(|h| h.record_backtrace_frame(&src, line));
}
}
Err(e)
}
},
};
VM_POOL.with(|p| {
let mut pool = p.borrow_mut();
if pool.len() < VM_POOL_MAX {
pool.push((id, vm));
}
});
result
}
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)"));
}
if r.is_err() {
if let Some(code) = with_host(|h| h.pending_system_exit()) {
with_host(|h| h.pending_exc = None);
let code = run_at_exit_handlers().unwrap_or(code);
if with_host(|h| h.capturing()) {
with_host(|h| h.exit_status = Some(code));
return r;
}
use std::io::Write;
let _ = std::io::stdout().flush();
std::process::exit(code);
}
}
if r.is_err() {
if let Some(formatted) = uncaught_report() {
return Err(formatted);
}
}
r
}
fn uncaught_report() -> Option<String> {
let exc = with_host(|h| h.pending_exc.take())?;
let detailed = crate::builtins::uncaught_detailed_message(&exc);
with_host(|h| {
h.pending_exc = Some(exc);
h.format_uncaught_as(detailed)
})
}
pub fn run_at_exit_handlers() -> Option<i32> {
let mut status = None;
while let Some(p) = with_host(|h| h.at_exit_procs.pop()) {
if let Err(e) = call_proc(&p, &[]) {
with_host(|h| {
h.signal = None;
h.error = None;
});
if let Some(code) = with_host(|h| h.pending_system_exit()) {
with_host(|h| h.pending_exc = None);
status = Some(code);
} else {
let msg = uncaught_report().unwrap_or(e);
eprintln!("{msg}");
status = Some(1);
}
}
}
status
}
pub fn run_required_main(chunk: Chunk) -> Result<Value, String> {
let saved_active = with_host(|h| {
let frame_id = next_frame_id();
h.required_tops.insert(frame_id);
h.frames.push(Frame {
scope: Scope {
locals: new_env(),
block: None,
self_obj: Value::Obj(0),
method_name: None,
def_class: None,
frame_id,
},
args: Vec::new(),
line: 0,
});
h.active_scope.take()
});
let r = run_chunk_on(chunk);
with_host(|h| {
h.frames.pop();
h.active_scope = saved_active;
h.signal.take();
});
r
}
thread_local! {
static IN_ADVICE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}
fn in_advice() -> bool {
IN_ADVICE.with(|f| f.get() > 0)
}
fn fire_advice(handler: &str, args: &[Value]) -> Result<Value, String> {
IN_ADVICE.with(|f| f.set(f.get() + 1));
let r = call_method(handler, args, None);
IN_ADVICE.with(|f| f.set(f.get() - 1));
r
}
fn fire_advice_block(handler: &str, args: &[Value], block: Option<Value>) -> Result<Value, String> {
IN_ADVICE.with(|f| f.set(f.get() + 1));
let r = call_method(handler, args, block);
IN_ADVICE.with(|f| f.set(f.get() - 1));
r
}
#[allow(clippy::too_many_arguments)]
fn run_around(
handlers: &[String],
def: &MethodDef,
self_obj: &Value,
args: &[Value],
block: &Option<Value>,
method_name: &Option<String>,
def_class: &Option<String>,
) -> Result<Value, String> {
let base = with_host(|h| h.around_len());
let idx = with_host(|h| {
h.push_around(
handlers.to_vec(),
def.clone(),
self_obj.clone(),
args.to_vec(),
block.clone(),
method_name.clone(),
def_class.clone(),
)
});
let r = drive_around(idx);
with_host(|h| h.truncate_around(base));
r
}
fn drive_around(idx: usize) -> Result<Value, String> {
let call = with_host(|h| h.around_call(idx));
match call.handlers.split_first() {
None => run_method(
&call.def,
call.self_obj,
&call.args,
call.block,
call.method_name,
call.def_class,
),
Some((handler, rest)) => {
let child = with_host(|h| {
h.push_around(
rest.to_vec(),
call.def.clone(),
call.self_obj.clone(),
call.args.clone(),
call.block.clone(),
call.method_name.clone(),
call.def_class.clone(),
)
});
let blk = with_host(|h| h.new_around_block(child));
fire_advice_block(handler, &call.args, Some(blk))
}
}
}
fn kw_list(names: &[String]) -> String {
names
.iter()
.map(|n| format!(":{n}"))
.collect::<Vec<_>>()
.join(", ")
}
fn check_arity(def: &MethodDef, args: &[Value]) -> Result<(), String> {
check_call_arity(&ArityFacts::of_method(def), args)
}
pub struct ArityFacts<'a> {
req: u16,
opt: u16,
has_rest: bool,
kwnames: &'a [String],
kwreq: &'a [String],
has_kwrest: bool,
no_kw: bool,
}
impl<'a> ArityFacts<'a> {
pub fn of_method(def: &'a MethodDef) -> Self {
ArityFacts {
req: def.req,
opt: def.opt,
has_rest: def.splat.is_some(),
kwnames: &def.kwparams,
kwreq: &def.kwreq,
has_kwrest: def
.kwsplat
.as_deref()
.is_some_and(|k| k != crate::parser::NO_KEYWORDS_PARAM),
no_kw: def.kwsplat.as_deref() == Some(crate::parser::NO_KEYWORDS_PARAM),
}
}
pub fn of_block(arity: &'a crate::ast::BlockArity, has_rest: bool) -> Self {
ArityFacts {
req: arity.req,
opt: arity.opt,
has_rest,
kwnames: &arity.kwnames,
kwreq: &arity.kwreq,
has_kwrest: arity
.kwsplat
.as_deref()
.is_some_and(|k| k != crate::parser::NO_KEYWORDS_PARAM),
no_kw: arity.kwsplat.as_deref() == Some(crate::parser::NO_KEYWORDS_PARAM),
}
}
pub fn min_max(&self) -> (i64, Option<i64>) {
let min = self.req as i64 + !self.kwreq.is_empty() as i64;
let max = if self.has_rest {
None
} else {
Some(
self.req as i64
+ self.opt as i64
+ (!self.kwnames.is_empty() || self.has_kwrest) as i64,
)
};
(min, max)
}
pub fn arity_value(&self, strict: bool) -> i64 {
let (min, max) = self.min_max();
let fixed = if strict {
max == Some(min)
} else {
max.is_some()
};
if fixed {
min
} else {
-min - 1
}
}
}
fn check_call_arity(def: &ArityFacts, args: &[Value]) -> Result<(), String> {
if def.no_kw {
let passed = args.last().is_some_and(|v| {
with_host(|h| h.is_kwargs(v) && h.as_hash(v).is_some_and(|m| !m.is_empty()))
});
if passed {
return Err(crate::builtins::raise_exc(
"ArgumentError",
"no keywords accepted",
));
}
}
let wants_kw = !def.kwnames.is_empty() || def.has_kwrest;
let (positional, kwhash) = if wants_kw {
match args.last() {
Some(v) if with_host(|h| h.is_kwargs(v) && h.as_hash(v).is_some()) => {
(args.len() - 1, with_host(|h| h.as_hash(v)))
}
_ => (args.len(), None),
}
} else {
(args.len(), None)
};
let (req, opt) = (def.req as usize, def.opt as usize);
let ok = if def.has_rest {
positional >= req
} else {
positional >= req && positional <= req + opt
};
if !ok {
let expected = if def.has_rest {
format!("{req}+")
} else if opt > 0 {
format!("{req}..{}", req + opt)
} else {
req.to_string()
};
let suffix = match def.kwreq.len() {
0 => String::new(),
1 => format!("; required keyword: {}", def.kwreq[0]),
_ => format!("; required keywords: {}", def.kwreq.join(", ")),
};
return Err(crate::builtins::raise_exc(
"ArgumentError",
&format!("wrong number of arguments (given {positional}, expected {expected}{suffix})"),
));
}
if !wants_kw {
return Ok(());
}
let missing: Vec<String> = def
.kwreq
.iter()
.filter(|k| {
!kwhash
.as_ref()
.is_some_and(|m| m.contains_key(&RKey::Sym((*k).clone())))
})
.cloned()
.collect();
if !missing.is_empty() {
let label = if missing.len() == 1 {
"missing keyword"
} else {
"missing keywords"
};
return Err(crate::builtins::raise_exc(
"ArgumentError",
&format!("{label}: {}", kw_list(&missing)),
));
}
if !def.has_kwrest {
let unknown: Vec<String> = kwhash
.iter()
.flat_map(|m| m.keys())
.filter_map(|k| match k {
RKey::Sym(s) if !def.kwnames.iter().any(|p| p == s) => Some(s.clone()),
_ => None,
})
.collect();
if !unknown.is_empty() {
let label = if unknown.len() == 1 {
"unknown keyword"
} else {
"unknown keywords"
};
return Err(crate::builtins::raise_exc(
"ArgumentError",
&format!("{label}: {}", kw_list(&unknown)),
));
}
}
Ok(())
}
pub fn run_top_method(
def: &MethodDef,
self_obj: Value,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
run_method(def, self_obj, args, block, Some(name.to_string()), None)
}
#[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> {
if with_host(|h| h.frame_depth()) > 2000 {
return Err(format!(
"stack level too deep: {}",
method_name.as_deref().unwrap_or("(unknown)")
));
}
let advice: Option<Vec<(Advice, String)>> = if intercepts::any() && !in_advice() {
method_name
.as_deref()
.map(intercepts::matches)
.filter(|m| !m.is_empty())
} else {
None
};
if let Some(adv) = &advice {
for (kind, handler) in adv {
if *kind == Advice::Before {
fire_advice(handler, args)?;
}
}
let arounds: Vec<String> = adv
.iter()
.filter(|(k, _)| *k == Advice::Around)
.map(|(_, h)| h.clone())
.collect();
if !arounds.is_empty() {
let val = run_around(
&arounds,
def,
&self_obj,
args,
&block,
&method_name,
&def_class,
)?;
for (kind, handler) in adv {
if *kind == Advice::After {
fire_advice(handler, std::slice::from_ref(&val))?;
}
}
return Ok(val);
}
}
let class_body_target = match (&method_name, &def_class) {
(Some(n), Some(c)) if n.starts_with("__class_body__") => Some(c.clone()),
_ => None,
};
check_arity(def, args)?;
let block = crate::builtins::coerce_block_arg(block)?;
let frame_id = next_frame_id();
let saved_active = with_host(|h| {
let mut binding = h.bind_params(
&def.params,
def.positional_shape(),
&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,
frame_id,
},
args: args.to_vec(),
line: 0,
});
h.active_scope.take()
});
let def_target_pushed = DEF_TARGET.with(|t| {
let mut b = t.borrow_mut();
if let Some(cls) = &class_body_target {
b.push(DefTarget::Instance(cls.clone()));
true
} else if b.is_empty() {
false
} else {
b.push(DefTarget::None);
true
}
});
let r = run_method_chunk(def, args);
if def_target_pushed {
DEF_TARGET.with(|t| {
t.borrow_mut().pop();
});
}
let sig = with_host(|h| {
h.frames.pop();
h.active_scope = saved_active;
h.drop_frame_match(frame_id);
h.signal.take()
});
let result = match sig {
Some(Signal::Return(v, None)) => Ok(v),
Some(Signal::Return(v, Some(home))) => {
if home == frame_id {
Ok(v)
} else {
with_host(|h| h.signal = Some(Signal::Return(v, Some(home))));
r
}
}
Some(other @ Signal::Throw(..)) => {
with_host(|h| h.signal = Some(other));
r
}
Some(other @ Signal::Break(_)) => {
with_host(|h| h.signal = Some(other));
r
}
_ => r,
};
let Some(adv) = advice else {
return result;
};
match result {
Ok(val) => {
for (kind, handler) in &adv {
if *kind == Advice::After {
fire_advice(handler, std::slice::from_ref(&val))?;
}
}
Ok(val)
}
err => err,
}
}
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}' for {}",
with_host(|h| h.receiver_phrase(&self_obj))
));
};
run_method(&def, self_obj, args, block, Some(name.into()), None)
}
pub fn call_method_def(
recv: Value,
def: &MethodDef,
owner: &str,
name: &str,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
run_method(
def,
recv,
args,
block,
Some(name.into()),
Some(owner.into()),
)
}
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 {}",
with_host(|h| h.receiver_phrase(&recv))
)
})?;
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> {
call_super_blk(explicit_args, None)
}
pub fn call_super_blk(
explicit_args: Option<Vec<Value>>,
block_override: Option<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());
};
if RubyHost::is_refinement_class(&def_class) {
let args = explicit_args.unwrap_or(cur_args);
let block = match block_override {
Some(b) => Some(b),
None => with_host(|h| h.cur_scope().block.clone()),
};
with_host(|h| h.skip_refined_once(&method));
return crate::builtins::dispatch(&self_obj, &method, &args, block);
}
let method = with_host(|h| h.alias_original(&def_class, &method)).unwrap_or(method);
if with_host(|h| h.object_class(&self_obj)).is_none() {
if let Some(cls) = with_host(|h| h.classref_name(&self_obj)) {
if let Some((def, owner)) =
with_host(|h| h.find_super_class_method(&cls, &def_class, &method))
{
let args = explicit_args.unwrap_or(cur_args);
let block = match block_override {
Some(b) => Some(b),
None => with_host(|h| h.cur_scope().block.clone()),
};
return run_method(&def, self_obj, &args, block, Some(method), Some(owner));
}
let _ = cls;
}
}
let recv_class = with_host(|h| h.object_class(&self_obj)).unwrap_or_else(|| def_class.clone());
let Some((def, owner)) = with_host(|h| h.find_super(&recv_class, &def_class, &method)) else {
if method == "initialize" {
let args = explicit_args.unwrap_or(cur_args);
let is_exc = with_host(|h| h.is_exception_class(&recv_class));
if is_exc {
crate::builtins::exception_initialize(&self_obj, &recv_class, &args)?;
} else if with_host(|h| h.is_struct_class(&recv_class)) {
crate::builtins::struct_default_init(&self_obj, &recv_class, &args)?;
}
return Ok(Value::Undef);
}
if method == "respond_to_missing?" {
return Ok(Value::Bool(false));
}
if matches!(method.as_str(), "subclasses" | "descendants") {
if let Some(cls) = with_host(|h| h.classref_name(&self_obj)) {
let names = with_host(|h| {
if method == "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();
return Ok(with_host(|h| h.new_array(refs)));
}
return Ok(with_host(|h| h.new_array(vec![])));
}
if matches!(method.as_str(), "backtrace" | "backtrace_locations") {
let stored = with_host(|h| h.ivar_of(&self_obj, "backtrace"));
return Ok(if matches!(stored, Value::Undef) {
with_host(|h| h.new_array(vec![]))
} else {
stored
});
}
if method == "cause" {
return Ok(with_host(|h| h.ivar_of(&self_obj, "cause")));
}
if matches!(method.as_str(), "include" | "prepend" | "extend") {
let args = explicit_args.clone().unwrap_or_else(|| cur_args.clone());
if let Some(cls) = with_host(|h| h.classref_name(&self_obj)) {
for a in &args {
if let Some(m) = with_host(|h| h.classref_name(a)) {
with_host(|h| h.class_mixin(&cls, &m, &method));
}
}
}
return Ok(self_obj.clone());
}
if matches!(method.as_str(), "append_features" | "prepend_features") {
let args = explicit_args.clone().unwrap_or_else(|| cur_args.clone());
if let (Some(module), Some(base)) = (
with_host(|h| h.classref_name(&self_obj)),
args.first().and_then(|a| with_host(|h| h.classref_name(a))),
) {
let kind = if method == "append_features" {
"include"
} else {
"prepend"
};
with_host(|h| h.class_mixin(&base, &module, kind));
}
return Ok(Value::Undef);
}
if matches!(
method.as_str(),
"included"
| "extended"
| "prepended"
| "inherited"
| "method_added"
| "method_removed"
| "method_undefined"
| "singleton_method_added"
| "singleton_method_removed"
| "singleton_method_undefined"
) {
return Ok(Value::Undef);
}
if method == "autoload" {
let args = explicit_args.unwrap_or(cur_args);
if let (Some(const_arg), Some(path_arg)) = (args.first(), args.get(1)) {
if let Some(cls) = with_host(|h| h.classref_name(&self_obj)) {
let const_name = with_host(|h| h.to_s(const_arg));
let path = with_host(|h| h.as_str(path_arg)).unwrap_or_default();
let full = format!("{cls}::{const_name}");
with_host(|h| h.set_autoload(&full, &path));
}
}
return Ok(Value::Undef);
}
if matches!(method.as_str(), "is_a?" | "kind_of?" | "instance_of?") {
let args = explicit_args.clone().unwrap_or_else(|| cur_args.clone());
let ans = args
.first()
.and_then(|arg| {
with_host(|h| h.classref_name(arg)).map(|cname| {
if method == "instance_of?" {
with_host(|h| h.class_of(&self_obj)) == cname
} else {
with_host(|h| h.is_a(&self_obj, &cname))
}
})
})
.unwrap_or(false);
return Ok(Value::Bool(ans));
}
if method == "respond_to?" {
let args = explicit_args.clone().unwrap_or_else(|| cur_args.clone());
let mname = args
.first()
.map(|a| with_host(|h| h.to_s(a)))
.unwrap_or_default();
let cls = with_host(|h| h.class_of(&self_obj));
let ans = with_host(|h| {
h.is_method_defined(&cls, &mname) || h.attr_access(&cls, &mname).is_some()
});
return Ok(Value::Bool(ans));
}
if method == "method_missing" {
let args = explicit_args.clone().unwrap_or_else(|| cur_args.clone());
let mname = args
.first()
.map(|a| with_host(|h| h.to_s(a)))
.unwrap_or_default();
let target = with_host(|h| match h.classref_name(&self_obj) {
Some(c) => format!("class {c}"),
None => format!("an instance of {}", h.class_of(&self_obj)),
});
return Err(crate::builtins::raise_exc(
"NoMethodError",
&format!("undefined method '{mname}' for {target}"),
));
}
if method == "new" {
let args = explicit_args.unwrap_or(cur_args);
let target =
with_host(|h| h.classref_name(&self_obj)).unwrap_or_else(|| recv_class.clone());
let obj = with_host(|h| h.new_object(&target));
if let Some((def, owner)) = with_host(|h| h.find_method_owner(&target, "initialize")) {
run_method(
&def,
obj.clone(),
&args,
block_override,
Some("initialize".into()),
Some(owner),
)?;
}
return Ok(obj);
}
let base = with_host(|h| h.dispatch_class(&self_obj));
if base != recv_class {
let args = explicit_args.clone().unwrap_or_else(|| cur_args.clone());
let block = match block_override.clone() {
Some(b) => Some(b),
None => with_host(|h| h.cur_scope().block.clone()),
};
let r = crate::builtins::dispatch_by_type(&base, &self_obj, &method, &args, block);
match &r {
Ok(_) => return r,
Err(e) if !e.starts_with("undefined method") => return r,
_ => {}
}
}
if crate::builtins::is_exception_class(&recv_class) {
let args = explicit_args.clone().unwrap_or_else(|| cur_args.clone());
let block = match block_override.clone() {
Some(b) => Some(b),
None => with_host(|h| h.cur_scope().block.clone()),
};
let r = crate::builtins::dispatch_object_native(
&self_obj,
&recv_class,
&method,
&args,
block,
);
match &r {
Ok(_) => return r,
Err(e) if !e.starts_with("undefined method") => return r,
_ => {
with_host(|h| h.take_pending_exc());
}
}
if method == "inspect" {
let s = crate::builtins::dispatch(&self_obj, "to_s", &[], None)?;
let msg = with_host(|h| h.to_s(&s));
let shown = if msg.is_empty() {
recv_class.clone()
} else if msg.contains('\n') {
format!("#<{recv_class}:{}>", inspect_string(&msg))
} else {
format!("#<{recv_class}: {msg}>")
};
return Ok(with_host(|h| h.new_string(shown)));
}
}
if let Some(native) = with_host(|h| {
h.find_alias(&recv_class, &method)
.and_then(|t| RubyHost::native_alias_target(&t).map(str::to_string))
}) {
let args = explicit_args.clone().unwrap_or_else(|| cur_args.clone());
let block = match block_override.clone() {
Some(b) => Some(b),
None => with_host(|h| h.cur_scope().block.clone()),
};
return crate::builtins::dispatch(&self_obj, &native, &args, block);
}
if let Some((field, is_writer)) = with_host(|h| h.attr_access(&recv_class, &method)) {
let args = explicit_args.clone().unwrap_or_else(|| cur_args.clone());
return Ok(if is_writer {
let v = args.first().cloned().unwrap_or(Value::Undef);
with_host(|h| h.set_ivar_of(&self_obj, &field, v.clone()));
v
} else {
with_host(|h| h.ivar_of(&self_obj, &field))
});
}
if matches!(
method.as_str(),
"initialize_copy" | "initialize_dup" | "initialize_clone"
) {
return Ok(self_obj.clone());
}
return Err(format!("super: no superclass method '{method}'"));
};
let args = explicit_args.unwrap_or(cur_args);
let block = match block_override {
Some(b) => Some(b),
None => 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_proc_chunk(id);
with_host(|h| {
let env = h.cur_env();
for (p, prev) in saved {
match prev {
Some(v) => {
env.lock().unwrap().vars.insert(p, v);
}
None => {
env.lock().unwrap().vars.shift_remove(&p);
}
}
}
});
r
}
pub(crate) fn infer_exc_class(msg: &str) -> String {
let m = msg;
if m.starts_with("undefined method") || m.starts_with("undefined singleton method") {
"NoMethodError"
} else if m.starts_with("undefined local variable")
|| m.starts_with("uninitialized constant")
|| m.starts_with("undefined method 'const")
{
"NameError"
} else if m.starts_with("wrong number of arguments") || m.contains("wrong number of arguments")
{
"ArgumentError"
} else if m.starts_with("can't modify frozen") {
"FrozenError"
} else if m.starts_with("no implicit conversion")
|| m.contains("can't be coerced")
|| m.contains("is not a class")
|| m.contains("is not a module")
|| m.contains("is not a symbol")
{
"TypeError"
} else if m.contains("divided by 0") {
"ZeroDivisionError"
} else if m.starts_with("key not found") || m.starts_with("index") && m.contains("out of") {
"KeyError"
} else if m.starts_with("No such file") || m.contains("Errno::") {
"IOError"
} else if m.starts_with("stack level too deep") {
"SystemStackError"
} else {
"RuntimeError"
}
.to_string()
}
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 mut exc = with_host(|h| h.take_pending_exc());
if exc.is_none() {
let class = infer_exc_class(&e);
let v = with_host(|h| h.new_exception(&class, &e));
exc = Some(v);
}
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 is_bare = rd.classes.is_empty()
&& rd.splat.is_none()
&& with_host(|h| h.exc_matches(&exc_class, "StandardError"));
let static_match = rd
.classes
.iter()
.any(|c| with_host(|h| h.exc_matches(&exc_class, c)));
let splat_match = if !is_bare && !static_match {
match rd.splat {
Some(sid) => {
let cv = run_template(sid, &[])?;
let names: Vec<String> = with_host(|h| match h.as_array(&cv) {
Some(arr) => arr.iter().filter_map(|v| h.classref_name(v)).collect(),
None => h.classref_name(&cv).into_iter().collect(),
});
names
.iter()
.any(|c| with_host(|h| h.exc_matches(&exc_class, c)))
}
None => false,
}
} else {
false
};
let matches = is_bare || static_match || splat_match;
if matches {
let prev_bang = with_host(|h| h.get_global("!"));
with_host(|h| h.seal_backtrace(&excv));
with_host(|h| h.set_global("!", excv.clone()));
result = run_template(rd.body, &[]);
with_host(|h| h.set_global("!", prev_bang));
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 {
let in_flight = if result.is_err() && with_host(|h| h.signal.is_none()) {
with_host(|h| h.pending_exc.clone())
} else {
None
};
let prev_bang = with_host(|h| h.get_global("!"));
if let Some(exc) = &in_flight {
with_host(|h| h.set_global("!", exc.clone()));
}
let ran = run_template(eid, &[]);
if in_flight.is_some() {
with_host(|h| h.set_global("!", prev_bang));
}
ran?;
}
result
}
pub fn call_proc(proc_val: &Value, args: &[Value]) -> Result<Value, String> {
call_proc_self(proc_val, args, None)
}
thread_local! {
static CUR_FIBER: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
static FIBERS: RefCell<Vec<FiberCell>> = const { RefCell::new(Vec::new()) };
static CURRENT_THREAD: RefCell<Option<Value>> = const { RefCell::new(None) };
static MAIN_FIBER: RefCell<Option<Value>> = const { RefCell::new(None) };
}
pub fn current_fiber() -> Value {
if let Some(v) = MAIN_FIBER.with(|c| c.borrow().clone()) {
return v;
}
let v = with_host(|h| h.new_object("Fiber"));
MAIN_FIBER.with(|c| *c.borrow_mut() = Some(v.clone()));
v
}
pub fn current_thread() -> Value {
if let Some(v) = CURRENT_THREAD.with(|c| c.borrow().clone()) {
return v;
}
let v = with_host(|h| {
let id = h.threads.len() as u32;
h.threads.push(ThreadCell {
handle: None,
result: Arc::new(Mutex::new(None)),
exc: Arc::new(Mutex::new(None)),
done: Arc::new(std::sync::atomic::AtomicBool::new(false)),
});
h.alloc(RObj::Thread { id })
});
CURRENT_THREAD.with(|c| *c.borrow_mut() = Some(v.clone()));
v
}
fn with_fibers<R>(f: impl FnOnce(&mut Vec<FiberCell>) -> R) -> R {
FIBERS.with(|c| f(&mut c.borrow_mut()))
}
impl RubyHost {
fn install_fiber_ctx(&mut self, mut c: FiberContext) -> FiberContext {
std::mem::swap(&mut self.active_scope, &mut c.active_scope);
std::mem::swap(&mut self.signal, &mut c.signal);
std::mem::swap(&mut self.catch_tags, &mut c.catch_tags);
std::mem::swap(&mut self.pending_exc, &mut c.pending_exc);
std::mem::swap(&mut self.error, &mut c.error);
std::mem::swap(&mut self.frames, &mut c.frames);
std::mem::swap(&mut self.enum_sinks, &mut c.enum_sinks);
std::mem::swap(&mut self.around_stack, &mut c.around_stack);
CALL_SITES.with(|s| std::mem::swap(&mut *s.borrow_mut(), &mut c.call_sites));
c
}
}
fn fiber_root_frame() -> Frame {
Frame {
scope: Scope {
locals: new_env(),
block: None,
self_obj: Value::Undef,
method_name: None,
def_class: None,
frame_id: next_frame_id(),
},
args: Vec::new(),
line: 0,
}
}
pub fn new_fiber(block: Value) -> Value {
let id = with_fibers(|fibers| {
let id = fibers.len() as u32;
fibers.push(FiberCell {
coro: None,
yielder: std::ptr::null(),
ctx: FiberContext {
frames: vec![fiber_root_frame()],
..FiberContext::default()
},
done: false,
});
id
});
let coro = corosensei::Coroutine::new(
move |yielder: &corosensei::Yielder<Value, Value>, first: Value| {
with_fibers(|fibers| fibers[id as usize].yielder = yielder as *const _ as *const ());
call_proc(&block, std::slice::from_ref(&first))
},
);
with_fibers(|fibers| fibers[id as usize].coro = Some(coro));
with_host(|h| h.alloc(RObj::Fiber { id }))
}
pub fn fiber_yield(v: Value) -> Result<Value, String> {
let id = match CUR_FIBER.with(|c| c.get()) {
Some(id) => id,
None => {
return Err(crate::builtins::raise_exc(
"FiberError",
"attempt to yield on a not resumed fiber",
))
}
};
let yp = with_fibers(|fibers| fibers[id as usize].yielder);
let yielder = unsafe { &*(yp as *const corosensei::Yielder<Value, Value>) };
Ok(yielder.suspend(v))
}
pub fn fiber_resume(fiber: &Value, v: Value) -> Result<Value, String> {
let id = match with_host(|h| h.obj(fiber).cloned()) {
Some(RObj::Fiber { id }) => id,
_ => return Err("not a fiber".into()),
};
if with_fibers(|fibers| fibers[id as usize].done) {
return Err(crate::builtins::raise_exc(
"FiberError",
"attempt to resume a terminated fiber",
));
}
let mut coro = with_fibers(|fibers| fibers[id as usize].coro.take())
.ok_or_else(|| crate::builtins::raise_exc("FiberError", "double resume of a fiber"))?;
let fiber_ctx = with_fibers(|fibers| std::mem::take(&mut fibers[id as usize].ctx));
let caller_ctx = with_host(|h| h.install_fiber_ctx(fiber_ctx));
let prev = CUR_FIBER.with(|c| c.replace(Some(id)));
let out = coro.resume(v);
CUR_FIBER.with(|c| c.set(prev));
let mut fiber_ctx = with_host(|h| h.install_fiber_ctx(caller_ctx));
let out = match out {
corosensei::CoroutineResult::Yield(y) => Ok(y),
corosensei::CoroutineResult::Return(r) => {
with_fibers(|fibers| fibers[id as usize].done = true);
if r.is_err() {
if let Some(exc) = fiber_ctx.pending_exc.take() {
with_host(|h| h.set_pending_exc(exc));
}
}
r }
};
with_fibers(|fibers| {
fibers[id as usize].ctx = fiber_ctx;
fibers[id as usize].coro = Some(coro);
});
out
}
pub fn fiber_alive(fiber: &Value) -> bool {
match with_host(|h| h.obj(fiber).cloned()) {
Some(RObj::Fiber { id }) => with_fibers(|fibers| !fibers[id as usize].done),
_ => false,
}
}
pub fn spawn_thread(block: Value) -> Value {
use std::sync::atomic::AtomicBool;
let result: Arc<Mutex<Option<Result<Value, String>>>> = Arc::new(Mutex::new(None));
let exc: Arc<Mutex<Option<Value>>> = Arc::new(Mutex::new(None));
let done = Arc::new(AtomicBool::new(false));
let (r2, e2, d2) = (result.clone(), exc.clone(), done.clone());
let parent_vm = current_vm();
let handle = std::thread::spawn(move || {
install_current_vm(parent_vm);
let (out, raised) = run_thread_body(&block);
*r2.lock().unwrap() = Some(out);
*e2.lock().unwrap() = raised;
d2.store(true, std::sync::atomic::Ordering::SeqCst);
});
with_host(|h| {
let id = h.threads.len() as u32;
h.threads.push(ThreadCell {
handle: Some(handle),
result,
exc,
done,
});
h.alloc(RObj::Thread { id })
})
}
fn run_thread_body(block: &Value) -> (Result<Value, String>, Option<Value>) {
with_gvl(|| {
let fresh = FiberContext {
frames: vec![fiber_root_frame()],
..FiberContext::default()
};
let saved = with_host(|h| h.install_fiber_ctx(fresh));
let r = call_proc(block, &[]);
let raised = if r.is_err() {
with_host(|h| h.take_pending_exc())
} else {
None
};
with_host(|h| h.install_fiber_ctx(saved));
(r, raised)
})
}
pub fn thread_join(thread: &Value) -> Result<Value, String> {
let id = match with_host(|h| h.obj(thread).cloned()) {
Some(RObj::Thread { id }) => id as usize,
_ => return Err("not a thread".into()),
};
let handle = with_host(|h| h.threads.get_mut(id).and_then(|t| t.handle.take()));
if let Some(handle) = handle {
gvl_blocking(move || {
let _ = handle.join();
});
}
let (result, raised) = with_host(|h| {
h.threads
.get(id)
.map(|t| {
(
t.result.lock().unwrap().clone(),
t.exc.lock().unwrap().clone(),
)
})
.unwrap_or((None, None))
});
if let Some(exc) = raised {
with_host(|h| h.set_pending_exc(exc));
}
result.unwrap_or(Ok(Value::Undef))
}
pub fn thread_alive(thread: &Value) -> bool {
match with_host(|h| h.obj(thread).cloned()) {
Some(RObj::Thread { id }) => with_host(|h| {
h.threads
.get(id as usize)
.map(|t| !t.done.load(std::sync::atomic::Ordering::SeqCst))
.unwrap_or(false)
}),
_ => false,
}
}
pub fn new_queue(cap: Option<usize>) -> u32 {
with_host(|h| {
let id = h.queues.len() as u32;
h.queues.push(Arc::new(QueueSync {
data: Mutex::new(QueueData {
items: std::collections::VecDeque::new(),
closed: false,
cap,
}),
cv: std::sync::Condvar::new(),
}));
id
})
}
fn queue_sync(id: u32) -> Option<Arc<QueueSync>> {
with_host(|h| h.queues.get(id as usize).cloned())
}
pub fn queue_push(id: u32, v: Value, non_block: bool) -> Result<Value, String> {
let q = match queue_sync(id) {
Some(q) => q,
None => return Ok(Value::Undef),
};
let full = {
let d = q.data.lock().unwrap();
d.cap.is_some_and(|c| d.items.len() >= c)
};
if full {
if non_block {
return Err(crate::builtins::raise_exc("ThreadError", "queue full"));
}
gvl_blocking(|| {
let mut d = q.data.lock().unwrap();
while d.cap.is_some_and(|c| d.items.len() >= c) && !d.closed {
d = q.cv.wait(d).unwrap();
}
});
}
{
let mut d = q.data.lock().unwrap();
if d.closed {
return Err(crate::builtins::raise_exc(
"ClosedQueueError",
"queue closed",
));
}
d.items.push_back(v);
}
q.cv.notify_all();
Ok(Value::Undef)
}
pub fn queue_pop(id: u32, non_block: bool) -> Result<Value, String> {
let q = match queue_sync(id) {
Some(q) => q,
None => return Ok(Value::Undef),
};
loop {
{
let mut d = q.data.lock().unwrap();
if let Some(v) = d.items.pop_front() {
drop(d);
q.cv.notify_all(); return Ok(v);
}
if d.closed {
return Ok(Value::Undef);
}
}
if non_block {
return Err(crate::builtins::raise_exc("ThreadError", "queue empty"));
}
gvl_blocking(|| {
let mut d = q.data.lock().unwrap();
while d.items.is_empty() && !d.closed {
d = q.cv.wait(d).unwrap();
}
});
}
}
pub fn queue_len(id: u32) -> usize {
queue_sync(id).map_or(0, |q| q.data.lock().unwrap().items.len())
}
pub fn queue_close(id: u32) {
if let Some(q) = queue_sync(id) {
q.data.lock().unwrap().closed = true;
q.cv.notify_all();
}
}
pub fn queue_closed(id: u32) -> bool {
queue_sync(id).is_some_and(|q| q.data.lock().unwrap().closed)
}
pub fn queue_clear(id: u32) {
if let Some(q) = queue_sync(id) {
q.data.lock().unwrap().items.clear();
}
}
pub fn new_condvar() -> u32 {
with_host(|h| {
let id = h.condvars.len() as u32;
h.condvars.push(Arc::new(CondVarSync {
gen: Mutex::new(0),
cv: std::sync::Condvar::new(),
}));
id
})
}
fn condvar_sync(id: u32) -> Option<Arc<CondVarSync>> {
with_host(|h| h.condvars.get(id as usize).cloned())
}
pub fn condvar_wait(id: u32) {
let Some(c) = condvar_sync(id) else { return };
gvl_blocking(|| {
let mut g = c.gen.lock().unwrap();
let start = *g;
while *g == start {
g = c.cv.wait(g).unwrap();
}
});
}
pub fn condvar_notify(id: u32, all: bool) {
if let Some(c) = condvar_sync(id) {
*c.gen.lock().unwrap() += 1;
if all {
c.cv.notify_all();
} else {
c.cv.notify_one();
}
}
}
pub fn db_open(path: &str) -> Result<Value, String> {
let conn = if path == ":memory:" || path.is_empty() {
rusqlite::Connection::open_in_memory()
} else {
rusqlite::Connection::open(path)
}
.map_err(|e| e.to_string())?;
Ok(with_host(|h| {
let id = h.db_handles.len() as u32;
h.db_handles.push(Some(DbCell {
conn,
results_as_hash: false,
}));
h.alloc(RObj::Db { id })
}))
}
fn db_id(v: &Value) -> Option<u32> {
match with_host(|h| h.obj(v).cloned()) {
Some(RObj::Db { id }) => Some(id),
_ => None,
}
}
pub fn db_execute(
v: &Value,
sql: &str,
binds: &[SqlVal],
) -> Result<(Vec<String>, Vec<Vec<SqlVal>>), String> {
let id = db_id(v).ok_or_else(|| "not a database handle".to_string())?;
with_host(|h| {
let cell = h
.db_handles
.get(id as usize)
.and_then(|c| c.as_ref())
.ok_or_else(|| "cannot use a closed database".to_string())?;
let mut stmt = cell.conn.prepare(sql).map_err(|e| e.to_string())?;
let ncol = stmt.column_count();
let cols: Vec<String> = stmt.column_names().iter().map(|s| s.to_string()).collect();
let nparams = stmt.parameter_count();
let mut binds = binds.to_vec();
binds.resize(binds.len().max(nparams), SqlVal::Null);
let mut rows = stmt
.query(rusqlite::params_from_iter(binds.iter()))
.map_err(|e| e.to_string())?;
let mut out = Vec::new();
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
let mut r = Vec::with_capacity(ncol);
for i in 0..ncol {
let val: SqlVal = row.get(i).map_err(|e| e.to_string())?;
r.push(val);
}
out.push(r);
}
Ok((cols, out))
})
}
pub fn db_last_insert_rowid(v: &Value) -> i64 {
match db_id(v) {
Some(id) => with_host(|h| {
h.db_handles
.get(id as usize)
.and_then(|c| c.as_ref())
.map(|c| c.conn.last_insert_rowid())
.unwrap_or(0)
}),
None => 0,
}
}
pub fn db_changes(v: &Value) -> i64 {
match db_id(v) {
Some(id) => with_host(|h| {
h.db_handles
.get(id as usize)
.and_then(|c| c.as_ref())
.map(|c| c.conn.changes() as i64)
.unwrap_or(0)
}),
None => 0,
}
}
pub fn db_close(v: &Value) {
if let Some(id) = db_id(v) {
with_host(|h| {
if let Some(slot) = h.db_handles.get_mut(id as usize) {
*slot = None;
}
});
}
}
pub fn db_closed(v: &Value) -> bool {
match db_id(v) {
Some(id) => with_host(|h| !matches!(h.db_handles.get(id as usize), Some(Some(_)))),
None => true,
}
}
pub fn db_set_results_as_hash(v: &Value, on: bool) {
if let Some(id) = db_id(v) {
with_host(|h| {
if let Some(Some(cell)) = h.db_handles.get_mut(id as usize) {
cell.results_as_hash = on;
}
});
}
}
pub fn db_results_as_hash(v: &Value) -> bool {
match db_id(v) {
Some(id) => with_host(
|h| matches!(h.db_handles.get(id as usize), Some(Some(c)) if c.results_as_hash),
),
None => false,
}
}
pub fn fiddle_dlopen(path: Option<&str>) -> Result<Value, String> {
let lib = match path {
None => libloading::os::unix::Library::this(),
Some(p) => {
unsafe {
libloading::os::unix::Library::open(Some(p), libc::RTLD_LAZY | libc::RTLD_GLOBAL)
.map_err(|e| e.to_string())?
}
}
};
Ok(with_host(|h| {
let id = h.fiddle_libs.len() as u32;
h.fiddle_libs.push(Some(FiddleLib(lib)));
h.alloc(RObj::FiddleHandle { id })
}))
}
pub fn fiddle_sym(v: &Value, name: &str) -> Result<u64, String> {
let id = match with_host(|h| h.obj(v).cloned()) {
Some(RObj::FiddleHandle { id }) => id,
_ => return Err("not a Fiddle::Handle".to_string()),
};
with_host(|h| {
let lib = h
.fiddle_libs
.get(id as usize)
.and_then(|l| l.as_ref())
.ok_or_else(|| "closed handle".to_string())?;
let mut sym_bytes = name.as_bytes().to_vec();
sym_bytes.push(0);
let sym: libloading::os::unix::Symbol<*mut std::ffi::c_void> =
unsafe { lib.0.get(&sym_bytes).map_err(|e| e.to_string())? };
Ok(sym.into_raw() as u64)
})
}
pub fn fiddle_func_parts(v: &Value) -> Option<(u64, Vec<i32>, i32)> {
match with_host(|h| h.obj(v).cloned()) {
Some(RObj::FiddleFunc { addr, args, ret }) => Some((addr, args, ret)),
_ => None,
}
}
pub fn fiddle_ptr_parts(v: &Value) -> Option<(u64, i64)> {
match with_host(|h| h.obj(v).cloned()) {
Some(RObj::FiddlePtr { addr, size, .. }) => Some((addr, size)),
_ => None,
}
}
pub fn fiddle_func_new(addr: u64, args: Vec<i32>, ret: i32) -> Value {
with_host(|h| h.alloc(RObj::FiddleFunc { addr, args, ret }))
}
pub fn fiddle_handle_close(v: &Value) {
if let Some(RObj::FiddleHandle { id }) = with_host(|h| h.obj(v).cloned()) {
with_host(|h| {
if let Some(slot) = h.fiddle_libs.get_mut(id as usize) {
*slot = None;
}
});
}
}
pub fn fiddle_alloc(buf: Vec<u8>, size: i64) -> Value {
with_host(|h| {
let id = h.fiddle_mem.len() as u32;
h.fiddle_mem.push(Some(buf.into_boxed_slice()));
let addr = h.fiddle_mem[id as usize].as_ref().unwrap().as_ptr() as u64;
h.alloc(RObj::FiddlePtr {
addr,
size,
owned: Some(id),
})
})
}
pub fn fiddle_ptr_raw(addr: u64, size: i64) -> Value {
with_host(|h| {
h.alloc(RObj::FiddlePtr {
addr,
size,
owned: None,
})
})
}
pub fn fiddle_free(v: &Value) {
if let Some(RObj::FiddlePtr {
owned: Some(id), ..
}) = with_host(|h| h.obj(v).cloned())
{
with_host(|h| {
if let Some(slot) = h.fiddle_mem.get_mut(id as usize) {
*slot = None;
}
});
}
}
pub fn fiddle_read_cstr(addr: u64) -> String {
if addr == 0 {
return String::new();
}
unsafe {
std::ffi::CStr::from_ptr(addr as *const std::os::raw::c_char)
.to_string_lossy()
.into_owned()
}
}
pub fn fiddle_read_bytes(addr: u64, len: usize) -> String {
if addr == 0 || len == 0 {
return String::new();
}
unsafe {
let sl = std::slice::from_raw_parts(addr as *const u8, len);
String::from_utf8_lossy(sl).into_owned()
}
}
pub fn fiddle_read_byte(addr: u64) -> u8 {
if addr == 0 {
return 0;
}
unsafe { *(addr as *const u8) }
}
pub fn fiddle_write_bytes(addr: u64, bytes: &[u8]) {
if addr == 0 || bytes.is_empty() {
return;
}
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), addr as *mut u8, bytes.len());
}
}
pub fn fiddle_read_cstr_or_len(addr: u64, size: i64) -> String {
if size > 0 {
let raw = fiddle_read_bytes(addr, size as usize);
match raw.find('\0') {
Some(i) => raw[..i].to_string(),
None => raw,
}
} else {
fiddle_read_cstr(addr)
}
}
pub fn io_alloc_file(file: std::fs::File, path: String) -> Value {
with_host(|h| {
let id = h.io_handles.len() as u32;
h.io_handles.push(IoCell::File {
file: Some(file),
path,
});
h.alloc(RObj::IoHandle { id })
})
}
fn io_id(v: &Value) -> Option<u32> {
match with_host(|h| h.obj(v).cloned()) {
Some(RObj::IoHandle { id }) => Some(id),
_ => None,
}
}
pub fn io_fd_info(v: &Value) -> Result<(i64, bool), String> {
use std::io::IsTerminal;
let id = io_id(v).ok_or("not an IO")?;
with_host(|h| match h.io_handles.get(id as usize) {
Some(IoCell::Stdin) => Ok((0, h.stdin.is_terminal())),
Some(IoCell::Stdout) => Ok((1, std::io::stdout().is_terminal())),
Some(IoCell::Stderr) => Ok((2, std::io::stderr().is_terminal())),
Some(IoCell::File { file: Some(f), .. }) => {
#[cfg(unix)]
let fd = i64::from(std::os::unix::io::AsRawFd::as_raw_fd(f));
#[cfg(not(unix))]
let fd = -1;
Ok((fd, f.is_terminal()))
}
Some(IoCell::File { file: None, .. }) => Err("closed stream".to_string()),
_ => Err("not an IO".to_string()),
})
}
pub fn io_closed(v: &Value) -> bool {
match io_id(v) {
Some(id) => with_host(|h| {
matches!(
h.io_handles.get(id as usize),
Some(IoCell::File { file: None, .. })
)
}),
None => false,
}
}
pub fn write_stdout(s: &str) {
write_stdout_bytes(s.as_bytes());
}
pub fn write_stdout_bytes(s: &[u8]) {
if !redirected_write("stdout", s) {
with_host(|h| h.write_out(s, false));
}
}
pub fn write_stderr(s: &str) {
if !redirected_write("stderr", s.as_bytes()) {
with_host(|h| h.write_out(s.as_bytes(), true));
}
}
pub fn is_standard_stream(global: &str) -> bool {
let target = with_host(|h| h.get_global(global));
match io_id(&target) {
Some(id) => with_host(|h| {
matches!(
h.io_handles.get(id as usize),
Some(IoCell::Stdout) | Some(IoCell::Stderr)
)
}),
None => matches!(target, Value::Undef),
}
}
fn redirected_write(global: &str, s: &[u8]) -> bool {
if is_standard_stream(global) {
return false;
}
let target = with_host(|h| h.get_global(global));
let text = with_host(|h| h.new_utf8_from_bytes(s.to_vec()));
let _ = crate::builtins::dispatch(&target, "write", &[text], None);
true
}
pub fn io_write_str(v: &Value, s: &str) -> Result<usize, String> {
io_write_bytes(v, s.as_bytes())
}
pub fn io_write_bytes(v: &Value, s: &[u8]) -> Result<usize, String> {
use std::io::Write;
let id = io_id(v).ok_or("not an IO")?;
if with_host(|h| matches!(h.io_handles.get(id as usize), Some(IoCell::Stdout))) {
write_stdout_bytes(s);
return Ok(s.len());
}
if with_host(|h| matches!(h.io_handles.get(id as usize), Some(IoCell::Stderr))) {
if !redirected_write("stderr", s) {
with_host(|h| h.write_out(s, true));
}
return Ok(s.len());
}
with_host(|h| match h.io_handles.get_mut(id as usize) {
Some(IoCell::Stdout) | Some(IoCell::Stderr) => unreachable!("handled above"),
Some(IoCell::Stdin) => Err("not opened for writing".to_string()),
Some(IoCell::File { file: Some(f), .. }) => {
f.write_all(s).map(|_| s.len()).map_err(|e| e.to_string())
}
Some(IoCell::File { file: None, .. }) => Err("closed stream".to_string()),
Some(IoCell::TcpListener { .. }) | Some(IoCell::TcpStream { .. }) => {
Err("not an IO".to_string())
}
None => Err("not an IO".to_string()),
})
}
pub fn io_read_all(v: &Value) -> Result<String, String> {
use std::io::Read;
let id = io_id(v).ok_or("not an IO")?;
with_host(|h| {
let mut s = String::new();
match h.io_handles.get_mut(id as usize) {
Some(IoCell::File { file: Some(f), .. }) => {
f.read_to_string(&mut s).map_err(|e| e.to_string())?;
Ok(s)
}
Some(IoCell::File { file: None, .. }) => Err("closed stream".to_string()),
Some(IoCell::Stdin) => {
h.stdin.read_to_string(&mut s).map_err(|e| e.to_string())?;
Ok(s)
}
Some(IoCell::Stdout) | Some(IoCell::Stderr) => {
Err("not opened for reading".to_string())
}
Some(IoCell::TcpListener { .. }) | Some(IoCell::TcpStream { .. }) => {
Err("not an IO".to_string())
}
None => Err("not an IO".to_string()),
}
})
}
pub fn io_with_file<T>(
v: &Value,
op: impl FnOnce(&mut std::fs::File) -> std::io::Result<T>,
) -> Result<T, String> {
let id = io_id(v).ok_or("not an IO")?;
with_host(|h| match h.io_handles.get_mut(id as usize) {
Some(IoCell::File { file: Some(f), .. }) => op(f).map_err(|e| e.to_string()),
Some(IoCell::File { file: None, .. }) => Err("closed stream".to_string()),
_ => Err("Illegal seek".to_string()),
})
}
pub fn io_read_bytes(v: &Value, length: usize) -> Result<Vec<u8>, String> {
use std::io::Read;
io_with_file(v, |f| {
let mut buf = Vec::with_capacity(length);
f.take(length as u64).read_to_end(&mut buf)?;
Ok(buf)
})
}
pub fn io_lineno(v: &Value) -> i64 {
io_id(v)
.map(|id| with_host(|h| h.io_linenos.get(&id).copied().unwrap_or(0)))
.unwrap_or(0)
}
pub fn io_set_lineno(v: &Value, n: i64) {
if let Some(id) = io_id(v) {
with_host(|h| h.io_linenos.insert(id, n));
}
}
pub fn io_sync(v: &Value) -> bool {
let Some(id) = io_id(v) else { return false };
with_host(|h| {
h.io_syncs.get(&id).copied().unwrap_or_else(|| {
matches!(
h.io_handles.get(id as usize),
Some(IoCell::Stderr | IoCell::TcpStream { .. } | IoCell::TcpListener { .. })
)
})
})
}
pub fn io_set_sync(v: &Value, on: bool) {
if let Some(id) = io_id(v) {
with_host(|h| h.io_syncs.insert(id, on));
}
}
pub fn io_gets(v: &Value) -> Result<Value, String> {
use std::io::Read;
let id = io_id(v).ok_or("not an IO")?;
with_host(|h| {
let mut buf: Vec<u8> = Vec::new();
loop {
let mut one = [0u8; 1];
let n = match h.io_handles.get_mut(id as usize) {
Some(IoCell::File { file: Some(f), .. }) => f.read(&mut one),
Some(IoCell::File { file: None, .. }) => return Err("closed stream".to_string()),
Some(IoCell::Stdin) => h.stdin.read(&mut one),
Some(IoCell::Stdout) | Some(IoCell::Stderr) => {
return Err("not opened for reading".to_string())
}
Some(IoCell::TcpListener { .. }) | Some(IoCell::TcpStream { .. }) => {
return Err("not an IO".to_string())
}
None => return Err("not an IO".to_string()),
};
match n {
Ok(0) => break,
Ok(_) => {
buf.push(one[0]);
if one[0] == b'\n' {
break;
}
}
Err(e) => return Err(e.to_string()),
}
}
if buf.is_empty() {
Ok(Value::Undef)
} else {
Ok(h.new_string(String::from_utf8_lossy(&buf).into_owned()))
}
})
}
pub fn io_readlines(v: &Value) -> Result<Vec<Value>, String> {
let all = io_read_all(v)?;
Ok(with_host(|h| {
all.split_inclusive('\n')
.map(|l| h.new_string(l.to_string()))
.collect()
}))
}
pub fn io_close(v: &Value) -> Result<(), String> {
let id = io_id(v).ok_or("not an IO")?;
with_host(|h| {
if let Some(IoCell::File { file, .. }) = h.io_handles.get_mut(id as usize) {
*file = None;
}
});
Ok(())
}
pub fn io_flush(v: &Value) -> Result<(), String> {
use std::io::Write;
let id = io_id(v).ok_or("not an IO")?;
with_host(|h| match h.io_handles.get_mut(id as usize) {
Some(IoCell::Stdout) => std::io::stdout().flush().map_err(|e| e.to_string()),
Some(IoCell::Stderr) => std::io::stderr().flush().map_err(|e| e.to_string()),
Some(IoCell::File { file: Some(f), .. }) => f.flush().map_err(|e| e.to_string()),
_ => Ok(()),
})
}
fn io_alloc_cell(cell: IoCell) -> Value {
with_host(|h| {
let id = h.io_handles.len() as u32;
h.io_handles.push(cell);
h.alloc(RObj::IoHandle { id })
})
}
fn tcp_stream_clone(id: u32) -> Result<std::net::TcpStream, String> {
with_host(|h| match h.io_handles.get(id as usize) {
Some(IoCell::TcpStream {
stream: Some(s), ..
}) => s.try_clone().map_err(|e| e.to_string()),
Some(IoCell::TcpStream { stream: None, .. }) => Err("closed stream".to_string()),
_ => Err("not a TCPSocket".to_string()),
})
}
fn tcp_rbuf_len(id: u32) -> Result<usize, String> {
with_host(|h| match h.io_handles.get(id as usize) {
Some(IoCell::TcpStream { rbuf, .. }) => Ok(rbuf.len()),
_ => Err("not a TCPSocket".to_string()),
})
}
fn tcp_rbuf_take(id: u32, max: usize) -> Vec<u8> {
with_host(|h| match h.io_handles.get_mut(id as usize) {
Some(IoCell::TcpStream { rbuf, .. }) => {
let n = max.min(rbuf.len());
rbuf.drain(..n).collect()
}
_ => Vec::new(),
})
}
fn tcp_fill(id: u32) -> Result<usize, String> {
use std::io::Read;
let stream = tcp_stream_clone(id)?;
let mut buf = [0u8; 4096];
let n = (&stream).read(&mut buf).map_err(|e| e.to_string())?;
with_host(|h| {
if let Some(IoCell::TcpStream { rbuf, .. }) = h.io_handles.get_mut(id as usize) {
rbuf.extend(&buf[..n]);
}
});
Ok(n)
}
fn tcp_new_string(bytes: &[u8]) -> Value {
with_host(|h| h.new_string(String::from_utf8_lossy(bytes).into_owned()))
}
pub fn tcp_listen(host: &str, port: u16) -> Result<Value, String> {
let listener = std::net::TcpListener::bind((host, port)).map_err(|e| e.to_string())?;
let local = listener
.local_addr()
.map(|a| a.to_string())
.unwrap_or_default();
Ok(io_alloc_cell(IoCell::TcpListener {
listener: Some(listener),
local,
}))
}
pub fn tcp_accept(v: &Value) -> Result<Value, String> {
let id = io_id(v).ok_or("not a socket")?;
let listener = with_host(|h| match h.io_handles.get(id as usize) {
Some(IoCell::TcpListener {
listener: Some(l), ..
}) => l.try_clone().map_err(|e| e.to_string()),
Some(IoCell::TcpListener { listener: None, .. }) => Err("closed stream".to_string()),
_ => Err("not a TCPServer".to_string()),
})?;
let (stream, peer) = listener.accept().map_err(|e| e.to_string())?;
Ok(io_alloc_cell(IoCell::TcpStream {
stream: Some(stream),
peer: peer.to_string(),
rbuf: std::collections::VecDeque::new(),
}))
}
pub fn tcp_connect(host: &str, port: u16) -> Result<Value, String> {
let stream = std::net::TcpStream::connect((host, port)).map_err(|e| e.to_string())?;
let peer = stream
.peer_addr()
.map(|a| a.to_string())
.unwrap_or_default();
Ok(io_alloc_cell(IoCell::TcpStream {
stream: Some(stream),
peer,
rbuf: std::collections::VecDeque::new(),
}))
}
pub fn tcp_write(v: &Value, s: &str) -> Result<usize, String> {
use std::io::Write;
let id = io_id(v).ok_or("not a socket")?;
let stream = tcp_stream_clone(id)?;
(&stream)
.write_all(s.as_bytes())
.map_err(|e| e.to_string())?;
Ok(s.len())
}
pub fn tcp_gets(v: &Value) -> Result<Value, String> {
let id = io_id(v).ok_or("not a socket")?;
loop {
let line = with_host(|h| match h.io_handles.get_mut(id as usize) {
Some(IoCell::TcpStream { rbuf, .. }) => Ok(rbuf
.iter()
.position(|&b| b == b'\n')
.map(|pos| rbuf.drain(..=pos).collect::<Vec<u8>>())),
_ => Err("not a TCPSocket".to_string()),
})?;
if let Some(bytes) = line {
return Ok(tcp_new_string(&bytes));
}
if tcp_fill(id)? == 0 {
let rest = tcp_rbuf_take(id, usize::MAX);
return Ok(if rest.is_empty() {
Value::Undef
} else {
tcp_new_string(&rest)
});
}
}
}
pub fn tcp_read(v: &Value, n: Option<usize>) -> Result<Value, String> {
let id = io_id(v).ok_or("not a socket")?;
match n {
Some(n) => {
while tcp_rbuf_len(id)? < n {
if tcp_fill(id)? == 0 {
break;
}
}
let bytes = tcp_rbuf_take(id, n);
if bytes.is_empty() && n > 0 {
return Ok(Value::Undef);
}
Ok(tcp_new_string(&bytes))
}
None => {
while tcp_fill(id)? != 0 {}
let bytes = tcp_rbuf_take(id, usize::MAX);
Ok(tcp_new_string(&bytes))
}
}
}
pub fn tcp_readpartial(v: &Value, n: usize) -> Result<Option<Value>, String> {
let id = io_id(v).ok_or("not a socket")?;
if tcp_rbuf_len(id)? == 0 && tcp_fill(id)? == 0 {
return Ok(None);
}
Ok(Some(tcp_new_string(&tcp_rbuf_take(id, n))))
}
pub fn tcp_read_nonblock(v: &Value, n: usize) -> Result<Option<Value>, String> {
use std::io::Read;
let id = io_id(v).ok_or("not a socket")?;
if tcp_rbuf_len(id)? > 0 {
return Ok(Some(tcp_new_string(&tcp_rbuf_take(id, n))));
}
let stream = tcp_stream_clone(id)?;
stream.set_nonblocking(true).map_err(|e| e.to_string())?;
let mut buf = vec![0u8; n.max(1)];
let res = (&stream).read(&mut buf);
let _ = stream.set_nonblocking(false);
match res {
Ok(0) => Ok(None),
Ok(k) => Ok(Some(tcp_new_string(&buf[..k]))),
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => Err("__EAGAIN__".to_string()),
Err(e) => Err(e.to_string()),
}
}
pub fn tcp_addr(v: &Value, peer: bool) -> Result<Value, String> {
let id = io_id(v).ok_or("not a socket")?;
let addr: std::net::SocketAddr = with_host(|h| match h.io_handles.get(id as usize) {
Some(IoCell::TcpListener {
listener: Some(l), ..
}) if !peer => l.local_addr().map_err(|e| e.to_string()),
Some(IoCell::TcpStream {
stream: Some(s), ..
}) => {
if peer {
s.peer_addr().map_err(|e| e.to_string())
} else {
s.local_addr().map_err(|e| e.to_string())
}
}
Some(IoCell::TcpListener { listener: None, .. })
| Some(IoCell::TcpStream { stream: None, .. }) => Err("closed stream".to_string()),
_ => Err("not a socket".to_string()),
})?;
let fam = if addr.is_ipv6() {
"AF_INET6"
} else {
"AF_INET"
};
let ip = addr.ip().to_string();
Ok(with_host(|h| {
let items = vec![
h.new_string(fam.to_string()),
Value::Int(addr.port() as i64),
h.new_string(ip.clone()),
h.new_string(ip),
];
h.new_array(items)
}))
}
pub fn tcp_close(v: &Value) -> Result<(), String> {
let id = io_id(v).ok_or("not a socket")?;
with_host(|h| match h.io_handles.get_mut(id as usize) {
Some(IoCell::TcpListener { listener, .. }) => *listener = None,
Some(IoCell::TcpStream { stream, .. }) => *stream = None,
_ => {}
});
Ok(())
}
pub fn tcp_closed(v: &Value) -> bool {
match io_id(v) {
Some(id) => with_host(|h| {
matches!(
h.io_handles.get(id as usize),
Some(IoCell::TcpListener { listener: None, .. })
| Some(IoCell::TcpStream { stream: None, .. })
)
}),
None => false,
}
}
thread_local! {
static PROC_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
const PROC_DEPTH_LIMIT: usize = 2000;
struct ProcDepth;
impl ProcDepth {
fn enter() -> Result<Self, String> {
let depth = PROC_DEPTH.with(|c| {
let next = c.get() + 1;
c.set(next);
next
});
if depth > PROC_DEPTH_LIMIT {
PROC_DEPTH.with(|c| c.set(c.get() - 1));
return Err("stack level too deep: block".to_string());
}
Ok(ProcDepth)
}
}
impl Drop for ProcDepth {
fn drop(&mut self) {
PROC_DEPTH.with(|c| c.set(c.get().saturating_sub(1)));
}
}
pub fn call_proc_self(
proc_val: &Value,
args: &[Value],
self_override: Option<&Value>,
) -> Result<Value, String> {
call_proc_self_ctx(proc_val, args, self_override, None, None)
}
pub fn call_proc_block(
proc_val: &Value,
args: &[Value],
block: Option<Value>,
) -> Result<Value, String> {
call_proc_self_ctx(proc_val, args, None, None, block)
}
pub fn call_proc_self_ctx(
proc_val: &Value,
args: &[Value],
self_override: Option<&Value>,
method_ctx: Option<(String, String)>,
passed_block: Option<Value>,
) -> Result<Value, String> {
let _depth = ProcDepth::enter()?;
let (template, scope, kind, is_lambda, home) = match with_host(|h| h.obj(proc_val).cloned()) {
Some(RObj::Proc {
template,
scope,
kind,
is_lambda,
home,
}) => (template, scope, kind, is_lambda, home),
Some(RObj::Method {
recv, name, via, ..
}) => {
return match via {
Some(class) => call_instance_method(recv.clone(), &class, &name, args, None),
None => crate::builtins::call_bound(&recv, &name, args, None),
};
}
Some(RObj::RaiseProc { class, message }) => {
return Err(crate::builtins::raise_exc(&class, &message));
}
Some(RObj::CycleProc(buf)) => {
if buf.is_empty() {
return Ok(Value::Undef);
}
let Some(yielder) = args.first().cloned() else {
return Err("no yielder is available".to_string());
};
loop {
for v in &buf {
crate::builtins::dispatch(&yielder, "<<", std::slice::from_ref(v), None)?;
if has_pending_signal() {
return Ok(Value::Undef);
}
}
}
}
Some(RObj::SeqProc(lo)) => {
let Some(yielder) = args.first().cloned() else {
return Err("no yielder is available".to_string());
};
let mut i = lo;
loop {
crate::builtins::dispatch(&yielder, "<<", &[Value::Int(i)], None)?;
if has_pending_signal() {
return Ok(Value::Undef);
}
i += 1;
}
}
Some(RObj::ProduceProc { init, block }) => {
let Some(yielder) = args.first().cloned() else {
return Err("no yielder is available".to_string());
};
let mut cur = match init {
Some(v) => v,
None => match call_proc(&block, &[Value::Undef]) {
Ok(v) => v,
Err(e) if is_stop_iteration(&e) => return Ok(Value::Undef),
Err(e) => return Err(e),
},
};
loop {
crate::builtins::dispatch(&yielder, "<<", std::slice::from_ref(&cur), None)?;
if has_pending_signal() {
return Ok(Value::Undef);
}
cur = match call_proc(&block, std::slice::from_ref(&cur)) {
Ok(v) => v,
Err(e) if is_stop_iteration(&e) => return Ok(Value::Undef),
Err(e) => return Err(e),
};
}
}
Some(RObj::StepProc { from, by, float }) => {
let Some(yielder) = args.first().cloned() else {
return Err("no yielder is available".to_string());
};
if float {
let to_f = |v: &Value| -> Result<f64, String> {
match crate::builtins::dispatch(v, "to_f", &[], None)? {
Value::Float(f) => Ok(f),
other => Ok(match other {
Value::Int(n) => n as f64,
_ => 0.0,
}),
}
};
let (base, unit) = (to_f(&from)?, to_f(&by)?);
let mut i = 0.0f64;
loop {
let v = Value::Float(i * unit + base);
crate::builtins::dispatch(&yielder, "<<", &[v], None)?;
if has_pending_signal() {
return Ok(Value::Undef);
}
i += 1.0;
}
}
let mut cur = from;
loop {
crate::builtins::dispatch(&yielder, "<<", std::slice::from_ref(&cur), None)?;
if has_pending_signal() {
return Ok(Value::Undef);
}
cur = crate::builtins::dispatch(&cur, "+", std::slice::from_ref(&by), None)?;
}
}
Some(RObj::DeriveProc { src, kind }) => {
let Some(yielder) = args.first().cloned() else {
return Err("no yielder is available".to_string());
};
return crate::builtins::drive_derived(&src, &kind, &yielder);
}
Some(RObj::SymProc(s)) => {
return match args.split_first() {
Some((recv, rest)) => crate::builtins::dispatch(recv, &s, rest, None),
None => Err("no receiver given".to_string()),
};
}
Some(_) | None => {
let conv = crate::builtins::probe_dispatch(proc_val, "to_proc", &[])
.filter(|c| c != proc_val)
.ok_or_else(|| crate::builtins::conv_error(proc_val, "Proc"))?;
return crate::builtins::dispatch(&conv, "call", args, None);
}
};
match kind {
ProcKind::Composed { first, second } => {
let call = |f: &Value, a: &[Value]| {
if with_host(|h| h.is_proc(f)) {
call_proc(f, a)
} else {
crate::builtins::dispatch(f, "call", a, None)
}
};
let mid = call(&first, args)?;
return call(&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,
kind: ProcKind::Normal,
home,
})
});
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,
},
home,
})
}));
}
ProcKind::MethodCurried {
target,
arity,
collected,
} => {
let mut all = collected.clone();
all.extend_from_slice(args);
if all.len() >= arity {
return call_proc(&target, &all);
}
return Ok(with_host(|h| {
h.alloc(RObj::Proc {
template,
scope: scope.clone(),
is_lambda: true,
kind: ProcKind::MethodCurried {
target: target.clone(),
arity,
collected: all,
},
home,
})
}));
}
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::SetsMatch {
inner,
matches,
next,
} => {
with_host(|h| {
if let Some(RObj::Proc {
kind: ProcKind::SetsMatch { next: n, .. },
..
}) = h.obj_mut(proc_val)
{
*n += 1;
}
if let Some(md) = matches.get(next) {
h.set_global("~", md.clone());
}
});
return call_proc(&inner, args);
}
ProcKind::Around(idx) => {
return drive_around(idx);
}
ProcKind::Normal => {}
}
let def = with_host(|h| h.proc_sig(template));
let strict = is_lambda || method_ctx.is_some();
if strict {
check_call_arity(&ArityFacts::of_block(&def.arity, def.splat.is_some()), args)?;
}
let kw_cap = def.params.last().is_some_and(|p| p == "__blockkw");
let (args, kwhash) = match args.last() {
Some(last) if kw_cap && with_host(|h| h.is_kwargs(last)) => {
(&args[..args.len() - 1], last.clone())
}
_ => (args, Value::Undef),
};
let params = &def.params[..def.params.len() - kw_cap as usize];
let bound: Vec<Value> = if !strict && 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());
if kw_cap {
child
.lock()
.unwrap()
.vars
.insert("__blockkw".to_string(), kwhash);
}
match def.splat {
None => {
for (i, p) in params.iter().enumerate() {
child
.lock()
.unwrap()
.vars
.insert(p.clone(), bound.get(i).cloned().unwrap_or(Value::Undef));
}
}
Some(si) => {
let after = params.len() - si - 1;
for (i, p) in params.iter().take(si).enumerate() {
let v = bound.get(i).cloned().unwrap_or(Value::Undef);
child.lock().unwrap().vars.insert(p.clone(), v);
}
let splat_end = bound.len().saturating_sub(after).max(si);
let rest: Vec<Value> = bound
.get(si..splat_end)
.map(|s| s.to_vec())
.unwrap_or_default();
let arr = with_host(|h| h.new_array(rest));
child.lock().unwrap().vars.insert(params[si].clone(), arr);
for (j, p) in params.iter().skip(si + 1).enumerate() {
let v = bound.get(splat_end + j).cloned().unwrap_or(Value::Undef);
child.lock().unwrap().vars.insert(p.clone(), v);
}
}
}
if let Some(bp) = &def.arity.blockparam {
let v = passed_block.clone().unwrap_or(Value::Undef);
child.lock().unwrap().vars.insert(bp.clone(), v);
}
for name in crate::compiler::block_own_locals(&def.arity) {
child
.lock()
.unwrap()
.vars
.entry(name)
.or_insert(Value::Undef);
}
let home_frame = scope.frame_id;
let block_ctx = with_host(|h| {
let label = h.block_context(&scope, h.procs[template].block_depth);
(h.frames.len(), label)
});
let mut block_scope = Scope {
locals: child,
self_obj: self_override
.cloned()
.unwrap_or_else(|| scope.self_obj.clone()),
..scope
};
if let Some((name, owner)) = method_ctx {
block_scope.method_name = Some(name);
block_scope.def_class = Some(owner);
}
let prev_active = with_host(|h| h.active_scope.replace(block_scope));
BLOCK_CTX.with(|s| s.borrow_mut().push(block_ctx));
let r = loop {
let r = run_proc_chunk(template);
if r.is_err() || !take_redo_signal() {
break r;
}
};
with_host(|h| {
h.active_scope = prev_active;
});
let sig = with_host(|h| h.signal.take());
let out = match sig {
Some(Signal::Next(v)) => Ok(v),
Some(Signal::Return(v, _)) | Some(Signal::Break(v)) if is_lambda => Ok(v),
Some(Signal::Return(v, None)) => {
with_host(|h| h.signal = Some(Signal::Return(v, Some(home_frame))));
r
}
Some(Signal::Break(_)) if take_lexical_break() && !block_home_is_live(home) => {
Err(crate::builtins::raise_exc_with(
"LocalJumpError",
"break from proc-closure",
&[("reason", with_host(|h| h.new_symbol("break")))],
))
}
Some(other) => {
with_host(|h| h.signal = Some(other));
r
}
None => r,
};
BLOCK_CTX.with(|s| {
s.borrow_mut().pop();
});
out
}
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, None)));
}
pub fn raise_signal_retry() {
with_host(|h| h.signal = Some(Signal::Retry));
}
pub fn raise_signal_redo() {
with_host(|h| h.signal = Some(Signal::Redo));
}
pub fn raise_signal_throw(tag: Value, value: Value) {
with_host(|h| h.signal = Some(Signal::Throw(tag, value)));
}
pub fn push_catch_tag(tag: Value) {
with_host(|h| h.catch_tags.push(tag));
}
pub fn pop_catch_tag() {
with_host(|h| {
h.catch_tags.pop();
});
}
pub fn catch_tag_active(tag: &Value) -> bool {
with_host(|h| h.catch_tags.iter().any(|t| t == tag))
}
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_redo_signal() -> bool {
with_host(|h| {
if matches!(h.signal, Some(Signal::Redo)) {
h.signal = None;
true
} else {
false
}
})
}
thread_local! {
static BLOCK_LITERAL_CALL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub fn mark_block_literal() {
BLOCK_LITERAL_CALL.with(|c| c.set(true));
}
thread_local! {
static BLOCK_HOMES: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
}
pub fn enter_block_home(block: Option<&Value>) -> Option<u64> {
let block = block?;
let id = NEXT_BLOCK_HOME.with(|c| {
let id = c.get();
c.set(id + 1);
id
});
let stamped = with_host(|h| match h.obj_mut(block) {
Some(RObj::Proc { home, .. }) => {
*home = Some(id);
true
}
_ => false,
});
if !stamped {
return None;
}
BLOCK_HOMES.with(|s| s.borrow_mut().push(id));
Some(id)
}
pub fn leave_block_home(id: Option<u64>) {
if id.is_some() {
BLOCK_HOMES.with(|s| {
s.borrow_mut().pop();
});
}
}
thread_local! {
static BLOCK_CTX: RefCell<Vec<(usize, String)>> = const { RefCell::new(Vec::new()) };
static NEXT_BLOCK_HOME: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
static LEXICAL_BREAK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
struct CallSite {
file_depth: usize,
line: u32,
frames: usize,
blocks: usize,
yielder: Option<(Value, String)>,
native: Option<&'static str>,
}
thread_local! {
static CALL_SITES: RefCell<Vec<CallSite>> = const { RefCell::new(Vec::new()) };
}
pub fn enter_call_site(line: u32, yielder: Option<(Value, String)>) -> usize {
let file_depth = FILE_PATH_STACK.with(|s| s.borrow().len());
let blocks = BLOCK_CTX.with(|s| s.borrow().len());
let frames = with_host(|h| h.frames.len());
CALL_SITES.with(|s| {
let mut s = s.borrow_mut();
let depth = s.len();
s.push(CallSite {
file_depth,
line,
frames,
blocks,
yielder,
native: None,
});
depth
})
}
thread_local! {
static NATIVE_RAISE_FRAME: RefCell<Option<String>> = const { RefCell::new(None) };
}
pub fn set_native_raise_frame(label: Option<String>) {
NATIVE_RAISE_FRAME.with(|f| *f.borrow_mut() = label);
}
fn take_native_raise_frame() -> Option<String> {
NATIVE_RAISE_FRAME.with(|f| f.borrow_mut().take())
}
pub fn raise_backtrace(line: u32) -> Vec<LiveFrame> {
let depth = enter_call_site(line, None);
let stack = live_backtrace();
leave_call_site(depth);
stack
}
pub fn mark_native_frame(label: &'static str) {
CALL_SITES.with(|s| {
if let Some(site) = s.borrow_mut().last_mut() {
site.native = Some(label);
}
});
}
pub fn clear_native_frame() {
CALL_SITES.with(|s| {
if let Some(site) = s.borrow_mut().last_mut() {
site.native = None;
}
});
}
pub fn leave_call_site(depth: usize) {
CALL_SITES.with(|s| s.borrow_mut().truncate(depth));
}
pub struct LiveFrame {
pub path: String,
pub line: u32,
pub label: String,
}
pub fn live_backtrace() -> Vec<LiveFrame> {
let paths = FILE_PATH_STACK.with(|s| s.borrow().clone());
let path_at = |depth: usize| {
depth
.checked_sub(1)
.and_then(|i| paths.get(i).cloned())
.unwrap_or_else(|| "-e".into())
};
CALL_SITES.with(|sites| {
let sites = sites.borrow();
let mut out = Vec::with_capacity(sites.len());
for (i, site) in sites.iter().enumerate().rev() {
let path = path_at(site.file_depth);
let yielding = sites
.get(i + 1)
.is_some_and(|inner| inner.frames == site.frames && inner.blocks > site.blocks);
if let (true, Some((recv, name))) = (yielding, &site.yielder) {
let label = with_host(|h| h.builtin_frame_label(recv, name));
out.push(LiveFrame {
path: path.clone(),
line: site.line,
label,
});
}
if let Some(label) = site.native {
out.push(LiveFrame {
path: path.clone(),
line: site.line,
label: label.to_string(),
});
}
let label = with_host(|h| h.context_at(site.frames, site.blocks));
out.push(LiveFrame {
path,
line: site.line,
label,
});
}
out
})
}
pub fn mark_lexical_break() {
LEXICAL_BREAK.with(|c| c.set(true));
}
fn take_lexical_break() -> bool {
LEXICAL_BREAK.with(|c| c.replace(false))
}
fn block_home_is_live(home: Option<u64>) -> bool {
match home {
None => true,
Some(id) => BLOCK_HOMES.with(|s| s.borrow().contains(&id)),
}
}
pub fn take_block_literal() -> bool {
BLOCK_LITERAL_CALL.with(|c| c.replace(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 take_next() -> Option<Value> {
with_host(|h| match &h.signal {
Some(Signal::Next(_)) => match h.signal.take() {
Some(Signal::Next(v)) => Some(v),
_ => None,
},
_ => None,
})
}
pub fn pending_signal_is_loop_flow() -> bool {
with_host(|h| {
matches!(
h.signal,
Some(Signal::Break(_)) | Some(Signal::Next(_)) | Some(Signal::Redo)
)
})
}
pub fn peek_break() -> Value {
with_host(|h| Value::Bool(matches!(h.signal, Some(Signal::Break(_)))))
}
pub fn has_pending_signal() -> bool {
with_host(|h| h.signal.is_some())
}
const _: fn() = || {
fn assert_send<T: Send>() {}
assert_send::<RubyHost>();
};
type RangeEnds = (Value, Value, bool);
pub const WARNING_CATEGORIES: &[&str] = &[
"deprecated",
"experimental",
"performance",
"strict_unused_block",
];
static WARNING_ENABLED: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
pub fn reset_warning_categories(level: u8) {
let bits = match level {
0 => 0,
1 => 0b10,
_ => 0b11,
};
WARNING_ENABLED.store(bits, std::sync::atomic::Ordering::Relaxed);
}
pub fn warning_enabled(category: &str) -> bool {
WARNING_CATEGORIES
.iter()
.position(|c| *c == category)
.is_some_and(|i| WARNING_ENABLED.load(std::sync::atomic::Ordering::Relaxed) & (1 << i) != 0)
}
pub fn set_warning_enabled(category: &str, on: bool) {
if let Some(i) = WARNING_CATEGORIES.iter().position(|c| *c == category) {
let bit = 1 << i;
if on {
WARNING_ENABLED.fetch_or(bit, std::sync::atomic::Ordering::Relaxed);
} else {
WARNING_ENABLED.fetch_and(!bit, std::sync::atomic::Ordering::Relaxed);
}
}
}