use fusevm::{Chunk, VMResult, Value, VM};
pub type NameMap = IndexMap<String, Value, rustc_hash::FxBuildHasher>;
use indexmap::IndexMap;
use std::cell::RefCell;
use std::rc::Rc;
pub mod ops {
pub const GETVAR: u16 = 1;
pub const GETFUN: u16 = 2;
pub const SETVAR: u16 = 3;
pub const SETSUPER: u16 = 4;
pub const MKARGS: u16 = 5;
pub const CALL: u16 = 6;
pub const MKCLOSURE: u16 = 7;
pub const CONST_DBL: u16 = 8;
pub const CONST_INT: u16 = 9;
pub const CONST_STR: u16 = 10;
pub const CONST_LGL: u16 = 11;
pub const CONST_NULL: u16 = 12;
pub const CONST_NA: u16 = 13;
pub const DOTS: u16 = 14;
pub const BINOP: u16 = 20;
pub const UNOP: u16 = 21;
pub const SPECIAL: u16 = 22;
pub const INDEX: u16 = 30;
pub const INDEX2: u16 = 31;
pub const DOLLAR: u16 = 32;
pub const INDEX_SET: u16 = 33;
pub const INDEX2_SET: u16 = 34;
pub const DOLLAR_SET: u16 = 35;
pub const REPLACE: u16 = 36;
pub const TRUTHY: u16 = 40;
pub const SIG_BREAK: u16 = 41;
pub const SIG_NEXT: u16 = 42;
pub const SIG_RETURN: u16 = 43;
pub const SEQ_LEN: u16 = 44;
pub const SEQ_ELEM: u16 = 45;
pub const AUTOPRINT: u16 = 46;
pub const IS_FALSE: u16 = 47;
pub const IS_TRUE: u16 = 48;
pub const MISSING: u16 = 49;
pub const NULL_INVISIBLE: u16 = 50;
pub const SWITCH_INDEX: u16 = 51;
pub const RANGE_FROM: u16 = 52;
pub const RANGE_STEP: u16 = 53;
pub const RANGE_LEN: u16 = 54;
pub const SET_VISIBLE: u16 = 55;
pub const WARN_FLUSH: u16 = 56;
pub const MARK_SHARED: u16 = 57;
pub const OPEN_CALL: u16 = 58;
pub const CALL_OPENED: u16 = 59;
pub const LOGIC2_ARG: u16 = 60;
pub const LOOP_SIGNAL: u16 = 61;
pub const TAKE_LOOP_SIGNAL: u16 = 62;
}
pub struct EnvData {
pub vars: NameMap,
pub parent: Option<Env>,
}
pub type Env = Rc<RefCell<EnvData>>;
fn new_env(parent: Option<Env>) -> Env {
Rc::new(RefCell::new(EnvData {
vars: NameMap::default(),
parent,
}))
}
#[derive(Clone)]
pub struct ClosureDef {
pub params: Vec<String>,
pub chunk: Chunk,
pub src: Vec<String>,
}
#[derive(Debug, Clone)]
pub enum Signal {
Break,
Next,
Return(Value),
}
#[derive(Clone)]
pub struct RObj {
pub data: RData,
pub attrs: NameMap,
pub refcnt: u32,
}
const REFCNT_MAX: u32 = u32::MAX;
fn retain(heap: &mut [RObj], v: &Value) {
let Value::Obj(i) = v else { return };
let nested = {
let Some(o) = heap.get_mut(*i as usize) else {
return;
};
if o.refcnt == REFCNT_MAX {
return;
}
o.refcnt += 1;
match &o.data {
RData::Args(items) => items.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>(),
_ => Vec::new(),
}
};
for v in &nested {
retain(heap, v);
}
}
fn release(heap: &mut [RObj], v: &Value) {
let Value::Obj(i) = v else { return };
let nested = {
let Some(o) = heap.get_mut(*i as usize) else {
return;
};
if o.refcnt == REFCNT_MAX || o.refcnt == 0 {
return;
}
o.refcnt -= 1;
match &o.data {
RData::Args(items) => items.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>(),
_ => Vec::new(),
}
};
for v in &nested {
release(heap, v);
}
}
fn bind_in(heap: &mut [RObj], env: &Env, name: &str, val: Value) {
let old = env.borrow_mut().vars.insert(name.to_string(), val.clone());
if old.as_ref() == Some(&val) {
return;
}
if let Some(o) = old {
release(heap, &o);
}
retain(heap, &val);
}
#[derive(Clone, Copy)]
pub enum CombinatorKind {
Negate,
Vectorize,
}
#[derive(Clone)]
pub enum RData {
Null,
Lgl(Vec<Option<bool>>),
Int(Vec<Option<i64>>),
Dbl(Vec<Option<f64>>),
Str(Vec<Option<String>>),
List(Vec<Value>),
Closure {
id: usize,
env: Env,
},
Builtin(String),
Promise {
thunk: Value,
value: Option<Value>,
ctx_depth: usize,
},
RForeign(usize),
Combinator {
kind: CombinatorKind,
inner: Value,
},
Environment(Env),
Args(Vec<(Option<String>, Value)>),
Lang(crate::ast::Expr),
Sym(String),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RKind {
Null,
Promise,
Lgl,
Int,
Dbl,
Str,
List,
Closure,
Builtin,
RForeign,
Combinator,
Environment,
Args,
Lang,
Sym,
}
impl RKind {
pub fn of(d: &RData) -> RKind {
match d {
RData::Null => RKind::Null,
RData::Promise { .. } => RKind::Promise,
RData::Lgl(_) => RKind::Lgl,
RData::Int(_) => RKind::Int,
RData::Dbl(_) => RKind::Dbl,
RData::Str(_) => RKind::Str,
RData::List(_) => RKind::List,
RData::Closure { .. } => RKind::Closure,
RData::Builtin(_) => RKind::Builtin,
RData::RForeign(_) => RKind::RForeign,
RData::Combinator { .. } => RKind::Combinator,
RData::Environment(_) => RKind::Environment,
RData::Args(_) => RKind::Args,
RData::Lang(_) => RKind::Lang,
RData::Sym(_) => RKind::Sym,
}
}
pub fn rank(self) -> u8 {
match self {
RKind::Null => 0,
RKind::Lgl => 1,
RKind::Int => 2,
RKind::Dbl => 3,
RKind::Str => 4,
_ => 5,
}
}
}
pub fn type_rank(d: &RData) -> u8 {
match d {
RData::Null => 0,
RData::Lgl(_) => 1,
RData::Int(_) => 2,
RData::Dbl(_) => 3,
RData::Str(_) => 4,
_ => 5,
}
}
pub struct Frame {
pub env: Env,
pub promise: bool,
pub args: Vec<(Option<String>, Value)>,
pub fun_name: Option<String>,
pub fun: Option<(usize, Env)>,
pub dispatch: Option<(String, Vec<String>)>,
pub on_exit: Vec<Value>,
pub defaulted: Vec<String>,
}
pub struct HandlerFrame {
pub calling: bool,
pub handlers: Vec<(String, Value)>,
pub disabled: bool,
pub muffle: Option<String>,
}
pub struct RestartFrame {
pub id: u64,
pub name: String,
pub description: String,
pub handler: Option<Value>,
}
pub type RestartInvoke = (u64, Vec<(Option<String>, Value)>);
pub const RESTART_UNWIND: &str = "\u{1}restart";
fn ctx_text(v: &Value) -> String {
ctx_source(v).lines().next().unwrap_or_default().to_string()
}
pub fn ctx_source(v: &Value) -> String {
match v {
Value::Str(s) => s.to_string(),
_ => String::new(),
}
}
pub struct CallCtx {
pub text: Value,
pub entered: bool,
pub closure: bool,
}
pub struct Warning {
pub msg: String,
pub call: Option<String>,
}
pub struct RHost {
heap: Vec<RObj>,
pub global: Env,
pub frames: Vec<Frame>,
pub closures: Vec<ClosureDef>,
pub error: Option<String>,
pub error_classes: Vec<String>,
pub error_condition: Option<Value>,
pub errmessage: String,
pub error_call: Option<String>,
pub error_trace: Vec<String>,
pub error_call_known: bool,
pub handlers: Vec<HandlerFrame>,
pub restarts: Vec<Vec<RestartFrame>>,
pub next_restart_id: u64,
pub restart_invoke: Option<RestartInvoke>,
pub pending_dispatch: Option<(String, Vec<String>)>,
pub suppress_s3: bool,
pub signal: Option<Signal>,
pub visible: bool,
pub echo: bool,
pub calls: Vec<CallCtx>,
pub warnings: Vec<Warning>,
pub warn_count: usize,
pub rng: crate::rng::Rng,
null: Option<Value>,
}
thread_local! {
static HOST: RefCell<RHost> = RefCell::new(RHost::new());
static CAPTURE: RefCell<Option<String>> = const { RefCell::new(None) };
}
pub fn emit(s: &str) {
CAPTURE.with(|c| {
if let Some(buf) = c.borrow_mut().as_mut() {
buf.push_str(s);
} else {
use std::io::Write as _;
let mut out = std::io::stdout();
let _ = out.write_all(s.as_bytes());
}
});
}
pub fn start_capture() {
CAPTURE.with(|c| *c.borrow_mut() = Some(String::new()));
}
pub fn with_capture<T>(f: impl FnOnce() -> T) -> (T, String) {
let outer = CAPTURE.with(|c| c.borrow_mut().replace(String::new()));
let out = f();
let text = CAPTURE.with(|c| std::mem::replace(&mut *c.borrow_mut(), outer));
(out, text.unwrap_or_default())
}
pub fn take_capture() -> String {
CAPTURE.with(|c| c.borrow_mut().take().unwrap_or_default())
}
thread_local! {
static STDIN: RefCell<Option<String>> = const { RefCell::new(None) };
}
pub fn set_stdin(text: &str) {
STDIN.with(|s| *s.borrow_mut() = Some(text.to_string()));
}
pub fn read_stdin_lines(limit: Option<usize>) -> Vec<String> {
STDIN.with(|s| {
let mut installed = s.borrow_mut();
let mut next_line = || {
let mut line = match installed.as_mut() {
Some(buf) if buf.is_empty() => return None,
Some(buf) => {
let end = buf.find('\n').map_or(buf.len(), |i| i + 1);
buf.drain(..end).collect::<String>()
}
None => {
let mut line = String::new();
match std::io::stdin().read_line(&mut line) {
Ok(0) | Err(_) => return None,
Ok(_) => line,
}
}
};
if line.ends_with('\n') {
line.pop();
}
Some(line)
};
let mut lines = Vec::new();
while limit.is_none_or(|n| lines.len() < n) {
match next_line() {
Some(line) => lines.push(line),
None => break,
}
}
lines
})
}
thread_local! {
#[allow(clippy::type_complexity)]
static STDERR_HOOK: RefCell<Option<Box<dyn Fn(&str)>>> = const { RefCell::new(None) };
}
pub fn set_stderr_hook(f: Box<dyn Fn(&str)>) {
STDERR_HOOK.with(|h| *h.borrow_mut() = Some(f));
}
pub fn clear_stderr_hook() {
STDERR_HOOK.with(|h| *h.borrow_mut() = None);
}
pub fn emit_stderr(s: &str) {
let handled = STDERR_HOOK.with(|h| h.borrow().as_ref().map(|f| f(s)).is_some());
if !handled {
eprint!("{s}");
}
}
pub fn with_host<R>(f: impl FnOnce(&mut RHost) -> R) -> R {
HOST.with(|h| f(&mut h.borrow_mut()))
}
pub fn reset_host() {
CLOSURE_VMS.with(|c| c.borrow_mut().clear());
with_host(|h| *h = RHost::new());
}
const R_SPECIAL_PRIMITIVES: &[&str] = &[
"$",
"$<-",
"&&",
".Internal",
"::",
":::",
"<-",
"<<-",
"=",
"@",
"@<-",
"Exec",
"Tailcall",
"UseMethod",
"[",
"[<-",
"[[",
"[[<-",
"break",
"call",
"declare",
"expression",
"for",
"forceAndCall",
"function",
"if",
"log",
"missing",
"next",
"on.exit",
"quote",
"rep",
"repeat",
"return",
"round",
"signif",
"substitute",
"switch",
"while",
"{",
"||",
"~",
];
pub fn builtin_type(name: &str) -> &'static str {
if !crate::compiler::is_r_primitive(name) {
"closure"
} else if R_SPECIAL_PRIMITIVES.binary_search(&name).is_ok() {
"special"
} else {
"builtin"
}
}
impl Default for RHost {
fn default() -> Self {
Self::new()
}
}
impl RHost {
pub fn new() -> Self {
let global = new_env(None);
RHost {
heap: Vec::new(),
global: global.clone(),
frames: vec![Frame {
promise: false,
env: global,
args: Vec::new(),
fun_name: None,
fun: None,
dispatch: None,
on_exit: Vec::new(),
defaulted: Vec::new(),
}],
closures: Vec::new(),
error: None,
error_classes: Vec::new(),
error_condition: None,
errmessage: String::new(),
error_call: None,
error_trace: Vec::new(),
error_call_known: false,
handlers: Vec::new(),
restarts: Vec::new(),
next_restart_id: 0,
restart_invoke: None,
pending_dispatch: None,
suppress_s3: false,
signal: None,
visible: true,
echo: true,
calls: Vec::new(),
warnings: Vec::new(),
warn_count: 0,
rng: crate::rng::Rng::default(),
null: None,
}
}
pub fn load_closures(&mut self, closures: Vec<ClosureDef>) {
CLOSURE_VMS.with(|c| c.borrow_mut().clear());
self.closures = closures;
}
pub fn alloc(&mut self, data: RData) -> Value {
self.alloc_with(data, NameMap::default())
}
pub fn alloc_with(&mut self, data: RData, attrs: NameMap) -> Value {
match &data {
RData::List(xs) => {
for v in xs {
retain(&mut self.heap, v);
}
}
RData::Combinator { inner, .. } => retain(&mut self.heap, inner),
RData::Promise { thunk, .. } => retain(&mut self.heap, thunk),
_ => {}
}
for v in attrs.values() {
retain(&mut self.heap, v);
}
self.heap.push(RObj {
data,
attrs,
refcnt: 0,
});
Value::Obj((self.heap.len() - 1) as u32)
}
pub fn refcnt(&self, v: &Value) -> u32 {
match v {
Value::Obj(i) => self.heap.get(*i as usize).map_or(REFCNT_MAX, |o| o.refcnt),
_ => REFCNT_MAX,
}
}
pub fn may_mutate(&self, v: &Value) -> bool {
self.refcnt(v) <= 1
}
pub fn with_data_mut<R>(&mut self, v: &Value, f: impl FnOnce(&mut RData) -> R) -> Option<R> {
self.get_mut(v).map(|o| f(&mut o.data))
}
pub fn set_list_elements(&mut self, x: &Value, positions: &[usize], val: &Value) -> Option<()> {
let null = self.null();
let displaced = self.with_data_mut(x, |d| match d {
RData::List(items) => Some(
positions
.iter()
.map(|p| {
while items.len() <= *p {
items.push(null.clone());
}
std::mem::replace(&mut items[*p], val.clone())
})
.collect::<Vec<_>>(),
),
_ => None,
})??;
for old in &displaced {
release(&mut self.heap, old);
}
for _ in 0..positions.len() {
retain(&mut self.heap, val);
}
Some(())
}
pub fn mark_shared(&mut self, v: &Value) {
if let Value::Obj(i) = v {
if let Some(o) = self.heap.get_mut(*i as usize) {
o.refcnt = REFCNT_MAX;
}
}
}
pub fn get(&self, v: &Value) -> Option<&RObj> {
match v {
Value::Obj(i) => self.heap.get(*i as usize),
_ => None,
}
}
fn get_mut(&mut self, v: &Value) -> Option<&mut RObj> {
match v {
Value::Obj(i) => self.heap.get_mut(*i as usize),
_ => None,
}
}
pub fn data_of(&self, v: &Value) -> RData {
match unboxed(v) {
Some(Ub::I(n)) => return RData::Int(vec![Some(n)]),
Some(Ub::F(f)) => return RData::Dbl(vec![Some(f)]),
Some(Ub::B(b)) => return RData::Lgl(vec![Some(b)]),
None => {}
}
self.get(v).map(|o| o.data.clone()).unwrap_or(RData::Null)
}
pub fn kind_of(&self, v: &Value) -> RKind {
match unboxed(v) {
Some(Ub::I(_)) => return RKind::Int,
Some(Ub::F(_)) => return RKind::Dbl,
Some(Ub::B(_)) => return RKind::Lgl,
None => {}
}
self.get(v)
.map(|o| RKind::of(&o.data))
.unwrap_or(RKind::Null)
}
pub fn scalar_real(&self, v: &Value) -> Option<(f64, bool)> {
match unboxed(v) {
Some(Ub::I(n)) => return Some((n as f64, true)),
Some(Ub::F(f)) => return Some((f, false)),
Some(Ub::B(b)) => return Some((b as i64 as f64, true)),
None => {}
}
let o = self.get(v)?;
if !o.attrs.is_empty() {
return None;
}
match &o.data {
RData::Int(x) if x.len() == 1 => x[0].map(|n| (n as f64, true)),
RData::Lgl(x) if x.len() == 1 => x[0].map(|b| (b as i64 as f64, true)),
RData::Dbl(x) if x.len() == 1 => x[0].map(|n| (n, false)),
_ => None,
}
}
pub fn attrs_of(&self, v: &Value) -> NameMap {
if unboxed(v).is_some() {
return NameMap::default();
}
self.get(v).map(|o| o.attrs.clone()).unwrap_or_default()
}
pub fn attr(&self, v: &Value, name: &str) -> Option<Value> {
if unboxed(v).is_some() {
return None;
}
self.get(v).and_then(|o| o.attrs.get(name).cloned())
}
pub fn set_attr(&mut self, v: &Value, name: &str, val: Value) {
let is_null = matches!(self.data_of(&val), RData::Null);
let Some(o) = self.get_mut(v) else { return };
let old = if is_null {
o.attrs.shift_remove(name)
} else {
o.attrs.insert(name.to_string(), val.clone())
};
if old.as_ref() == Some(&val) {
return;
}
if let Some(o) = old {
release(&mut self.heap, &o);
}
if !is_null {
retain(&mut self.heap, &val);
}
}
pub fn null(&mut self) -> Value {
if let Some(v) = &self.null {
return v.clone();
}
let v = self.alloc(RData::Null);
self.null = Some(v.clone());
v
}
pub fn dbl(&mut self, xs: Vec<Option<f64>>) -> Value {
self.alloc(RData::Dbl(xs))
}
pub fn int(&mut self, xs: Vec<Option<i64>>) -> Value {
self.alloc(RData::Int(xs))
}
pub fn lgl(&mut self, xs: Vec<Option<bool>>) -> Value {
self.alloc(RData::Lgl(xs))
}
pub fn str_vec(&mut self, xs: Vec<Option<String>>) -> Value {
self.alloc(RData::Str(xs))
}
pub fn list(&mut self, xs: Vec<Value>) -> Value {
self.alloc(RData::List(xs))
}
pub fn scalar_dbl(&mut self, x: f64) -> Value {
self.dbl(vec![Some(x)])
}
pub fn scalar_int(&mut self, x: i64) -> Value {
self.int(vec![Some(x)])
}
pub fn scalar_lgl(&mut self, x: bool) -> Value {
self.lgl(vec![Some(x)])
}
pub fn scalar_str(&mut self, x: impl Into<String>) -> Value {
self.str_vec(vec![Some(x.into())])
}
pub fn length(&self, v: &Value) -> usize {
if unboxed(v).is_some() {
return 1;
}
match self.get(v).map(|o| &o.data) {
Some(RData::Null) | None => 0,
Some(RData::Lgl(x)) => x.len(),
Some(RData::Int(x)) => x.len(),
Some(RData::Dbl(x)) => x.len(),
Some(RData::Str(x)) => x.len(),
Some(RData::List(x)) => x.len(),
Some(RData::Args(x)) => x.len(),
Some(RData::Environment(e)) => e.borrow().vars.len(),
Some(RData::Lang(e)) => crate::builtins::lang_len(e),
_ => 1,
}
}
pub fn as_lgl(&self, v: &Value) -> Vec<Option<bool>> {
match unboxed(v) {
Some(Ub::I(n)) => return vec![Some(n != 0)],
Some(Ub::F(f)) => return vec![Some(f != 0.0)],
Some(Ub::B(b)) => return vec![Some(b)],
None => {}
}
match self.get(v).map(|o| &o.data) {
Some(RData::Lgl(x)) => x.clone(),
Some(RData::Int(x)) => x.iter().map(|e| e.map(|n| n != 0)).collect(),
Some(RData::Dbl(x)) => x.iter().map(|e| e.map(|n| n != 0.0)).collect(),
Some(RData::Str(x)) => x
.iter()
.map(|e| match e.as_deref() {
Some("T") | Some("TRUE") | Some("true") | Some("True") => Some(true),
Some("F") | Some("FALSE") | Some("false") | Some("False") => Some(false),
_ => None,
})
.collect(),
Some(RData::List(x)) => x.iter().flat_map(|e| self.as_lgl(e)).collect(),
_ => Vec::new(),
}
}
pub fn as_int(&self, v: &Value) -> Vec<Option<i64>> {
match unboxed(v) {
Some(Ub::I(n)) => return vec![Some(n)],
Some(Ub::F(f)) => return vec![f.is_finite().then_some(f.trunc() as i64)],
Some(Ub::B(b)) => return vec![Some(b as i64)],
None => {}
}
match self.get(v).map(|o| &o.data) {
Some(RData::Lgl(x)) => x.iter().map(|e| e.map(|b| b as i64)).collect(),
Some(RData::Int(x)) => x.clone(),
Some(RData::Dbl(x)) => x
.iter()
.map(|e| e.and_then(|n| n.is_finite().then_some(n.trunc() as i64)))
.collect(),
Some(RData::Str(x)) => x
.iter()
.map(|e| e.as_ref().and_then(|s| parse_num(s.trim())))
.map(|o| o.and_then(|n| n.is_finite().then_some(n.trunc() as i64)))
.collect(),
Some(RData::List(x)) => x.iter().flat_map(|e| self.as_int(e)).collect(),
_ => Vec::new(),
}
}
pub fn as_dbl(&self, v: &Value) -> Vec<Option<f64>> {
match unboxed(v) {
Some(Ub::I(n)) => return vec![Some(n as f64)],
Some(Ub::F(f)) => return vec![Some(f)],
Some(Ub::B(b)) => return vec![Some(b as i64 as f64)],
None => {}
}
match self.get(v).map(|o| &o.data) {
Some(RData::Lgl(x)) => x.iter().map(|e| e.map(|b| b as i64 as f64)).collect(),
Some(RData::Int(x)) => x.iter().map(|e| e.map(|n| n as f64)).collect(),
Some(RData::Dbl(x)) => x.clone(),
Some(RData::Str(x)) => x
.iter()
.map(|e| e.as_ref().and_then(|s| parse_num(s.trim())))
.collect(),
Some(RData::List(x)) => x.iter().flat_map(|e| self.as_dbl(e)).collect(),
_ => Vec::new(),
}
}
pub fn as_str(&self, v: &Value) -> Vec<Option<String>> {
match unboxed(v) {
Some(Ub::I(n)) => return vec![Some(n.to_string())],
Some(Ub::F(f)) => return vec![Some(format_dbl(f))],
Some(Ub::B(b)) => return vec![Some(if b { "TRUE" } else { "FALSE" }.to_string())],
None => {}
}
match self.get(v).map(|o| &o.data) {
Some(RData::Lgl(x)) => x
.iter()
.map(|e| e.map(|b| if b { "TRUE" } else { "FALSE" }.to_string()))
.collect(),
Some(RData::Int(x)) => x.iter().map(|e| e.map(|n| n.to_string())).collect(),
Some(RData::Dbl(x)) => x.iter().map(|e| e.map(format_dbl)).collect(),
Some(RData::Str(x)) => x.clone(),
Some(RData::List(x)) => x.iter().flat_map(|e| self.as_str(e)).collect(),
_ => Vec::new(),
}
}
pub fn str1(&self, v: &Value) -> Option<String> {
self.as_str(v).into_iter().next().flatten()
}
pub fn num1(&self, v: &Value) -> Option<f64> {
self.as_dbl(v).into_iter().next().flatten()
}
pub fn lgl1(&self, v: &Value) -> Option<bool> {
self.as_lgl(v).into_iter().next().flatten()
}
pub fn elements(&mut self, v: &Value) -> Vec<Value> {
match self.data_of(v) {
RData::List(xs) => xs,
RData::Null => Vec::new(),
_ => (0..self.length(v)).map(|i| self.element_at(v, i)).collect(),
}
}
pub fn element_at(&mut self, v: &Value, i: usize) -> Value {
if unboxed(v).is_some() {
return if i == 0 { v.clone() } else { self.null() };
}
enum Elem {
Lgl(Option<bool>),
Int(Option<i64>),
Dbl(Option<f64>),
Str(Option<String>),
Val(Value),
Null,
}
let e = match self.get(v).map(|o| &o.data) {
Some(RData::Lgl(x)) => Elem::Lgl(x.get(i).cloned().flatten()),
Some(RData::Int(x)) => Elem::Int(x.get(i).cloned().flatten()),
Some(RData::Dbl(x)) => Elem::Dbl(x.get(i).cloned().flatten()),
Some(RData::Str(x)) => Elem::Str(x.get(i).cloned().flatten()),
Some(RData::List(x)) => x.get(i).cloned().map(Elem::Val).unwrap_or(Elem::Null),
_ => Elem::Null,
};
match e {
Elem::Lgl(Some(b)) => Value::Bool(b),
Elem::Int(Some(n)) => Value::Int(n),
Elem::Dbl(Some(f)) => Value::Float(f),
Elem::Lgl(o) => self.lgl(vec![o]),
Elem::Int(o) => self.int(vec![o]),
Elem::Dbl(o) => self.dbl(vec![o]),
Elem::Str(o) => self.str_vec(vec![o]),
Elem::Val(v) => v,
Elem::Null => self.null(),
}
}
pub fn names(&self, v: &Value) -> Vec<Option<String>> {
if let Some(n) = self.attr(v, "names") {
return self.as_str(&n);
}
let one_d = self.attr(v, "dim").is_some_and(|d| self.length(&d) == 1);
if one_d {
if let Some(dn) = self.attr(v, "dimnames") {
if let Some(RObj {
data: RData::List(xs),
..
}) = self.get(&dn)
{
if let Some(first) = xs.first() {
return self.as_str(first);
}
}
}
}
Vec::new()
}
pub fn is_null(&self, v: &Value) -> bool {
if unboxed(v).is_some() {
return false;
}
matches!(self.get(v).map(|o| &o.data), Some(RData::Null) | None)
}
pub fn is_function(&self, v: &Value) -> bool {
matches!(
self.get(v).map(|o| &o.data),
Some(RData::Closure { .. }) | Some(RData::Builtin(_)) | Some(RData::Combinator { .. })
)
}
pub fn class_of(&self, v: &Value) -> Vec<String> {
if let Some(c) = self.attr(v, "class") {
let cs: Vec<String> = self.as_str(&c).into_iter().flatten().collect();
if !cs.is_empty() {
return cs;
}
}
match self.attr(v, "dim").map(|d| self.length(&d)) {
Some(2) => return vec!["matrix".into(), "array".into()],
Some(n) if n > 0 => return vec!["array".into()],
_ => {}
}
match unboxed(v) {
Some(Ub::I(_)) => return vec!["integer".into()],
Some(Ub::F(_)) => return vec!["numeric".into()],
Some(Ub::B(_)) => return vec!["logical".into()],
None => {}
}
vec![match self.get(v).map(|o| &o.data) {
Some(RData::Null) | None => "NULL",
Some(RData::Lgl(_)) => "logical",
Some(RData::Int(_)) => "integer",
Some(RData::Dbl(_)) => "numeric",
Some(RData::Str(_)) => "character",
Some(RData::List(_)) => "list",
Some(RData::Closure { .. })
| Some(RData::Builtin(_))
| Some(RData::Combinator { .. }) => "function",
Some(RData::Environment(_)) => "environment",
Some(RData::Args(_)) => "list",
Some(RData::Lang(e)) => match e {
crate::ast::Expr::Block(_) => "{",
crate::ast::Expr::Paren(_) => "(",
crate::ast::Expr::If { .. } => "if",
crate::ast::Expr::For { .. } => "for",
crate::ast::Expr::While { .. } => "while",
crate::ast::Expr::Assign {
super_assign: false,
..
} => "<-",
_ => "call",
},
Some(RData::Sym(_)) => "name",
Some(RData::RForeign(_)) => "R_object",
Some(RData::Promise { .. }) => "promise",
}
.to_string()]
}
pub fn type_of(&self, v: &Value) -> &'static str {
match unboxed(v) {
Some(Ub::I(_)) => return "integer",
Some(Ub::F(_)) => return "double",
Some(Ub::B(_)) => return "logical",
None => {}
}
match self.get(v).map(|o| &o.data) {
Some(RData::Null) | None => "NULL",
Some(RData::Lgl(_)) => "logical",
Some(RData::Int(_)) => "integer",
Some(RData::Dbl(_)) => "double",
Some(RData::Str(_)) => "character",
Some(RData::List(_)) | Some(RData::Args(_)) => "list",
Some(RData::RForeign(_)) => "externalptr",
Some(RData::Closure { .. }) | Some(RData::Combinator { .. }) => "closure",
Some(RData::Builtin(name)) => builtin_type(name),
Some(RData::Environment(_)) => "environment",
Some(RData::Lang(_)) => "language",
Some(RData::Sym(_)) => "symbol",
Some(RData::Promise { .. }) => "promise",
}
}
pub fn env(&self) -> Env {
self.frames
.last()
.map(|f| f.env.clone())
.unwrap_or_else(|| self.global.clone())
}
pub fn lookup(&self, name: &str) -> Option<Value> {
self.lookup_from(self.env(), name)
}
pub fn lookup_from(&self, env: Env, name: &str) -> Option<Value> {
let mut e = Some(env);
while let Some(cur) = e {
if let Some(v) = cur.borrow().vars.get(name) {
return Some(v.clone());
}
e = cur.borrow().parent.clone();
}
None
}
pub fn unsupplied_formal(&self, name: &str) -> bool {
let Some(frame) = self.frames.last() else {
return false;
};
let Some((id, _)) = &frame.fun else {
return false;
};
if frame.promise || frame.env.borrow().vars.contains_key(name) {
return false;
}
self.closures
.get(*id)
.is_some_and(|c| c.params.iter().any(|p| p == name))
}
pub fn lookup_function(&self, name: &str) -> Option<Value> {
let mut e = Some(self.env());
while let Some(cur) = e {
let hit = cur.borrow().vars.get(name).cloned();
if let Some(v) = hit {
if self.is_function(&v) {
return Some(v);
}
}
e = cur.borrow().parent.clone();
}
None
}
pub fn current_call(&self) -> Option<String> {
self.calls.last().map(|c| ctx_text(&c.text))
}
pub fn current_call_source(&self) -> Option<String> {
self.calls.last().map(|c| ctx_source(&c.text))
}
pub fn current_call_arg_sources(&self) -> Vec<String> {
let Some(src) = self.current_call_source() else {
return Vec::new();
};
let Ok(mut exprs) = crate::parser::parse(&src) else {
return Vec::new();
};
if exprs.len() != 1 {
return Vec::new();
}
let crate::ast::Expr::Call { args, .. } = exprs.remove(0) else {
return Vec::new();
};
args.iter()
.map(|a| {
a.value
.as_ref()
.map(crate::deparse::deparse_first_line)
.unwrap_or_default()
})
.collect()
}
pub fn enclosing_call_source(&self) -> Option<String> {
self.calls
.iter()
.rev()
.skip(1)
.find(|c| c.closure)
.map(|c| ctx_source(&c.text))
}
pub fn context_call(&self) -> Option<String> {
self.innermost_context(0)
}
pub fn context_call_source(&self) -> Option<String> {
self.enclosing_ctx(0).map(|c| ctx_source(&c.text))
}
pub fn enclosing_call(&self) -> Option<String> {
self.innermost_context(1)
}
fn innermost_context(&self, skip: usize) -> Option<String> {
self.enclosing_ctx(skip).map(|c| ctx_text(&c.text))
}
pub fn entered_ctx_depth(&self) -> usize {
self.calls
.iter()
.rposition(|c| c.entered)
.map_or(0, |i| i + 1)
}
pub fn nframe(&self) -> usize {
self.sys_contexts().len()
}
fn sys_contexts(&self) -> Vec<&CallCtx> {
let found = self
.calls
.iter()
.enumerate()
.rev()
.filter(|(i, _)| !ctx_hidden(*i))
.skip(1)
.find(|(_, c)| c.closure && c.entered);
match found {
Some((k, _)) => self.calls[..=k].iter().filter(|c| c.closure).collect(),
None => Vec::new(),
}
}
pub fn sys_frame_number(&self, which: i64) -> Result<usize, String> {
let cur = self.nframe() as i64;
let target = if which > 0 { which } else { cur + which };
if target < 0 || target > cur {
return Err("not that many frames on the stack".into());
}
Ok(target as usize)
}
pub fn sys_call_source(&self, which: i64) -> Result<Option<String>, String> {
let n = self.sys_frame_number(which)?;
Ok(n.checked_sub(1)
.and_then(|i| self.sys_contexts().get(i).map(|c| ctx_source(&c.text))))
}
pub fn sys_calls_source(&self) -> Vec<String> {
self.sys_contexts()
.iter()
.map(|c| ctx_source(&c.text))
.collect()
}
pub fn sys_function_at(&self, n: usize) -> Option<(usize, Env)> {
self.frames
.iter()
.filter(|f| !f.promise)
.nth(n)
.and_then(|f| f.fun.clone())
}
pub fn enclosing_source(&self) -> Option<String> {
self.enclosing_source_from(1)
}
pub fn enclosing_source_from(&self, skip: usize) -> Option<String> {
self.calls
.iter()
.enumerate()
.rev()
.filter(|(i, _)| !ctx_hidden(*i))
.skip(skip)
.find(|(_, c)| c.closure && c.entered)
.map(|(_, c)| ctx_source(&c.text))
}
fn enclosing_ctx(&self, skip: usize) -> Option<&CallCtx> {
self.calls.iter().rev().skip(skip).find(|c| c.closure)
}
pub fn current_formals(&self) -> Option<Vec<String>> {
let (id, _) = self.innermost_call()?.fun.as_ref()?;
Some(self.closures.get(*id)?.params.clone())
}
pub fn innermost_call(&self) -> Option<&Frame> {
let env = self.env();
self.frames
.iter()
.rev()
.find(|f| !f.promise && Rc::ptr_eq(&f.env, &env))
.or_else(|| self.frames.iter().rev().find(|f| !f.promise))
}
pub fn promise_expr(&self, v: &Value) -> Option<(crate::ast::Expr, Env)> {
let RData::Promise {
thunk, value: None, ..
} = &self.get(v)?.data
else {
return None;
};
let RData::Closure { id, env } = &self.get(thunk)?.data else {
return None;
};
let src = self.closures.get(*id)?.src.join("\n");
let mut exprs = crate::parser::parse(&src).ok()?;
match exprs.pop() {
Some(crate::ast::Expr::Function { params, body })
if exprs.is_empty() && params.is_empty() =>
{
Some((*body, env.clone()))
}
_ => None,
}
}
pub fn promise_symbol(&self, v: &Value) -> Option<(String, Env)> {
match self.promise_expr(v)? {
(crate::ast::Expr::Ident(s), env) => Some((s, env)),
_ => None,
}
}
pub fn is_missing_in(&self, env: &Env, name: &str) -> bool {
let bound = env.borrow().vars.get(name).cloned();
match bound {
None => self.frames.iter().rev().any(|f| {
!f.promise
&& Rc::ptr_eq(&f.env, env)
&& f.fun
.as_ref()
.and_then(|(id, _)| self.closures.get(*id))
.is_some_and(|c| c.params.iter().any(|p| p == name))
}),
Some(v) => match self.promise_symbol(&v) {
Some((s, e)) if s == name && Rc::ptr_eq(&e, env) => true,
Some((s, e)) => self.is_missing_in(&e, &s),
None => false,
},
}
}
pub fn parent_frame_env(&self, n: usize) -> Env {
let frame_of = |env: &Env, below: usize| {
self.frames[..below]
.iter()
.rposition(|f| !f.promise && Rc::ptr_eq(&f.env, env))
};
let mut cur = frame_of(&self.env(), self.frames.len());
for _ in 0..n {
cur = match cur {
Some(i) if i > 0 => frame_of(&self.frames[i - 1].env, i),
_ => None,
};
}
match cur {
Some(i) => self.frames[i].env.clone(),
None => self.global.clone(),
}
}
pub fn set_var(&mut self, name: &str, val: Value) {
let env = self.env();
bind_in(&mut self.heap, &env, name, val);
}
pub fn bind(&mut self, env: &Env, name: &str, val: Value) {
bind_in(&mut self.heap, env, name, val);
}
pub fn set_super(&mut self, name: &str, val: Value) {
let mut e = self.env().borrow().parent.clone();
while let Some(cur) = e {
let has = cur.borrow().vars.contains_key(name);
if has {
bind_in(&mut self.heap, &cur, name, val);
return;
}
e = cur.borrow().parent.clone();
}
let g = self.global.clone();
bind_in(&mut self.heap, &g, name, val);
}
pub fn exists(&self, name: &str) -> bool {
self.lookup(name).is_some()
}
pub fn dots(&self) -> Vec<(Option<String>, Value)> {
match self.lookup("...").map(|v| self.data_of(&v)) {
Some(RData::Args(a)) => a,
_ => Vec::new(),
}
}
pub fn fail<T>(&mut self, msg: impl Into<String>) -> Option<T> {
if self.error.is_none() {
let call = self.current_call_source();
self.set_error_call(call);
self.error = Some(msg.into());
}
None
}
pub fn set_error_call(&mut self, call: Option<String>) {
if self.error_call_known {
return;
}
self.error_trace = self
.calls
.iter()
.filter(|c| c.closure)
.map(|c| ctx_source(&c.text))
.collect();
self.error_call = call;
self.error_call_known = true;
}
pub fn clear_error_call(&mut self) {
self.error_call = None;
self.error_condition = None;
self.error_trace.clear();
self.error_call_known = false;
}
pub fn take_error(&mut self) -> Option<String> {
self.error.take()
}
}
enum Ub {
I(i64),
F(f64),
B(bool),
}
fn unboxed(v: &Value) -> Option<Ub> {
match v {
Value::Int(n) => Some(Ub::I(*n)),
Value::Float(f) => Some(Ub::F(*f)),
Value::Bool(b) => Some(Ub::B(*b)),
_ => None,
}
}
fn parse_num(s: &str) -> Option<f64> {
match s {
"Inf" => Some(f64::INFINITY),
"-Inf" => Some(f64::NEG_INFINITY),
"NaN" => Some(f64::NAN),
_ => {
if let Some(hex) = s
.strip_prefix("0x")
.or_else(|| s.strip_prefix("0X"))
.or_else(|| s.strip_prefix("-0x").or_else(|| s.strip_prefix("-0X")))
{
let neg = s.starts_with('-');
return i64::from_str_radix(hex, 16)
.ok()
.map(|n| if neg { -n } else { n } as f64);
}
s.parse().ok()
}
}
}
thread_local! {
static PRINT_DIGITS: std::cell::Cell<usize> = const { std::cell::Cell::new(7) };
static PRINT_SCIPEN: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
static OUT_DEC: std::cell::RefCell<String> = std::cell::RefCell::new(".".into());
}
pub fn out_dec(s: String) -> String {
OUT_DEC.with(|d| {
let d = d.borrow();
if d.as_str() == "." {
s
} else {
s.replacen('.', &d, 1)
}
})
}
pub fn with_point<T>(f: impl FnOnce() -> T) -> T {
let prev = OUT_DEC.with(|d| std::mem::replace(&mut *d.borrow_mut(), ".".into()));
let out = f();
OUT_DEC.with(|d| *d.borrow_mut() = prev);
out
}
pub const AS_CHARACTER_DIGITS: usize = 15;
pub const SCIPEN_MIN: i32 = -9;
pub fn print_digits() -> usize {
PRINT_DIGITS.with(|c| c.get())
}
pub fn set_print_digits(d: usize) -> usize {
PRINT_DIGITS.with(|c| c.replace(d.max(1)))
}
pub fn print_scipen() -> i32 {
PRINT_SCIPEN.with(|c| c.get())
}
pub fn set_print_scipen(s: i32) -> i32 {
PRINT_SCIPEN.with(|c| c.replace(s.max(SCIPEN_MIN)))
}
pub fn with_print_digits<T>(digits: usize, f: impl FnOnce() -> T) -> T {
let prev = set_print_digits(digits);
let out = f();
set_print_digits(prev);
out
}
#[derive(Clone, Debug, PartialEq)]
pub enum OptionValue {
Int(i64),
Dbl(f64),
Str(String),
Lgl(bool),
}
thread_local! {
static OTHER_OPTIONS: std::cell::RefCell<std::collections::HashMap<String, OptionValue>> =
std::cell::RefCell::new(std::collections::HashMap::new());
}
pub const DIGITS_MIN: i64 = 1;
pub const DIGITS_MAX: i64 = 22;
pub fn option_get(name: &str) -> Option<OptionValue> {
match name {
"digits" => Some(OptionValue::Int(print_digits() as i64)),
"scipen" => Some(OptionValue::Int(print_scipen() as i64)),
"OutDec" => Some(OptionValue::Str(OUT_DEC.with(|d| d.borrow().clone()))),
"warn" => Some(
OTHER_OPTIONS
.with(|o| o.borrow().get(name).cloned())
.unwrap_or(OptionValue::Int(0)),
),
_ => OTHER_OPTIONS.with(|o| o.borrow().get(name).cloned()),
}
}
pub fn option_set(
name: &str,
value: OptionValue,
) -> Result<(Option<OptionValue>, Option<String>), String> {
let prev = option_get(name);
let mut warning = None;
match name {
"digits" => {
let d = match value {
OptionValue::Int(n) => n,
OptionValue::Dbl(x) if x.is_finite() => x.trunc() as i64,
_ => return Err("invalid 'digits' parameter, allowed 1...22".into()),
};
if !(DIGITS_MIN..=DIGITS_MAX).contains(&d) {
return Err("invalid 'digits' parameter, allowed 1...22".into());
}
set_print_digits(d as usize);
}
"scipen" => {
let s = match value {
OptionValue::Int(n) => n,
OptionValue::Dbl(x) if x.is_finite() => x.trunc() as i64,
_ => return Err("invalid 'scipen' parameter".into()),
};
let s = s.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
if s < SCIPEN_MIN {
warning = Some(format!("invalid 'scipen' {s}, used {SCIPEN_MIN}"));
}
set_print_scipen(s);
}
"OutDec" => {
let OptionValue::Str(dec) = value else {
return Err("invalid value for 'OutDec'".into());
};
if dec.chars().count() != 1 {
warning = Some("'OutDec' must be a string of one character".into());
}
OUT_DEC.with(|d| *d.borrow_mut() = dec);
}
_ => {
OTHER_OPTIONS.with(|o| o.borrow_mut().insert(name.to_string(), value));
}
}
Ok((prev, warning))
}
pub fn prefers_fixed(fixed_width: usize, sci_width: usize) -> bool {
(fixed_width as i64) <= sci_width as i64 + print_scipen() as i64
}
pub fn fixed_decimals(x: f64) -> usize {
if !x.is_finite() || (x == x.trunc() && x.abs() < 1e15) {
return 0;
}
let mag = x.abs().log10().floor() as i32;
let sig = print_digits() as i32;
let d = ((sig - 1) - mag).clamp(0, 340) as usize;
let s = format!("{x:.d$}");
let trimmed = s.trim_end_matches('0');
match trimmed.split_once('.') {
Some((_, frac)) => frac.len(),
None => 0,
}
}
fn r_sci(x: f64, decimals: usize) -> String {
let s = format!("{x:.decimals$e}");
let (mant, exp) = s.split_once('e').unwrap_or((s.as_str(), "0"));
let e: i32 = exp.parse().unwrap_or(0);
format!("{mant}e{}{:02}", if e < 0 { '-' } else { '+' }, e.abs())
}
pub fn sci_decimals(x: f64) -> usize {
if !x.is_finite() || x == 0.0 {
return 0;
}
let prec = print_digits().saturating_sub(1);
let s = r_sci(x, prec);
let mant = s.split_once('e').map_or(s.as_str(), |(m, _)| m);
match mant.trim_end_matches('0').split_once('.') {
Some((_, frac)) => frac.len(),
None => 0,
}
}
pub fn render_fixed(x: f64, decimals: usize) -> String {
if x.is_nan() {
return "NaN".into();
}
if x.is_infinite() {
return if x > 0.0 { "Inf" } else { "-Inf" }.into();
}
let x = if x == 0.0 { 0.0 } else { x };
format!("{x:.decimals$}")
}
pub fn render_sci(x: f64, decimals: usize) -> String {
if !x.is_finite() {
return render_fixed(x, 0);
}
r_sci(if x == 0.0 { 0.0 } else { x }, decimals)
}
pub fn format_dbl(x: f64) -> String {
let fixed = render_fixed(x, fixed_decimals(x));
if !x.is_finite() {
return fixed;
}
let sci = render_sci(x, sci_decimals(x));
out_dec(
if prefers_fixed(fixed.chars().count(), sci.chars().count()) {
fixed
} else {
sci
},
)
}
pub fn run_chunk(chunk: Chunk) -> Result<Value, String> {
let mut vm = fresh_vm(chunk);
let r = drive(&mut vm);
r
}
thread_local! {
static CLOSURE_VMS: RefCell<Vec<Option<Box<VM>>>> = const { RefCell::new(Vec::new()) };
}
fn fresh_vm(chunk: Chunk) -> VM {
let mut vm = VM::new(chunk);
crate::builtins::install(&mut vm);
vm
}
fn run_closure_chunk(id: usize) -> Result<Value, String> {
let parked = CLOSURE_VMS.with(|c| c.borrow_mut().get_mut(id).and_then(Option::take));
let mut vm = match parked {
Some(mut vm) => {
let chunk = std::mem::take(&mut vm.chunk);
vm.reset(chunk);
vm
}
None => {
let chunk = with_host(|h| h.closures.get(id).map(|d| d.chunk.clone()))
.ok_or_else(|| format!("internal: unknown closure #{id}"))?;
Box::new(fresh_vm(chunk))
}
};
let r = drive(&mut vm);
CLOSURE_VMS.with(|c| {
let mut slots = c.borrow_mut();
if slots.len() <= id {
slots.resize_with(id + 1, || None);
}
slots[id] = Some(vm);
});
r
}
const OP_SITES_TAG: &str = "\u{1}rlang.op_sites";
pub fn op_sites_constant(sites: Vec<(usize, String)>) -> Value {
let mut table = Vec::with_capacity(1 + 2 * sites.len());
table.push(Value::str(OP_SITES_TAG));
for (ip, text) in sites {
table.push(Value::Int(ip as i64));
table.push(Value::str(text));
}
Value::Array(std::sync::Arc::new(table))
}
#[derive(Clone)]
pub enum OpSite {
Op(usize),
Text(Value),
}
struct OpContext {
chunk: *const Chunk,
site: Option<OpSite>,
}
thread_local! {
static OP_CONTEXT: RefCell<OpContext> = const {
RefCell::new(OpContext {
chunk: std::ptr::null(),
site: None,
})
};
}
pub fn in_op_site<T>(site: OpSite, f: impl FnOnce() -> T) -> T {
let prev = OP_CONTEXT.with(|c| c.borrow_mut().site.replace(site));
let out = f();
OP_CONTEXT.with(|c| c.borrow_mut().site = prev);
out
}
pub fn op_site_call() -> Option<String> {
op_site_value().map(|v| ctx_text(&v))
}
pub fn op_site_source() -> Option<String> {
op_site_value().map(|v| ctx_source(&v))
}
fn op_site_value() -> Option<Value> {
let (chunk, site) = OP_CONTEXT.with(|c| {
let c = c.borrow();
(c.chunk, c.site.clone())
});
match site? {
OpSite::Text(v) => Some(v),
OpSite::Op(_) if chunk.is_null() => None,
OpSite::Op(ip) => {
let chunk = unsafe { &*chunk };
let table = chunk.constants.iter().rev().find_map(|c| match c {
Value::Array(t) if matches!(t.first(), Some(Value::Str(s)) if s.as_str() == OP_SITES_TAG) => {
Some(t)
}
_ => None,
})?;
table[1..].chunks_exact(2).find_map(|pair| match pair {
[Value::Int(at), text] if *at == ip as i64 => Some(text.clone()),
_ => None,
})
}
}
}
fn drive(vm: &mut VM) -> Result<Value, String> {
let outer = OP_CONTEXT.with(|c| {
std::mem::replace(
&mut *c.borrow_mut(),
OpContext {
chunk: &vm.chunk as *const Chunk,
site: None,
},
)
});
let out = drive_unwound(vm);
OP_CONTEXT.with(|c| *c.borrow_mut() = outer);
out
}
fn drive_unwound(vm: &mut VM) -> Result<Value, String> {
let depth = with_host(|h| h.calls.len());
let out = drive_inner(vm);
with_host(|h| h.calls.truncate(depth));
out
}
fn drive_inner(vm: &mut VM) -> Result<Value, String> {
let outcome = vm.run();
if let Some(e) = with_host(|h| h.take_error()) {
return Err(e);
}
match outcome {
VMResult::Ok(v) => Ok(v),
VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
VMResult::Error(e) => Err(e),
}
}
pub fn run_main(chunk: Chunk) -> Result<Value, String> {
let r = run_chunk(chunk);
with_host(|h| h.signal = None);
if r.is_ok() {
flush_warnings(false);
}
r
}
pub const MAX_WARNINGS: usize = 50;
pub fn queue_warning(msg: &str, call: Option<String>) {
match warn_level() {
w if w < 0 => {}
0 => with_host(|h| {
h.warn_count += 1;
if h.warnings.len() < MAX_WARNINGS {
h.warnings.push(Warning {
msg: msg.to_string(),
call,
});
}
}),
_ => {
let text = match &call {
None => format!("Warning: {msg}\n"),
Some(c) => format!("Warning in {c} :{}", fold(c, msg, 18)),
};
emit_stderr(&text);
}
}
}
const LONGWARN: usize = 75;
fn fold(call: &str, msg: &str, overhead: usize) -> String {
let first = msg.split('\n').next().unwrap_or(msg);
let width = |s: &str| crate::strwidth::display_width(s);
if overhead + width(call) + width(first) > LONGWARN {
format!("\n {msg}\n")
} else {
format!(" {msg}\n")
}
}
pub fn flush_warnings(after_error: bool) {
let (msgs, count) = with_host(|h| {
(
std::mem::take(&mut h.warnings),
std::mem::replace(&mut h.warn_count, 0),
)
});
if count == 0 {
return;
}
let lead = if after_error { "In addition: " } else { "" };
let text = if count == 1 {
format!("{lead}Warning message:\n{}", warning_line(&msgs[0], 6))
} else if count <= 10 {
let body: String = msgs
.iter()
.enumerate()
.map(|(i, w)| format!("{}: {}", i + 1, warning_line(w, 10)))
.collect();
format!("{lead}Warning messages:\n{body}")
} else if count < MAX_WARNINGS {
format!("{lead}There were {count} warnings (use warnings() to see them)\n")
} else {
format!(
"{lead}There were {MAX_WARNINGS} or more warnings (use warnings() to see the first {MAX_WARNINGS})\n"
)
};
emit_stderr(&text);
}
pub fn error_report(msg: &str, call: Option<&str>) -> String {
match call.and_then(|c| c.lines().next()) {
None => format!("Error: {msg}\n"),
Some(c) => format!("Error in {c} : {}", fold_error(c, msg)),
}
}
const N_SHOW_CALLS: usize = 50;
pub fn traceback(frames: &[String], call: Option<&str>) -> Option<String> {
let mut names: Vec<String> = Vec::new();
let mut ncalls = 0usize;
let mut top: Option<String> = None;
let mut elided = false;
for text in frames.iter().rev() {
let this = call_name(text);
if matches!(
this.as_str(),
"stop" | "warning" | "suppressWarnings" | ".signalSimpleWarning"
) {
names.clear();
ncalls = 0;
top = None;
elided = false;
continue;
}
ncalls += 1;
if elided || names.join(" -> ").len() > N_SHOW_CALLS {
elided = true;
top = Some(this);
} else {
names.push(this);
}
}
let mut out = names
.iter()
.rev()
.map(String::as_str)
.collect::<Vec<_>>()
.join(" -> ");
if elided {
out = match top.filter(|t| t.len() < 50) {
Some(t) => format!("{t} ... {out}"),
None => format!("... {out}"),
};
}
if ncalls == 1 && call.map(call_name).as_deref() == Some(out.as_str()) {
return None;
}
(!out.is_empty()).then_some(out)
}
fn call_name(text: &str) -> String {
let head = text.lines().next().unwrap_or_default();
let head = head.split('(').next().unwrap_or_default();
let head = head
.strip_prefix('`')
.and_then(|h| h.strip_suffix('`'))
.unwrap_or(head);
match crate::deparse::is_syntactic_name(head) {
true => head.to_string(),
false => "<Anonymous>".into(),
}
}
fn fold_error(call: &str, msg: &str) -> String {
let first = msg.split('\n').next().unwrap_or(msg);
let width = |s: &str| crate::strwidth::display_width(s);
if 14 + width(call) + width(first) > LONGWARN {
format!("\n {msg}\n")
} else {
format!("{msg}\n")
}
}
fn warning_line(w: &Warning, overhead: usize) -> String {
match &w.call {
None => format!("{} \n", w.msg),
Some(c) => format!("In {c} :{}", fold(c, &w.msg, overhead)),
}
}
pub fn warn_level() -> i64 {
match option_get("warn") {
Some(OptionValue::Int(n)) => n,
Some(OptionValue::Dbl(x)) if x.is_finite() => x.trunc() as i64,
_ => 0,
}
}
pub fn force_all(
args: Vec<(Option<String>, Value)>,
) -> Result<Vec<(Option<String>, Value)>, String> {
if !args.iter().any(|(_, v)| {
with_host(|h| matches!(h.get(v).map(|o| &o.data), Some(RData::Promise { .. })))
}) {
return Ok(args);
}
let mut out = Vec::with_capacity(args.len());
for (n, v) in args {
out.push((n, force_value(&v)?));
}
Ok(out)
}
thread_local! {
static FORCING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static HIDDEN: std::cell::RefCell<Vec<(usize, usize)>> = const {
std::cell::RefCell::new(Vec::new())
};
}
fn ctx_hidden(i: usize) -> bool {
HIDDEN.with(|s| s.borrow().iter().any(|(lo, hi)| i >= *lo && i < *hi))
}
pub fn force_value(v: &Value) -> Result<Value, String> {
let Some((thunk, memo, depth)) = with_host(|h| match h.get(v).map(|o| &o.data) {
Some(RData::Promise {
thunk,
value,
ctx_depth,
}) => Some((thunk.clone(), value.clone(), *ctx_depth)),
_ => None,
}) else {
return Ok(v.clone());
};
if let Some(done) = memo {
return Ok(done);
}
let out = eval_promise_thunk(&thunk, depth)?;
with_host(|h| {
retain(&mut h.heap, &out);
if let Some(o) = h.get_mut(v) {
if let RData::Promise { value, .. } = &mut o.data {
*value = Some(out.clone());
}
}
});
Ok(out)
}
pub fn eval_promise_thunk(thunk: &Value, depth: usize) -> Result<Value, String> {
HIDDEN.with(|s| s.borrow_mut().push((depth, with_host(|h| h.calls.len()))));
FORCING.with(|f| f.set(true));
let out = call_value(thunk, Vec::new(), None);
FORCING.with(|f| f.set(false));
HIDDEN.with(|s| {
s.borrow_mut().pop();
});
out
}
pub fn lookup_function_forcing(name: &str) -> Result<Option<Value>, String> {
let mut e = Some(with_host(|h| h.env()));
while let Some(cur) = e {
let hit = cur.borrow().vars.get(name).cloned();
if let Some(v) = hit {
let v = force_value(&v)?;
if with_host(|h| h.is_function(&v)) {
return Ok(Some(v));
}
}
e = cur.borrow().parent.clone();
}
Ok(None)
}
pub fn call_value(
f: &Value,
args: Vec<(Option<String>, Value)>,
fun_name: Option<String>,
) -> Result<Value, String> {
match with_host(|h| h.data_of(f)) {
RData::Builtin(name) => crate::builtins::call_primitive(&name, args),
RData::Closure { id, env } => call_closure(id, env, args, fun_name),
RData::Combinator { kind, inner } => {
crate::builtins::call_combinator(kind, &inner, force_all(args)?)
}
#[cfg(not(target_arch = "wasm32"))]
RData::RForeign(ptr) => crate::rembed::call_handle(ptr, &force_all(args)?),
RData::Str(names) if names.len() == 1 => {
let name = names[0].clone().unwrap_or_default();
let f = crate::builtins::function_named(&name)
.ok_or_else(|| format!("could not find function \"{name}\""))?;
call_value(&f, args, Some(name))
}
_ => Err("attempt to apply non-function".into()),
}
}
pub const MAX_DEPTH: usize = 5000;
thread_local! {
static STACK_BOUNDS: std::cell::OnceCell<Option<(usize, usize)>> =
const { std::cell::OnceCell::new() };
}
#[cfg(target_vendor = "apple")]
fn thread_stack_bounds() -> Option<(usize, usize)> {
unsafe {
let me = libc::pthread_self();
let top = libc::pthread_get_stackaddr_np(me) as usize;
Some((top, libc::pthread_get_stacksize_np(me)))
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn thread_stack_bounds() -> Option<(usize, usize)> {
unsafe {
let mut attr = std::mem::MaybeUninit::<libc::pthread_attr_t>::uninit();
if libc::pthread_getattr_np(libc::pthread_self(), attr.as_mut_ptr()) != 0 {
return None;
}
let mut low: *mut libc::c_void = std::ptr::null_mut();
let mut size: libc::size_t = 0;
let ok = libc::pthread_attr_getstack(attr.as_ptr(), &mut low, &mut size) == 0;
libc::pthread_attr_destroy(attr.as_mut_ptr());
ok.then(|| (low as usize + size, size))
}
}
#[cfg(not(any(target_vendor = "apple", target_os = "linux", target_os = "android")))]
fn thread_stack_bounds() -> Option<(usize, usize)> {
None
}
const STACK_STEP: usize = 2 * 1024 * 1024;
pub fn stack_exhausted() -> Option<String> {
let (top, size) = STACK_BOUNDS.with(|b| *b.get_or_init(thread_stack_bounds))?;
let here = 0u8;
let usage = top.saturating_sub(std::ptr::addr_of!(here) as usize);
let limit = (size as f64 * 0.95) as usize;
(usage + STACK_STEP.min(size / 4) > limit)
.then(|| format!("C stack usage {usage} is too close to the limit"))
}
pub fn check_stack() -> Result<(), String> {
let Some(msg) = stack_exhausted() else {
return Ok(());
};
with_host(|h| {
if h.error.is_none() {
h.set_error_call(None);
h.error_classes = [
"CStackOverflowError",
"stackOverflowError",
"error",
"condition",
]
.iter()
.map(|s| s.to_string())
.collect();
}
});
Err(msg)
}
pub fn call_closure(
id: usize,
env: Env,
args: Vec<(Option<String>, Value)>,
fun_name: Option<String>,
) -> Result<Value, String> {
let params = with_host(|h| h.closures.get(id).map(|d| d.params.clone()))
.ok_or_else(|| format!("internal: unknown closure #{id}"))?;
if with_host(|h| h.frames.len()) >= MAX_DEPTH {
return Err("evaluation nested too deeply: infinite recursion?".into());
}
check_stack()?;
let promise = FORCING.with(|f| f.replace(false));
let frame_env = if promise {
env.clone()
} else {
new_env(Some(env.clone()))
};
let bindings = match_args(¶ms, &args)?;
with_host(|h| {
for (k, v) in bindings {
h.bind(&frame_env, &k, v);
}
});
with_host(|h| {
for (_, v) in &args {
retain(&mut h.heap, v);
}
let dispatch = h.pending_dispatch.take();
if let Some((generic, _)) = &dispatch {
let g = h.alloc(RData::Str(vec![Some(generic.clone())]));
h.bind(&frame_env, ".Generic", g);
}
h.frames.push(Frame {
env: frame_env,
promise,
args,
fun_name,
fun: Some((id, env)),
dispatch,
on_exit: Vec::new(),
defaulted: Vec::new(),
})
});
let out = run_closure_chunk(id);
let exits = with_host(|h| {
let e = h.frames.last_mut().map(|f| std::mem::take(&mut f.on_exit));
if let Some(f) = h.frames.pop() {
for (_, v) in &f.args {
release(&mut h.heap, v);
}
if Rc::strong_count(&f.env) == 1 {
let held: Vec<Value> = f.env.borrow().vars.values().cloned().collect();
for v in &held {
release(&mut h.heap, v);
}
}
}
e.unwrap_or_default()
});
let mut out = out;
for thunk in exits {
let (sig, vis) = with_host(|h| (h.signal.take(), h.visible));
let cleanup = call_value(&thunk, Vec::new(), None);
with_host(|h| {
h.signal = sig;
h.visible = vis;
});
if out.is_ok() {
if let Err(e) = cleanup {
out = Err(e);
}
}
}
let out = out?;
if promise {
if let Some(Signal::Return(v)) = with_host(|h| h.signal.clone()) {
return Ok(v);
}
}
let sig = with_host(|h| h.signal.take());
match sig {
Some(Signal::Return(v)) => Ok(v),
Some(other) => {
with_host(|h| h.signal = Some(other));
Ok(out)
}
None => Ok(out),
}
}
pub fn match_positions(
params: &[String],
tags: &[Option<String>],
) -> Result<Vec<Option<usize>>, String> {
let mut to = vec![None; tags.len()];
let mut taken = vec![false; params.len()];
let dots_at = params.iter().position(|p| p == "...");
for (ai, tag) in tags.iter().enumerate() {
let Some(tag) = tag else { continue };
if let Some(pi) = params.iter().position(|p| p == tag) {
if taken[pi] {
return Err(format!(
"formal argument \"{tag}\" matched by multiple actual arguments"
));
}
taken[pi] = true;
to[ai] = Some(pi);
}
}
let partial_limit = dots_at.unwrap_or(params.len());
for (ai, tag) in tags.iter().enumerate() {
if to[ai].is_some() {
continue;
}
let Some(tag) = tag else { continue };
let hits: Vec<usize> = (0..partial_limit)
.filter(|&pi| !taken[pi] && params[pi].starts_with(tag.as_str()))
.collect();
match hits.len() {
0 => {}
1 => {
taken[hits[0]] = true;
to[ai] = Some(hits[0]);
}
_ => return Err(format!("argument {tag} matches multiple formal arguments")),
}
}
let mut pi = 0usize;
for (ai, tag) in tags.iter().enumerate() {
if to[ai].is_some() || tag.is_some() {
continue;
}
while pi < params.len() && taken[pi] && params[pi] != "..." {
pi += 1;
}
if pi >= params.len() || params[pi] == "..." {
break;
}
taken[pi] = true;
to[ai] = Some(pi);
pi += 1;
}
Ok(to)
}
pub fn match_args(
params: &[String],
args: &[(Option<String>, Value)],
) -> Result<Vec<(String, Value)>, String> {
let tags: Vec<Option<String>> = args.iter().map(|(t, _)| t.clone()).collect();
let to = match_positions(params, &tags)?;
let mut bound: Vec<Option<Value>> = vec![None; params.len()];
for (ai, slot) in to.iter().enumerate() {
if let Some(pi) = slot {
bound[*pi] = Some(args[ai].1.clone());
}
}
let mut out = Vec::new();
for (i, p) in params.iter().enumerate() {
if p == "..." {
continue;
}
if let Some(v) = &bound[i] {
if !matches!(v, Value::Undef) {
out.push((p.clone(), v.clone()));
}
}
}
let rest: Vec<(Option<String>, Value)> = args
.iter()
.zip(&to)
.filter(|(_, slot)| slot.is_none())
.map(|(a, _)| a.clone())
.collect();
if params.iter().any(|p| p == "...") {
let dots = with_host(|h| h.alloc(RData::Args(rest)));
out.push(("...".to_string(), dots));
} else if !rest.is_empty() {
let written = with_host(|h| h.current_call_arg_sources());
let named: Vec<String> = to
.iter()
.enumerate()
.filter(|(_, slot)| slot.is_none())
.map(|(ai, _)| {
let src = written.get(ai).cloned().unwrap_or_default();
match &args[ai].0 {
Some(t) => format!("{t} = {src}"),
None => src,
}
})
.collect();
let plural = if named.len() > 1 { "s" } else { "" };
return Err(format!("unused argument{plural} ({})", named.join(", ")));
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_dbl_matches_r_seven_significant_digits() {
assert_eq!(format_dbl(1.0), "1");
assert_eq!(format_dbl(1.5), "1.5");
assert_eq!(format_dbl(1.0 / 3.0), "0.3333333");
assert_eq!(format_dbl(123.456), "123.456");
assert_eq!(format_dbl(f64::INFINITY), "Inf");
assert_eq!(format_dbl(f64::NAN), "NaN");
}
#[test]
fn exact_tags_beat_position() {
reset_host();
let (a, b) = with_host(|h| (h.scalar_dbl(1.0), h.scalar_dbl(2.0)));
let bound = match_args(
&["x".into(), "y".into()],
&[(Some("y".into()), a.clone()), (None, b.clone())],
)
.unwrap();
assert_eq!(bound[0].0, "x");
assert_eq!(bound[0].1, b);
assert_eq!(bound[1].0, "y");
assert_eq!(bound[1].1, a);
}
#[test]
fn partial_tags_match_unique_prefixes_only() {
reset_host();
let v = with_host(|h| h.scalar_dbl(1.0));
let ok = match_args(&["verbose".into()], &[(Some("verb".into()), v.clone())]).unwrap();
assert_eq!(ok[0].0, "verbose");
let ambiguous = match_args(
&["value".into(), "verbose".into()],
&[(Some("v".into()), v.clone())],
);
assert!(ambiguous.is_err());
}
#[test]
fn extra_arguments_need_dots() {
reset_host();
let v = with_host(|h| h.scalar_dbl(1.0));
assert!(match_args(&["x".into()], &[(None, v.clone()), (None, v.clone())]).is_err());
let with_dots =
match_args(&["x".into(), "...".into()], &[(None, v.clone()), (None, v)]).unwrap();
assert_eq!(with_dots.len(), 2);
assert_eq!(with_dots[1].0, "...");
}
}