use crate::ast::{Arg, Expr};
use crate::host::NameMap;
use crate::host::{
call_value, fixed_decimals, ops, render_fixed, render_sci, sci_decimals, with_host,
CombinatorKind, RData, RKind, Signal,
};
use fusevm::{Value, VM};
use std::cell::RefCell;
use std::rc::Rc;
pub fn install(vm: &mut VM) {
vm.set_numeric_hook(std::sync::Arc::new(|op, a, b| {
let name = match op {
fusevm::NumOp::Add => "+",
fusevm::NumOp::Sub => "-",
fusevm::NumOp::Mul => "*",
fusevm::NumOp::Div => "/",
fusevm::NumOp::Mod => "%%",
fusevm::NumOp::Pow => "^",
fusevm::NumOp::Neg => "-",
fusevm::NumOp::Lt => "<",
fusevm::NumOp::Gt => ">",
fusevm::NumOp::Le => "<=",
fusevm::NumOp::Ge => ">=",
fusevm::NumOp::Eq => "==",
fusevm::NumOp::Ne => "!=",
};
binop(name, a, b)
}));
vm.set_fixnum_range(-(i32::MAX as i64), i32::MAX as i64);
vm.register_builtin(ops::GETVAR, b_getvar);
vm.register_builtin(ops::GETFUN, b_getfun);
vm.register_builtin(ops::SETVAR, b_setvar);
vm.register_builtin(ops::SETSUPER, b_setsuper);
vm.register_builtin(ops::MKARGS, b_mkargs);
vm.register_builtin(ops::CALL, b_call);
vm.register_builtin(ops::MKCLOSURE, b_mkclosure);
vm.register_builtin(ops::CONST_DBL, b_const_dbl);
vm.register_builtin(ops::CONST_INT, b_const_int);
vm.register_builtin(ops::CONST_STR, b_const_str);
vm.register_builtin(ops::CONST_LGL, b_const_lgl);
vm.register_builtin(ops::CONST_NULL, b_const_null);
vm.register_builtin(ops::CONST_NA, b_const_na);
vm.register_builtin(ops::DOTS, b_dots);
vm.register_builtin(ops::BINOP, b_binop);
vm.register_builtin(ops::UNOP, b_unop);
vm.register_builtin(ops::SPECIAL, b_special);
vm.register_builtin(ops::INDEX, b_index);
vm.register_builtin(ops::INDEX2, b_index2);
vm.register_builtin(ops::DOLLAR, b_dollar);
vm.register_builtin(ops::INDEX_SET, b_index_set);
vm.register_builtin(ops::INDEX2_SET, b_index2_set);
vm.register_builtin(ops::DOLLAR_SET, b_dollar_set);
vm.register_builtin(ops::REPLACE, b_replace);
vm.register_builtin(ops::TRUTHY, b_truthy);
vm.register_builtin(ops::SEQ_LEN, b_seq_len);
vm.register_builtin(ops::SEQ_ELEM, b_seq_elem);
vm.register_builtin(ops::RANGE_FROM, b_range_from);
vm.register_builtin(ops::RANGE_STEP, b_range_step);
vm.register_builtin(ops::RANGE_LEN, b_range_len);
vm.register_builtin(ops::AUTOPRINT, b_autoprint);
vm.register_builtin(ops::IS_FALSE, b_is_false);
vm.register_builtin(ops::IS_TRUE, b_is_true);
vm.register_builtin(ops::MISSING, b_missing);
vm.register_builtin(ops::NULL_INVISIBLE, b_null_invisible);
vm.register_builtin(ops::SET_VISIBLE, b_set_visible);
vm.register_builtin(ops::SWITCH_INDEX, b_switch_index);
vm.register_builtin(ops::WARN_FLUSH, b_warn_flush);
vm.register_builtin(ops::MARK_SHARED, b_mark_shared);
vm.register_builtin(ops::OPEN_CALL, b_open_call);
vm.register_builtin(ops::CALL_OPENED, b_call_opened);
}
fn as_dbl(v: &Value) -> Vec<Option<f64>> {
with_host(|h| h.as_dbl(v))
}
fn as_int(v: &Value) -> Vec<Option<i64>> {
with_host(|h| h.as_int(v))
}
fn as_lgl(v: &Value) -> Vec<Option<bool>> {
with_host(|h| h.as_lgl(v))
}
fn as_str(v: &Value) -> Vec<Option<String>> {
with_host(|h| h.as_str(v))
}
fn str1(v: &Value) -> Option<String> {
with_host(|h| h.str1(v))
}
fn num1(v: &Value) -> Option<f64> {
with_host(|h| h.num1(v))
}
fn lgl1(v: &Value) -> Option<bool> {
with_host(|h| h.lgl1(v))
}
fn len(v: &Value) -> usize {
with_host(|h| h.length(v))
}
fn is_null(v: &Value) -> bool {
with_host(|h| h.is_null(v))
}
fn data(v: &Value) -> RData {
with_host(|h| h.data_of(v))
}
fn kind(v: &Value) -> RKind {
with_host(|h| h.kind_of(v))
}
pub(crate) fn mk_dbl(xs: Vec<Option<f64>>) -> Value {
with_host(|h| h.dbl(xs))
}
pub(crate) fn mk_int(xs: Vec<Option<i64>>) -> Value {
with_host(|h| h.int(xs))
}
pub(crate) fn mk_lgl(xs: Vec<Option<bool>>) -> Value {
with_host(|h| h.lgl(xs))
}
pub(crate) fn mk_str(xs: Vec<Option<String>>) -> Value {
with_host(|h| h.str_vec(xs))
}
pub(crate) fn mk_list(xs: Vec<Value>) -> Value {
with_host(|h| h.list(xs))
}
pub(crate) fn mk_lang(e: Expr) -> Value {
match e {
Expr::Ident(n) => with_host(|h| h.alloc(RData::Sym(n))),
Expr::Num(x) => scalar_dbl(x),
Expr::Int(n) => scalar_int(n),
Expr::Str(t) => scalar_str(t),
Expr::Bool(b) => scalar_lgl(b),
Expr::Null => null(),
other => with_host(|h| h.alloc(RData::Lang(other))),
}
}
fn call_arg_sources(src: &str) -> Option<Vec<String>> {
let mut exprs = crate::parser::parse(src).ok()?;
if exprs.len() != 1 {
return None;
}
let Expr::Call { args, .. } = exprs.remove(0) else {
return None;
};
Some(
args.iter()
.map(|a| {
a.value
.as_ref()
.map(crate::deparse::deparse_first_line)
.unwrap_or_default()
})
.collect(),
)
}
fn in_method<T>(method: &str, body: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
let dispatched = with_host(|h| h.current_call_source()).and_then(|src| {
let (_, rest) = src.split_once('(')?;
Some(format!("{method}({rest}"))
});
let Some(call) = dispatched else {
return body();
};
push_context(&call);
let out = body();
with_host(|h| {
if out.is_err() && h.error.is_none() {
let c = h.current_call_source();
h.set_error_call(c);
}
h.calls.pop();
});
out
}
fn inline_call_text(f: &Value) -> String {
match function_src(f).and_then(|s| s.into_iter().next()) {
Some(head) => format!("({head}"),
None => "FUN()".to_string(),
}
}
fn write_text(path: &str, text: &str, append: bool) -> Result<(), String> {
use std::io::Write as _;
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.append(append)
.truncate(!append)
.open(path)
.map_err(|_| format!("cannot open file '{path}'"))?;
f.write_all(text.as_bytes())
.map_err(|e| format!("cannot write to '{path}': {e}"))
}
fn matrix_rows(x: &Value) -> Option<usize> {
let dim = with_host(|h| h.attr(x, "dim"))?;
let d = as_int(&dim);
match d.len() {
2 => Some(d[0]? as usize),
_ => None,
}
}
fn row_count(n: i64, rows: i64) -> usize {
let kept = match n < 0 {
true => (rows + n).max(0),
false => n.min(rows),
};
kept as usize
}
fn take_rows(x: &Value, rows: &[usize]) -> Value {
let dim = with_host(|h| h.attr(x, "dim")).map(|d| as_int(&d)).unwrap();
let (nr, nc) = (dim[0].unwrap() as usize, dim[1].unwrap() as usize);
let pos: Vec<Option<usize>> = (0..nc)
.flat_map(|c| rows.iter().map(move |r| Some(c * nr + r)))
.collect();
let out = take_positions(x, &pos);
let d = mk_int(vec![Some(rows.len() as i64), Some(nc as i64)]);
with_host(|h| h.set_attr(&out, "dim", d));
let dn = dimnames_of(x);
let pick = |i: usize| dn.get(i).and_then(|o| o.clone());
let rn = pick(0).map(|names| {
rows.iter()
.map(|r| names.get(*r).cloned().flatten())
.collect()
});
if rn.is_some() || pick(1).is_some() {
set_dimnames(&out, rn, pick(1));
}
out
}
fn label_from_first(out: &Value, first: Option<&Value>) {
let Some(first) = first else { return };
let nm = names_of(first);
if !nm.is_empty() {
set_names(out, nm);
} else if kind(first) == RKind::Str {
set_names(out, as_str(first));
}
}
fn env_of(v: &Value) -> Option<crate::host::Env> {
match data(v) {
RData::Environment(e) => Some(e),
_ => None,
}
}
fn in_env<T>(env: crate::host::Env, body: impl FnOnce() -> T) -> T {
with_host(|h| {
h.frames.push(crate::host::Frame {
promise: false,
env,
args: Vec::new(),
fun_name: None,
fun: None,
dispatch: None,
on_exit: Vec::new(),
})
});
let out = body();
with_host(|h| {
h.frames.pop();
});
out
}
fn eval_expr(e: &Expr) -> Result<Value, String> {
let src = crate::deparse::deparse_lines(e);
let prog = crate::compile_no_slots(&src)?;
let base = with_host(|h| h.closures.len());
let shifted = crate::compiler::shift_closure_ids(prog, base);
let echo = with_host(|h| std::mem::replace(&mut h.echo, false));
with_host(|h| h.closures.extend(shifted.closures));
let out = crate::host::run_chunk(shifted.main);
with_host(|h| h.echo = echo);
out
}
fn frame_substitutions() -> Option<Vec<(String, Expr)>> {
let params = with_host(|h| h.current_formals())?;
let src = with_host(|h| h.enclosing_source_from(0))?;
let mut exprs = crate::parser::parse(&src).ok()?;
if exprs.len() != 1 {
return None;
}
let Expr::Call { args, .. } = exprs.remove(0) else {
return None;
};
let tags: Vec<Option<String>> = args.iter().map(|a| a.name.clone()).collect();
let to = crate::host::match_positions(¶ms, &tags).ok()?;
let mut map: Vec<(String, Expr)> = Vec::new();
for (ai, slot) in to.iter().enumerate() {
let Some(pi) = slot else { continue };
if let (Some(p), Some(v)) = (params.get(*pi), args[ai].value.clone()) {
map.push((p.clone(), v));
}
}
let dots: Vec<Arg> = args
.iter()
.zip(&to)
.filter(|(_, slot)| slot.is_none())
.map(|(a, _)| a.clone())
.collect();
if !dots.is_empty() {
map.push((
"...".to_string(),
Expr::Call {
fun: Box::new(Expr::Ident("...".into())),
args: dots,
},
));
}
Some(map)
}
fn value_as_expr(v: &Value) -> Option<Expr> {
let mut exprs = crate::parser::parse(&deparse_value(v)).ok()?;
match exprs.len() {
1 => Some(exprs.remove(0)),
_ => None,
}
}
fn substitute_in(e: &Expr, map: &[(String, Expr)], by_value: bool) -> Expr {
let sub = |x: &Expr| substitute_in(x, map, by_value);
let boxed = |x: &Expr| Box::new(substitute_in(x, map, by_value));
match e {
Expr::Ident(n) => {
if let Some((_, r)) = map.iter().find(|(k, _)| k == n) {
return r.clone();
}
if by_value {
if let Some(v) = with_host(|h| h.lookup(n)) {
if let Some(x) = value_as_expr(&v) {
return x;
}
}
}
e.clone()
}
Expr::Call { fun, args } => Expr::Call {
fun: boxed(fun),
args: substitute_args(args, map, by_value),
},
Expr::Binary { op, lhs, rhs } => Expr::Binary {
op: op.clone(),
lhs: boxed(lhs),
rhs: boxed(rhs),
},
Expr::Special { name, lhs, rhs } => Expr::Special {
name: name.clone(),
lhs: boxed(lhs),
rhs: boxed(rhs),
},
Expr::Unary { op, operand } => Expr::Unary {
op: op.clone(),
operand: boxed(operand),
},
Expr::Paren(x) => Expr::Paren(boxed(x)),
Expr::Block(xs) => Expr::Block(xs.iter().map(sub).collect()),
Expr::If { cond, then, els } => Expr::If {
cond: boxed(cond),
then: boxed(then),
els: els.as_ref().map(|x| boxed(x)),
},
Expr::Index { kind, obj, args } => Expr::Index {
kind: *kind,
obj: boxed(obj),
args: substitute_args(args, map, by_value),
},
other => other.clone(),
}
}
fn substitute_args(args: &[Arg], map: &[(String, Expr)], by_value: bool) -> Vec<Arg> {
let mut out = Vec::with_capacity(args.len());
for a in args {
match &a.value {
Some(Expr::Dots) => match map.iter().find(|(k, _)| k == "...") {
Some((_, Expr::Call { args: dots, .. })) => out.extend(dots.iter().cloned()),
_ => out.push(a.clone()),
},
Some(v) => out.push(Arg {
name: a.name.clone(),
value: Some(substitute_in(v, map, by_value)),
}),
None => out.push(a.clone()),
}
}
out
}
fn parse_one(src: &str) -> Result<Value, String> {
let mut exprs = crate::parser::parse(src)?;
match exprs.len() {
1 => Ok(mk_lang(exprs.remove(0))),
_ => Err(format!("not a single expression: {src}")),
}
}
fn matched_call(src: &str, params: &[String]) -> Result<Option<Expr>, String> {
let mut exprs = crate::parser::parse(src)?;
if exprs.len() != 1 {
return Ok(None);
}
let Expr::Call { fun, args } = exprs.remove(0) else {
return Ok(None);
};
let tags: Vec<Option<String>> = args.iter().map(|a| a.name.clone()).collect();
let to = crate::host::match_positions(params, &tags)?;
let mut out: Vec<Arg> = Vec::with_capacity(args.len());
for (pi, p) in params.iter().enumerate() {
if p == "..." {
continue;
}
if let Some(ai) = to.iter().position(|slot| *slot == Some(pi)) {
out.push(Arg {
name: Some(p.clone()),
value: args[ai].value.clone(),
});
}
}
for (ai, arg) in args.iter().enumerate() {
if to[ai].is_none() {
out.push(arg.clone());
}
}
Ok(Some(Expr::Call { fun, args: out }))
}
pub(crate) fn lang_len(e: &Expr) -> usize {
match e {
Expr::Call { args, .. } => 1 + args.len(),
Expr::Binary { .. } | Expr::Special { .. } | Expr::Assign { .. } => 3,
Expr::Unary { .. } | Expr::Paren(_) | Expr::Repeat(_) => 2,
Expr::Block(xs) => 1 + xs.len(),
Expr::If { els, .. } => 3 + usize::from(els.is_some()),
Expr::While { .. } => 3,
Expr::For { .. } => 4,
Expr::Index { args, .. } => 2 + args.len(),
_ => 1,
}
}
pub(crate) fn lang_parts(e: &Expr) -> Vec<(Option<String>, Value)> {
use crate::ast::{IndexKind, UnOp};
let sym = |n: &str| with_host(|h| h.alloc(RData::Sym(n.to_string())));
let part = |x: &Expr| (None, mk_lang(x.clone()));
match e {
Expr::Call { fun, args } => {
let mut out = vec![(None, mk_lang((**fun).clone()))];
for arg in args {
let v = match &arg.value {
Some(x) => mk_lang(x.clone()),
None => Value::Undef,
};
out.push((arg.name.clone(), v));
}
out
}
Expr::Binary { op, lhs, rhs } => vec![
(None, sym(crate::deparse::binop_symbol(op))),
part(lhs),
part(rhs),
],
Expr::Special { name, lhs, rhs } => {
let spelled = match name.as_str() {
"" => "%%".to_string(),
"/" => "%/%".to_string(),
other => format!("%{other}%"),
};
vec![(None, sym(&spelled)), part(lhs), part(rhs)]
}
Expr::Unary { op, operand } => {
let n = match op {
UnOp::Neg => "-",
UnOp::Plus => "+",
UnOp::Not => "!",
};
vec![(None, sym(n)), part(operand)]
}
Expr::Paren(x) => vec![(None, sym("(")), part(x)],
Expr::Block(xs) => {
let mut out = vec![(None, sym("{"))];
out.extend(xs.iter().map(part));
out
}
Expr::If { cond, then, els } => {
let mut out = vec![(None, sym("if")), part(cond), part(then)];
if let Some(e) = els {
out.push(part(e));
}
out
}
Expr::While { cond, body } => vec![(None, sym("while")), part(cond), part(body)],
Expr::Repeat(b) => vec![(None, sym("repeat")), part(b)],
Expr::For { var, seq, body } => {
vec![(None, sym("for")), (None, sym(var)), part(seq), part(body)]
}
Expr::Assign {
target,
value,
super_assign,
} => vec![
(None, sym(if *super_assign { "<<-" } else { "<-" })),
part(target),
part(value),
],
Expr::Index { kind, obj, args } => {
let head = match kind {
IndexKind::Single => "[",
IndexKind::Double => "[[",
IndexKind::Dollar => "$",
IndexKind::At => "@",
};
let mut out = vec![(None, sym(head)), part(obj)];
for arg in args {
let v = match &arg.value {
Some(Expr::Str(n)) if matches!(kind, IndexKind::Dollar | IndexKind::At) => {
sym(n)
}
Some(x) => mk_lang(x.clone()),
None => Value::Undef,
};
out.push((arg.name.clone(), v));
}
out
}
other => vec![(None, mk_lang(other.clone()))],
}
}
fn lang_text(e: &Expr) -> Vec<String> {
match e {
Expr::Ident(n) => vec![n.clone()],
other => lang_parts(other)
.into_iter()
.map(|(_, v)| deparse_value(&v))
.collect(),
}
}
pub(crate) fn lang_of(v: &Value) -> Option<Expr> {
match data(v) {
RData::Lang(e) => Some(e),
RData::Sym(n) => Some(Expr::Ident(n)),
_ => None,
}
}
fn scalar_dbl(x: f64) -> Value {
with_host(|h| h.scalar_dbl(x))
}
fn scalar_int(x: i64) -> Value {
with_host(|h| h.scalar_int(x))
}
fn scalar_lgl(x: bool) -> Value {
with_host(|h| h.scalar_lgl(x))
}
fn scalar_str(x: impl Into<String>) -> Value {
with_host(|h| h.scalar_str(x))
}
pub(crate) fn null() -> Value {
with_host(|h| h.null())
}
pub(crate) fn names_of(v: &Value) -> Vec<Option<String>> {
with_host(|h| h.names(v))
}
fn class_of(v: &Value) -> Vec<String> {
with_host(|h| h.class_of(v))
}
fn elements(v: &Value) -> Vec<Value> {
with_host(|h| h.elements(v))
}
fn is_factor(v: &Value) -> bool {
class_of(v).iter().any(|c| c == "factor")
}
fn is_ordered(v: &Value) -> bool {
class_of(v).iter().any(|c| c == "ordered")
}
fn levels_of(v: &Value) -> Vec<String> {
with_host(|h| h.attr(v, "levels"))
.map(|l| as_str(&l).into_iter().flatten().collect())
.unwrap_or_default()
}
fn factor_labels(v: &Value) -> Vec<Option<String>> {
let levels = levels_of(v);
as_int(v)
.iter()
.map(|c| c.and_then(|i| levels.get((i - 1) as usize).cloned()))
.collect()
}
fn as_str_labels(v: &Value) -> Vec<Option<String>> {
if is_factor(v) {
factor_labels(v)
} else {
as_str(v)
}
}
fn mk_factor(codes: Vec<Option<i64>>, levels: Vec<String>, ordered: bool) -> Value {
let out = mk_int(codes);
let lv = mk_str(levels.into_iter().map(Some).collect());
let cls = if ordered {
mk_str(vec![Some("ordered".into()), Some("factor".into())])
} else {
scalar_str("factor")
};
with_host(|h| {
h.set_attr(&out, "levels", lv);
h.set_attr(&out, "class", cls);
});
out
}
fn carry_factor(out: &Value, src: &Value) {
if !is_factor(src) {
return;
}
with_host(|h| {
if let Some(l) = h.attr(src, "levels") {
h.set_attr(out, "levels", l);
}
if let Some(c) = h.attr(src, "class") {
h.set_attr(out, "class", c);
}
});
}
fn drop_unused_levels(v: &Value) -> Value {
let levels = levels_of(v);
let labels = factor_labels(v);
let kept: Vec<String> = levels
.into_iter()
.filter(|l| labels.iter().any(|s| s.as_deref() == Some(l.as_str())))
.collect();
let codes = labels
.iter()
.map(|s| {
s.as_ref()
.and_then(|s| kept.iter().position(|l| l == s))
.map(|p| p as i64 + 1)
})
.collect();
mk_factor(codes, kept, is_ordered(v))
}
fn element_field(v: &Value, name: &str) -> Option<Value> {
let names = names_of(v);
let i = names.iter().position(|n| n.as_deref() == Some(name))?;
elements(v).into_iter().nth(i)
}
fn element_at(v: &Value, i: usize) -> Value {
with_host(|h| h.element_at(v, i))
}
pub(crate) fn set_names(v: &Value, names: Vec<Option<String>>) {
if names.iter().all(|n| n.is_none()) {
with_host(|h| {
let nl = h.null();
h.set_attr(v, "names", nl)
});
return;
}
let nv = mk_str(names);
with_host(|h| h.set_attr(v, "names", nv));
}
fn r_to_fusevm(v: &Value) -> Result<Value, String> {
match data(v) {
RData::Str(_) => str1(v)
.map(Value::str)
.ok_or_else(|| "`.Call`: NA string argument".to_string()),
RData::Int(_) | RData::Lgl(_) => as_int(v)
.first()
.copied()
.flatten()
.map(Value::Int)
.ok_or_else(|| "`.Call`: NA integer argument".to_string()),
RData::Dbl(_) => num1(v)
.map(Value::Float)
.ok_or_else(|| "`.Call`: NA numeric argument".to_string()),
_ => Err("`.Call` arguments must be length-1 numeric, integer, or character".to_string()),
}
}
fn fusevm_to_r(v: Value) -> Value {
match v {
Value::Int(n) => scalar_int(n),
Value::Float(f) => scalar_dbl(f),
Value::Bool(b) => scalar_lgl(b),
Value::Str(s) => scalar_str(s.to_string()),
_ => null(),
}
}
fn name_of(v: &Value) -> String {
match v {
Value::Str(s) => s.to_string(),
other => with_host(|h| h.str1(other)).unwrap_or_default(),
}
}
fn pop_n(vm: &mut VM, n: usize) -> Vec<Value> {
let mut out = vec![Value::Undef; n];
for slot in out.iter_mut().rev() {
*slot = vm.pop();
}
out
}
fn abort(vm: &mut VM, msg: String) -> Value {
with_host(|h| {
if h.error.is_none() {
let call = h.current_call_source();
h.set_error_call(call);
h.error = Some(msg);
}
});
vm.ip = vm.chunk.ops.len();
Value::Undef
}
fn propagate(vm: &mut VM, v: Value) -> Value {
let pending = with_host(|h| h.signal.is_some() || h.error.is_some());
if pending {
vm.ip = vm.chunk.ops.len();
}
v
}
fn b_getvar(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
with_host(|h| h.visible = true);
match with_host(|h| h.lookup(&name)) {
Some(v) => match crate::host::force_value(&v) {
Ok(forced) => forced,
Err(e) => abort(vm, e),
},
None => match primitive_value(&name) {
Some(v) => v,
None if cran_has_function(&name) => with_host(|h| h.alloc(RData::Builtin(name))),
None => abort(vm, format!("object '{name}' not found")),
},
}
}
#[cfg(not(target_arch = "wasm32"))]
fn cran_has_function(name: &str) -> bool {
crate::rembed::has_function(name)
}
#[cfg(target_arch = "wasm32")]
fn cran_has_function(_: &str) -> bool {
false
}
fn b_getfun(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
match with_host(|h| h.lookup_function(&name)) {
Some(v) => v,
None => primitive_value(&name)
.unwrap_or_else(|| with_host(|h| h.alloc(RData::Builtin(name.clone())))),
}
}
fn primitive_value(name: &str) -> Option<Value> {
if let Some(v) = base_constant(name) {
return Some(v);
}
is_primitive(name).then(|| with_host(|h| h.alloc(RData::Builtin(name.to_string()))))
}
fn base_constant(name: &str) -> Option<Value> {
let letters = |upper: bool| {
mk_str(
(b'a'..=b'z')
.map(|c| Some(((if upper { c - 32 } else { c }) as char).to_string()))
.collect(),
)
};
match name {
"pi" => Some(scalar_dbl(std::f64::consts::PI)),
"T" => Some(scalar_lgl(true)),
"F" => Some(scalar_lgl(false)),
".Machine" => {
let vals = vec![
scalar_int(i32::MAX as i64),
scalar_dbl(f64::EPSILON),
scalar_dbl(f64::MIN_POSITIVE),
scalar_dbl(f64::MAX),
];
let out = mk_list(vals);
set_names(
&out,
["integer.max", "double.eps", "double.xmin", "double.xmax"]
.into_iter()
.map(|s| Some(s.to_string()))
.collect(),
);
Some(out)
}
"LETTERS" => Some(letters(true)),
"letters" => Some(letters(false)),
"month.name" => Some(mk_str(
[
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
.into_iter()
.map(|m| Some(m.to_string()))
.collect(),
)),
"month.abb" => Some(mk_str(
[
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
]
.into_iter()
.map(|m| Some(m.to_string()))
.collect(),
)),
_ => None,
}
}
fn b_setvar(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = name_of(&vm.pop());
with_host(|h| {
h.set_var(&name, val.clone());
h.visible = false;
});
val
}
fn b_setsuper(vm: &mut VM, _: u8) -> Value {
let val = vm.pop();
let name = name_of(&vm.pop());
with_host(|h| {
h.set_super(&name, val.clone());
h.visible = false;
});
val
}
fn b_mkargs(vm: &mut VM, argc: u8) -> Value {
let flat = pop_n(vm, argc as usize);
let mut out: Vec<(Option<String>, Value)> = Vec::with_capacity(flat.len() / 2);
for pair in flat.chunks(2) {
let tag = match &pair[0] {
Value::Undef => None,
other => Some(name_of(other)),
};
let val = pair[1].clone();
match (&tag, data(&val)) {
(None, RData::Args(inner)) => out.extend(inner),
_ => out.push((tag, val)),
}
}
with_host(|h| h.alloc(RData::Args(out)))
}
fn b_open_call(vm: &mut VM, _: u8) -> Value {
let text = vm.peek().clone();
with_host(|h| {
h.calls.push(crate::host::CallCtx {
text,
closure: true,
entered: false,
})
});
vm.pop()
}
fn b_call(vm: &mut VM, _: u8) -> Value {
call_op(vm, false)
}
fn b_call_opened(vm: &mut VM, _: u8) -> Value {
call_op(vm, true)
}
fn call_op(vm: &mut VM, opened: bool) -> Value {
let argv = vm.pop();
let f = vm.pop();
let call = vm.pop();
let args = match data(&argv) {
RData::Args(a) => a,
_ => Vec::new(),
};
let name = match data(&f) {
RData::Builtin(n) => Some(n),
_ => None,
};
let closure = matches!(data(&f), RData::Closure { .. });
let transparent = matches!(
name.as_deref(),
Some("suppressMessages" | "suppressWarnings" | "suppressPackageStartupMessages")
);
if !transparent {
with_host(|h| h.visible = true);
}
let shim = name.as_deref().is_some_and(|n| n.starts_with(".rlang_"));
if !shim {
with_host(|h| match opened {
true => {
if let Some(c) = h.calls.last_mut() {
c.entered = true;
}
}
false => h.calls.push(crate::host::CallCtx {
text: call,
closure,
entered: true,
}),
});
}
let out = call_value(&f, args, name);
if !shim {
with_host(|h| {
if out.is_err() && h.error.is_none() {
let call = h.current_call_source();
h.set_error_call(call);
}
h.calls.pop();
});
}
match out {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn b_mkclosure(vm: &mut VM, _: u8) -> Value {
let id = match vm.pop() {
Value::Int(i) => i as usize,
_ => 0,
};
with_host(|h| {
let env = h.env();
h.alloc(RData::Closure { id, env })
})
}
fn b_const_dbl(vm: &mut VM, _: u8) -> Value {
let x = match vm.pop() {
Value::Float(f) => f,
Value::Int(i) => i as f64,
_ => f64::NAN,
};
scalar_dbl(x)
}
fn b_const_int(vm: &mut VM, _: u8) -> Value {
let x = match vm.pop() {
Value::Int(i) => i,
Value::Float(f) => f as i64,
_ => 0,
};
scalar_int(x)
}
fn b_const_str(vm: &mut VM, _: u8) -> Value {
let s = name_of(&vm.pop());
scalar_str(s)
}
fn b_const_lgl(vm: &mut VM, _: u8) -> Value {
let b = matches!(vm.pop(), Value::Bool(true));
scalar_lgl(b)
}
fn b_const_null(_: &mut VM, _: u8) -> Value {
null()
}
fn b_null_invisible(_: &mut VM, _: u8) -> Value {
with_host(|h| h.visible = false);
null()
}
fn b_set_visible(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
with_host(|h| h.visible = true);
v
}
fn b_switch_index(vm: &mut VM, argc: u8) -> Value {
let all = pop_n(vm, argc as usize);
let expr = all.first().cloned().unwrap_or(Value::Undef);
let names: Vec<String> = all.iter().skip(1).map(name_of).collect();
let expr_v = expr; let idx = if kind(&expr_v) == RKind::Str {
match str1(&expr_v) {
Some(s) => names
.iter()
.position(|n| *n == s)
.or_else(|| names.iter().position(|n| n.is_empty()))
.map(|p| p as i64)
.unwrap_or(-1),
None => -1,
}
} else {
match num1(&expr_v) {
Some(n) => {
let n = n as i64;
if n >= 1 && n <= names.len() as i64 {
n - 1
} else {
-1
}
}
None => -1,
}
};
Value::Int(idx)
}
fn b_const_na(vm: &mut VM, _: u8) -> Value {
match vm.pop() {
Value::Int(1) => mk_int(vec![None]),
Value::Int(2) => mk_dbl(vec![None]),
Value::Int(3) => mk_str(vec![None]),
_ => mk_lgl(vec![None]),
}
}
fn b_dots(_: &mut VM, _: u8) -> Value {
let d = with_host(|h| h.dots());
with_host(|h| h.alloc(RData::Args(d)))
}
fn b_missing(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
let bound = with_host(|h| h.env().borrow().vars.contains_key(&name));
Value::Bool(!bound)
}
fn b_binop(vm: &mut VM, _: u8) -> Value {
let op = name_of(&vm.pop());
let rhs = vm.pop();
let lhs = vm.pop();
match binop(&op, &lhs, &rhs) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn b_unop(vm: &mut VM, _: u8) -> Value {
let op = name_of(&vm.pop());
let x = vm.pop();
if let Some(r) = ops_factor(&op, &x, None) {
return match r {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
};
}
let out = match op.as_str() {
"-" => match data(&x) {
RData::Int(v) => mk_int(v.iter().map(|e| e.map(|n| -n)).collect()),
_ => mk_dbl(as_dbl(&x).iter().map(|e| e.map(|n| -n)).collect()),
},
"+" => return x,
"!" => mk_lgl(as_lgl(&x).iter().map(|e| e.map(|b| !b)).collect()),
other => return abort(vm, format!("invalid unary operator '{other}'")),
};
carry_attrs(&out, &x, &x);
out
}
fn b_special(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
let rhs = vm.pop();
let lhs = vm.pop();
let out = match name.as_str() {
"" => binop("%%", &lhs, &rhs),
"/" => binop("%/%", &lhs, &rhs),
"in" => Ok(value_in(&lhs, &rhs)),
other => {
let fname = format!("%{other}%");
match with_host(|h| h.lookup_function(&fname)).or_else(|| primitive_value(&fname)) {
Some(f) => call_value(&f, vec![(None, lhs), (None, rhs)], Some(fname)),
None => Err(format!("could not find function \"{fname}\"")),
}
}
};
match out {
Ok(v) => propagate(vm, v),
Err(e) => abort(vm, e),
}
}
fn value_in(x: &Value, table: &Value) -> Value {
let hay: Vec<Option<String>> = as_str_labels(table);
let out = as_str_labels(x)
.into_iter()
.map(|e| Some(hay.contains(&e)))
.collect();
mk_lgl(out)
}
fn r_warning(msg: &str, call: Option<String>) {
crate::host::queue_warning(msg, call);
}
fn user_warning(msg: &str) {
let call = with_host(|h| h.enclosing_call());
crate::host::queue_warning(msg, call);
}
fn coercion_warning(msg: &str) -> Result<(), String> {
signal_warning_in(msg, with_host(|h| h.context_call()))
}
fn binop_warning(msg: &str) -> Result<(), String> {
signal_warning_in(msg, None)
}
fn call_fun(f: &Value, args: Vec<(Option<String>, Value)>, call: &str) -> Result<Value, String> {
if !matches!(data(f), RData::Closure { .. }) {
return call_value(f, args, None);
}
push_context(call);
let out = call_value(f, args, None);
with_host(|h| {
h.calls.pop();
});
out
}
fn push_context(call: &str) {
let text = Value::str(call);
with_host(|h| {
h.calls.push(crate::host::CallCtx {
text,
closure: true,
entered: true,
})
});
}
const FUN_CALL: &str = "FUN(X[[i]], ...)";
fn b_warn_flush(_: &mut VM, _: u8) -> Value {
crate::host::flush_warnings(false);
null()
}
fn warn_coerced_na(x: &Value, produced_na: impl Iterator<Item = bool>) -> Result<(), String> {
if kind(x) != RKind::Str {
return Ok(());
}
let src = as_str(x);
if produced_na
.enumerate()
.any(|(i, na)| na && src.get(i).is_some_and(|e| e.is_some()))
{
coercion_warning("NAs introduced by coercion")?;
}
Ok(())
}
fn r_to_option_value(v: &Value) -> Result<crate::host::OptionValue, String> {
use crate::host::OptionValue as O;
match data(v) {
RData::Int(xs) => xs
.first()
.copied()
.flatten()
.map(O::Int)
.ok_or_else(|| "invalid value in 'options'".to_string()),
RData::Dbl(xs) => xs
.first()
.copied()
.flatten()
.map(O::Dbl)
.ok_or_else(|| "invalid value in 'options'".to_string()),
RData::Lgl(xs) => xs
.first()
.copied()
.flatten()
.map(O::Lgl)
.ok_or_else(|| "invalid value in 'options'".to_string()),
RData::Str(xs) => xs
.first()
.cloned()
.flatten()
.map(O::Str)
.ok_or_else(|| "invalid value in 'options'".to_string()),
_ => Err("invalid value in 'options'".into()),
}
}
fn option_value_to_r(v: Option<crate::host::OptionValue>) -> Value {
use crate::host::OptionValue as O;
match v {
Some(O::Int(n)) => scalar_int(n),
Some(O::Dbl(x)) => scalar_dbl(x),
Some(O::Lgl(b)) => scalar_lgl(b),
Some(O::Str(s)) => scalar_str(s),
None => null(),
}
}
fn ops_factor(op: &str, lhs: &Value, rhs: Option<&Value>) -> Option<Result<Value, String>> {
let lf = is_factor(lhs);
let rf = rhs.is_some_and(is_factor);
if (!lf && !rf) || op == ":" {
return None;
}
let ordered = (lf && is_ordered(lhs)) || (rf && is_ordered(rhs.unwrap()));
let ok = match op {
"==" | "!=" => true,
"<" | ">" | "<=" | ">=" => ordered,
_ => false,
};
if !ok {
let msg = if ordered {
format!("'{op}' is not meaningful for ordered factors")
} else {
format!("\u{2018}{op}\u{2019} not meaningful for factors")
};
if let Err(e) = binop_warning(&msg) {
return Some(Err(e));
}
let n = len(lhs).max(rhs.map_or(0, len));
return Some(Ok(mk_lgl(vec![None; n])));
}
let rhs = rhs.expect("a binary operator reached the comparison path");
if lf && rf {
let (l1, l2) = (levels_of(lhs), levels_of(rhs));
let mismatch = if op == "==" || op == "!=" {
let (mut a, mut b) = (l1.clone(), l2.clone());
a.sort();
b.sort();
a != b
} else {
l1 != l2
};
if mismatch {
return Some(Err("level sets of factors are different".into()));
}
}
if op == "==" || op == "!=" {
return Some(compare(
op,
&mk_str(as_str_labels(lhs)),
&mk_str(as_str_labels(rhs)),
));
}
let levels = if lf { levels_of(lhs) } else { levels_of(rhs) };
let rank = |v: &Value| -> Value {
if is_factor(v) {
mk_int(as_int(v))
} else {
mk_int(
as_str(v)
.iter()
.map(|s| {
s.as_ref()
.and_then(|s| levels.iter().position(|l| l == s))
.map(|p| p as i64 + 1)
})
.collect(),
)
}
};
Some(compare(op, &rank(lhs), &rank(rhs)))
}
pub fn binop(op: &str, lhs: &Value, rhs: &Value) -> Result<Value, String> {
if kind(lhs) == RKind::RForeign || kind(rhs) == RKind::RForeign {
return cran_call(op, &[(None, lhs.clone()), (None, rhs.clone())]);
}
if let Some(r) = ops_factor(op, lhs, Some(rhs)) {
return r;
}
match op {
"+" | "-" | "*" | "/" | "^" | "%%" | "%/%" => arith(op, lhs, rhs),
"==" | "!=" | "<" | ">" | "<=" | ">=" => compare(op, lhs, rhs),
"&" | "|" => logic(op, lhs, rhs),
":" => Ok(colon(lhs, rhs)),
other => Err(format!("invalid operator '{other}'")),
}
}
fn recycle_len(a: usize, b: usize) -> Result<usize, String> {
if a == 0 || b == 0 {
return Ok(0);
}
let (lo, hi) = (a.min(b), a.max(b));
if hi % lo != 0 {
binop_warning("longer object length is not a multiple of shorter object length")?;
}
Ok(hi)
}
fn carry_attrs(out: &Value, lhs: &Value, rhs: &Value) {
let src = if len(lhs) >= len(rhs) { lhs } else { rhs };
for key in ["names", "dim", "dimnames"] {
if let Some(a) = with_host(|h| h.attr(src, key)) {
with_host(|h| h.set_attr(out, key, a));
}
}
}
fn shaped_like(out: Value, x: &Value) -> Result<Value, String> {
carry_attrs(&out, x, x);
Ok(out)
}
const INT_OVERFLOW: &str = "NAs produced by integer overflow";
fn int_in_range(x: f64) -> bool {
x.is_finite() && x.abs() <= i32::MAX as f64
}
const INT_COERCE_RANGE: &str = "NAs introduced by coercion to integer range";
fn int_range_na(xs: Vec<Option<i64>>) -> Vec<Option<i64>> {
let mut lost = false;
let out = xs
.into_iter()
.map(|e| {
e.and_then(|n| match int_in_range(n as f64) {
true => Some(n),
false => {
lost = true;
None
}
})
})
.collect();
if lost {
r_warning(INT_COERCE_RANGE, with_host(|h| h.context_call()));
}
out
}
fn arith(op: &str, lhs: &Value, rhs: &Value) -> Result<Value, String> {
if let (Some((x, xi)), Some((y, yi))) = (
with_host(|h| h.scalar_real(lhs)),
with_host(|h| h.scalar_real(rhs)),
) {
let r = match op {
"+" => x + y,
"-" => x - y,
"*" => x * y,
"/" => x / y,
"^" => r_pow(x, y),
"%%" => r_mod(x, y),
_ => r_idiv(x, y),
};
let int_result = matches!(op, "+" | "-" | "*" | "%%" | "%/%") && xi && yi;
return Ok(if int_result {
match int_in_range(r) {
true => Value::Int(r as i64),
false => {
if r.is_finite() {
r_warning(INT_OVERFLOW, None);
}
mk_int(vec![None])
}
}
} else {
Value::Float(r)
});
}
if kind(lhs) == RKind::Str || kind(rhs) == RKind::Str {
return Err("non-numeric argument to binary operator".into());
}
let n = recycle_len(len(lhs), len(rhs))?;
let int_result = matches!(op, "+" | "-" | "*" | "%%" | "%/%")
&& matches!(kind(lhs), RKind::Int | RKind::Lgl)
&& matches!(kind(rhs), RKind::Int | RKind::Lgl);
let (a, b) = (as_dbl(lhs), as_dbl(rhs));
let mut out: Vec<Option<f64>> = Vec::with_capacity(n);
for i in 0..n {
let (x, y) = (a[i % a.len()], b[i % b.len()]);
out.push(match (x, y) {
_ if op == "^" && (y == Some(0.0) || x == Some(1.0)) => Some(1.0),
(Some(x), Some(y)) => Some(match op {
"+" => x + y,
"-" => x - y,
"*" => x * y,
"/" => x / y,
"^" => r_pow(x, y),
"%%" => r_mod(x, y),
_ => r_idiv(x, y),
}),
_ => None,
});
}
let v = if int_result {
let mut overflowed = false;
let ints = out
.into_iter()
.map(|e| {
e.and_then(|x| {
let ok = int_in_range(x);
overflowed |= !ok && x.is_finite();
ok.then_some(x as i64)
})
})
.collect();
if overflowed {
r_warning(INT_OVERFLOW, None);
}
mk_int(ints)
} else {
mk_dbl(out)
};
carry_attrs(&v, lhs, rhs);
Ok(v)
}
fn compare(op: &str, lhs: &Value, rhs: &Value) -> Result<Value, String> {
if let (Some((x, _)), Some((y, _))) = (
with_host(|h| h.scalar_real(lhs)),
with_host(|h| h.scalar_real(rhs)),
) {
return Ok(
match (!x.is_nan() && !y.is_nan()).then(|| cmp_result(op, x.partial_cmp(&y).unwrap())) {
Some(b) => Value::Bool(b),
None => mk_lgl(vec![None]),
},
);
}
let n = recycle_len(len(lhs), len(rhs))?;
let as_text = kind(lhs) == RKind::Str || kind(rhs) == RKind::Str;
let mut out: Vec<Option<bool>> = Vec::with_capacity(n);
if as_text {
let (a, b) = (as_str(lhs), as_str(rhs));
for i in 0..n {
let (x, y) = (&a[i % a.len()], &b[i % b.len()]);
out.push(match (x, y) {
(Some(x), Some(y)) => Some(cmp_result(op, crate::collate::str_cmp(x, y))),
_ => None,
});
}
} else {
let (a, b) = (as_dbl(lhs), as_dbl(rhs));
for i in 0..n {
let (x, y) = (a[i % a.len()], b[i % b.len()]);
out.push(match (x, y) {
(Some(x), Some(y)) if !x.is_nan() && !y.is_nan() => {
Some(cmp_result(op, x.partial_cmp(&y).unwrap()))
}
_ => None,
});
}
}
let v = mk_lgl(out);
carry_attrs(&v, lhs, rhs);
Ok(v)
}
fn cmp_result(op: &str, ord: std::cmp::Ordering) -> bool {
use std::cmp::Ordering::*;
match op {
"==" => ord == Equal,
"!=" => ord != Equal,
"<" => ord == Less,
">" => ord == Greater,
"<=" => ord != Greater,
_ => ord != Less,
}
}
fn logic(op: &str, lhs: &Value, rhs: &Value) -> Result<Value, String> {
let n = recycle_len(len(lhs), len(rhs))?;
let (a, b) = (as_lgl(lhs), as_lgl(rhs));
let mut out = Vec::with_capacity(n);
for i in 0..n {
let (x, y) = (a[i % a.len()], b[i % b.len()]);
out.push(match op {
"&" => match (x, y) {
(Some(false), _) | (_, Some(false)) => Some(false),
(Some(true), Some(true)) => Some(true),
_ => None,
},
_ => match (x, y) {
(Some(true), _) | (_, Some(true)) => Some(true),
(Some(false), Some(false)) => Some(false),
_ => None,
},
});
}
Ok(mk_lgl(out))
}
fn colon(lhs: &Value, rhs: &Value) -> Value {
let from = num1(lhs).unwrap_or(f64::NAN);
let to = num1(rhs).unwrap_or(f64::NAN);
if from.is_nan() || to.is_nan() {
return mk_int(vec![None]);
}
let whole = from == from.trunc() && to == to.trunc();
let mut out = Vec::new();
if from <= to {
let mut x = from;
while x <= to + 1e-10 {
out.push(Some(x));
x += 1.0;
}
} else {
let mut x = from;
while x >= to - 1e-10 {
out.push(Some(x));
x -= 1.0;
}
}
if whole {
mk_int(out.into_iter().map(|e| e.map(|x| x as i64)).collect())
} else {
mk_dbl(out)
}
}
fn b_truthy(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
match as_lgl(&v).first().copied() {
Some(Some(b)) => Value::Bool(b),
Some(None) => abort(vm, "missing value where TRUE/FALSE needed".into()),
None => abort(vm, "argument is of length zero".into()),
}
}
fn b_is_false(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
Value::Bool(matches!(as_lgl(&v).first(), Some(Some(false))))
}
fn b_is_true(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
Value::Bool(matches!(as_lgl(&v).first(), Some(Some(true))))
}
fn b_seq_len(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
Value::Int(len(&v) as i64)
}
fn range_ends(vm: &mut VM) -> (f64, f64, bool) {
let to = num1(&vm.pop()).unwrap_or(f64::NAN);
let from = num1(&vm.pop()).unwrap_or(f64::NAN);
let whole = from == from.trunc() && to == to.trunc();
(from, to, whole)
}
fn b_range_from(vm: &mut VM, _: u8) -> Value {
let (from, to, whole) = range_ends(vm);
if from.is_nan() || to.is_nan() {
return mk_int(vec![None]);
}
if whole {
Value::Int(from as i64)
} else {
Value::Float(from)
}
}
fn b_range_step(vm: &mut VM, _: u8) -> Value {
let (from, to, whole) = range_ends(vm);
let up = !matches!(from.partial_cmp(&to), Some(std::cmp::Ordering::Greater));
if whole {
Value::Int(if up { 1 } else { -1 })
} else {
Value::Float(if up { 1.0 } else { -1.0 })
}
}
fn b_range_len(vm: &mut VM, _: u8) -> Value {
let (from, to, _) = range_ends(vm);
if from.is_nan() || to.is_nan() {
return Value::Int(1);
}
Value::Int(((to - from).abs() + 1e-10).floor() as i64 + 1)
}
fn b_seq_elem(vm: &mut VM, _: u8) -> Value {
let i = match vm.pop() {
Value::Int(i) => i as usize,
Value::Float(f) => f as usize,
_ => 0,
};
let v = vm.pop();
element_at(&v, i)
}
fn b_autoprint(vm: &mut VM, _: u8) -> Value {
let v = vm.pop();
let show = with_host(|h| {
let s = h.echo && h.visible && h.error.is_none() && h.signal.is_none();
if h.echo {
h.visible = true;
}
s
});
if show {
match s3_primitive_method("print", std::slice::from_ref(&(None, v.clone()))) {
Some(Err(e)) => return abort(vm, e),
Some(Ok(_)) => {}
None => print_value(&v),
}
}
propagate(vm, v)
}
fn args_of(v: &Value) -> Vec<(Option<String>, Value)> {
match data(v) {
RData::Args(a) => a,
_ => Vec::new(),
}
}
fn foreign_index(vm: &mut VM, op: &str, x: Value, mut args: Vec<(Option<String>, Value)>) -> Value {
args.insert(0, (None, x));
match cran_call(op, &args) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn foreign_index_set(
vm: &mut VM,
op: &str,
x: Value,
mut args: Vec<(Option<String>, Value)>,
value: Value,
) -> Value {
args.insert(0, (None, x));
args.push((None, value));
match cran_call(op, &args) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn b_index(vm: &mut VM, _: u8) -> Value {
let argv = vm.pop();
let x = vm.pop();
if kind(&x) == RKind::RForeign {
return foreign_index(vm, "[", x, args_of(&argv));
}
match index_single(&x, &args_of(&argv)) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn b_index2(vm: &mut VM, _: u8) -> Value {
let argv = vm.pop();
let x = vm.pop();
if kind(&x) == RKind::RForeign {
return foreign_index(vm, "[[", x, args_of(&argv));
}
match index_double(&x, &args_of(&argv)) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn b_dollar(vm: &mut VM, _: u8) -> Value {
let name = name_of(&vm.pop());
let x = vm.pop();
if kind(&x) == RKind::RForeign {
return foreign_index(vm, "[[", x, vec![(None, scalar_str(name))]);
}
match data(&x) {
RData::Environment(e) => e.borrow().vars.get(&name).cloned().unwrap_or_else(null),
_ => {
let names = names_of(&x);
match names
.iter()
.position(|n| n.as_deref() == Some(name.as_str()))
{
Some(i) => match data(&x) {
RData::List(xs) => xs.get(i).cloned().unwrap_or_else(null),
_ => element_at(&x, i),
},
None => null(),
}
}
}
}
fn resolve_index(
idx: &Value,
n: usize,
names: &[Option<String>],
) -> Result<Vec<Option<usize>>, String> {
match data(idx) {
RData::Str(keys) => Ok(keys
.iter()
.map(|k| {
k.as_ref().and_then(|k| {
names
.iter()
.position(|nm| nm.as_deref() == Some(k.as_str()))
})
})
.collect()),
RData::Lgl(mask) if !mask.is_empty() => {
let width = n.max(mask.len());
let mut out = Vec::new();
for i in 0..width {
match mask[i % mask.len()] {
Some(true) => out.push((i < n).then_some(i)),
Some(false) => {}
None => out.push(None),
}
}
Ok(out)
}
_ => {
let nums = as_dbl(idx);
if nums.iter().flatten().any(|x| *x < 0.0) {
if nums.iter().flatten().any(|x| *x > 0.0) {
return Err("can't mix positive and negative subscripts".into());
}
let drop: Vec<usize> = nums
.iter()
.flatten()
.map(|x| (-x) as usize)
.filter(|x| *x >= 1)
.collect();
return Ok((0..n)
.filter(|i| !drop.contains(&(i + 1)))
.map(Some)
.collect());
}
Ok(nums
.iter()
.filter(|x| **x != Some(0.0))
.map(|x| match x {
Some(v) => {
let i = *v as usize;
(i >= 1 && i <= n).then_some(i - 1)
}
None => None,
})
.collect())
}
}
}
fn index_single(x: &Value, args: &[(Option<String>, Value)]) -> Result<Value, String> {
let supplied: Vec<&Value> = args
.iter()
.filter(|(_, v)| !matches!(v, Value::Undef))
.map(|(_, v)| v)
.collect();
if args.len() >= 2 {
if let Some(dim) = with_host(|h| h.attr(x, "dim")) {
let d: Vec<usize> = as_int(&dim)
.iter()
.map(|e| e.unwrap_or(0) as usize)
.collect();
let subs: Vec<(Option<String>, Value)> = args
.iter()
.filter(|(t, _)| t.as_deref() != Some("drop"))
.cloned()
.collect();
let drop = args
.iter()
.find(|(t, _)| t.as_deref() == Some("drop"))
.and_then(|(_, v)| as_lgl(v).first().copied().flatten())
.unwrap_or(true);
if d.len() == subs.len() {
return array_index(x, &subs, &d, drop);
}
}
}
if supplied.is_empty() {
return Ok(x.clone());
}
if supplied.len() == 1 {
if let Some(lin) = matrix_subscript(x, supplied[0])? {
return index_single(x, &[(None, mk_int(lin))]);
}
}
let n = len(x);
let names = names_of(x);
let pos = resolve_index(supplied[0], n, &names)?;
let out = take_positions(x, &pos);
if !names.is_empty() {
let sel: Vec<Option<String>> = pos
.iter()
.map(|p| p.and_then(|i| names.get(i).cloned().flatten()))
.collect();
let nv = mk_str(sel);
with_host(|h| h.set_attr(&out, "names", nv));
}
carry_factor(&out, x);
let drop = args
.iter()
.find(|(t, _)| t.as_deref() == Some("drop"))
.and_then(|(_, v)| as_lgl(v).first().copied().flatten())
.unwrap_or(false);
if drop && is_factor(x) {
return Ok(drop_unused_levels(&out));
}
Ok(out)
}
fn matrix_subscript(x: &Value, idx: &Value) -> Result<Option<Vec<Option<i64>>>, String> {
let to_dims =
|v: &Value| -> Vec<usize> { as_int(v).iter().map(|e| e.unwrap_or(0) as usize).collect() };
let (Some(xd), Some(idd)) = (
with_host(|h| h.attr(x, "dim")),
with_host(|h| h.attr(idx, "dim")),
) else {
return Ok(None);
};
let (d, id) = (to_dims(&xd), to_dims(&idd));
if d.len() < 2 || id.len() != 2 || id[1] != d.len() {
return Ok(None);
}
let (rows, cols) = (id[0], id[1]);
let oob = || "subscript out of bounds".to_string();
let dn = dimnames_of(x);
let mut coords: Vec<Vec<Option<Option<usize>>>> = Vec::with_capacity(cols);
for (c, dim) in d.iter().enumerate().take(cols) {
let mut col = Vec::with_capacity(rows);
for r in 0..rows {
col.push(match data(idx) {
RData::Str(keys) => {
let labels = dn.get(c).cloned().flatten().unwrap_or_default();
match keys.get(c * rows + r).cloned().flatten() {
None => Some(None),
Some(k) => Some(Some(
labels
.iter()
.position(|l| l.as_deref() == Some(k.as_str()))
.ok_or_else(oob)?,
)),
}
}
_ => match as_int(idx).get(c * rows + r).copied().flatten() {
None => Some(None),
Some(0) => None,
Some(n) if n < 0 => {
return Err("negative values are not allowed in a matrix subscript".into())
}
Some(n) if n as usize > *dim => return Err(oob()),
Some(n) => Some(Some(n as usize - 1)),
},
});
}
coords.push(col);
}
Ok(Some(
(0..rows)
.filter(|&r| coords.iter().all(|col| col[r].is_some()))
.map(|r| {
let mut lin = 0usize;
let mut stride = 1usize;
for (c, dc) in d.iter().enumerate() {
lin += coords[c][r].flatten()? * stride;
stride *= dc;
}
Some(lin as i64 + 1)
})
.collect(),
))
}
fn take_positions(x: &Value, pos: &[Option<usize>]) -> Value {
enum Picked {
Lgl(Vec<Option<bool>>),
Int(Vec<Option<i64>>),
Dbl(Vec<Option<f64>>),
Str(Vec<Option<String>>),
List(Vec<Option<Value>>),
Null,
}
let picked = with_host(|h| match h.get(x).map(|o| &o.data) {
Some(RData::Lgl(v)) => Picked::Lgl(
pos.iter()
.map(|p| p.and_then(|i| v.get(i).copied().flatten()))
.collect(),
),
Some(RData::Int(v)) => Picked::Int(
pos.iter()
.map(|p| p.and_then(|i| v.get(i).copied().flatten()))
.collect(),
),
Some(RData::Dbl(v)) => Picked::Dbl(
pos.iter()
.map(|p| p.and_then(|i| v.get(i).copied().flatten()))
.collect(),
),
Some(RData::Str(v)) => Picked::Str(
pos.iter()
.map(|p| p.and_then(|i| v.get(i).cloned().flatten()))
.collect(),
),
Some(RData::List(v)) => Picked::List(
pos.iter()
.map(|p| p.and_then(|i| v.get(i).cloned()))
.collect(),
),
None => match h.data_of(x) {
RData::Lgl(v) => Picked::Lgl(
pos.iter()
.map(|p| p.and_then(|i| v.get(i).copied().flatten()))
.collect(),
),
RData::Int(v) => Picked::Int(
pos.iter()
.map(|p| p.and_then(|i| v.get(i).copied().flatten()))
.collect(),
),
RData::Dbl(v) => Picked::Dbl(
pos.iter()
.map(|p| p.and_then(|i| v.get(i).copied().flatten()))
.collect(),
),
_ => Picked::Null,
},
_ => Picked::Null,
});
match picked {
Picked::Lgl(v) => mk_lgl(v),
Picked::Int(v) => mk_int(v),
Picked::Dbl(v) => mk_dbl(v),
Picked::Str(v) => mk_str(v),
Picked::List(v) => mk_list(v.into_iter().map(|e| e.unwrap_or_else(null)).collect()),
Picked::Null => null(),
}
}
type ArraySelection = (Vec<Option<usize>>, Vec<Vec<usize>>);
fn array_positions(
args: &[(Option<String>, Value)],
dims: &[usize],
dimnames: &[Option<Vec<Option<String>>>],
) -> Result<ArraySelection, String> {
let k = dims.len();
let sel: Vec<Vec<usize>> = (0..k)
.map(|d| match &args[d].1 {
Value::Undef => Ok((0..dims[d]).collect()),
v => {
let labels = dimnames.get(d).cloned().flatten().unwrap_or_default();
resolve_index(v, dims[d], &labels).map(|p| p.into_iter().flatten().collect())
}
})
.collect::<Result<_, String>>()?;
let mut stride = vec![1usize; k];
for d in 1..k {
stride[d] = stride[d - 1] * dims[d - 1];
}
let shape: Vec<usize> = sel.iter().map(|s| s.len()).collect();
let total: usize = shape.iter().product();
let mut pos = Vec::with_capacity(total);
let mut idx = vec![0usize; k];
for _ in 0..total {
let lin: usize = (0..k).map(|d| sel[d][idx[d]] * stride[d]).sum();
pos.push(Some(lin));
for d in 0..k {
idx[d] += 1;
if idx[d] < shape[d] {
break;
}
idx[d] = 0;
}
}
Ok((pos, sel))
}
fn array_index(
x: &Value,
args: &[(Option<String>, Value)],
dims: &[usize],
drop: bool,
) -> Result<Value, String> {
let dn = dimnames_of(x);
let (pos, sel) = array_positions(args, dims, &dn)?;
let out = take_positions(x, &pos);
let shape: Vec<usize> = sel.iter().map(|s| s.len()).collect();
let labels = |d: usize| -> Option<Vec<Option<String>>> {
let all = dn.get(d).cloned().flatten()?;
Some(
sel[d]
.iter()
.map(|&i| all.get(i).cloned().flatten())
.collect(),
)
};
let kept: Vec<usize> = (0..shape.len())
.filter(|&d| !drop || shape[d] != 1)
.collect();
if kept.len() >= 2 {
let dim = mk_int(kept.iter().map(|&d| Some(shape[d] as i64)).collect());
with_host(|h| h.set_attr(&out, "dim", dim));
if kept.iter().any(|&d| labels(d).is_some()) {
let dnv = mk_list(
kept.iter()
.map(|&d| labels(d).map(mk_str).unwrap_or_else(null))
.collect(),
);
with_host(|h| h.set_attr(&out, "dimnames", dnv));
}
} else if let Some(&d) = kept.first() {
if let Some(l) = labels(d) {
if l.iter().any(|n| n.is_some()) {
set_names(&out, l);
}
}
}
Ok(out)
}
fn index_double(x: &Value, args: &[(Option<String>, Value)]) -> Result<Value, String> {
let Some((_, idx)) = args.first() else {
return Err("subscript out of bounds".into());
};
if let RData::Environment(e) = data(x) {
let key = str1(idx).unwrap_or_default();
return Ok(e.borrow().vars.get(&key).cloned().unwrap_or_else(null));
}
if let RData::Lang(e) = data(x) {
let parts = lang_parts(&e);
let i = num1(idx).unwrap_or(0.0) as usize;
return match i.checked_sub(1).and_then(|i| parts.get(i)) {
Some((_, v)) => Ok(v.clone()),
None => Err("subscript out of bounds".into()),
};
}
let names = names_of(x);
let i = match data(idx) {
RData::Str(k) => {
let key = k.first().cloned().flatten().unwrap_or_default();
match names
.iter()
.position(|n| n.as_deref() == Some(key.as_str()))
{
Some(i) => i,
None => return Ok(null()),
}
}
_ => match num1(idx) {
Some(v) if v >= 1.0 && (v as usize) <= len(x) => v as usize - 1,
_ => return Err("subscript out of bounds".into()),
},
};
match data(x) {
RData::List(v) => Ok(v.get(i).cloned().unwrap_or_else(null)),
_ if is_factor(x) => {
let out = mk_int(vec![as_int(x).get(i).copied().flatten()]);
carry_factor(&out, x);
Ok(out)
}
_ => Ok(element_at(x, i)),
}
}
fn b_mark_shared(vm: &mut VM, _: u8) -> Value {
let v = vm.peek().clone();
with_host(|h| h.mark_shared(&v));
vm.pop()
}
fn may_mutate(vm: &VM, x: &Value) -> bool {
let Value::Obj(i) = x else { return false };
if !with_host(|h| h.may_mutate(x)) {
return false;
}
let same = |o: &Value| matches!(o, Value::Obj(j) if j == i);
!vm.stack.iter().any(same)
&& !vm.globals.iter().any(same)
&& !vm.frames.iter().any(|f| f.slots.iter().any(same))
}
fn b_index_set(vm: &mut VM, _: u8) -> Value {
let value = vm.pop();
let argv = vm.pop();
let x = vm.pop();
if kind(&x) == RKind::RForeign {
return foreign_index_set(vm, "[<-", x, args_of(&argv), value);
}
let inplace = may_mutate(vm, &x);
match assign_index(&x, &args_of(&argv), &value, false, inplace) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn b_index2_set(vm: &mut VM, _: u8) -> Value {
let value = vm.pop();
let argv = vm.pop();
let x = vm.pop();
if kind(&x) == RKind::RForeign {
return foreign_index_set(vm, "[[<-", x, args_of(&argv), value);
}
let inplace = may_mutate(vm, &x);
match assign_index(&x, &args_of(&argv), &value, true, inplace) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn b_dollar_set(vm: &mut VM, _: u8) -> Value {
let value = vm.pop();
let name = name_of(&vm.pop());
let x = vm.pop();
if let RData::Environment(e) = data(&x) {
with_host(|h| h.bind(&e, &name, value));
return x;
}
if kind(&x) == RKind::RForeign {
return foreign_index_set(vm, "[[<-", x, vec![(None, scalar_str(name))], value);
}
let key = scalar_str(name);
let args = vec![(None, key)];
let inplace = may_mutate(vm, &x);
match assign_index(&x, &args, &value, true, inplace) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn assign_index(
x: &Value,
args: &[(Option<String>, Value)],
value: &Value,
single_slot: bool,
inplace: bool,
) -> Result<Value, String> {
if args.len() >= 2 {
if let Some(dim) = with_host(|h| h.attr(x, "dim")) {
let d: Vec<usize> = as_int(&dim)
.iter()
.map(|e| e.unwrap_or(0) as usize)
.collect();
if d.len() == args.len() {
let (pos, _) = array_positions(args, &d, &dimnames_of(x))?;
let lin: Vec<Option<i64>> =
pos.into_iter().map(|p| p.map(|i| i as i64 + 1)).collect();
return assign_index(x, &[(None, mk_int(lin))], value, false, inplace);
}
}
}
let Some((_, idx)) = args.iter().find(|(_, v)| !matches!(v, Value::Undef)) else {
return Ok(x.clone());
};
if !single_slot && args.len() == 1 {
if let Some(lin) = matrix_subscript(x, idx)? {
return assign_index(x, &[(None, mk_int(lin))], value, false, inplace);
}
}
let is_list = kind(x) == RKind::List
|| (single_slot && !is_null(value) && len(value) > 1)
|| matches!(kind(value), RKind::List | RKind::Closure | RKind::Builtin);
let n = len(x);
let mut names: Option<Vec<Option<String>>> = None;
let mut positions: Vec<usize> = Vec::new();
let mut new_names: Vec<(usize, String)> = Vec::new();
match data(idx) {
RData::Str(keys) => {
let known = names.insert(names_of(x));
let mut next = n;
for k in keys.iter().flatten() {
match known
.iter()
.position(|nm| nm.as_deref() == Some(k.as_str()))
{
Some(i) => positions.push(i),
None => {
positions.push(next);
new_names.push((next, k.clone()));
next += 1;
}
}
}
}
_ => {
let highest = as_dbl(idx).iter().flatten().fold(0.0f64, |a, b| a.max(*b)) as usize;
for p in resolve_index(idx, n.max(highest), &[])? {
match p {
Some(i) => positions.push(i),
None => return Err("NAs are not allowed in subscripted assignments".into()),
}
}
}
}
let grows = positions.iter().any(|p| *p >= n);
let bare = with_host(|h| h.get(x).is_some_and(|o| o.attrs.is_empty()));
if inplace && new_names.is_empty() && !positions.is_empty() && (!grows || bare) {
let xk = kind(x);
let vk = kind(value);
if is_list
&& xk == RKind::List
&& single_slot
&& !is_null(value)
&& with_host(|h| h.set_list_elements(x, &positions, value)).is_some()
{
return Ok(x.clone());
}
if !is_list && vk.rank() <= xk.rank() {
macro_rules! write_into {
($variant:ident, $coerce:expr) => {{
let s = $coerce;
with_host(|h| {
h.with_data_mut(x, |d| match d {
RData::$variant(v) => {
splice(v, &positions, &s, n);
true
}
_ => false,
})
})
}};
}
let wrote = match xk {
RKind::Lgl => write_into!(Lgl, as_lgl(value)),
RKind::Int => write_into!(Int, as_int(value)),
RKind::Dbl => write_into!(Dbl, as_dbl(value)),
RKind::Str => write_into!(Str, as_str(value)),
_ => None,
};
if wrote == Some(true) {
return Ok(x.clone());
}
}
}
let mut names = names.unwrap_or_else(|| names_of(x));
if is_list {
let mut items: Vec<Value> = match data(x) {
RData::List(v) => v,
RData::Null => Vec::new(),
_ => elements(x),
};
if is_null(value) && single_slot {
let mut sorted = positions.clone();
sorted.sort_unstable();
for p in sorted.into_iter().rev() {
if p < items.len() {
items.remove(p);
if p < names.len() {
names.remove(p);
}
}
}
let out = mk_list(items);
if !names.is_empty() {
set_names(&out, names);
}
return Ok(out);
}
let vals: Vec<Value> = if single_slot {
vec![value.clone()]
} else {
elements(value)
};
for (k, p) in positions.iter().enumerate() {
while items.len() <= *p {
items.push(null());
names.push(blank());
}
items[*p] = vals[k % vals.len().max(1)].clone();
}
for (i, nm) in new_names {
while names.len() <= i {
names.push(blank());
}
names[i] = Some(nm);
}
let grew = items.len() > n;
let out = mk_list(items);
if !names.is_empty() {
set_names(&out, names.clone());
}
copy_attrs(x, &out, grew);
return Ok(out);
}
let rank = with_host(|h| h.kind_of(x).rank().max(h.kind_of(value).rank()));
let grow = positions
.iter()
.copied()
.max()
.map(|m| m + 1)
.unwrap_or(n)
.max(n);
let out = match rank {
1 => {
let mut v = as_lgl(x);
let s = as_lgl(value);
splice(&mut v, &positions, &s, grow);
mk_lgl(v)
}
2 => {
let mut v = as_int(x);
let s = as_int(value);
splice(&mut v, &positions, &s, grow);
mk_int(v)
}
4 => {
let mut v = as_str(x);
let s = as_str(value);
splice(&mut v, &positions, &s, grow);
mk_str(v)
}
_ => {
let mut v = as_dbl(x);
let s = as_dbl(value);
splice(&mut v, &positions, &s, grow);
mk_dbl(v)
}
};
for (i, nm) in new_names {
while names.len() <= i {
names.push(blank());
}
names[i] = Some(nm);
}
if !names.is_empty() {
while names.len() < grow {
names.push(blank());
}
set_names(&out, names);
}
copy_attrs(x, &out, grow > n);
Ok(out)
}
fn blank() -> Option<String> {
Some(String::new())
}
fn copy_attrs(x: &Value, out: &Value, grew: bool) {
for (k, v) in with_host(|h| h.attrs_of(x)) {
let dropped = k == "names" || (grew && (k == "dim" || k == "dimnames"));
if !dropped {
with_host(|h| h.set_attr(out, &k, v));
}
}
}
fn splice<T: Clone>(dst: &mut Vec<Option<T>>, positions: &[usize], src: &[Option<T>], grow: usize) {
while dst.len() < grow {
dst.push(None);
}
if src.is_empty() {
return;
}
for (k, p) in positions.iter().enumerate() {
while dst.len() <= *p {
dst.push(None);
}
dst[*p] = src[k % src.len()].clone();
}
}
fn b_replace(vm: &mut VM, _: u8) -> Value {
let value = vm.pop();
let argv = vm.pop();
let x = vm.pop();
let fname = name_of(&vm.pop());
let extra = args_of(&argv);
match replacement(&fname, &x, &extra, &value) {
Ok(v) => v,
Err(e) => abort(vm, e),
}
}
fn replacement(
fname: &str,
x: &Value,
extra: &[(Option<String>, Value)],
value: &Value,
) -> Result<Value, String> {
let out = copy_of(x);
match fname {
"names" => {
let nm = if is_null(value) {
null()
} else {
mk_str(as_str(value))
};
with_host(|h| h.set_attr(&out, "names", nm));
Ok(out)
}
"class" => {
with_host(|h| h.set_attr(&out, "class", value.clone()));
Ok(out)
}
"dim" => {
let d = mk_int(as_int(value));
with_host(|h| h.set_attr(&out, "dim", d));
Ok(out)
}
"attr" => {
let key = extra
.iter()
.find(|(n, _)| n.as_deref() == Some("which"))
.or_else(|| extra.first())
.map(|(_, v)| str1(v).unwrap_or_default())
.unwrap_or_default();
with_host(|h| h.set_attr(&out, &key, value.clone()));
Ok(out)
}
"length" => {
let want = num1(value).unwrap_or(0.0) as usize;
let pos: Vec<Option<usize>> = (0..want).map(|i| (i < len(x)).then_some(i)).collect();
Ok(take_positions(x, &pos))
}
"levels" => {
with_host(|h| h.set_attr(&out, "levels", mk_str(as_str(value))));
Ok(out)
}
"dimnames" => {
let dn = if is_null(value) {
null()
} else {
mk_list(
elements(value)
.iter()
.map(|e| {
if is_null(e) {
null()
} else {
mk_str(as_str(e))
}
})
.collect(),
)
};
with_host(|h| h.set_attr(&out, "dimnames", dn));
Ok(out)
}
"rownames" | "colnames" => {
let idx = usize::from(fname == "colnames");
let ndim = with_host(|h| h.attr(&out, "dim"))
.map(|d| len(&d))
.unwrap_or(2)
.max(idx + 1);
let old = dimnames_of(&out);
let mut margins: Vec<Value> = (0..ndim)
.map(|k| match old.get(k).cloned().flatten() {
Some(names) => mk_str(names),
None => null(),
})
.collect();
margins[idx] = if is_null(value) {
null()
} else {
mk_str(as_str(value))
};
let dn = if margins.iter().all(is_null) {
null()
} else {
mk_list(margins)
};
with_host(|h| h.set_attr(&out, "dimnames", dn));
Ok(out)
}
"substr" => {
let start = extra.first().and_then(|(_, v)| num1(v)).unwrap_or(1.0) as usize;
let stop = extra.get(1).and_then(|(_, v)| num1(v)).unwrap_or(1e6) as usize;
let vals = as_str(value);
Ok(mk_str(
as_str(x)
.iter()
.enumerate()
.map(|(i, s)| {
s.as_ref().map(|s| {
let repl: Vec<char> = vals
.get(i % vals.len().max(1))
.cloned()
.flatten()
.unwrap_or_default()
.chars()
.collect();
let mut chars: Vec<char> = s.chars().collect();
let span = stop.saturating_sub(start.saturating_sub(1));
for (j, rc) in repl.iter().take(span).enumerate() {
let pos = start.saturating_sub(1) + j;
if pos < chars.len() {
chars[pos] = *rc;
}
}
chars.into_iter().collect()
})
})
.collect(),
))
}
other => {
let fq = format!("{other}<-");
let f = with_host(|h| h.lookup_function(&fq))
.ok_or_else(|| format!("could not find function \"{fq}\""))?;
let mut args: Vec<(Option<String>, Value)> = vec![(None, x.clone())];
args.extend(extra.iter().cloned());
args.push((Some("value".into()), value.clone()));
call_value(&f, args, Some(fq))
}
}
}
fn copy_of(x: &Value) -> Value {
with_host(|h| {
let d = h.data_of(x);
let a = h.attrs_of(x);
h.alloc_with(d, a)
})
}
pub fn is_primitive(name: &str) -> bool {
PRIMITIVE_SET.with(|set| set.contains(name))
}
thread_local! {
static PRIMITIVE_SET: std::collections::HashSet<&'static str, rustc_hash::FxBuildHasher> =
PRIMITIVES.iter().chain(OPERATORS).copied().collect();
}
pub const OPERATORS: &[&str] = &[
"+", "-", "*", "/", "^", "%%", "%/%", "==", "!=", "<", ">", "<=", ">=", "&", "|", "!", ":",
"[", "[[", "$",
];
pub const PRIMITIVES: &[&str] = &[
"c",
"length",
"lengths",
"names",
"attr",
"attributes",
"class",
"inherits",
"unclass",
"structure",
"print",
"cat",
"str",
"tempfile",
"readLines",
"file.exists",
"unlink",
"paste",
"paste0",
"format",
"formatC",
"prettyNum",
"sprintf",
"message",
"warning",
"stop",
"invisible",
"identity",
"force",
"withVisible",
"seq",
"seq.int",
"rep_len",
"unname",
"all.equal",
"seq_len",
"seq_along",
"rep",
"rev",
"sort",
"order",
"unique",
"which",
"which.max",
"which.min",
"match",
"is.element",
"duplicated",
"rank",
"sort.list",
"xtfrm",
"any",
"all",
"xor",
"sum",
"prod",
"mean",
"median",
"quantile",
"cor",
"rle",
"inverse.rle",
"var",
"sd",
"min",
"max",
"range",
"abs",
"sqrt",
"exp",
"log",
"log2",
"log10",
"floor",
"ceiling",
"round",
"signif",
"trunc",
"sign",
"sin",
"cos",
"tan",
"asin",
"acos",
"atan",
"atan2",
"sinh",
"cosh",
"tanh",
"expm1",
"log1p",
"gamma",
"lgamma",
"factorial",
"lfactorial",
"choose",
"beta",
"lbeta",
"cumsum",
"cumprod",
"cummax",
"cummin",
"diff",
"pmax",
"pmin",
"tabulate",
"findInterval",
"is.null",
"is.na",
"is.nan",
"is.finite",
"is.infinite",
"anyNA",
"complete.cases",
"is.double",
"is.integer",
"is.numeric",
"is.character",
"is.logical",
"is.function",
"is.list",
"is.vector",
"as.numeric",
"as.double",
"as.integer",
"as.character",
"as.logical",
"as.vector",
"as.list",
"list",
"unlist",
"lapply",
"sapply",
"vapply",
"Map",
"mapply",
"Reduce",
"Filter",
"Find",
"Position",
"split",
"tapply",
"modifyList",
"rapply",
"do.call",
"nchar",
"substr",
"substring",
"strtrim",
"utf8ToInt",
"intToUtf8",
"toupper",
"tolower",
"casefold",
"chartr",
"strtoi",
"strrep",
"encodeString",
"strsplit",
"sub",
"gsub",
"grepl",
"grep",
"regexpr",
"gregexpr",
"regexec",
"regmatches",
"trimws",
"startsWith",
"endsWith",
"matrix",
"array",
"aperm",
"dim",
"nrow",
"ncol",
"t",
"rowSums",
"colSums",
"rowMeans",
"colMeans",
"apply",
"diag",
"%*%",
"%o%",
"outer",
"crossprod",
"tcrossprod",
"cbind",
"rbind",
"head",
"tail",
"append",
"setdiff",
"union",
"intersect",
"identical",
"isTRUE",
"isFALSE",
"ifelse",
"stopifnot",
"numeric",
"character",
"logical",
"integer",
"vector",
"setNames",
"exists",
"get",
"assign",
"environment",
"new.env",
"missing",
"return",
"UseMethod",
"NextMethod",
"tryCatch",
"withCallingHandlers",
"try",
"on.exit",
"conditionMessage",
"conditionCall",
"simpleError",
"simpleWarning",
"simpleMessage",
"simpleCondition",
"signalCondition",
"withRestarts",
"invokeRestart",
"computeRestarts",
"restartDescription",
"isRestart",
"factor",
"levels",
"nlevels",
"droplevels",
"cut",
"table",
"typeof",
"mode",
"storage.mode",
"bitwAnd",
"bitwOr",
"bitwXor",
"bitwNot",
"bitwShiftL",
"bitwShiftR",
"Recall",
"Negate",
"Vectorize",
"toString",
"deparse",
"rownames",
"colnames",
"dimnames",
"options",
"getOption",
".rust",
".Call",
"library",
"require",
"requireNamespace",
"loadNamespace",
"suppressMessages",
"suppressWarnings",
"suppressPackageStartupMessages",
".rlang_formula",
".rlang_quote",
"quote",
"bquote",
"as.name",
"as.symbol",
"sys.call",
"match.call",
"sys.function",
"eval",
"evalq",
".rlang_substitute",
"substitute",
"parent.frame",
"ls",
"objects",
"globalenv",
"environmentName",
"is.call",
"is.name",
"is.symbol",
];
pub fn call_combinator(
kind: CombinatorKind,
inner: &Value,
args: Vec<(Option<String>, Value)>,
) -> Result<Value, String> {
match kind {
CombinatorKind::Negate => {
let r = call_value(inner, args, None)?;
Ok(mk_lgl(as_lgl(&r).iter().map(|e| e.map(|b| !b)).collect()))
}
CombinatorKind::Vectorize => {
let lists: Vec<Vec<Value>> = args.iter().map(|(_, v)| elements(v)).collect();
let n = lists.iter().map(|l| l.len()).max().unwrap_or(0);
let mut out = Vec::with_capacity(n);
for i in 0..n {
let call_args: Vec<(Option<String>, Value)> = lists
.iter()
.map(|l| (None, l[i % l.len().max(1)].clone()))
.collect();
out.push(call_value(inner, call_args, None)?);
}
Ok(simplify(&mk_list(out)))
}
}
}
const VISIBILITY_TRANSPARENT: &[&str] = &[
"suppressMessages",
"suppressWarnings",
"suppressPackageStartupMessages",
"identity",
"force",
"withVisible",
];
pub fn call_primitive(name: &str, args: Vec<(Option<String>, Value)>) -> Result<Value, String> {
let args = if args.iter().any(|(_, v)| kind(v) == RKind::Promise) {
let mut forced = Vec::with_capacity(args.len());
for (n, v) in args {
forced.push((n, crate::host::force_value(&v)?));
}
if !VISIBILITY_TRANSPARENT.contains(&name) {
with_host(|h| h.visible = true);
}
forced
} else {
args
};
if OPERATORS.contains(&name) {
return call_operator(name, &args);
}
if args.iter().any(|(_, v)| kind(v) == RKind::RForeign) {
return cran_call(name, &args);
}
if !with_host(|h| std::mem::take(&mut h.suppress_s3)) {
if let Some(res) = s3_primitive_method(name, &args) {
return res;
}
}
let a = Args::new(args);
match name {
"c" => Ok(concat(&a)),
"list" => {
let out = mk_list(a.values());
let nm = a.tags();
if nm.iter().any(|n| n.is_some()) {
set_names(
&out,
nm.into_iter()
.map(|n| Some(n.unwrap_or_default()))
.collect(),
);
}
Ok(out)
}
"vector" => {
let mode = a
.get(0, "mode")
.and_then(|v| str1(&v))
.unwrap_or_else(|| "logical".into());
let n = a.get(1, "length").and_then(|v| num1(&v)).unwrap_or(0.0) as usize;
Ok(empty_vector(&mode, n))
}
"numeric" | "double" => Ok(mk_dbl(vec![Some(0.0); a.n(0, 0.0) as usize])),
"integer" => Ok(mk_int(vec![Some(0); a.n(0, 0.0) as usize])),
"character" => Ok(mk_str(vec![Some(String::new()); a.n(0, 0.0) as usize])),
"logical" => Ok(mk_lgl(vec![Some(false); a.n(0, 0.0) as usize])),
"as.numeric" | "as.double" => {
let x = a.req(0, "x")?;
let out = as_dbl(&x);
warn_coerced_na(&x, out.iter().map(|e| e.is_none()))?;
Ok(mk_dbl(out))
}
"as.integer" => {
let x = a.req(0, "x")?;
let out = int_range_na(as_int(&x));
warn_coerced_na(&x, out.iter().map(|e| e.is_none()))?;
Ok(mk_int(out))
}
"as.character" => {
let x = a.req(0, "x")?;
if let Some(e) = lang_of(&x) {
return Ok(mk_str(lang_text(&e).into_iter().map(Some).collect()));
}
if class_of(&x).iter().any(|c| c == "factor") {
let levels = with_host(|h| h.attr(&x, "levels"))
.map(|l| as_str(&l))
.unwrap_or_default();
return Ok(mk_str(
as_int(&x)
.iter()
.map(|c| c.and_then(|i| levels.get((i - 1) as usize).cloned().flatten()))
.collect(),
));
}
Ok(mk_str(crate::host::with_print_digits(
crate::host::AS_CHARACTER_DIGITS,
|| as_str(&x),
)))
}
"as.logical" => Ok(mk_lgl(as_lgl(&a.req(0, "x")?))),
"as.vector" => {
let x = a.req(0, "x")?;
if is_factor(&x) {
return Ok(mk_str(factor_labels(&x)));
}
match a.get(1, "mode").and_then(|v| str1(&v)).as_deref() {
Some("integer") => return Ok(mk_int(int_range_na(as_int(&x)))),
Some("double") | Some("numeric") => return Ok(mk_dbl(as_dbl(&x))),
Some("character") => return Ok(mk_str(as_str(&x))),
Some("logical") => return Ok(mk_lgl(as_lgl(&x))),
Some("list") => return Ok(mk_list(elements(&x))),
_ => {}
}
let out = copy_of(&x);
with_host(|h| {
let nl = h.null();
for attr in ["names", "dim", "class", "levels", "dimnames"] {
h.set_attr(&out, attr, nl.clone());
}
});
Ok(out)
}
"as.list" => {
let x = a.req(0, "x")?;
if let RData::Lang(e) = data(&x) {
let parts = lang_parts(&e);
let out = mk_list(parts.iter().map(|(_, v)| v.clone()).collect());
if parts.iter().any(|(t, _)| t.is_some()) {
let nm = parts
.iter()
.map(|(t, _)| Some(t.clone().unwrap_or_default()))
.collect();
set_names(&out, nm);
}
return Ok(out);
}
let out = mk_list(elements(&x));
let nm = names_of(&x);
if !nm.is_empty() {
set_names(&out, nm);
}
Ok(out)
}
"unlist" => Ok(unlist(&a.req(0, "x")?)),
"length" => Ok(scalar_int(len(&a.req(0, "x")?) as i64)),
"lengths" => {
let x = a.req(0, "x")?;
let nm = names_of(&x);
let out = mk_int(elements(&x).iter().map(|e| Some(len(e) as i64)).collect());
if !nm.is_empty() {
set_names(&out, nm);
}
Ok(out)
}
"names" => {
let x = a.req(0, "x")?;
let nm = names_of(&x);
if nm.is_empty() {
let has = with_host(|h| h.attr(&x, "names")).is_some_and(|n| !is_null(&n));
return Ok(if has { mk_str(vec![]) } else { null() });
}
Ok(mk_str(nm))
}
"setNames" => {
let x = copy_of(&a.req(0, "object")?);
let nm = a.req(1, "nm")?;
set_names(&x, as_str(&nm));
Ok(x)
}
"attr" => {
let x = a.req(0, "x")?;
let which = a.get(1, "which").and_then(|v| str1(&v)).unwrap_or_default();
Ok(with_host(|h| h.attr(&x, &which)).unwrap_or_else(null))
}
"attributes" => {
let x = a.req(0, "x")?;
let attrs = with_host(|h| h.attrs_of(&x));
if attrs.is_empty() {
return Ok(null());
}
let out = mk_list(attrs.values().cloned().collect());
set_names(&out, attrs.keys().map(|k| Some(k.clone())).collect());
Ok(out)
}
"class" => Ok(mk_str(
class_of(&a.req(0, "x")?).into_iter().map(Some).collect(),
)),
"inherits" => {
let x = a.req(0, "x")?;
let what: Vec<String> = as_str(&a.req(1, "what")?).into_iter().flatten().collect();
let cls = class_of(&x);
Ok(scalar_lgl(what.iter().any(|w| cls.contains(w))))
}
"unclass" => {
let out = copy_of(&a.req(0, "x")?);
let nl = null();
with_host(|h| h.set_attr(&out, "class", nl));
Ok(out)
}
"structure" => {
let out = copy_of(&a.req(0, ".Data")?);
for (tag, v) in a.rest(1) {
if let Some(t) = tag {
let key = if t == ".Names" {
"names".to_string()
} else {
t
};
with_host(|h| h.set_attr(&out, &key, v));
}
}
Ok(out)
}
"typeof" => {
let x = a.req(0, "x")?;
Ok(scalar_str(with_host(|h| h.type_of(&x))))
}
"mode" => {
let x = a.req(0, "x")?;
let t = with_host(|h| h.type_of(&x));
Ok(scalar_str(match t {
"integer" | "double" => "numeric",
"closure" | "builtin" => "function",
"language" => "call",
"symbol" => "name",
other => other,
}))
}
"storage.mode" => {
let x = a.req(0, "x")?;
Ok(scalar_str(with_host(|h| h.type_of(&x))))
}
"dim" => {
let x = a.req(0, "x")?;
Ok(with_host(|h| h.attr(&x, "dim")).unwrap_or_else(null))
}
"nrow" | "ncol" => {
let x = a.req(0, "x")?;
let d = with_host(|h| h.attr(&x, "dim"))
.map(|d| as_int(&d))
.unwrap_or_default();
let i = usize::from(name == "ncol");
Ok(match d.get(i) {
Some(Some(n)) => scalar_int(*n),
_ => null(),
})
}
"rownames" | "colnames" => {
let x = a.req(0, "x")?;
let idx = if name == "rownames" { 0 } else { 1 };
match dimnames_of(&x).get(idx) {
Some(Some(names)) => Ok(mk_str(names.clone())),
_ => Ok(null()),
}
}
"dimnames" => {
let x = a.req(0, "x")?;
Ok(with_host(|h| h.attr(&x, "dimnames")).unwrap_or_else(null))
}
".rust" => {
let code = a.req(0, "code")?;
let src = str1(&code)
.ok_or_else(|| "`.rust` expects a character string of Rust source".to_string())?;
crate::ffi::register(&src)?;
with_host(|h| h.visible = false);
Ok(null())
}
".Call" => {
let name_v = a.req(0, ".NAME")?;
let routine = str1(&name_v).ok_or_else(|| {
"`.Call` expects a routine name as its first argument".to_string()
})?;
let mut fargs: Vec<Value> = Vec::new();
for v in a.values().iter().skip(1) {
fargs.push(r_to_fusevm(v)?);
}
let out = crate::ffi::call(&routine, &fargs)?;
Ok(fusevm_to_r(out))
}
"print" => {
let x = a.req(0, "x")?;
let restore = a
.named("digits")
.and_then(|v| num1(&v))
.map(|d| crate::host::set_print_digits(d as usize));
print_value(&x);
if let Some(prev) = restore {
crate::host::set_print_digits(prev);
}
with_host(|h| h.visible = false);
Ok(x)
}
".rlang_promise" => {
let thunk = a.req(0, "thunk")?;
Ok(with_host(|h| {
let ctx_depth = h.entered_ctx_depth();
h.alloc(RData::Promise {
thunk,
value: None,
ctx_depth,
})
}))
}
"str" => {
let x = a.req(0, "object")?;
for line in str_lines(&x, 0) {
crate::host::emit(&line);
crate::host::emit("\n");
}
with_host(|h| h.visible = false);
Ok(null())
}
"tempfile" => {
let pattern = a
.named("pattern")
.and_then(|v| str1(&v))
.unwrap_or_else(|| "file".into());
let ext = a
.named("fileext")
.and_then(|v| str1(&v))
.unwrap_or_default();
let dir = a
.named("tmpdir")
.and_then(|v| str1(&v))
.unwrap_or_else(|| std::env::temp_dir().to_string_lossy().into_owned());
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
let tag = format!(
"{:x}{:x}",
std::process::id(),
SEQ.fetch_add(1, Ordering::Relaxed)
);
Ok(scalar_str(format!("{dir}/{pattern}{tag}{ext}")))
}
"readLines" => {
let path = str1(&a.req(0, "con")?).unwrap_or_default();
let text = std::fs::read_to_string(&path)
.map_err(|_| format!("cannot open file '{path}': No such file or directory"))?;
let mut lines: Vec<Option<String>> =
text.split('\n').map(|l| Some(l.to_string())).collect();
if text.ends_with('\n') {
lines.pop();
}
Ok(mk_str(lines))
}
"file.exists" => {
let xs = as_str(&a.req(0, "...")?);
Ok(mk_lgl(
xs.into_iter()
.map(|p| Some(p.is_some_and(|p| std::path::Path::new(&p).exists())))
.collect(),
))
}
"unlink" => {
let xs = as_str(&a.req(0, "x")?);
let mut code = 0;
for p in xs.into_iter().flatten() {
let path = std::path::Path::new(&p);
if !path.exists() {
continue;
}
let removed = if path.is_dir() {
let recursive = a.named("recursive").and_then(|v| lgl1(&v)).unwrap_or(false);
recursive && std::fs::remove_dir_all(path).is_ok()
} else {
std::fs::remove_file(path).is_ok()
};
if !removed {
code = 1;
}
}
with_host(|h| h.visible = false);
Ok(scalar_int(code))
}
"cat" => {
let sep = a
.named("sep")
.and_then(|v| str1(&v))
.unwrap_or_else(|| " ".into());
let objs: Vec<&Value> = a
.all
.iter()
.filter(|(t, _)| !CAT_CONTROL_ARGS.contains(&t.as_deref().unwrap_or("")))
.map(|(_, v)| v)
.collect();
let mut out = String::new();
for (i, v) in objs.iter().enumerate() {
let n = len(v);
if i != 0 && n > 0 {
out.push_str(&sep);
}
if n == 0 {
continue;
}
if let Some(kind) = uncatable(v) {
crate::host::emit(&out);
return Err(format!(
"argument {} (type '{kind}') cannot be handled by 'cat'",
i + 1
));
}
for (k, s) in as_str(v).into_iter().enumerate() {
out.push_str(&s.unwrap_or_else(|| "NA".into()));
if k + 1 < n {
out.push_str(&sep);
}
}
}
let tail = if sep.contains('\n') { "\n" } else { "" };
let text = format!("{out}{tail}");
match a
.named("file")
.and_then(|v| str1(&v))
.filter(|p| !p.is_empty())
{
Some(path) => {
let append = a.named("append").and_then(|v| lgl1(&v)).unwrap_or(false);
write_text(&path, &text, append)?;
}
None => crate::host::emit(&text),
}
with_host(|h| h.visible = false);
Ok(null())
}
"message" | "warning" => {
let text: Vec<String> = a.values().iter().flat_map(as_str).flatten().collect();
let text = text.join("") + if name == "message" { "\n" } else { "" };
let warn = name == "warning";
let classes: Vec<String> = if warn {
["simpleWarning", "warning", "condition"]
} else {
["simpleMessage", "message", "condition"]
}
.iter()
.map(|s| s.to_string())
.collect();
let muffle = if warn {
"muffleWarning"
} else {
"muffleMessage"
};
let raised_in = with_host(|h| h.enclosing_call_source());
match signal_condition_with_muffle(&text, &classes, muffle, raised_in.clone())? {
Signalled::Unwind => {
raise_condition(text, classes, raised_in);
return Ok(null());
}
Signalled::Fell => {
if warn {
user_warning(&text);
} else {
eprint!("{text}");
}
}
Signalled::Muffled => {}
}
let out = if warn { scalar_str(&text) } else { null() };
with_host(|h| h.visible = false);
Ok(out)
}
"stop" => {
let text: Vec<String> = a.values().iter().flat_map(as_str).flatten().collect();
let cond = a
.get(0, "message")
.filter(|v| class_of(v).iter().any(|c| c == "condition"));
let (text, classes) = match &cond {
Some(c) => (
element_field(c, "message")
.and_then(|m| str1(&m))
.unwrap_or_default(),
class_of(c),
),
None => (
text.join(""),
["simpleError", "error", "condition"]
.iter()
.map(|s| s.to_string())
.collect(),
),
};
let obj = match cond {
Some(c) => c,
None => mk_condition(
&text,
&classes.iter().map(String::as_str).collect::<Vec<_>>(),
with_host(|h| h.enclosing_call_source()),
),
};
signal_to_handlers(&obj, &classes)?;
with_host(|h| {
let call = h.enclosing_call_source();
h.set_error_call(call);
h.error_classes = classes;
});
Err(text)
}
"stopifnot" => {
let written = with_host(|h| h.current_call_source())
.and_then(|src| call_arg_sources(&src))
.unwrap_or_default();
for (i, (tag, v)) in a.all.iter().enumerate() {
let flags = as_lgl(v);
if flags.iter().all(|e| *e == Some(true)) {
continue;
}
with_host(|h| {
let c = h.enclosing_call_source();
h.set_error_call(c);
});
if let Some(t) = tag {
return Err(t.clone());
}
let what = written.get(i).cloned().unwrap_or_default();
let tail = match flags.len() > 1 {
true => "are not all TRUE",
false => "is not TRUE",
};
return Err(format!("{what} {tail}"));
}
with_host(|h| h.visible = false);
Ok(null())
}
"invisible" => {
let v = a.get(0, "x").unwrap_or_else(null);
with_host(|h| h.visible = false);
Ok(v)
}
"identity" | "force" => a.req(0, "x"),
"withVisible" => {
let x = a.req(0, "x")?;
let seen = with_host(|h| h.visible);
let out = mk_list(vec![x, scalar_lgl(seen)]);
set_names(&out, vec![Some("value".into()), Some("visible".into())]);
with_host(|h| h.visible = true);
Ok(out)
}
"paste" | "paste0" => Ok(crate::host::with_print_digits(
crate::host::AS_CHARACTER_DIGITS,
|| paste(&a, name == "paste0"),
)),
"toString" => {
let x = a.req(0, "x")?;
let parts: Vec<String> =
crate::host::with_print_digits(crate::host::AS_CHARACTER_DIGITS, || {
as_str_labels(&x)
})
.into_iter()
.map(|s| s.unwrap_or_else(|| "NA".into()))
.collect();
Ok(scalar_str(parts.join(", ")))
}
"options" => {
let mut names: Vec<Option<String>> = Vec::new();
let mut olds: Vec<Value> = Vec::new();
let mut any_set = false;
let mut record = |name: &str, old: Option<crate::host::OptionValue>| {
names.push(Some(name.to_string()));
olds.push(option_value_to_r(old));
};
for (tag, v) in a.all.iter() {
match tag {
Some(name) => {
any_set = true;
let (prev, warning) = crate::host::option_set(name, r_to_option_value(v)?)?;
record(name, prev);
if let Some(w) = warning {
r_warning(&w, with_host(|h| h.current_call()));
}
}
None if kind(v) == RKind::List => {
let elems = match data(v) {
RData::List(xs) => xs,
_ => unreachable!(),
};
let tags = with_host(|h| h.attr(v, "names"))
.map(|n| as_str(&n))
.unwrap_or_default();
for (i, e) in elems.iter().enumerate() {
let Some(Some(name)) = tags.get(i) else {
return Err("invalid argument to 'options'".into());
};
any_set = true;
let (prev, warning) =
crate::host::option_set(name, r_to_option_value(e)?)?;
record(name, prev);
if let Some(w) = warning {
r_warning(&w, with_host(|h| h.current_call()));
}
}
}
None => {
for s in as_str(v).into_iter().flatten() {
record(&s, crate::host::option_get(&s));
}
}
}
}
let out = mk_list(olds);
set_names(&out, names);
if any_set {
with_host(|h| h.visible = false);
}
Ok(out)
}
"getOption" => {
let name = str1(&a.req(0, "x")?)
.ok_or_else(|| "'x' must be a character string".to_string())?;
match crate::host::option_get(&name) {
Some(v) => Ok(option_value_to_r(Some(v))),
None => Ok(a.get(1, "default").unwrap_or_else(null)),
}
}
"deparse" => {
let x = a.req(0, "expr")?;
if let RData::Sym(n) = data(&x) {
return Ok(scalar_str(n));
}
if let Some(e) = lang_of(&x) {
return Ok(mk_str(
crate::deparse::deparse_all_lines(&e)
.into_iter()
.map(Some)
.collect(),
));
}
if let Some(src) = function_src(&x) {
return Ok(mk_str(src.into_iter().map(Some).collect()));
}
Ok(scalar_str(deparse_value(&x)))
}
"format" => {
let x = a.req(0, "x")?;
if let Some(src) = function_src(&x) {
return Ok(mk_str(src.into_iter().map(Some).collect()));
}
if let Some(e) = lang_of(&x) {
return Ok(mk_str(
crate::deparse::deparse_all_lines(&e)
.into_iter()
.map(Some)
.collect(),
));
}
if is_null(&x) {
return Ok(mk_str(vec![Some("NULL".into())]));
}
let nsmall = a.named("nsmall").and_then(|v| num1(&v)).unwrap_or(0.0) as usize;
let digits = a.named("digits").and_then(|v| num1(&v)).map(|d| d as i32);
let big = a
.named("big.mark")
.and_then(|v| str1(&v))
.unwrap_or_default();
let numeric = matches!(kind(&x), RKind::Dbl | RKind::Int);
let scientific = a.named("scientific").and_then(|v| lgl1(&v));
let is_dbl = kind(&x) == RKind::Dbl;
let base: Vec<Option<String>> = if numeric && (is_dbl || digits.is_some() || nsmall > 0)
{
let restore = digits.map(|d| crate::host::set_print_digits(d.max(1) as usize));
let dbl = as_dbl(&x);
let finite: Vec<f64> = dbl
.iter()
.flatten()
.copied()
.filter(|v| v.is_finite())
.collect();
let fixed_d = finite
.iter()
.map(|v| crate::host::fixed_decimals(*v))
.max()
.unwrap_or(0);
let sci_d = finite
.iter()
.map(|v| crate::host::sci_decimals(*v))
.max()
.unwrap_or(0);
let width = |f: &dyn Fn(f64) -> String| {
finite
.iter()
.map(|v| f(*v).chars().count())
.max()
.unwrap_or(0)
};
let use_sci = scientific.unwrap_or_else(|| {
!crate::host::prefers_fixed(
width(&|v| render_fixed(v, fixed_d)),
width(&|v| render_sci(v, sci_d)),
)
});
let fixed_d = fixed_d.max(nsmall);
let out = dbl
.iter()
.map(|e| {
e.map(|v| match (v.is_finite(), use_sci) {
(true, true) => render_sci(v, sci_d),
(true, false) => render_fixed(v, fixed_d),
(false, _) => render_fixed(v, 0),
})
})
.collect();
if let Some(prev) = restore {
crate::host::set_print_digits(prev);
}
out
} else {
as_str(&x)
};
let out: Vec<Option<String>> = base
.into_iter()
.map(|s| {
let mut s = s.unwrap_or_else(|| "NA".into());
if numeric && !big.is_empty() {
s = insert_big_mark(&s, &big);
}
Some(s)
})
.collect();
let width = a
.named("width")
.and_then(|v| num1(&v))
.unwrap_or(0.0)
.max(0.0) as usize;
let justify = a
.named("justify")
.and_then(|v| str1(&v))
.unwrap_or_else(|| "left".into());
let is_str = kind(&x) == RKind::Str;
let out = if is_str && justify == "none" {
out
} else if out.len() > 1 || width > 0 {
let w = out
.iter()
.flatten()
.map(|s| crate::strwidth::display_width(s))
.max()
.unwrap_or(0)
.max(width);
if is_str && justify == "centre" {
out.into_iter()
.map(|s| s.map(|s| centre_display(&s, w)))
.collect()
} else {
let left = is_str && justify != "right";
out.into_iter()
.map(|s| s.map(|s| crate::strwidth::pad_display(&s, w, left)))
.collect()
}
} else {
out
};
shaped_like(mk_str(out), &x)
}
"formatC" => format_c(&a),
"prettyNum" => {
let x = a.req(0, "x")?;
let big = a
.named("big.mark")
.and_then(|v| str1(&v))
.unwrap_or_default();
Ok(mk_str(
as_str(&x)
.into_iter()
.map(|s| s.map(|s| insert_big_mark(&s, &big)))
.collect(),
))
}
"sprintf" => sprintf(&a),
"seq_len" => {
let n = a.n(0, 0.0) as i64;
Ok(mk_int((1..=n).map(Some).collect()))
}
"seq_along" => {
let n = len(&a.req(0, "along.with")?) as i64;
Ok(mk_int((1..=n).map(Some).collect()))
}
"seq" => in_method("seq.default", || seq(&a)),
"seq.int" => seq(&a),
"rep" => Ok(rep(&a)),
"rep_len" => {
let x = a.req(0, "x")?;
let n = a.get(1, "length.out").and_then(|v| num1(&v)).unwrap_or(0.0) as usize;
let src = len(&x).max(1);
let pos: Vec<Option<usize>> = (0..n).map(|i| Some(i % src)).collect();
let out = take_positions(&x, &pos);
carry_factor(&out, &x);
Ok(out)
}
"rev" => {
let x = a.req(0, "x")?;
let nm = names_of(&x);
let pos: Vec<Option<usize>> = (0..len(&x)).rev().map(Some).collect();
let out = take_positions(&x, &pos);
if !nm.is_empty() {
set_names(&out, nm.into_iter().rev().collect());
}
carry_factor(&out, &x);
Ok(out)
}
"unname" => {
let out = copy_of(&a.req(0, "obj")?);
with_host(|h| {
let nl = h.null();
h.set_attr(&out, "names", nl);
});
Ok(out)
}
"all.equal" => {
let x = a.req(0, "target")?;
let y = a.req(1, "current")?;
let (xs, ys) = (as_dbl(&x), as_dbl(&y));
let numeric = matches!(kind(&x), RKind::Dbl | RKind::Int)
&& matches!(kind(&y), RKind::Dbl | RKind::Int);
if numeric && xs.len() == ys.len() {
let tol = 1.5e-8;
let mut sum_abs_diff = 0.0;
let mut sum_abs_tgt = 0.0;
for (a, b) in xs.iter().zip(ys.iter()) {
match (a, b) {
(Some(a), Some(b)) if a != b => {
sum_abs_diff += (a - b).abs();
sum_abs_tgt += a.abs();
}
(Some(_), Some(_)) => {}
_ => return Ok(scalar_str("'is.NA' value mismatch")),
}
}
let rel = if sum_abs_tgt > tol {
sum_abs_diff / sum_abs_tgt
} else {
sum_abs_diff
};
if rel <= tol {
Ok(scalar_lgl(true))
} else {
Ok(scalar_str(format!(
"Mean relative difference: {}",
crate::host::format_dbl(rel)
)))
}
} else {
Ok(if identical(&x, &y) {
scalar_lgl(true)
} else {
scalar_str("objects differ")
})
}
}
"head" | "tail" => {
let x = a.req(0, "x")?;
let n = a.get(1, "n").and_then(|v| num1(&v)).unwrap_or(6.0) as i64;
if let Some(rows) = matrix_rows(&x) {
let k = row_count(n, rows as i64);
let taken: Vec<usize> = match name == "head" {
true => (0..k).collect(),
false => (rows - k..rows).collect(),
};
let out = take_rows(&x, &taken);
let dn = dimnames_of(&x);
if name == "tail" && dn.first().map_or(true, |d| d.is_none()) {
let labels = taken.iter().map(|r| Some(format!("[{},]", r + 1)));
let cols = dn.get(1).and_then(|c| c.clone());
set_dimnames(&out, Some(labels.collect()), cols);
}
return Ok(out);
}
let total = len(&x) as i64;
let k = if n < 0 {
(total + n).max(0)
} else {
n.min(total)
} as usize;
let pos: Vec<Option<usize>> = if name == "head" {
(0..k).map(Some).collect()
} else {
(total as usize - k..total as usize).map(Some).collect()
};
let out = take_positions(&x, &pos);
carry_factor(&out, &x);
Ok(out)
}
"append" => {
let x = a.req(0, "x")?;
let y = a.req(1, "values")?;
let n = len(&x);
let after = a
.get(2, "after")
.and_then(|v| num1(&v))
.map(|v| (v.max(0.0) as usize).min(n))
.unwrap_or(n);
let joined = if after == 0 {
Args::new(vec![(None, y), (None, x)])
} else if after >= n {
Args::new(vec![(None, x), (None, y)])
} else {
let head = take_positions(&x, &(0..after).map(Some).collect::<Vec<_>>());
let tail = take_positions(&x, &(after..n).map(Some).collect::<Vec<_>>());
let nm = names_of(&x);
if !nm.is_empty() {
set_names(&head, nm[..after].to_vec());
set_names(&tail, nm[after..].to_vec());
}
Args::new(vec![(None, head), (None, y), (None, tail)])
};
Ok(concat(&joined))
}
"sort" => {
let x = a.req(0, "x")?;
let decreasing = a
.named("decreasing")
.and_then(|v| lgl1(&v))
.unwrap_or(false);
let na_last = na_last_arg(&a, None);
let sorted = sort_value(&x, decreasing, na_last);
if a.named("index.return")
.and_then(|v| lgl1(&v))
.unwrap_or(false)
{
let ix = order_value(&x, decreasing, na_last);
let out = mk_list(vec![sorted, ix]);
set_names(&out, vec![Some("x".into()), Some("ix".into())]);
Ok(out)
} else {
Ok(sorted)
}
}
"order" => {
let keys: Vec<Value> = a
.all
.iter()
.filter(|(t, _)| t.is_none())
.map(|(_, v)| v.clone())
.collect();
if keys.is_empty() {
return Err("argument \"x\" is missing, with no default".into());
}
let decreasing = a
.named("decreasing")
.and_then(|v| lgl1(&v))
.unwrap_or(false);
Ok(mk_int(
order_by_keys(&keys, decreasing, na_last_arg(&a, Some(true)))
.into_iter()
.map(|i| Some(i as i64 + 1))
.collect(),
))
}
"sort.list" => {
let x = a.req(0, "x")?;
let decreasing = a
.named("decreasing")
.and_then(|v| lgl1(&v))
.unwrap_or(false);
let na_last = na_last_arg(&a, Some(true));
let ord = order_by_keys(std::slice::from_ref(&x), decreasing, na_last);
let out: Vec<Option<i64>> = if na_last.is_none() {
let key = SortKey::of(&x);
let mut compacted = vec![0i64; len(&x)];
let mut next = 0;
for (i, slot) in compacted.iter_mut().enumerate() {
if !key.missing(i) {
next += 1;
*slot = next;
}
}
ord.into_iter().map(|i| Some(compacted[i])).collect()
} else {
ord.into_iter().map(|i| Some(i as i64 + 1)).collect()
};
Ok(mk_int(out))
}
"xtfrm" => {
let x = a.req(0, "x")?;
if !is_factor(&x) && matches!(kind(&x), RKind::Int | RKind::Dbl) {
return Ok(x);
}
let key = SortKey::of(&x);
let n = len(&x);
let mut good: Vec<usize> = (0..n).filter(|&i| !key.missing(i)).collect();
good.sort_by(|&i, &j| key.cmp(i, j));
let mut out: Vec<Option<i64>> = vec![None; n];
let mut i = 0;
while i < good.len() {
let mut j = i + 1;
while j < good.len() && key.cmp(good[j], good[i]).is_eq() {
j += 1;
}
for &k in &good[i..j] {
out[k] = Some(i as i64 + 1);
}
i = j;
}
Ok(mk_int(out))
}
"unique" => {
let x = a.req(0, "x")?;
let keys = as_str(&x);
let mut seen: Vec<Option<String>> = Vec::new();
let mut pos = Vec::new();
for (i, k) in keys.iter().enumerate() {
if !seen.contains(k) {
seen.push(k.clone());
pos.push(Some(i));
}
}
let out = take_positions(&x, &pos);
carry_factor(&out, &x);
Ok(out)
}
"setdiff" | "union" | "intersect" => {
let x = a.req(0, "x")?;
let y = a.req(1, "y")?;
let (xs, ys) = (as_str_labels(&x), as_str_labels(&y));
let mut pos = Vec::new();
let mut seen: Vec<Option<String>> = Vec::new();
for (i, k) in xs.iter().enumerate() {
let keep = match name {
"setdiff" => !ys.contains(k),
"intersect" => ys.contains(k),
_ => true,
};
if keep && !seen.contains(k) {
seen.push(k.clone());
pos.push(Some(i));
}
}
let head = take_positions(&x, &pos);
carry_factor(&head, &x);
if name == "setdiff" {
return Ok(head);
}
let mut ypos = Vec::new();
if name == "union" {
for (i, k) in ys.iter().enumerate() {
if !seen.contains(k) {
seen.push(k.clone());
ypos.push(Some(i));
}
}
}
let tail = take_positions(&y, &ypos);
carry_factor(&tail, &y);
Ok(concat(&Args::new(vec![(None, head), (None, tail)])))
}
"match" => {
let xs = as_str_labels(&a.req(0, "x")?);
let table = as_str_labels(&a.req(1, "table")?);
Ok(mk_int(
xs.iter()
.map(|k| table.iter().position(|t| t == k).map(|p| p as i64 + 1))
.collect(),
))
}
"is.element" => {
let el = as_str_labels(&a.req(0, "el")?);
let table = as_str_labels(&a.req(1, "table")?);
Ok(mk_lgl(el.iter().map(|k| Some(table.contains(k))).collect()))
}
"duplicated" => {
let keys = as_str(&a.req(0, "x")?);
let mut seen: Vec<Option<String>> = Vec::new();
Ok(mk_lgl(
keys.iter()
.map(|k| {
let dup = seen.contains(k);
if !dup {
seen.push(k.clone());
}
Some(dup)
})
.collect(),
))
}
"rank" => {
let x = a.req(0, "x")?;
let key = SortKey::of(&x);
let n = len(&x);
let mut good: Vec<usize> = (0..n).filter(|&i| !key.missing(i)).collect();
good.sort_by(|&i, &j| key.cmp(i, j));
let mut ranks = vec![0.0; n];
let mut i = 0;
while i < good.len() {
let mut j = i + 1;
while j < good.len() && key.cmp(good[j], good[i]).is_eq() {
j += 1;
}
let avg = ((i + 1 + j) as f64) / 2.0;
for &k in &good[i..j] {
ranks[k] = avg;
}
i = j;
}
for (slot, i) in (0..n).filter(|&i| key.missing(i)).enumerate() {
ranks[i] = (good.len() + slot + 1) as f64;
}
shaped_like(mk_dbl(ranks.into_iter().map(Some).collect()), &x)
}
"which" => {
let x = a.req(0, "x")?;
let nm = names_of(&x);
let hits: Vec<usize> = as_lgl(&x)
.iter()
.enumerate()
.filter(|(_, e)| **e == Some(true))
.map(|(i, _)| i)
.collect();
let arr_ind = a
.named("arr.ind")
.and_then(|v| as_lgl(&v).first().copied().flatten())
.unwrap_or(false);
if arr_ind {
let d: Vec<usize> = with_host(|h| h.attr(&x, "dim"))
.map(|d| as_int(&d).iter().map(|e| e.unwrap_or(0) as usize).collect())
.unwrap_or_default();
if d.len() >= 2 {
return Ok(which_arr_ind(&x, &hits, &d));
}
}
let out = mk_int(hits.iter().map(|i| Some(*i as i64 + 1)).collect());
if !nm.is_empty() {
set_names(
&out,
hits.iter().map(|i| nm.get(*i).cloned().flatten()).collect(),
);
}
Ok(out)
}
"which.max" | "which.min" => {
let xs = as_dbl(&a.req(0, "x")?);
let mut best: Option<(usize, f64)> = None;
for (i, e) in xs.iter().enumerate() {
let Some(v) = e else { continue };
let better = match best {
None => true,
Some((_, b)) => {
if name == "which.max" {
*v > b
} else {
*v < b
}
}
};
if better {
best = Some((i, *v));
}
}
Ok(match best {
Some((i, _)) => scalar_int(i as i64 + 1),
None => mk_int(vec![]),
})
}
"sum" | "prod" => {
let mut acc = if name == "sum" { 0.0 } else { 1.0 };
let (mut na, mut nan) = (false, false);
let narm = a.named("na.rm").and_then(|v| lgl1(&v)).unwrap_or(false);
let all_int = a
.all
.iter()
.filter(|(t, _)| t.as_deref() != Some("na.rm"))
.all(|(_, v)| matches!(kind(v), RKind::Int | RKind::Lgl));
for (tag, v) in a.all.iter() {
if tag.as_deref() == Some("na.rm") {
continue;
}
for e in as_dbl(v) {
match e {
Some(x) if !x.is_nan() => {
if name == "sum" {
acc += x
} else {
acc *= x
}
}
Some(_) if !narm => nan = true,
None if !narm => na = true,
_ => {}
}
}
}
Ok(if na {
mk_dbl(vec![None])
} else if nan {
scalar_dbl(f64::NAN)
} else if all_int && name == "sum" {
scalar_int(acc as i64)
} else {
scalar_dbl(acc)
})
}
"mean" => {
if let Some(v) = missing_result(&a, &a.req(0, "x")?, true) {
return Ok(v);
}
let xs = numeric_arg(&a, 0, "x")?;
Ok(if xs.is_empty() {
scalar_dbl(f64::NAN)
} else {
scalar_dbl(xs.iter().sum::<f64>() / xs.len() as f64)
})
}
"median" => {
if let Some(v) = missing_result(&a, &a.req(0, "x")?, false) {
return Ok(v);
}
let mut xs = numeric_arg(&a, 0, "x")?;
if xs.is_empty() {
return Ok(mk_dbl(vec![None]));
}
xs.sort_by(|p, q| p.partial_cmp(q).unwrap());
let m = xs.len() / 2;
Ok(scalar_dbl(if xs.len() % 2 == 1 {
xs[m]
} else {
(xs[m - 1] + xs[m]) / 2.0
}))
}
"quantile" => {
let mut xs = numeric_arg(&a, 0, "x")?;
xs.sort_by(|p, q| p.partial_cmp(q).unwrap_or(std::cmp::Ordering::Equal));
let probs: Vec<f64> = match a.get(1, "probs") {
Some(p) => as_dbl(&p).into_iter().flatten().collect(),
None => vec![0.0, 0.25, 0.5, 0.75, 1.0],
};
let n = xs.len();
let vals: Vec<Option<f64>> = probs
.iter()
.map(|&p| {
if n == 0 {
return None;
}
let h = (n as f64 - 1.0) * p;
let lo = h.floor() as usize;
let frac = h - lo as f64;
Some(if lo + 1 < n {
xs[lo] + frac * (xs[lo + 1] - xs[lo])
} else {
xs[lo]
})
})
.collect();
let out = mk_dbl(vals);
let names = a.named("names").and_then(|v| lgl1(&v)).unwrap_or(true);
if names {
set_names(
&out,
probs
.iter()
.map(|&p| Some(format!("{}%", crate::host::format_dbl(p * 100.0))))
.collect(),
);
}
Ok(out)
}
"cor" => {
let x = numeric_arg(&a, 0, "x")?;
let y = as_dbl(&a.req(1, "y")?)
.into_iter()
.flatten()
.collect::<Vec<_>>();
let n = x.len().min(y.len());
if n < 2 {
return Ok(mk_dbl(vec![None]));
}
let mx = x[..n].iter().sum::<f64>() / n as f64;
let my = y[..n].iter().sum::<f64>() / n as f64;
let (mut sxy, mut sxx, mut syy) = (0.0, 0.0, 0.0);
for i in 0..n {
let (dx, dy) = (x[i] - mx, y[i] - my);
sxy += dx * dy;
sxx += dx * dx;
syy += dy * dy;
}
if sxx == 0.0 || syy == 0.0 {
Ok(mk_dbl(vec![None]))
} else {
Ok(scalar_dbl(sxy / (sxx.sqrt() * syy.sqrt())))
}
}
"rle" => {
let x = a.req(0, "x")?;
let keys = as_str(&x);
let mut starts: Vec<Option<usize>> = Vec::new();
let mut lengths: Vec<Option<i64>> = Vec::new();
let mut i = 0;
while i < keys.len() {
let mut j = i + 1;
while j < keys.len() && keys[j] == keys[i] {
j += 1;
}
starts.push(Some(i));
lengths.push(Some((j - i) as i64));
i = j;
}
let values = take_positions(&x, &starts);
let out = mk_list(vec![mk_int(lengths), values]);
set_names(&out, vec![Some("lengths".into()), Some("values".into())]);
let cls = scalar_str("rle");
with_host(|h| h.set_attr(&out, "class", cls));
Ok(out)
}
"inverse.rle" => {
let x = a.req(0, "x")?;
let lengths = element_field(&x, "lengths")
.map(|v| as_int(&v))
.unwrap_or_default();
let values = element_field(&x, "values").unwrap_or_else(null);
let mut pos: Vec<Option<usize>> = Vec::new();
for (i, l) in lengths.iter().enumerate() {
for _ in 0..l.unwrap_or(0).max(0) {
pos.push(Some(i));
}
}
Ok(take_positions(&values, &pos))
}
"var" | "sd" => {
let xs = numeric_arg(&a, 0, "x")?;
if xs.len() < 2 {
return Ok(mk_dbl(vec![None]));
}
let n = xs.len() as f64;
let mean = xs.iter().sum::<f64>() / n;
let mut s = 0.0;
let mut t = 0.0;
for x in &xs {
let d = x - mean;
s += d * d;
t += d;
}
let var = (s - t * t / n) / (n - 1.0);
Ok(scalar_dbl(if name == "sd" { var.sqrt() } else { var }))
}
"min" | "max" | "range" => {
if let Some(f) = a.all.iter().map(|(_, v)| v).find(|v| is_factor(v)) {
if !is_ordered(f) {
return Err(format!("'{name}' not meaningful for factors"));
}
let levels = levels_of(f);
let codes: Vec<i64> = as_int(f).into_iter().flatten().collect();
let pick: Vec<Option<i64>> = match name {
"min" => vec![codes.iter().min().copied()],
"max" => vec![codes.iter().max().copied()],
_ => vec![codes.iter().min().copied(), codes.iter().max().copied()],
};
return Ok(mk_factor(pick, levels, true));
}
let narm = a.named("na.rm").and_then(|v| lgl1(&v)).unwrap_or(false);
let mut xs: Vec<Option<f64>> = Vec::new();
let mut strings: Vec<Option<String>> = Vec::new();
let mut is_text = false;
for (tag, v) in a.all.iter() {
if tag.as_deref() == Some("na.rm") {
continue;
}
if kind(v) == RKind::Str {
is_text = true;
strings.extend(as_str(v));
} else {
xs.extend(as_dbl(v));
}
}
if is_text {
let mut ss: Vec<String> = strings.into_iter().flatten().collect();
ss.sort_by(|a, b| crate::collate::str_cmp(a, b));
if ss.is_empty() {
let via_range = name == "range";
let at = |own: &str| match via_range {
true => Some(format!("{own}(x, na.rm = na.rm)")),
false => with_host(|h| h.current_call_source()),
};
let empty = "no non-missing arguments, returning NA";
if name != "max" {
signal_warning_in(empty, at("min"))?;
}
if name != "min" {
signal_warning_in(empty, at("max"))?;
}
let n = if via_range { 2 } else { 1 };
return Ok(mk_str(vec![None; n]));
}
return Ok(match name {
"min" => scalar_str(ss.first().cloned().unwrap_or_default()),
"max" => scalar_str(ss.last().cloned().unwrap_or_default()),
_ => mk_str(vec![ss.first().cloned(), ss.last().cloned()]),
});
}
if !narm && xs.iter().any(|e| e.map(f64::is_nan).unwrap_or(true)) {
let marker = if xs.iter().any(|e| e.is_none()) {
None
} else {
Some(f64::NAN)
};
return Ok(mk_dbl(if name == "range" {
vec![marker, marker]
} else {
vec![marker]
}));
}
let vals: Vec<f64> = xs.into_iter().flatten().filter(|x| !x.is_nan()).collect();
if vals.is_empty() {
let via_range = name == "range";
let at = |own: &str| match via_range {
true => Some(format!("{own}(x)")),
false => with_host(|h| h.current_call()),
};
let warn_min = || {
signal_warning_in("no non-missing arguments to min; returning Inf", at("min"))
};
let warn_max = || {
signal_warning_in("no non-missing arguments to max; returning -Inf", at("max"))
};
return Ok(match name {
"min" => {
warn_min()?;
scalar_dbl(f64::INFINITY)
}
"max" => {
warn_max()?;
scalar_dbl(f64::NEG_INFINITY)
}
_ => {
warn_min()?;
warn_max()?;
mk_dbl(vec![Some(f64::INFINITY), Some(f64::NEG_INFINITY)])
}
});
}
let lo = vals.iter().cloned().fold(f64::INFINITY, f64::min);
let hi = vals.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
Ok(match name {
"min" => scalar_dbl(lo),
"max" => scalar_dbl(hi),
_ => mk_dbl(vec![Some(lo), Some(hi)]),
})
}
"cumsum" | "cumprod" => {
let x = a.req(0, "x")?;
let xs = as_dbl(&x);
let mut acc = if name == "cumsum" { 0.0 } else { 1.0 };
let mut na = false;
let out: Vec<Option<f64>> = xs
.iter()
.map(|e| {
if na {
return None;
}
match e {
Some(v) => {
if name == "cumsum" {
acc += v
} else {
acc *= v
}
Some(acc)
}
None => {
na = true;
None
}
}
})
.collect();
let acc = if name == "cumsum" && matches!(kind(&x), RKind::Int | RKind::Lgl) {
mk_int(out.into_iter().map(|e| e.map(|v| v as i64)).collect())
} else {
mk_dbl(out)
};
shaped_like(acc, &x)
}
"diff" => {
let x = a.req(0, "x")?;
let is_int = matches!(kind(&x), RKind::Int | RKind::Lgl);
let lag = a
.get(1, "lag")
.and_then(|v| num1(&v))
.unwrap_or(1.0)
.max(1.0) as usize;
let differences = a
.get(2, "differences")
.and_then(|v| num1(&v))
.unwrap_or(1.0)
.max(1.0) as usize;
let mut cur = as_dbl(&x);
for _ in 0..differences {
if cur.len() <= lag {
cur = Vec::new();
break;
}
cur = (lag..cur.len())
.map(|i| match (cur[i - lag], cur[i]) {
(Some(p), Some(q)) => Some(q - p),
_ => None,
})
.collect();
}
if is_int {
Ok(mk_int(
cur.into_iter().map(|e| e.map(|v| v as i64)).collect(),
))
} else {
Ok(mk_dbl(cur))
}
}
"abs" | "sqrt" | "exp" | "log2" | "log10" | "floor" | "ceiling" | "trunc" | "sign"
| "sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "sinh" | "cosh" | "tanh" | "expm1"
| "log1p" | "gamma" | "lgamma" | "factorial" | "lfactorial" => {
let x = a.req(0, "x")?;
require_numeric(&x)?;
let f: fn(f64) -> f64 = match name {
"abs" => f64::abs,
"sqrt" => f64::sqrt,
"exp" => f64::exp,
"log2" => f64::log2,
"log10" => f64::log10,
"floor" => f64::floor,
"ceiling" => f64::ceil,
"trunc" => f64::trunc,
"sin" => f64::sin,
"cos" => f64::cos,
"tan" => f64::tan,
"asin" => f64::asin,
"acos" => f64::acos,
"atan" => f64::atan,
"sinh" => f64::sinh,
"cosh" => f64::cosh,
"tanh" => f64::tanh,
"expm1" => f64::exp_m1,
"log1p" => f64::ln_1p,
"gamma" => r_tgamma,
"lgamma" => r_lgamma,
"factorial" => |v| r_tgamma(v + 1.0),
"lfactorial" => |v| r_lgamma(v + 1.0),
_ => r_sign,
};
if name == "abs" {
if let RData::Int(v) = data(&x) {
return Ok(mk_int(v.iter().map(|e| e.map(|n| n.abs())).collect()));
}
}
let input = as_dbl(&x);
let vals: Vec<Option<f64>> = input.iter().map(|e| e.map(f)).collect();
if produced_nan(&vals, &input) {
nan_warning()?;
}
let out = mk_dbl(vals);
carry_attrs(&out, &x, &x);
Ok(out)
}
"log" => {
let x = a.req(0, "x")?;
require_numeric(&x)?;
let base = a.get(1, "base").and_then(|v| num1(&v));
let input = as_dbl(&x);
let vals: Vec<Option<f64>> = input
.iter()
.map(|e| {
e.map(|v| match base {
Some(b) => v.log(b),
None => v.ln(),
})
})
.collect();
if produced_nan(&vals, &input) {
nan_warning()?;
}
shaped_like(mk_dbl(vals), &x)
}
"atan2" => {
let y = as_dbl(&a.req(0, "y")?);
let x = as_dbl(&a.req(1, "x")?);
let n = y.len().max(x.len());
Ok(mk_dbl(
(0..n)
.map(|i| match (y[i % y.len().max(1)], x[i % x.len().max(1)]) {
(Some(a), Some(b)) => Some(a.atan2(b)),
_ => None,
})
.collect(),
))
}
"choose" => {
let ns = as_dbl(&a.req(0, "n")?);
let ks = as_dbl(&a.req(1, "k")?);
let n = ns.len().max(ks.len());
Ok(mk_dbl(
(0..n)
.map(
|i| match (ns[i % ns.len().max(1)], ks[i % ks.len().max(1)]) {
(Some(nn), Some(kk)) => Some(choose(nn, kk)),
_ => None,
},
)
.collect(),
))
}
"beta" | "lbeta" => {
let av = as_dbl(&a.req(0, "a")?);
let bv = as_dbl(&a.req(1, "b")?);
let n = av.len().max(bv.len());
Ok(mk_dbl(
(0..n)
.map(
|i| match (av[i % av.len().max(1)], bv[i % bv.len().max(1)]) {
(Some(x), Some(y)) => Some({
let lb = r_lgamma(x) + r_lgamma(y) - r_lgamma(x + y);
if name == "lbeta" {
lb
} else {
lb.exp()
}
}),
_ => None,
},
)
.collect(),
))
}
"pmax" | "pmin" => {
let narm = a.named("na.rm").and_then(|v| lgl1(&v)).unwrap_or(false);
let cols: Vec<Vec<Option<f64>>> = a
.all
.iter()
.filter(|(t, _)| t.as_deref() != Some("na.rm"))
.map(|(_, v)| as_dbl(v))
.collect();
let n = cols.iter().map(|c| c.len()).max().unwrap_or(0);
if cols.iter().any(|c| !c.is_empty() && n % c.len() != 0) {
signal_warning("an argument will be fractionally recycled")?;
}
Ok(mk_dbl(
(0..n)
.map(|i| {
let mut best: Option<f64> = None;
for c in &cols {
match c[i % c.len().max(1)] {
Some(v) => {
best = Some(match best {
None => v,
Some(b) if name == "pmax" => b.max(v),
Some(b) => b.min(v),
})
}
None if !narm => return None,
None => {}
}
}
best
})
.collect(),
))
}
"cummax" | "cummin" => {
let xv = a.req(0, "x")?;
let xs = as_dbl(&xv);
let mut acc: Option<f64> = None;
let mut na = false;
let out: Vec<Option<f64>> = xs
.iter()
.map(|e| {
if na {
return None;
}
match e {
None => {
na = true;
None
}
Some(v) => {
acc = Some(match acc {
None => *v,
Some(a) if name == "cummax" => a.max(*v),
Some(a) => a.min(*v),
});
acc
}
}
})
.collect();
shaped_like(mk_dbl(out), &xv)
}
"tabulate" => {
let bins = as_int(&a.req(0, "bin")?);
let nbins = a
.get(1, "nbins")
.and_then(|v| num1(&v))
.map(|v| v as usize)
.unwrap_or_else(|| {
bins.iter().flatten().copied().max().unwrap_or(0).max(0) as usize
});
let mut counts = vec![0i64; nbins];
for b in bins.into_iter().flatten() {
if b >= 1 && (b as usize) <= nbins {
counts[b as usize - 1] += 1;
}
}
Ok(mk_int(counts.into_iter().map(Some).collect()))
}
"findInterval" => {
let x = as_dbl(&a.req(0, "x")?);
let vec = as_dbl(&a.req(1, "vec")?);
Ok(mk_int(
x.iter()
.map(|e| e.map(|v| vec.iter().flatten().filter(|&&b| b <= v).count() as i64))
.collect(),
))
}
"round" => {
let x = a.req(0, "x")?;
let digits = a.get(1, "digits").and_then(|v| num1(&v)).unwrap_or(0.0) as i32;
shaped_like(
mk_dbl(
as_dbl(&x)
.iter()
.map(|e| e.map(|v| r_round(v, digits)))
.collect(),
),
&x,
)
}
"signif" => {
let x = a.req(0, "x")?;
let digits = (a.get(1, "digits").and_then(|v| num1(&v)).unwrap_or(6.0) as i32).max(1);
shaped_like(
mk_dbl(
as_dbl(&x)
.iter()
.map(|e| e.map(|v| signif(v, digits)))
.collect(),
),
&x,
)
}
"is.null" => Ok(scalar_lgl(is_null(&a.get(0, "x").unwrap_or_else(null)))),
"is.na" => {
let x = a.req(0, "x")?;
let out: Vec<Option<bool>> = match data(&x) {
RData::Lgl(v) => v.iter().map(|e| Some(e.is_none())).collect(),
RData::Int(v) => v.iter().map(|e| Some(e.is_none())).collect(),
RData::Dbl(v) => v
.iter()
.map(|e| Some(e.map(f64::is_nan).unwrap_or(true)))
.collect(),
RData::Str(v) => v.iter().map(|e| Some(e.is_none())).collect(),
RData::List(v) => v
.iter()
.map(|e| Some(len(e) == 1 && as_dbl(e).first() == Some(&None)))
.collect(),
_ => vec![],
};
shaped_like(mk_lgl(out), &x)
}
"is.nan" => {
let x = a.req(0, "x")?;
let out = match data(&x) {
RData::Dbl(v) => v.iter().map(|e| Some(e.is_some_and(f64::is_nan))).collect(),
_ => vec![Some(false); len(&x)],
};
shaped_like(mk_lgl(out), &x)
}
"is.finite" => {
let x = a.req(0, "x")?;
let out = match data(&x) {
RData::Dbl(v) => v
.iter()
.map(|e| Some(e.is_some_and(f64::is_finite)))
.collect(),
RData::Int(v) => v.iter().map(|e| Some(e.is_some())).collect(),
RData::Lgl(v) => v.iter().map(|e| Some(e.is_some())).collect(),
_ => vec![Some(false); len(&x)],
};
shaped_like(mk_lgl(out), &x)
}
"is.infinite" => {
let x = a.req(0, "x")?;
let out = match data(&x) {
RData::Dbl(v) => v
.iter()
.map(|e| Some(e.is_some_and(f64::is_infinite)))
.collect(),
_ => vec![Some(false); len(&x)],
};
shaped_like(mk_lgl(out), &x)
}
"anyNA" => {
let x = a.req(0, "x")?;
let any = match data(&x) {
RData::Dbl(v) => v.iter().any(|e| e.map(f64::is_nan).unwrap_or(true)),
RData::Int(v) => v.iter().any(|e| e.is_none()),
RData::Lgl(v) => v.iter().any(|e| e.is_none()),
RData::Str(v) => v.iter().any(|e| e.is_none()),
RData::List(items) => items
.iter()
.any(|e| len(e) == 1 && as_dbl(e).first() == Some(&None)),
_ => false,
};
Ok(scalar_lgl(any))
}
"complete.cases" => {
let x = a.req(0, "x")?;
let na = match data(&x) {
RData::Dbl(v) => v
.iter()
.map(|e| e.map(f64::is_nan).unwrap_or(true))
.collect(),
RData::Int(v) => v.iter().map(|e| e.is_none()).collect(),
RData::Lgl(v) => v.iter().map(|e| e.is_none()).collect(),
RData::Str(v) => v.iter().map(|e| e.is_none()).collect(),
_ => vec![false; len(&x)],
};
Ok(mk_lgl(na.into_iter().map(|n: bool| Some(!n)).collect()))
}
"is.numeric" => {
let x = a.req(0, "x")?;
Ok(scalar_lgl(
matches!(kind(&x), RKind::Dbl | RKind::Int) && !is_factor(&x),
))
}
"is.double" => Ok(scalar_lgl(kind(&a.req(0, "x")?) == RKind::Dbl)),
"is.integer" => {
let x = a.req(0, "x")?;
Ok(scalar_lgl(kind(&x) == RKind::Int && !is_factor(&x)))
}
"is.character" => Ok(scalar_lgl(kind(&a.req(0, "x")?) == RKind::Str)),
"is.logical" => Ok(scalar_lgl(kind(&a.req(0, "x")?) == RKind::Lgl)),
"is.list" => Ok(scalar_lgl(kind(&a.req(0, "x")?) == RKind::List)),
"is.function" => Ok(scalar_lgl(with_host(|h| {
h.is_function(&a.req(0, "x").unwrap_or(Value::Undef))
}))),
"is.vector" => {
let x = a.req(0, "x")?;
let plain = with_host(|h| h.attrs_of(&x))
.iter()
.all(|(k, _)| k == "names");
Ok(scalar_lgl(
plain
&& matches!(
kind(&x),
RKind::Dbl | RKind::Int | RKind::Str | RKind::Lgl | RKind::List
),
))
}
"any" | "all" => {
let narm = a.named("na.rm").and_then(|v| lgl1(&v)).unwrap_or(false);
let mut saw_na = false;
let mut decided = false;
for (tag, v) in a.all.iter() {
if tag.as_deref() == Some("na.rm") {
continue;
}
for e in as_lgl(v) {
match e {
Some(b) if (name == "any") == b => decided = true,
Some(_) => {}
None => saw_na = true,
}
}
}
Ok(if decided {
scalar_lgl(name == "any")
} else if saw_na && !narm {
mk_lgl(vec![None])
} else {
scalar_lgl(name != "any")
})
}
"isTRUE" => Ok(scalar_lgl(matches!(
as_lgl(&a.req(0, "x")?).as_slice(),
[Some(true)]
))),
"isFALSE" => Ok(scalar_lgl(matches!(
as_lgl(&a.req(0, "x")?).as_slice(),
[Some(false)]
))),
"xor" => {
let x = as_lgl(&a.req(0, "x")?);
let y = as_lgl(&a.req(1, "y")?);
let n = x.len().max(y.len());
Ok(mk_lgl(
(0..n)
.map(|i| match (x[i % x.len().max(1)], y[i % y.len().max(1)]) {
(Some(a), Some(b)) => Some(a != b),
_ => None,
})
.collect(),
))
}
"bitwAnd" | "bitwOr" | "bitwXor" | "bitwShiftL" | "bitwShiftR" => {
let x = as_int(&a.req(0, "a")?);
let y = as_int(&a.req(1, "b")?);
let n = x.len().max(y.len());
Ok(mk_int(
(0..n)
.map(|i| {
let a = x[i % x.len().max(1)]?;
let b = y[i % y.len().max(1)]?;
Some(match name {
"bitwAnd" => a & b,
"bitwOr" => a | b,
"bitwXor" => a ^ b,
"bitwShiftL" => a << b,
_ => a >> b,
})
})
.collect(),
))
}
"bitwNot" => Ok(mk_int(
as_int(&a.req(0, "a")?)
.iter()
.map(|e| e.map(|v| !v))
.collect(),
)),
"identical" => {
let x = a.req(0, "x")?;
let y = a.req(1, "y")?;
Ok(scalar_lgl(identical(&x, &y)))
}
"ifelse" => {
let test = as_lgl(&a.req(0, "test")?);
let yes = a.req(1, "yes")?;
let no = a.req(2, "no")?;
let pos_yes: Vec<Option<usize>> = (0..len(&yes)).map(Some).collect();
let pos_no: Vec<Option<usize>> = (0..len(&no)).map(Some).collect();
let mut parts: Vec<(Option<String>, Value)> = Vec::new();
for (i, t) in test.iter().enumerate() {
let v = match t {
Some(true) => take_positions(&yes, &[pos_yes[i % pos_yes.len().max(1)]]),
Some(false) => take_positions(&no, &[pos_no[i % pos_no.len().max(1)]]),
None => mk_lgl(vec![None]),
};
parts.push((None, v));
}
Ok(concat(&Args::new(parts)))
}
"nchar" => {
let ty = a
.get(1, "type")
.and_then(|v| str1(&v))
.unwrap_or_else(|| "chars".into());
let count: fn(&str) -> i64 = match ty.as_str() {
"bytes" => |s: &str| s.len() as i64,
"width" => |s: &str| crate::strwidth::display_width(s) as i64,
_ => |s: &str| s.chars().count() as i64,
};
let x = a.req(0, "x")?;
shaped_like(
mk_int(as_str(&x).iter().map(|s| s.as_deref().map(count)).collect()),
&x,
)
}
"toupper" | "tolower" | "casefold" => {
let upper = if name == "casefold" {
a.named("upper").and_then(|v| lgl1(&v)).unwrap_or(false)
} else {
name == "toupper"
};
let f: fn(char) -> char = if upper {
crate::strwidth::simple_upper
} else {
crate::strwidth::simple_lower
};
let x = a.req(0, "x")?;
shaped_like(
mk_str(
as_str(&x)
.iter()
.map(|s| s.as_deref().map(|s| crate::strwidth::map_chars(s, f)))
.collect(),
),
&x,
)
}
"strtrim" => {
let x = as_str(&a.req(0, "x")?);
let w = as_int(&a.req(1, "width")?);
Ok(mk_str(
x.iter()
.enumerate()
.map(|(i, s)| {
let wi = w.get(i % w.len().max(1)).and_then(|e| *e).unwrap_or(0);
s.as_deref()
.map(|s| crate::strwidth::trim_to_width(s, wi.max(0) as usize))
})
.collect(),
))
}
"utf8ToInt" => {
let x = a.req(0, "x")?;
let Some(s) = str1(&x) else {
return Ok(mk_int(vec![None]));
};
Ok(mk_int(s.chars().map(|c| Some(c as i64)).collect()))
}
"intToUtf8" => {
let x = as_int(&a.req(0, "x")?);
let multiple = a.get(1, "multiple").and_then(|v| lgl1(&v)).unwrap_or(false);
let chr = |e: &Option<i64>| -> Option<char> {
u32::try_from(e.filter(|&v| v != 0)?)
.ok()
.and_then(char::from_u32)
};
if multiple {
return Ok(mk_str(
x.iter()
.map(|e| e.map(|_| chr(e).map(String::from).unwrap_or_default()))
.collect(),
));
}
if x.iter().any(|e| e.is_none()) {
return Ok(mk_str(vec![None]));
}
Ok(scalar_str(x.iter().filter_map(chr).collect::<String>()))
}
"trimws" => {
let which = a
.get(1, "which")
.and_then(|v| str1(&v))
.unwrap_or_else(|| "both".into());
let xv = a.req(0, "x")?;
shaped_like(
mk_str(
as_str(&xv)
.iter()
.map(|s| {
s.as_ref().map(|s| match which.as_str() {
"left" => s.trim_start().to_string(),
"right" => s.trim_end().to_string(),
_ => s.trim().to_string(),
})
})
.collect(),
),
&xv,
)
}
"substr" => {
let xv = a.req(0, "x")?;
let start = a.get(1, "start").and_then(|v| num1(&v)).unwrap_or(1.0) as usize;
let stop = a.get(2, "stop").and_then(|v| num1(&v)).unwrap_or(1e6) as usize;
shaped_like(
mk_str(
as_str(&xv)
.iter()
.map(|s| s.as_ref().map(|s| substr_of(s, start, stop)))
.collect(),
),
&xv,
)
}
"substring" => {
let text = as_str(&a.req(0, "text")?);
let first = as_dbl(&a.get(1, "first").unwrap_or_else(|| scalar_dbl(1.0)));
let last = as_dbl(&a.get(2, "last").unwrap_or_else(|| scalar_dbl(1e6)));
let n = text.len().max(first.len()).max(last.len()).max(1);
let out = mk_str(
(0..n)
.map(|i| {
let s = text.get(i % text.len().max(1)).cloned().flatten()?;
let f = first[i % first.len().max(1)].unwrap_or(1.0) as usize;
let l = last[i % last.len().max(1)].unwrap_or(1e6) as usize;
Some(substr_of(&s, f, l))
})
.collect(),
);
let tv = a.req(0, "text")?;
if n == text.len() {
carry_attrs(&out, &tv, &tv);
}
Ok(out)
}
"strrep" => {
let x = as_str(&a.req(0, "x")?);
let times = as_int(&a.req(1, "times")?);
let n = x.len().max(times.len());
Ok(mk_str(
(0..n)
.map(|i| {
let s = x.get(i % x.len().max(1)).cloned().flatten()?;
let t = times[i % times.len().max(1)].unwrap_or(0).max(0) as usize;
Some(s.repeat(t))
})
.collect(),
))
}
"encodeString" => Ok(mk_str(
as_str(&a.req(0, "x")?)
.into_iter()
.map(|s| s.map(|s| encode_string(&s)))
.collect(),
)),
"startsWith" | "endsWith" => {
let x = as_str(&a.req(0, "x")?);
let p = as_str(&a.req(1, "prefix")?);
let n = x.len().max(p.len());
Ok(mk_lgl(
(0..n)
.map(|i| {
let s = x.get(i % x.len().max(1)).cloned().flatten()?;
let pre = p.get(i % p.len().max(1)).cloned().flatten()?;
Some(if name == "startsWith" {
s.starts_with(&pre)
} else {
s.ends_with(&pre)
})
})
.collect(),
))
}
"strsplit" => {
let x = as_str(&a.req(0, "x")?);
let sep = str1(&a.req(1, "split")?).unwrap_or_default();
let fixed = a.named("fixed").and_then(|v| lgl1(&v)).unwrap_or(false);
let re = if sep.is_empty() {
None
} else {
let pat = if fixed {
regex::escape(&sep)
} else {
sep.clone()
};
Some(
cached_regex(&pat)
.map_err(|e| format!("invalid regular expression '{sep}': {e}"))?,
)
};
let parts: Vec<Value> = x
.iter()
.map(|s| match s {
Some(s) => {
let pieces: Vec<Option<String>> = match &re {
None => s.chars().map(|c| Some(c.to_string())).collect(),
Some(re) => r_strsplit(s, re),
};
mk_str(pieces)
}
None => mk_str(vec![None]),
})
.collect();
Ok(mk_list(parts))
}
"sub" | "gsub" | "grepl" | "grep" => regex_op(name, &a),
"chartr" => {
let old = expand_char_ranges(&str1(&a.req(0, "old")?).unwrap_or_default());
let new = expand_char_ranges(&str1(&a.req(1, "new")?).unwrap_or_default());
if old.len() > new.len() {
return Err("'old' is longer than 'new'".into());
}
let map: std::collections::HashMap<char, char> =
old.iter().copied().zip(new.iter().copied()).collect();
let xv = a.req(2, "x")?;
shaped_like(
mk_str(
as_str(&xv)
.iter()
.map(|s| {
s.as_ref()
.map(|s| s.chars().map(|c| *map.get(&c).unwrap_or(&c)).collect())
})
.collect(),
),
&xv,
)
}
"strtoi" => {
let x = as_str(&a.req(0, "x")?);
let base = a.get(1, "base").and_then(|v| num1(&v)).unwrap_or(10.0) as u32;
Ok(mk_int(
x.iter()
.map(|s| {
s.as_ref().and_then(|s| {
let t = s.trim();
let t = if base == 16 {
t.strip_prefix("0x")
.or_else(|| t.strip_prefix("0X"))
.unwrap_or(t)
} else {
t
};
i64::from_str_radix(t, base).ok()
})
})
.collect(),
))
}
"regexec" => {
let pat = str1(&a.req(0, "pattern")?).unwrap_or_default();
let re = cached_regex(&pat)
.map_err(|e| format!("invalid regular expression '{pat}': {e}"))?;
let x = as_str(&a.req(1, "text")?);
let ascii = pat.is_ascii() && x.iter().flatten().all(|s| s.is_ascii());
let per: Vec<Value> = x
.iter()
.map(|s| {
let (mut starts, mut lens) = (Vec::new(), Vec::new());
match s.as_ref().and_then(|s| re.captures(s).map(|c| (s, c))) {
Some((s, caps)) => {
for i in 0..caps.len() {
match caps.get(i) {
Some(m) => {
starts.push(Some(char_pos(s, m.start()) as i64 + 1));
lens.push(Some(
s[m.start()..m.end()].chars().count() as i64
));
}
None => {
starts.push(Some(-1));
lens.push(Some(-1));
}
}
}
}
None => {
starts.push(Some(-1));
lens.push(Some(-1));
}
}
let v = mk_int(starts);
let ml = mk_int(lens);
with_host(|h| h.set_attr(&v, "match.length", ml));
if ascii {
let it = scalar_str("chars");
let ub = scalar_lgl(true);
with_host(|h| {
h.set_attr(&v, "index.type", it);
h.set_attr(&v, "useBytes", ub);
});
}
v
})
.collect();
Ok(mk_list(per))
}
"regexpr" | "gregexpr" => {
let pat = str1(&a.req(0, "pattern")?).unwrap_or_default();
let re = cached_regex(&pat)
.map_err(|e| format!("invalid regular expression '{pat}': {e}"))?;
let x = as_str(&a.req(1, "text")?);
let ascii = pat.is_ascii() && x.iter().flatten().all(|s| s.is_ascii());
let tag = |v: &Value| {
if ascii {
let it = scalar_str("chars");
let ub = scalar_lgl(true);
with_host(|h| {
h.set_attr(v, "index.type", it);
h.set_attr(v, "useBytes", ub);
});
}
};
if name == "regexpr" {
let (mut starts, mut lens) = (Vec::new(), Vec::new());
for s in &x {
match s.as_ref().and_then(|s| re.find(s).map(|m| (s, m))) {
Some((s, m)) => {
starts.push(Some(char_pos(s, m.start()) as i64 + 1));
lens.push(Some(s[m.start()..m.end()].chars().count() as i64));
}
None => {
starts.push(Some(-1));
lens.push(Some(-1));
}
}
}
let out = mk_int(starts);
let ml = mk_int(lens);
with_host(|h| h.set_attr(&out, "match.length", ml));
tag(&out);
Ok(out)
} else {
let per: Vec<Value> = x
.iter()
.map(|s| {
let (mut starts, mut lens) = (Vec::new(), Vec::new());
if let Some(s) = s {
for m in re.find_iter(s) {
starts.push(Some(char_pos(s, m.start()) as i64 + 1));
lens.push(Some(s[m.start()..m.end()].chars().count() as i64));
}
}
if starts.is_empty() {
starts.push(Some(-1));
lens.push(Some(-1));
}
let v = mk_int(starts);
let ml = mk_int(lens);
with_host(|h| h.set_attr(&v, "match.length", ml));
tag(&v);
v
})
.collect();
Ok(mk_list(per))
}
}
"regmatches" => {
let x = as_str(&a.req(0, "x")?);
let m = a.req(1, "m")?;
let extract = |s: &str, start: i64, len: i64| -> String {
s.chars()
.skip((start - 1).max(0) as usize)
.take(len.max(0) as usize)
.collect()
};
match data(&m) {
RData::List(items) => {
let out: Vec<Value> = items
.iter()
.enumerate()
.map(|(i, mi)| {
let starts = as_int(mi);
let lens = with_host(|h| h.attr(mi, "match.length"))
.map(|v| as_int(&v))
.unwrap_or_default();
let s = x.get(i).cloned().flatten().unwrap_or_default();
let hits: Vec<Option<String>> = starts
.iter()
.zip(lens.iter())
.filter_map(|(st, ln)| {
let st = (*st)?;
(st >= 1).then(|| Some(extract(&s, st, ln.unwrap_or(0))))
})
.collect();
mk_str(hits)
})
.collect();
Ok(mk_list(out))
}
_ => {
let starts = as_int(&m);
let lens = with_host(|h| h.attr(&m, "match.length"))
.map(|v| as_int(&v))
.unwrap_or_default();
let mut out = Vec::new();
for (i, s) in x.iter().enumerate() {
let st = starts.get(i).and_then(|e| *e).unwrap_or(-1);
if st < 1 {
continue;
}
let ln = lens.get(i).and_then(|e| *e).unwrap_or(0);
if let Some(s) = s {
out.push(Some(extract(s, st, ln)));
}
}
Ok(mk_str(out))
}
}
}
"lapply" | "sapply" => {
let x = a.req(0, "X")?;
let f = a.req(1, "FUN")?;
let extra: Vec<(Option<String>, Value)> = a
.rest(2)
.into_iter()
.filter(|(t, _)| !matches!(t.as_deref(), Some("simplify") | Some("USE.NAMES")))
.collect();
let items = elements(&x);
let via_lapply = name == "sapply";
if via_lapply {
push_context("lapply(X = X, FUN = FUN, ...)");
}
let mut out = Vec::with_capacity(items.len());
let mut err = None;
for it in items {
let mut call_args = vec![(None, it)];
call_args.extend(extra.clone());
match call_fun(&f, call_args, FUN_CALL) {
Ok(v) => out.push(v),
Err(e) => {
err = Some(e);
break;
}
}
}
if via_lapply {
with_host(|h| {
h.calls.pop();
});
}
if let Some(e) = err {
return Err(e);
}
let res = mk_list(out);
let nm = names_of(&x);
if !nm.is_empty() {
set_names(&res, nm.clone());
} else if kind(&x) == RKind::Str && name == "sapply" {
set_names(&res, as_str(&x));
}
Ok(if name == "sapply" {
simplify(&res)
} else {
res
})
}
"vapply" => {
let x = a.req(0, "X")?;
let f = a.req(1, "FUN")?;
let items = elements(&x);
if items.is_empty() {
let proto = a.req(2, "FUN.VALUE")?;
let out = take_positions(&proto, &[]);
if kind(&x) == RKind::Str {
let nv = mk_str(vec![]);
with_host(|h| h.set_attr(&out, "names", nv));
}
return Ok(out);
}
let mut out = Vec::with_capacity(items.len());
for it in items {
out.push(call_fun(&f, vec![(None, it)], FUN_CALL)?);
}
let res = mk_list(out);
let nm = names_of(&x);
if !nm.is_empty() {
set_names(&res, nm);
} else if kind(&x) == RKind::Str {
set_names(&res, as_str(&x));
}
Ok(simplify(&res))
}
"Map" => {
let f = a.req(0, "f")?;
let rest = a.rest(1);
let lists: Vec<Vec<Value>> = rest.iter().map(|(_, v)| elements(v)).collect();
let n = lists.iter().map(|l| l.len()).min().unwrap_or(0);
let mut out = Vec::with_capacity(n);
for i in 0..n {
let call_args: Vec<(Option<String>, Value)> =
lists.iter().map(|l| (None, l[i].clone())).collect();
out.push(call_value(&f, call_args, None)?);
}
let res = mk_list(out);
label_from_first(&res, rest.first().map(|(_, v)| v));
Ok(res)
}
"mapply" => {
let f = a.req(0, "FUN")?;
let rest = a.rest(1);
let lists: Vec<Vec<Value>> = rest.iter().map(|(_, v)| elements(v)).collect();
let n = lists.iter().map(|l| l.len()).max().unwrap_or(0);
let mut out = Vec::with_capacity(n);
for i in 0..n {
let call_args: Vec<(Option<String>, Value)> = lists
.iter()
.map(|l| (None, l[i % l.len().max(1)].clone()))
.collect();
out.push(call_value(&f, call_args, None)?);
}
let res = mk_list(out);
label_from_first(&res, rest.first().map(|(_, v)| v));
Ok(simplify(&res))
}
"Filter" => {
let f = a.req(0, "f")?;
let x = a.req(1, "x")?;
let items = elements(&x);
let nm = names_of(&x);
let mut keep = Vec::new();
for (i, it) in items.iter().enumerate() {
let r = call_fun(&f, vec![(None, it.clone())], FUN_CALL)?;
if as_lgl(&r).first() == Some(&Some(true)) {
keep.push(Some(i));
}
}
let out = take_positions(&x, &keep);
if !nm.is_empty() {
set_names(
&out,
keep.iter()
.map(|p| p.and_then(|i| nm.get(i).cloned().flatten()))
.collect(),
);
}
Ok(out)
}
"Position" | "Find" => {
let f = a.req(0, "f")?;
let x = a.req(1, "x")?;
for (i, it) in elements(&x).into_iter().enumerate() {
let r = call_fun(&f, vec![(None, it.clone())], FUN_CALL)?;
if as_lgl(&r).first() == Some(&Some(true)) {
return Ok(if name == "Position" {
scalar_int(i as i64 + 1)
} else {
it
});
}
}
Ok(if name == "Position" {
mk_int(vec![None])
} else {
null()
})
}
"Reduce" => {
let f = a.req(0, "f")?;
let x = a.req(1, "x")?;
let accumulate = a
.named("accumulate")
.and_then(|v| lgl1(&v))
.unwrap_or(false);
let from_right = a.named("right").and_then(|v| lgl1(&v)).unwrap_or(false);
let mut seq = elements(&x);
if from_right {
seq.reverse();
}
let mut it = seq.into_iter();
let mut acc = match a.get(2, "init") {
Some(v) => v,
None => match it.next() {
Some(v) => v,
None => return Ok(null()),
},
};
let mut steps = vec![acc.clone()];
for e in it {
let args = if from_right {
vec![(None, e), (None, acc)]
} else {
vec![(None, acc), (None, e)]
};
acc = call_fun(&f, args, "f(init, x[[i]])")?;
steps.push(acc.clone());
}
if accumulate {
if from_right {
steps.reverse();
}
Ok(simplify(&mk_list(steps)))
} else {
Ok(acc)
}
}
"split" => {
let x = a.req(0, "x")?;
let f = as_str_labels(&a.req(1, "f")?);
let levels = factor_levels(&a.req(1, "f")?);
let groups: Vec<Value> = levels
.iter()
.map(|lev| {
let pos: Vec<Option<usize>> = f
.iter()
.enumerate()
.filter(|(_, k)| k.as_deref() == Some(lev.as_str()))
.map(|(i, _)| Some(i))
.collect();
let group = take_positions(&x, &pos);
carry_factor(&group, &x);
group
})
.collect();
let out = mk_list(groups);
set_names(&out, levels.into_iter().map(Some).collect());
Ok(out)
}
"tapply" => {
let x = a.req(0, "X")?;
let index = as_str_labels(&a.req(1, "INDEX")?);
let f = a.req(2, "FUN")?;
let levels = factor_levels(&a.req(1, "INDEX")?);
let mut results = Vec::with_capacity(levels.len());
for lev in &levels {
let pos: Vec<Option<usize>> = index
.iter()
.enumerate()
.filter(|(_, k)| k.as_deref() == Some(lev.as_str()))
.map(|(i, _)| Some(i))
.collect();
let group = take_positions(&x, &pos);
results.push(call_value(&f, vec![(None, group)], None)?);
}
let out = simplify(&mk_list(results));
set_names(&out, levels.into_iter().map(Some).collect());
Ok(out)
}
"modifyList" => {
let x = a.req(0, "x")?;
let val = a.req(1, "val")?;
let mut names = names_of(&x);
let mut items = elements(&x);
let vnames = names_of(&val);
for (i, v) in elements(&val).into_iter().enumerate() {
let key = vnames.get(i).cloned().flatten();
match key
.as_ref()
.and_then(|k| names.iter().position(|n| n.as_deref() == Some(k.as_str())))
{
Some(p) => items[p] = v,
None => {
items.push(v);
names.push(key);
}
}
}
let out = mk_list(items);
set_names(&out, names);
Ok(out)
}
"rapply" => {
let x = a.req(0, "object")?;
let f = a.req(1, "f")?;
let how = a
.named("how")
.and_then(|v| str1(&v))
.unwrap_or_else(|| "unlist".into());
fn walk(v: &Value, f: &Value) -> Result<Value, String> {
match data(v) {
RData::List(items) => {
let mapped: Result<Vec<Value>, String> =
items.iter().map(|it| walk(it, f)).collect();
let out = mk_list(mapped?);
let nm = names_of(v);
if !nm.is_empty() {
set_names(&out, nm);
}
Ok(out)
}
_ => call_value(f, vec![(None, v.clone())], None),
}
}
let out = walk(&x, &f)?;
Ok(match how.as_str() {
"unlist" => unlist(&out),
_ => out,
})
}
"do.call" => {
let f = a.req(0, "what")?;
let f = match str1(&f) {
Some(fname) if !with_host(|h| h.is_function(&f)) => {
with_host(|h| h.lookup_function(&fname))
.or_else(|| primitive_value(&fname))
.ok_or_else(|| format!("could not find function \"{fname}\""))?
}
_ => f,
};
let argl = a.req(1, "args")?;
let nm = names_of(&argl);
let items = elements(&argl);
let call_args: Vec<(Option<String>, Value)> = items
.into_iter()
.enumerate()
.map(|(i, v)| (nm.get(i).cloned().flatten(), v))
.collect();
call_fun(&f, call_args, &inline_call_text(&f))
}
"Negate" => {
let f = a.req(0, "f")?;
Ok(with_host(|h| {
h.alloc(RData::Combinator {
kind: CombinatorKind::Negate,
inner: f,
})
}))
}
"Vectorize" => {
let f = a.req(0, "FUN")?;
Ok(with_host(|h| {
h.alloc(RData::Combinator {
kind: CombinatorKind::Vectorize,
inner: f,
})
}))
}
"matrix" => {
let x = a.get(0, "data").unwrap_or_else(|| mk_lgl(vec![None]));
let n = len(&x).max(1);
let nrow = a.get(1, "nrow").and_then(|v| num1(&v)).map(|v| v as usize);
let ncol = a.get(2, "ncol").and_then(|v| num1(&v)).map(|v| v as usize);
let (nr, nc) = match (nrow, ncol) {
(Some(r), Some(c)) => (r, c),
(Some(r), None) => (r, n.div_ceil(r)),
(None, Some(c)) => (n.div_ceil(c), c),
(None, None) => (n, 1),
};
let total = nr * nc;
if let Some(msg) = matrix_fill_warning(len(&x), nr, nc) {
signal_warning(&msg)?;
}
let byrow = a.named("byrow").and_then(|v| lgl1(&v)).unwrap_or(false);
let pos: Vec<Option<usize>> = if byrow {
let mut p = vec![Some(0usize); total];
for r in 0..nr {
for c in 0..nc {
p[c * nr + r] = Some((r * nc + c) % n);
}
}
p
} else {
(0..total).map(|i| Some(i % n)).collect()
};
let out = take_positions(&x, &pos);
let dim = mk_int(vec![Some(nr as i64), Some(nc as i64)]);
with_host(|h| h.set_attr(&out, "dim", dim));
if let Some(dn) = a.get(4, "dimnames").filter(|v| kind(v) != RKind::Null) {
let parts = elements(&dn);
let pick = |i: usize| -> Option<Vec<Option<String>>> {
parts.get(i).filter(|e| kind(e) != RKind::Null).map(as_str)
};
set_dimnames(&out, pick(0), pick(1));
}
Ok(out)
}
"t" => {
let x = a.req(0, "x")?;
let d = with_host(|h| h.attr(&x, "dim"))
.map(|d| as_int(&d))
.unwrap_or_default();
let (nr, nc) = match d.as_slice() {
[Some(r), Some(c)] => (*r as usize, *c as usize),
_ => (len(&x), 1),
};
let mut pos = Vec::with_capacity(nr * nc);
for r in 0..nr {
for c in 0..nc {
pos.push(Some(c * nr + r));
}
}
let out = take_positions(&x, &pos);
let dim = mk_int(vec![Some(nc as i64), Some(nr as i64)]);
with_host(|h| h.set_attr(&out, "dim", dim));
let (rn, cn) = match d.as_slice() {
[Some(_), Some(_)] => {
let mut dn = dimnames_of(&x);
dn.resize(2, None);
(dn[1].clone(), dn[0].clone())
}
_ => {
let nm = names_of(&x);
(None, (!nm.is_empty()).then_some(nm))
}
};
if rn.is_some() || cn.is_some() {
set_dimnames(&out, rn, cn);
}
Ok(out)
}
"array" => {
let data = a.get(0, "data").unwrap_or_else(|| mk_lgl(vec![None]));
let dims: Vec<usize> = match a.get(1, "dim") {
Some(d) => as_int(&d)
.into_iter()
.map(|e| e.unwrap_or(0) as usize)
.collect(),
None => vec![len(&data)],
};
let total: usize = dims.iter().product();
let n = len(&data).max(1);
let pos: Vec<Option<usize>> = (0..total).map(|i| Some(i % n)).collect();
let out = take_positions(&data, &pos);
let dim = mk_int(dims.iter().map(|&d| Some(d as i64)).collect());
with_host(|h| h.set_attr(&out, "dim", dim));
if let Some(dn) = a.get(2, "dimnames").filter(|v| !is_null(v)) {
with_host(|h| h.set_attr(&out, "dimnames", dn));
}
Ok(out)
}
"aperm" => {
let x = a.req(0, "a")?;
let dims = dims_of(&x);
let k = dims.len();
let perm: Vec<usize> = match a.get(1, "perm") {
Some(p) => as_int(&p)
.into_iter()
.flatten()
.map(|m| (m - 1) as usize)
.collect(),
None => (0..k).rev().collect(),
};
let mut stride = vec![1usize; k];
for d in 1..k {
stride[d] = stride[d - 1] * dims[d - 1];
}
let new_dims: Vec<usize> = perm.iter().map(|&p| dims[p]).collect();
let total: usize = dims.iter().product();
let mut pos = Vec::with_capacity(total);
let mut idx = vec![0usize; k];
for _ in 0..total {
let lin: usize = (0..k).map(|d| idx[d] * stride[perm[d]]).sum();
pos.push(Some(lin));
for d in 0..k {
idx[d] += 1;
if idx[d] < new_dims[d] {
break;
}
idx[d] = 0;
}
}
let out = take_positions(&x, &pos);
let dim = mk_int(new_dims.iter().map(|&n| Some(n as i64)).collect());
with_host(|h| h.set_attr(&out, "dim", dim));
Ok(out)
}
"rowSums" | "colSums" | "rowMeans" | "colMeans" => {
let x = a.req(0, "x")?;
let dims = dims_of(&x);
let data = as_dbl(&x);
let by_row = name.starts_with("row");
let mean = name.ends_with("Means");
let keep: Vec<usize> = if by_row {
vec![0]
} else {
(1..dims.len()).collect()
};
let reduce: Vec<usize> = (0..dims.len()).filter(|d| !keep.contains(d)).collect();
let mut stride = vec![1usize; dims.len()];
for d in 1..dims.len() {
stride[d] = stride[d - 1] * dims[d - 1];
}
let keep_shape: Vec<usize> = keep.iter().map(|&d| dims[d]).collect();
let red_shape: Vec<usize> = reduce.iter().map(|&d| dims[d]).collect();
let ktotal: usize = keep_shape.iter().product::<usize>().max(1);
let rtotal: usize = red_shape.iter().product::<usize>().max(1);
let mut out = Vec::with_capacity(ktotal);
let mut kidx = vec![0usize; keep.len()];
for _ in 0..ktotal {
let base: usize = keep
.iter()
.enumerate()
.map(|(i, &d)| kidx[i] * stride[d])
.sum();
let mut acc = 0.0;
let mut ridx = vec![0usize; reduce.len()];
for _ in 0..rtotal {
let off: usize = reduce
.iter()
.enumerate()
.map(|(i, &d)| ridx[i] * stride[d])
.sum();
acc += data.get(base + off).and_then(|e| *e).unwrap_or(f64::NAN);
for i in 0..reduce.len() {
ridx[i] += 1;
if ridx[i] < red_shape[i] {
break;
}
ridx[i] = 0;
}
}
out.push(Some(if mean { acc / rtotal as f64 } else { acc }));
for i in 0..keep.len() {
kidx[i] += 1;
if kidx[i] < keep_shape[i] {
break;
}
kidx[i] = 0;
}
}
let res = mk_dbl(out);
if keep.len() >= 2 {
let d = mk_int(keep_shape.iter().map(|&n| Some(n as i64)).collect());
with_host(|h| h.set_attr(&res, "dim", d));
} else if keep.len() == 1 {
if let Some(Some(names)) = dimnames_of(&x).get(keep[0]) {
set_names(&res, names.clone());
}
}
Ok(res)
}
"apply" => {
let x = a.req(0, "X")?;
let dims = dims_of(&x);
let margins: Vec<usize> = as_int(&a.req(1, "MARGIN")?)
.into_iter()
.flatten()
.map(|m| (m - 1) as usize)
.collect();
let f = a.req(2, "FUN")?;
let others: Vec<usize> = (0..dims.len()).filter(|d| !margins.contains(d)).collect();
let mut stride = vec![1usize; dims.len()];
for d in 1..dims.len() {
stride[d] = stride[d - 1] * dims[d - 1];
}
let dn = dimnames_of(&x);
let margin_shape: Vec<usize> = margins.iter().map(|&d| dims[d]).collect();
let other_shape: Vec<usize> = others.iter().map(|&d| dims[d]).collect();
let mtotal: usize = margin_shape.iter().product::<usize>().max(1);
let ototal: usize = other_shape.iter().product::<usize>().max(1);
let mut results = Vec::with_capacity(mtotal);
let mut midx = vec![0usize; margins.len()];
for _ in 0..mtotal {
let base: usize = margins
.iter()
.enumerate()
.map(|(k, &d)| midx[k] * stride[d])
.sum();
let mut slice_pos = Vec::with_capacity(ototal);
let mut oidx = vec![0usize; others.len()];
for _ in 0..ototal {
let off: usize = others
.iter()
.enumerate()
.map(|(k, &d)| oidx[k] * stride[d])
.sum();
slice_pos.push(Some(base + off));
for k in 0..others.len() {
oidx[k] += 1;
if oidx[k] < other_shape[k] {
break;
}
oidx[k] = 0;
}
}
let slice = take_positions(&x, &slice_pos);
if other_shape.len() >= 2 {
let d = mk_int(other_shape.iter().map(|&n| Some(n as i64)).collect());
with_host(|h| h.set_attr(&slice, "dim", d));
let labels = mk_list(
others
.iter()
.map(|&d| match dn.get(d).cloned().flatten() {
Some(names) => mk_str(names),
None => null(),
})
.collect(),
);
if elements(&labels).iter().any(|e| !is_null(e)) {
with_host(|h| h.set_attr(&slice, "dimnames", labels));
}
} else if let Some(Some(names)) =
others.first().map(|&d| dn.get(d).cloned().flatten())
{
set_names(&slice, names);
}
results.push(call_fun(&f, vec![(None, slice)], "FUN(newX[, i], ...)")?);
for k in 0..margins.len() {
midx[k] += 1;
if midx[k] < margin_shape[k] {
break;
}
midx[k] = 0;
}
}
let margin_dn: Vec<Option<Vec<Option<String>>>> = margins
.iter()
.map(|&d| dn.get(d).cloned().flatten())
.collect();
let result_names = results
.first()
.map(names_of)
.filter(|n| n.iter().any(|e| e.is_some()));
let out = simplify(&mk_list(results));
let has_dim = with_host(|h| h.attr(&out, "dim")).is_some();
if margins.len() >= 2 && !has_dim {
let d = mk_int(margin_shape.iter().map(|&n| Some(n as i64)).collect());
with_host(|h| h.set_attr(&out, "dim", d));
if margin_dn.iter().any(|m| m.is_some()) {
let labels = mk_list(
margin_dn
.iter()
.map(|m| match m {
Some(names) => mk_str(names.clone()),
None => null(),
})
.collect(),
);
with_host(|h| h.set_attr(&out, "dimnames", labels));
}
} else if !has_dim {
if let Some(Some(names)) = margin_dn.first() {
if len(&out) == names.len() {
set_names(&out, names.clone());
}
}
} else if margins.len() == 1 {
set_dimnames(&out, result_names, margin_dn[0].clone());
}
Ok(out)
}
"diag" => {
let x = a.req(0, "x")?;
let d = with_host(|h| h.attr(&x, "dim"));
match d {
Some(_) => {
let (nr, nc) = mat_dim(&x);
let k = nr.min(nc);
let pos: Vec<Option<usize>> = (0..k).map(|i| Some(i * nr + i)).collect();
Ok(take_positions(&x, &pos))
}
None if matches!(kind(&x), RKind::Int | RKind::Dbl) && len(&x) == 1 => {
let n = num1(&x).unwrap_or(0.0) as usize;
let mut vals = vec![Some(0.0); n * n];
for i in 0..n {
vals[i * n + i] = Some(1.0);
}
let out = mk_dbl(vals);
let dim = mk_int(vec![Some(n as i64), Some(n as i64)]);
with_host(|h| h.set_attr(&out, "dim", dim));
Ok(out)
}
None => {
let v = as_dbl(&x);
let n = v.len();
let mut vals = vec![Some(0.0); n * n];
for (i, e) in v.iter().enumerate() {
vals[i * n + i] = *e;
}
let out = mk_dbl(vals);
let dim = mk_int(vec![Some(n as i64), Some(n as i64)]);
with_host(|h| h.set_attr(&out, "dim", dim));
Ok(out)
}
}
}
"%*%" => {
let x = a.req(0, "x")?;
let y = a.req(1, "y")?;
Ok(mat_mul(&x, &y))
}
"crossprod" | "tcrossprod" => {
let x = a.req(0, "x")?;
let y = a.get(1, "y").unwrap_or_else(|| x.clone());
let out = if name == "crossprod" {
mat_mul(&transpose(&x), &y)
} else {
mat_mul(&x, &transpose(&y))
};
Ok(out)
}
"outer" | "%o%" => {
let xv = a.req(0, "X")?;
let yv = a.req(1, "Y")?;
let (nx, ny) = (len(&xv), len(&yv));
let xe = take_positions(&xv, &(0..nx * ny).map(|k| Some(k % nx)).collect::<Vec<_>>());
let ye = take_positions(&yv, &(0..nx * ny).map(|k| Some(k / nx)).collect::<Vec<_>>());
let fun = a.get(2, "FUN");
let res = match &fun {
Some(f) if with_host(|h| h.is_function(f)) => {
call_value(f, vec![(None, xe), (None, ye)], None)?
}
other => {
let op = other.as_ref().and_then(str1);
binop(op.as_deref().unwrap_or("*"), &xe, &ye)?
}
};
let dim = mk_int(vec![Some(nx as i64), Some(ny as i64)]);
with_host(|h| h.set_attr(&res, "dim", dim));
let (xn, yn) = (names_of(&xv), names_of(&yv));
if !xn.is_empty() || !yn.is_empty() {
let side = |nm: Vec<Option<String>>| match nm.is_empty() {
true => null(),
false => mk_str(nm),
};
let dn = mk_list(vec![side(xn), side(yn)]);
with_host(|h| h.set_attr(&res, "dimnames", dn));
}
Ok(res)
}
"cbind" | "rbind" => Ok(bind_matrix(&a, name == "cbind")),
"exists" => {
let n = str1(&a.req(0, "x")?).unwrap_or_default();
if let Some(e) = a.named("envir").and_then(|v| env_of(&v)) {
return Ok(scalar_lgl(with_host(|h| h.lookup_from(e, &n)).is_some()));
}
Ok(scalar_lgl(
with_host(|h| h.exists(&n)) || is_primitive(&n) || base_constant(&n).is_some(),
))
}
"get" => {
let n = str1(&a.req(0, "x")?).unwrap_or_default();
let env = a.named("envir").and_then(|v| env_of(&v));
let found = match env {
Some(e) => with_host(|h| h.lookup_from(e, &n)),
None => with_host(|h| h.lookup(&n)),
};
found
.or_else(|| primitive_value(&n))
.ok_or_else(|| format!("object '{n}' not found"))
}
"assign" => {
let n = str1(&a.req(0, "x")?).unwrap_or_default();
let v = a.req(1, "value")?;
let env = a.named("envir").and_then(|e| env_of(&e));
with_host(|h| {
match &env {
Some(e) => h.bind(e, &n, v.clone()),
None => h.set_var(&n, v.clone()),
}
h.visible = false;
});
Ok(v)
}
"environment" if a.get(0, "fun").is_some_and(|v| !is_null(&v)) => {
let f = a.req(0, "fun")?;
Ok(match data(&f) {
RData::Closure { env, .. } => with_host(|h| h.alloc(RData::Environment(env))),
_ => null(),
})
}
"environment" | "new.env" => {
let e = if name == "new.env" {
Rc::new(std::cell::RefCell::new(crate::host::EnvData {
vars: NameMap::default(),
parent: Some(with_host(|h| h.global.clone())),
}))
} else {
with_host(|h| h.env())
};
Ok(with_host(|h| h.alloc(RData::Environment(e))))
}
"missing" => {
let n = str1(&a.req(0, "x")?).unwrap_or_default();
Ok(scalar_lgl(!with_host(|h| {
h.env().borrow().vars.contains_key(&n)
})))
}
"return" => {
let v = a.get(0, "value").unwrap_or_else(null);
with_host(|h| h.signal = Some(Signal::Return(v.clone())));
Ok(v)
}
"UseMethod" => use_method(&a),
"NextMethod" => next_method(),
"tryCatch" => try_catch(&a),
"withCallingHandlers" => with_calling_handlers(&a),
"try" => r_try(&a),
"on.exit" => {
let thunk = a.req(0, "expr")?;
let add = a.named("add").and_then(|v| lgl1(&v)).unwrap_or(false);
let after = a.named("after").and_then(|v| lgl1(&v)).unwrap_or(true);
with_host(|h| {
if let Some(f) = h.frames.last_mut() {
if !add {
f.on_exit.clear();
}
match after {
true => f.on_exit.push(thunk),
false => f.on_exit.insert(0, thunk),
}
}
h.visible = false;
});
Ok(null())
}
"conditionMessage" => Ok(scalar_str(
element_field(&a.req(0, "c")?, "message")
.and_then(|m| str1(&m))
.unwrap_or_default(),
)),
"conditionCall" => Ok(element_field(&a.req(0, "c")?, "call").unwrap_or_else(null)),
"simpleError" | "simpleWarning" | "simpleMessage" | "simpleCondition" => {
let msg = str1(&a.req(0, "message")?).unwrap_or_default();
let classes: &[&str] = match name {
"simpleError" => &["simpleError", "error", "condition"],
"simpleWarning" => &["simpleWarning", "warning", "condition"],
"simpleMessage" => &["simpleMessage", "message", "condition"],
_ => &["simpleCondition", "condition"],
};
Ok(mk_condition(&msg, classes, None))
}
"signalCondition" => {
let c = a.req(0, "cond")?;
let msg = element_field(&c, "message")
.and_then(|m| str1(&m))
.unwrap_or_default();
let classes = class_of(&c);
if let Signalled::Unwind = signal_to_handlers(&c, &classes)? {
raise_condition(
msg,
classes,
element_field(&c, "call")
.and_then(|cl| lang_of(&cl))
.map(|e| crate::deparse::deparse_lines(&e)),
);
}
with_host(|h| h.visible = true);
Ok(null())
}
"withRestarts" => with_restarts(&a),
"invokeRestart" => invoke_restart(&a),
"computeRestarts" => Ok(compute_restarts()),
"restartDescription" => {
Ok(element_field(&a.req(0, "r")?, "description").unwrap_or_else(null))
}
"isRestart" => Ok(mk_lgl(vec![Some(
class_of(&a.req(0, "x")?).iter().any(|c| c == "restart"),
)])),
"Recall" => {
let here = with_host(|h| h.frames.last().and_then(|f| f.fun.clone()));
match here {
Some((id, env)) => {
let f = with_host(|h| h.alloc(RData::Closure { id, env }));
call_value(&f, a.all.clone(), None)
}
None => Err("Recall called from outside a closure".into()),
}
}
"factor" => {
let x = a.req(0, "x")?;
let levels: Vec<String> = match a.named("levels") {
Some(l) => as_str(&l).into_iter().flatten().collect(),
None => factor_levels(&x),
};
let codes: Vec<Option<i64>> = as_str_labels(&x)
.iter()
.map(|c| {
c.as_ref()
.and_then(|c| levels.iter().position(|l| l == c))
.map(|p| p as i64 + 1)
})
.collect();
let ordered = a
.named("ordered")
.and_then(|v| lgl1(&v))
.unwrap_or_else(|| is_ordered(&x));
Ok(mk_factor(codes, levels, ordered))
}
"levels" => {
let x = a.req(0, "x")?;
Ok(with_host(|h| h.attr(&x, "levels")).unwrap_or_else(null))
}
"nlevels" => {
let x = a.req(0, "x")?;
let n = with_host(|h| h.attr(&x, "levels"))
.map(|l| len(&l))
.unwrap_or(0);
Ok(scalar_int(n as i64))
}
"droplevels" => Ok(drop_unused_levels(&a.req(0, "x")?)),
"cut" => cut(&a),
"table" => {
let x = a.req(0, "x")?;
let is_factor = class_of(&x).iter().any(|c| c == "factor");
let levels: Vec<String> = if is_factor {
with_host(|h| h.attr(&x, "levels"))
.map(|l| as_str(&l).into_iter().flatten().collect())
.unwrap_or_default()
} else {
factor_levels(&x)
};
let obs: Vec<String> = if is_factor {
let codes = as_int(&x);
codes
.iter()
.filter_map(|c| c.and_then(|i| levels.get((i - 1) as usize).cloned()))
.collect()
} else {
as_str(&x).into_iter().flatten().collect()
};
let counts: Vec<Option<i64>> = levels
.iter()
.map(|l| Some(obs.iter().filter(|o| *o == l).count() as i64))
.collect();
let out = mk_int(counts);
let dim = mk_int(vec![Some(levels.len() as i64)]);
let labels = mk_str(levels.into_iter().map(Some).collect());
let dn = mk_list(vec![labels]);
if let Some(sym) = a.named(".dnn").and_then(|v| str1(&v)) {
set_names(&dn, vec![Some(sym)]);
}
let cls = scalar_str("table");
with_host(|h| {
h.set_attr(&out, "dim", dim);
h.set_attr(&out, "dimnames", dn);
h.set_attr(&out, "class", cls);
});
Ok(out)
}
"library" | "require" | "requireNamespace" | "loadNamespace" => {
let pkg = str1(&a.req(0, "package")?).unwrap_or_default();
let r = cran_eval(&format!("suppressMessages({name}({pkg}))"))?;
with_host(|h| h.visible = false);
if name.starts_with("require") {
Ok(r)
} else {
Ok(null())
}
}
"suppressWarnings" => suppress_conditions(&a, "warning"),
"suppressMessages" | "suppressPackageStartupMessages" => suppress_conditions(&a, "message"),
".rlang_quote" | "quote" | "bquote" => {
let src = str1(&a.req(0, "expr")?).unwrap_or_default();
let mut exprs = crate::parser::parse(&src)?;
match exprs.len() {
1 => Ok(mk_lang(exprs.remove(0))),
_ => Err(format!("invalid expression in quote: {src}")),
}
}
"eval" | "evalq" => {
let x = a.req(0, "expr")?;
let Some(e) = lang_of(&x) else { return Ok(x) };
match a.get(1, "envir").and_then(|v| env_of(&v)) {
Some(env) => in_env(env, || eval_expr(&e)),
None => eval_expr(&e),
}
}
".rlang_substitute" | "substitute" => {
let src = str1(&a.req(0, "expr")?).unwrap_or_default();
let mut exprs = crate::parser::parse(&src)?;
if exprs.len() != 1 {
return Err(format!("invalid expression in substitute: {src}"));
}
let e = exprs.remove(0);
if let Some(table) = a.get(1, "env") {
let names = names_of(&table);
let items = elements(&table);
let map: Vec<(String, Expr)> = names
.iter()
.zip(&items)
.filter_map(|(n, v)| Some((n.clone()?, value_as_expr(v)?)))
.collect();
return Ok(mk_lang(substitute_in(&e, &map, false)));
}
let Some(map) = frame_substitutions() else {
return Ok(mk_lang(e));
};
Ok(mk_lang(substitute_in(&e, &map, true)))
}
"parent.frame" => {
let up = a.get(0, "n").and_then(|v| num1(&v)).unwrap_or(1.0).max(1.0) as usize;
Ok(with_host(|h| {
let n = h.frames.len();
match n.checked_sub(up + 1).and_then(|i| h.frames.get(i)) {
Some(f) => {
let e = f.env.clone();
h.alloc(RData::Environment(e))
}
None => {
let g = h.global.clone();
h.alloc(RData::Environment(g))
}
}
}))
}
"globalenv" => Ok(with_host(|h| {
let g = h.global.clone();
h.alloc(RData::Environment(g))
})),
"environmentName" => {
let e = a.req(0, "env")?;
let global = env_of(&e).is_some_and(|e| with_host(|h| Rc::ptr_eq(&e, &h.global)));
Ok(scalar_str(match global {
true => "R_GlobalEnv",
false => "",
}))
}
"ls" | "objects" => {
let env = a
.get(0, "envir")
.and_then(|v| env_of(&v))
.unwrap_or_else(|| with_host(|h| h.env()));
let all = a.named("all.names").and_then(|v| lgl1(&v)).unwrap_or(false);
let mut names: Vec<String> = env
.borrow()
.vars
.keys()
.filter(|k| all || !k.starts_with('.'))
.cloned()
.collect();
names.sort_by(|a, b| crate::collate::str_cmp(a, b));
Ok(mk_str(names.into_iter().map(Some).collect()))
}
"sys.call" => Ok(match with_host(|h| h.enclosing_source()) {
Some(src) => parse_one(&src)?,
None => null(),
}),
"match.call" => {
let Some(src) = with_host(|h| h.enclosing_source()) else {
return Ok(null());
};
let Some(params) = with_host(|h| h.current_formals()) else {
return parse_one(&src);
};
match matched_call(&src, ¶ms)? {
Some(e) => Ok(mk_lang(e)),
None => parse_one(&src),
}
}
"sys.function" => Ok(with_host(|h| {
match h.frames.last().and_then(|f| f.fun.clone()) {
Some((id, env)) => h.alloc(RData::Closure { id, env }),
None => h.null(),
}
})),
"as.name" | "as.symbol" => {
let n = str1(&a.req(0, "x")?).unwrap_or_default();
Ok(with_host(|h| h.alloc(RData::Sym(n))))
}
"is.call" => Ok(scalar_lgl(kind(&a.req(0, "x")?) == RKind::Lang)),
"is.name" | "is.symbol" => Ok(scalar_lgl(kind(&a.req(0, "x")?) == RKind::Sym)),
".rlang_formula" => {
let src = str1(&a.req(0, "src")?).unwrap_or_default();
cran_eval(&format!("stats::as.formula({src:?})"))
}
other => cran_call(other, &a.all),
}
}
#[cfg(not(target_arch = "wasm32"))]
fn cran_call(name: &str, args: &[(Option<String>, Value)]) -> Result<Value, String> {
let r = crate::rembed::call(name, args)?;
if name.starts_with("print")
|| matches!(name, "cat" | "message" | "writeLines" | "str" | "invisible")
{
with_host(|h| h.visible = false);
}
Ok(r)
}
#[cfg(target_arch = "wasm32")]
fn cran_call(name: &str, _: &[(Option<String>, Value)]) -> Result<Value, String> {
Err(format!("could not find function \"{name}\""))
}
#[cfg(not(target_arch = "wasm32"))]
fn cran_eval(code: &str) -> Result<Value, String> {
crate::rembed::eval_source(code)
}
#[cfg(target_arch = "wasm32")]
fn cran_eval(_: &str) -> Result<Value, String> {
Err("package loading needs an R installation (unavailable on wasm)".into())
}
fn call_operator(name: &str, args: &[(Option<String>, Value)]) -> Result<Value, String> {
let vals: Vec<Value> = args.iter().map(|(_, v)| v.clone()).collect();
let first = vals
.first()
.cloned()
.ok_or_else(|| format!("argument to '{name}' is missing"))?;
match name {
"[" => return index_single(&first, &args[1..]),
"[[" => return index_double(&first, &args[1..]),
"$" => {
let key = vals.get(1).and_then(str1).unwrap_or_default();
let names = names_of(&first);
return Ok(
match names
.iter()
.position(|n| n.as_deref() == Some(key.as_str()))
{
Some(i) => element_at(&first, i),
None => null(),
},
);
}
_ => {}
}
match vals.len() {
1 => match name {
"-" => Ok(mk_dbl(
as_dbl(&first).iter().map(|e| e.map(|n| -n)).collect(),
)),
"+" => Ok(first),
"!" => Ok(mk_lgl(
as_lgl(&first).iter().map(|e| e.map(|b| !b)).collect(),
)),
other => Err(format!("invalid unary operator '{other}'")),
},
_ => binop(name, &first, &vals[1]),
}
}
struct Args {
all: Vec<(Option<String>, Value)>,
}
impl Args {
fn new(all: Vec<(Option<String>, Value)>) -> Self {
Args { all }
}
fn values(&self) -> Vec<Value> {
self.all.iter().map(|(_, v)| v.clone()).collect()
}
fn tags(&self) -> Vec<Option<String>> {
self.all.iter().map(|(t, _)| t.clone()).collect()
}
fn named(&self, name: &str) -> Option<Value> {
self.all
.iter()
.find(|(t, _)| t.as_deref() == Some(name))
.map(|(_, v)| v.clone())
}
fn get(&self, i: usize, name: &str) -> Option<Value> {
if let Some(v) = self.named(name) {
return Some(v);
}
self.all
.iter()
.filter(|(t, _)| t.is_none())
.nth(i)
.map(|(_, v)| v.clone())
}
fn req(&self, i: usize, name: &str) -> Result<Value, String> {
self.get(i, name)
.ok_or_else(|| format!("argument \"{name}\" is missing, with no default"))
}
fn n(&self, i: usize, default: f64) -> f64 {
self.get(i, "length.out")
.or_else(|| self.get(i, "n"))
.and_then(|v| num1(&v))
.unwrap_or(default)
}
fn rest(&self, i: usize) -> Vec<(Option<String>, Value)> {
let mut seen = 0usize;
self.all
.iter()
.filter(|(t, _)| {
if t.is_none() {
seen += 1;
seen > i
} else {
true
}
})
.cloned()
.collect()
}
}
fn missing_result(a: &Args, x: &Value, first_kind: bool) -> Option<Value> {
if a.named("na.rm").and_then(|v| lgl1(&v)).unwrap_or(false) {
return None;
}
let xs = as_dbl(x);
let first = xs.iter().find(|e| e.map(f64::is_nan).unwrap_or(true))?;
Some(if first_kind && first.is_some() {
scalar_dbl(f64::NAN)
} else {
mk_dbl(vec![None])
})
}
fn numeric_arg(a: &Args, i: usize, name: &str) -> Result<Vec<f64>, String> {
let v = a.req(i, name)?;
let narm = a.named("na.rm").and_then(|x| lgl1(&x)).unwrap_or(false);
let xs = as_dbl(&v);
let is_missing = |e: &Option<f64>| e.map(f64::is_nan).unwrap_or(true);
if !narm && xs.iter().any(is_missing) {
return Ok(vec![f64::NAN]);
}
Ok(xs.into_iter().flatten().filter(|x| !x.is_nan()).collect())
}
fn empty_vector(mode: &str, n: usize) -> Value {
match mode {
"numeric" | "double" => mk_dbl(vec![Some(0.0); n]),
"integer" => mk_int(vec![Some(0); n]),
"character" => mk_str(vec![Some(String::new()); n]),
"list" => mk_list((0..n).map(|_| null()).collect()),
_ => mk_lgl(vec![Some(false); n]),
}
}
fn concat(a: &Args) -> Value {
let parts: Vec<(Option<String>, Value)> =
a.all.iter().filter(|(_, v)| !is_null(v)).cloned().collect();
if parts.is_empty() {
return null();
}
let rank = parts
.iter()
.map(|(_, v)| with_host(|h| h.kind_of(v).rank()))
.max()
.unwrap_or(1);
let mut names: Vec<Option<String>> = Vec::new();
let mut any_named = false;
for (tag, v) in &parts {
let inner = names_of(v);
let n = len(v);
for i in 0..n {
let base = inner.get(i).cloned().flatten();
let nm = match (tag, &base) {
(Some(t), Some(b)) => Some(format!("{t}.{b}")),
(Some(t), None) if n == 1 => Some(t.clone()),
(Some(t), None) => Some(format!("{t}{}", i + 1)),
(None, b) => b.clone(),
};
any_named |= nm.is_some();
names.push(nm);
}
}
if parts.iter().all(|(_, v)| is_factor(v)) {
let mut levels: Vec<String> = Vec::new();
for (_, v) in &parts {
for l in levels_of(v) {
if !levels.contains(&l) {
levels.push(l);
}
}
}
let codes = parts
.iter()
.flat_map(|(_, v)| factor_labels(v))
.map(|s| {
s.and_then(|s| levels.iter().position(|l| *l == s))
.map(|p| p as i64 + 1)
})
.collect();
let ordered = parts
.iter()
.all(|(_, v)| is_ordered(v) && levels_of(v) == levels);
let out = mk_factor(codes, levels, ordered);
if any_named {
set_names(&out, names);
}
return out;
}
let out = if rank >= 5 {
mk_list(parts.iter().flat_map(|(_, v)| elements(v)).collect())
} else {
match rank {
1 => mk_lgl(parts.iter().flat_map(|(_, v)| as_lgl(v)).collect()),
2 => mk_int(parts.iter().flat_map(|(_, v)| as_int(v)).collect()),
4 => mk_str(parts.iter().flat_map(|(_, v)| as_str(v)).collect()),
_ => mk_dbl(parts.iter().flat_map(|(_, v)| as_dbl(v)).collect()),
}
};
if any_named {
set_names(&out, names);
}
out
}
fn unlist(x: &Value) -> Value {
match data(x) {
RData::List(items) => {
let names = names_of(x);
let parts: Vec<(Option<String>, Value)> = items
.iter()
.enumerate()
.map(|(i, v)| (names.get(i).cloned().flatten(), unlist(v)))
.collect();
concat(&Args::new(parts))
}
_ => x.clone(),
}
}
fn simplify(list: &Value) -> Value {
let items = match data(list) {
RData::List(v) => v,
_ => return list.clone(),
};
if items.is_empty() {
return list.clone();
}
let k = len(&items[0]);
if k != 1 && items.iter().any(|v| kind(v) == RKind::List) {
return list.clone();
}
if k >= 1 && items.iter().all(|v| len(v) == k) {
let parts: Vec<(Option<String>, Value)> = items.iter().map(|v| (None, v.clone())).collect();
let out = concat(&Args::new(parts));
if k == 1 {
let nm = names_of(list);
if !nm.is_empty() {
set_names(&out, nm);
}
} else {
let dim = mk_int(vec![Some(k as i64), Some(items.len() as i64)]);
with_host(|h| h.set_attr(&out, "dim", dim));
let rn = names_of(&items[0]);
let cn = names_of(list);
set_dimnames(
&out,
(!rn.is_empty()).then_some(rn),
(!cn.is_empty()).then_some(cn),
);
}
return out;
}
list.clone()
}
fn paste(a: &Args, zero: bool) -> Value {
let sep = if zero {
String::new()
} else {
a.named("sep")
.and_then(|v| str1(&v))
.unwrap_or_else(|| " ".into())
};
let collapse = a
.named("collapse")
.filter(|v| !is_null(v))
.and_then(|v| str1(&v));
let parts: Vec<Vec<Option<String>>> = a
.all
.iter()
.filter(|(t, _)| !matches!(t.as_deref(), Some("sep") | Some("collapse")))
.map(|(_, v)| as_str_labels(v))
.collect();
let n = parts.iter().map(|p| p.len()).max().unwrap_or(0);
if n == 0 && collapse.is_none() {
return mk_str(vec![]);
}
let joined: Vec<String> = (0..n)
.map(|i| {
parts
.iter()
.map(|p| match p.get(i % p.len().max(1)) {
Some(Some(s)) => s.clone(),
Some(None) => "NA".into(),
None => String::new(),
})
.collect::<Vec<_>>()
.join(&sep)
})
.collect();
match collapse {
Some(c) => scalar_str(joined.join(&c)),
None => mk_str(joined.into_iter().map(Some).collect()),
}
}
fn seq(a: &Args) -> Result<Value, String> {
if let Some(v) = a.named("along.with") {
return Ok(mk_int((1..=len(&v) as i64).map(Some).collect()));
}
let from = a.get(0, "from").and_then(|v| num1(&v)).unwrap_or(1.0);
let to = a.get(1, "to").and_then(|v| num1(&v));
let by = a.get(2, "by").and_then(|v| num1(&v));
let length_out = a.named("length.out").and_then(|v| num1(&v));
let (from, to) = match to {
Some(t) => (from, t),
None => match (length_out, by) {
(Some(n), _) => (from, from + by.unwrap_or(1.0) * (n - 1.0).max(0.0)),
(None, Some(_)) => (from, 1.0),
(None, None) => (1.0, from),
},
};
if let Some(b) = by {
if b == 0.0 && to != from {
return Err("invalid '(to - from)/by'".into());
}
if (to - from) * b < 0.0 {
return Err("wrong sign in 'by' argument".into());
}
}
let step = match (by, length_out) {
(Some(b), _) => b,
(None, Some(n)) if n > 1.0 => (to - from) / (n - 1.0),
(None, Some(_)) => 0.0,
(None, None) => {
if to >= from {
1.0
} else {
-1.0
}
}
};
let mut out = Vec::new();
if let Some(n) = length_out {
out = (0..n.max(0.0) as usize)
.map(|k| Some(from + step * k as f64))
.collect();
} else if step == 0.0 {
out.push(Some(from));
} else {
let count = ((to - from) / step + 1e-10) as i64;
for k in 0..=count.max(0) {
let v = from + step * k as f64;
out.push(Some(if step > 0.0 { v.min(to) } else { v.max(to) }));
}
}
let whole = out
.iter()
.flatten()
.all(|x| *x == x.trunc() && x.abs() < 1e15);
Ok(if whole && by.map(|b| b == b.trunc()).unwrap_or(true) {
mk_int(out.into_iter().map(|e| e.map(|x| x as i64)).collect())
} else {
mk_dbl(out)
})
}
fn rep(a: &Args) -> Value {
let x = match a.get(0, "x") {
Some(v) => v,
None => return null(),
};
let each = a
.named("each")
.and_then(|v| num1(&v))
.unwrap_or(1.0)
.max(0.0) as usize;
let n = len(&x);
let mut base: Vec<Option<usize>> = Vec::with_capacity(n * each);
for i in 0..n {
for _ in 0..each {
base.push(Some(i));
}
}
let times_arg = a.get(1, "times");
let mut pos: Vec<Option<usize>> = Vec::new();
match ×_arg {
Some(t) if len(t) > 1 => {
let counts = as_int(t);
for (k, p) in base.iter().enumerate() {
let c = counts.get(k).copied().flatten().unwrap_or(0).max(0) as usize;
for _ in 0..c {
pos.push(*p);
}
}
}
_ => {
let times = times_arg.and_then(|v| num1(&v)).unwrap_or(1.0).max(0.0) as usize;
for _ in 0..times {
pos.extend_from_slice(&base);
}
}
}
if let Some(want) = a.named("length.out").and_then(|v| num1(&v)) {
let want = want.max(0.0) as usize;
pos = match pos.len() {
0 => vec![None; want],
m => (0..want).map(|i| pos[i % m]).collect(),
};
}
let out = take_positions(&x, &pos);
let nm = names_of(&x);
if !nm.is_empty() {
set_names(
&out,
pos.iter()
.map(|p| p.and_then(|i| nm.get(i).cloned().flatten()))
.collect(),
);
}
carry_factor(&out, &x);
out
}
fn sort_value(x: &Value, decreasing: bool, na_last: Option<bool>) -> Value {
let idx = order_positions(x, decreasing, na_last);
let pos: Vec<Option<usize>> = idx.into_iter().map(Some).collect();
let out = take_positions(x, &pos);
let nm = names_of(x);
if !nm.is_empty() {
set_names(
&out,
pos.iter()
.map(|p| p.and_then(|i| nm.get(i).cloned().flatten()))
.collect(),
);
}
carry_factor(&out, x);
out
}
fn order_value(x: &Value, decreasing: bool, na_last: Option<bool>) -> Value {
mk_int(
order_positions(x, decreasing, na_last)
.into_iter()
.map(|i| Some(i as i64 + 1))
.collect(),
)
}
fn na_last_arg(a: &Args, default: Option<bool>) -> Option<bool> {
match a.named("na.last") {
Some(v) => lgl1(&v),
None => default,
}
}
enum SortKey {
Text(Vec<Option<String>>),
Num(Vec<Option<f64>>),
}
impl SortKey {
fn of(x: &Value) -> SortKey {
if kind(x) == RKind::Str {
SortKey::Text(as_str(x))
} else {
SortKey::Num(as_dbl(x))
}
}
fn missing(&self, i: usize) -> bool {
match self {
SortKey::Text(v) => v[i].is_none(),
SortKey::Num(v) => v[i].map(f64::is_nan).unwrap_or(true),
}
}
fn cmp(&self, p: usize, q: usize) -> std::cmp::Ordering {
match self {
SortKey::Text(v) => match (&v[p], &v[q]) {
(Some(a), Some(b)) => crate::collate::str_cmp(a, b),
(a, b) => a.cmp(b),
},
SortKey::Num(v) => v[p].partial_cmp(&v[q]).unwrap_or(std::cmp::Ordering::Equal),
}
}
}
fn order_by_keys(keys: &[Value], decreasing: bool, na_last: Option<bool>) -> Vec<usize> {
let n = keys.first().map(len).unwrap_or(0);
let ks: Vec<SortKey> = keys.iter().map(SortKey::of).collect();
let missing = |i: usize| ks.iter().any(|k| k.missing(i));
let mut good: Vec<usize> = (0..n).filter(|i| !missing(*i)).collect();
good.sort_by(|p, q| {
let ord = ks
.iter()
.map(|k| k.cmp(*p, *q))
.find(|o| o.is_ne())
.unwrap_or(std::cmp::Ordering::Equal);
if decreasing {
ord.reverse()
} else {
ord
}
});
let bad = || (0..n).filter(|i| missing(*i));
match na_last {
None => good,
Some(true) => {
good.extend(bad());
good
}
Some(false) => bad().chain(good).collect(),
}
}
fn order_positions(x: &Value, decreasing: bool, na_last: Option<bool>) -> Vec<usize> {
order_by_keys(std::slice::from_ref(x), decreasing, na_last)
}
fn identical(x: &Value, y: &Value) -> bool {
let (dx, dy) = (data(x), data(y));
if std::mem::discriminant(&dx) != std::mem::discriminant(&dy) {
return false;
}
if names_of(x) != names_of(y) {
return false;
}
match (dx, dy) {
(RData::Null, RData::Null) => true,
(RData::Lgl(a), RData::Lgl(b)) => a == b,
(RData::Int(a), RData::Int(b)) => a == b,
(RData::Dbl(a), RData::Dbl(b)) => a == b,
(RData::Str(a), RData::Str(b)) => a == b,
(RData::List(a), RData::List(b)) => {
a.len() == b.len() && a.iter().zip(b.iter()).all(|(p, q)| identical(p, q))
}
_ => x == y,
}
}
fn r_round(v: f64, digits: i32) -> f64 {
if !v.is_finite() {
return v;
}
if digits >= 0 {
format!("{:.*}", digits as usize, v).parse().unwrap_or(v)
} else {
let scale = 10f64.powi(-digits);
round_half_even(v / scale) * scale
}
}
fn r_mod(x: f64, y: f64) -> f64 {
if y == 0.0 {
return f64::NAN;
}
let r = x % y;
let r = if r != 0.0 && (r < 0.0) != (y < 0.0) {
r + y
} else {
r
};
if r == 0.0 {
0.0
} else {
r
}
}
fn r_idiv(x: f64, y: f64) -> f64 {
if y == 0.0 || !x.is_finite() {
return x / y;
}
let q = ((x - r_mod(x, y)) / y).round();
if q == 0.0 {
0.0
} else {
q
}
}
fn r_pow(x: f64, y: f64) -> f64 {
if y == 0.0 || x == 1.0 {
return 1.0;
}
if x < 0.0 && !(y.is_finite() && y == y.trunc()) {
return f64::NAN;
}
x.powf(y)
}
fn round_half_even(x: f64) -> f64 {
let r = x.round();
if (x - x.trunc()).abs() == 0.5 && r % 2.0 != 0.0 {
r - x.signum()
} else {
r
}
}
extern "C" {
fn tgamma(x: f64) -> f64;
fn lgamma_r(x: f64, sign: *mut i32) -> f64;
}
fn r_tgamma(x: f64) -> f64 {
unsafe { tgamma(x) }
}
fn r_lgamma(x: f64) -> f64 {
let mut sign = 0i32;
unsafe { lgamma_r(x, &mut sign) }
}
fn r_sign(x: f64) -> f64 {
if x.is_nan() {
f64::NAN
} else if x > 0.0 {
1.0
} else if x < 0.0 {
-1.0
} else {
0.0
}
}
fn choose(n: f64, k: f64) -> f64 {
let k = k.round();
if k < 0.0 {
return 0.0;
}
if k == 0.0 {
return 1.0;
}
let ki = k as i64;
let mut r = 1.0;
for i in 0..ki {
r *= (n - i as f64) / (ki - i) as f64;
}
if n == n.round() {
r.round()
} else {
r
}
}
fn transpose(x: &Value) -> Value {
let (nr, nc) = mat_dim(x);
let mut pos = Vec::with_capacity(nr * nc);
for r in 0..nr {
for c in 0..nc {
pos.push(Some(c * nr + r));
}
}
let out = take_positions(x, &pos);
let dim = mk_int(vec![Some(nc as i64), Some(nr as i64)]);
with_host(|h| h.set_attr(&out, "dim", dim));
out
}
const CAT_CONTROL_ARGS: &[&str] = &["sep", "fill", "file", "append", "labels"];
fn uncatable(v: &Value) -> Option<&'static str> {
match data(v) {
RData::List(_) | RData::Args(_) => Some("list"),
RData::Builtin(_) => Some("builtin"),
RData::Closure { .. } | RData::Combinator { .. } => Some("closure"),
_ => None,
}
}
const BIND_CONTROL_ARGS: &[&str] = &["deparse.level", ".deparse.sym", ".deparse.txt"];
fn recycle_to(v: &Value, n: usize) -> Value {
let l = len(v);
let pos: Vec<Option<usize>> = (0..n)
.map(|i| if l == 0 { None } else { Some(i % l) })
.collect();
take_positions(v, &pos)
}
fn bind_matrix(a: &Args, by_col: bool) -> Value {
let level = a
.named("deparse.level")
.and_then(|v| num1(&v))
.unwrap_or(1.0) as i64;
let sym = a
.named(".deparse.sym")
.map(|v| as_str(&v))
.unwrap_or_default();
let txt = a
.named(".deparse.txt")
.map(|v| as_str(&v))
.unwrap_or_default();
let inputs: Vec<(usize, Option<String>, Value)> = a
.all
.iter()
.enumerate()
.filter(|(_, (t, v))| {
!BIND_CONTROL_ARGS.contains(&t.as_deref().unwrap_or("")) && len(v) > 0
})
.map(|(i, (t, v))| (i, t.clone(), v.clone()))
.collect();
if inputs.is_empty() {
return null();
}
let is_matrix = |v: &Value| with_host(|h| h.attr(v, "dim")).is_some();
let cross = inputs
.iter()
.map(|(_, _, v)| {
if is_matrix(v) {
let (nr, nc) = mat_dim(v);
if by_col {
nr
} else {
nc
}
} else {
len(v)
}
})
.max()
.unwrap_or(0)
.max(1);
let mut strips: Vec<Value> = Vec::new();
let mut seam: Vec<Option<String>> = Vec::new();
let mut cross_names: Option<Vec<Option<String>>> = None;
for (i, tag, v) in &inputs {
if is_matrix(v) {
let (nr, nc) = mat_dim(v);
let (outer, inner) = if by_col { (nc, nr) } else { (nr, nc) };
let dn = dimnames_of(v);
let margin = |k: usize| dn.get(k).cloned().flatten();
let (seam_dn, cross_dn) = if by_col {
(margin(1), margin(0))
} else {
(margin(0), margin(1))
};
for o in 0..outer {
let pos: Vec<Option<usize>> = (0..inner)
.map(|k| {
let (r, c) = if by_col { (k, o) } else { (o, k) };
Some(c * nr + r)
})
.collect();
strips.push(recycle_to(&take_positions(v, &pos), cross));
seam.push(seam_dn.as_ref().and_then(|d| d.get(o).cloned().flatten()));
}
if cross_names.is_none() {
cross_names = cross_dn.filter(|d| d.len() == cross);
}
} else {
strips.push(recycle_to(v, cross));
seam.push(match tag {
Some(t) => Some(t.clone()),
None => match level {
0 => None,
2 => txt.get(*i).cloned().flatten(),
_ => sym.get(*i).cloned().flatten(),
},
});
if cross_names.is_none() {
let nm = names_of(v);
if nm.iter().any(|e| e.is_some()) && nm.len() == cross {
cross_names = Some(nm);
}
}
}
}
let flat = concat(&Args::new(
strips.into_iter().map(|s| (None, s)).collect::<Vec<_>>(),
));
let n = seam.len();
let (nr, nc) = if by_col { (cross, n) } else { (n, cross) };
let out = if by_col {
flat
} else {
let pos: Vec<Option<usize>> = (0..nr * nc).map(|k| Some((k % nr) * nc + k / nr)).collect();
take_positions(&flat, &pos)
};
let dim = mk_int(vec![Some(nr as i64), Some(nc as i64)]);
with_host(|h| h.set_attr(&out, "dim", dim));
let seam = seam.iter().any(|s| s.is_some()).then(|| {
seam.into_iter()
.map(|s| Some(s.unwrap_or_default()))
.collect::<Vec<_>>()
});
if by_col {
set_dimnames(&out, cross_names, seam);
} else {
set_dimnames(&out, seam, cross_names);
}
out
}
fn factor_levels(x: &Value) -> Vec<String> {
if is_factor(x) {
return levels_of(x);
}
if matches!(kind(x), RKind::Int | RKind::Dbl) {
let mut u: Vec<f64> = Vec::new();
for v in as_dbl(x).into_iter().flatten() {
if !u.contains(&v) {
u.push(v);
}
}
u.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
as_str(&mk_dbl(u.into_iter().map(Some).collect()))
.into_iter()
.flatten()
.collect()
} else {
let mut u: Vec<String> = Vec::new();
for v in as_str(x).into_iter().flatten() {
if !u.contains(&v) {
u.push(v);
}
}
u.sort_by(|a, b| crate::collate::str_cmp(a, b));
u
}
}
fn dims_of(x: &Value) -> Vec<usize> {
with_host(|h| h.attr(x, "dim"))
.map(|d| {
as_int(&d)
.into_iter()
.map(|e| e.unwrap_or(0) as usize)
.collect()
})
.unwrap_or_else(|| vec![len(x)])
}
fn which_arr_ind(x: &Value, hits: &[usize], dims: &[usize]) -> Value {
let k = dims.len();
let mut cells: Vec<Option<i64>> = Vec::with_capacity(hits.len() * k);
for d in 0..k {
let stride: usize = dims[..d].iter().product();
for &h in hits {
cells.push(Some((h / stride % dims[d]) as i64 + 1));
}
}
let out = mk_int(cells);
let dim = mk_int(vec![Some(hits.len() as i64), Some(k as i64)]);
with_host(|h| h.set_attr(&out, "dim", dim));
let colnames: Vec<Option<String>> = if k == 2 {
vec![Some("row".into()), Some("col".into())]
} else {
(1..=k).map(|i| Some(format!("dim{i}"))).collect()
};
let rownames = dimnames_of(x).first().cloned().flatten().map(|all| {
hits.iter()
.map(|&h| all.get(h % dims[0]).cloned().flatten())
.collect()
});
set_dimnames(&out, rownames, Some(colnames));
out
}
fn dimnames_of(x: &Value) -> Vec<Option<Vec<Option<String>>>> {
match with_host(|h| h.attr(x, "dimnames")) {
Some(dn) => elements(&dn)
.iter()
.map(|e| {
if kind(e) == RKind::Null {
None
} else {
Some(as_str(e))
}
})
.collect(),
None => Vec::new(),
}
}
fn set_dimnames(v: &Value, rn: Option<Vec<Option<String>>>, cn: Option<Vec<Option<String>>>) {
if rn.is_none() && cn.is_none() {
return;
}
let to_val = |o: Option<Vec<Option<String>>>| match o {
Some(names) => mk_str(names),
None => null(),
};
let dn = mk_list(vec![to_val(rn), to_val(cn)]);
with_host(|h| h.set_attr(v, "dimnames", dn));
}
fn mat_dim(x: &Value) -> (usize, usize) {
let d = with_host(|h| h.attr(x, "dim"))
.map(|d| as_int(&d))
.unwrap_or_default();
match d.as_slice() {
[Some(r), Some(c)] => (*r as usize, *c as usize),
_ => (len(x), 1),
}
}
fn mat_mul(x: &Value, y: &Value) -> Value {
let has_dim = |v: &Value| with_host(|h| h.attr(v, "dim")).is_some();
let (ar, ac) = if has_dim(x) { mat_dim(x) } else { (1, len(x)) };
let (br, bc) = if has_dim(y) { mat_dim(y) } else { (len(y), 1) };
let a = as_dbl(x);
let b = as_dbl(y);
if ac != br {
return mk_dbl(vec![None]);
}
let mut out = vec![Some(0.0); ar * bc];
for i in 0..ar {
for j in 0..bc {
let mut acc = 0.0;
for k in 0..ac {
let av = a.get(k * ar + i).and_then(|e| *e).unwrap_or(0.0);
let bv = b.get(j * br + k).and_then(|e| *e).unwrap_or(0.0);
acc += av * bv;
}
out[j * ar + i] = Some(acc);
}
}
let res = mk_dbl(out);
let dim = mk_int(vec![Some(ar as i64), Some(bc as i64)]);
with_host(|h| h.set_attr(&res, "dim", dim));
res
}
fn deparse_value(v: &Value) -> String {
let wrap = |parts: Vec<String>| {
if parts.len() == 1 {
parts.into_iter().next().unwrap()
} else {
format!("c({})", parts.join(", "))
}
};
match data(v) {
RData::Null => "NULL".into(),
RData::Lang(e) => crate::deparse::deparse_lines(&e),
RData::Sym(n) => n,
RData::Int(xs) => {
if let Some(seq) = int_colon(&xs) {
return seq;
}
wrap(
xs.iter()
.map(|e| e.map(|i| format!("{i}L")).unwrap_or_else(|| "NA".into()))
.collect(),
)
}
RData::Str(xs) => wrap(
xs.iter()
.map(|e| {
e.as_ref()
.map(|s| format!("\"{}\"", encode_string(s)))
.unwrap_or_else(|| "NA".into())
})
.collect(),
),
_ => wrap(
as_str(v)
.into_iter()
.map(|s| s.unwrap_or_else(|| "NA".into()))
.collect(),
),
}
}
fn int_colon(xs: &[Option<i64>]) -> Option<String> {
if xs.len() < 2 || xs.iter().any(|e| e.is_none()) {
return None;
}
let v: Vec<i64> = xs.iter().flatten().copied().collect();
let step = v[1] - v[0];
if (step == 1 || step == -1) && v.windows(2).all(|w| w[1] - w[0] == step) {
Some(format!("{}:{}", v[0], v[v.len() - 1]))
} else {
None
}
}
fn cut(a: &Args) -> Result<Value, String> {
let x = as_dbl(&a.req(0, "x")?);
let breaks_arg = a.req(1, "breaks")?;
let breaks: Vec<f64> = if len(&breaks_arg) == 1 {
let nb = num1(&breaks_arg).unwrap_or(1.0) as usize;
let vals: Vec<f64> = x.iter().flatten().copied().collect();
let mn = vals.iter().cloned().fold(f64::INFINITY, f64::min);
let mx = vals.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let dx = mx - mn;
if dx == 0.0 {
let pad = if mn != 0.0 { mn.abs() } else { 1.0 } / 1000.0;
let (lo, hi) = (mn - pad, mx + pad);
(0..=nb)
.map(|i| lo + (hi - lo) * i as f64 / nb as f64)
.collect()
} else {
let mut b: Vec<f64> = (0..=nb).map(|i| mn + dx * i as f64 / nb as f64).collect();
b[0] = mn - dx / 1000.0;
b[nb] = mx + dx / 1000.0;
b
}
} else {
as_dbl(&breaks_arg).into_iter().flatten().collect()
};
let dig_lab = a
.named("dig.lab")
.and_then(|v| num1(&v))
.map(|v| v as i32)
.unwrap_or(3);
let break_text = break_labels(&breaks, dig_lab);
let labels: Vec<String> = match a.named("labels") {
Some(l) if kind(&l) == RKind::Str => as_str(&l).into_iter().flatten().collect(),
_ => (0..breaks.len().saturating_sub(1))
.map(|i| format!("({},{}]", break_text[i], break_text[i + 1]))
.collect(),
};
let codes: Vec<Option<i64>> = x
.iter()
.map(|e| {
e.and_then(|v| {
(0..breaks.len().saturating_sub(1))
.find(|&i| v > breaks[i] && v <= breaks[i + 1])
.map(|i| i as i64 + 1)
})
})
.collect();
if a.named("labels").and_then(|l| lgl1(&l)) == Some(false) {
return Ok(mk_int(codes));
}
Ok(mk_factor(codes, labels, false))
}
fn break_labels(breaks: &[f64], dig_lab: i32) -> Vec<String> {
let render = |dig: i32| -> Vec<String> {
breaks
.iter()
.map(|&v| format!("{:.*}", dig.max(1) as usize, FmtG(v)))
.collect()
};
for dig in dig_lab..=12.max(dig_lab) {
let text = render(dig);
if text.windows(2).all(|w| w[0] != w[1]) {
return text;
}
}
render(12.max(dig_lab))
}
struct FmtG(f64);
impl std::fmt::Display for FmtG {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let digits = f.precision().unwrap_or(6).max(1);
let v = self.0;
if v == 0.0 || !v.is_finite() {
return write!(f, "{}", crate::host::format_dbl(v));
}
let exp = v.abs().log10().floor() as i32;
if exp < -4 || exp >= digits as i32 {
let s = format!("{:.*e}", digits - 1, v);
return write!(f, "{}", trim_g(&s));
}
let decimals = (digits as i32 - 1 - exp).max(0) as usize;
write!(f, "{}", trim_g(&format!("{v:.decimals$}")))
}
}
fn trim_g(s: &str) -> String {
let (mant, exp) = match s.split_once(['e', 'E']) {
Some((m, e)) => (m, Some(e)),
None => (s, None),
};
let mant = if mant.contains('.') {
mant.trim_end_matches('0').trim_end_matches('.')
} else {
mant
};
match exp {
Some(e) => format!("{mant}e{e}"),
None => mant.to_string(),
}
}
fn signif(v: f64, digits: i32) -> f64 {
if v == 0.0 || !v.is_finite() {
return v;
}
let power = digits as f64 - 1.0 - v.abs().log10().floor();
let factor = 10f64.powf(power);
round_half_even(v * factor) / factor
}
fn compile_re(pattern: &str, fixed: bool, ignore_case: bool) -> Result<Rc<regex::Regex>, String> {
let body = if fixed {
regex::escape(pattern)
} else {
pattern.to_string()
};
let full = if ignore_case {
format!("(?i){body}")
} else {
body
};
cached_regex(&full).map_err(|e| format!("invalid regular expression '{pattern}': {e}"))
}
const RE_CACHE_LIMIT: usize = 512;
thread_local! {
static RE_CACHE: RefCell<
std::collections::HashMap<String, Result<Rc<regex::Regex>, String>, rustc_hash::FxBuildHasher>,
> = RefCell::new(std::collections::HashMap::default());
}
fn cached_regex(full: &str) -> Result<Rc<regex::Regex>, String> {
RE_CACHE.with(|c| {
if let Some(hit) = c.borrow().get(full) {
return hit.clone();
}
let built = regex::Regex::new(full)
.map(Rc::new)
.map_err(|e| e.to_string());
let mut cache = c.borrow_mut();
if cache.len() >= RE_CACHE_LIMIT {
cache.clear();
}
cache.insert(full.to_string(), built.clone());
built
})
}
fn regex_op(name: &str, a: &Args) -> Result<Value, String> {
let pattern = str1(&a.req(0, "pattern")?).unwrap_or_default();
let fixed = a.named("fixed").and_then(|v| lgl1(&v)).unwrap_or(false);
let ignore_case = a
.named("ignore.case")
.and_then(|v| lgl1(&v))
.unwrap_or(false);
let (subject_idx, subject_name) = if name == "sub" || name == "gsub" {
(2, "x")
} else {
(1, "x")
};
let subject = a.req(subject_idx, subject_name)?;
let x = as_str(&subject);
let re = compile_re(&pattern, fixed, ignore_case)?;
match name {
"grepl" => Ok(mk_lgl(
x.iter()
.map(|s| s.as_ref().map(|s| re.is_match(s)))
.collect(),
)),
"grep" => {
let value = a.named("value").and_then(|v| lgl1(&v)).unwrap_or(false);
let hits = x
.iter()
.enumerate()
.filter(|(_, s)| s.as_ref().is_some_and(|s| re.is_match(s)));
if value {
Ok(mk_str(hits.map(|(_, s)| s.clone()).collect()))
} else {
Ok(mk_int(hits.map(|(i, _)| Some(i as i64 + 1)).collect()))
}
}
_ => {
let replacement = str1(&a.req(1, "replacement")?).unwrap_or_default();
let rep = if fixed {
replacement.replace('$', "$$")
} else {
let mut out = String::new();
let mut chars = replacement.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\' {
match chars.next() {
Some(d) if d.is_ascii_digit() => {
out.push_str("${");
out.push(d);
out.push('}');
}
Some(d) => out.push(d),
None => out.push('\\'),
}
} else if c == '$' {
out.push_str("$$");
} else {
out.push(c);
}
}
out
};
shaped_like(
mk_str(
x.iter()
.map(|s| {
s.as_ref().map(|s| {
if name == "sub" {
re.replace(s, rep.as_str()).into_owned()
} else {
re.replace_all(s, rep.as_str()).into_owned()
}
})
})
.collect(),
),
&subject,
)
}
}
}
fn sprintf(a: &Args) -> Result<Value, String> {
let fmts = as_str(&a.req(0, "fmt")?);
let rest = a.rest(1);
let n = rest
.iter()
.map(|(_, v)| len(v))
.chain(std::iter::once(fmts.len()))
.max()
.unwrap_or(1);
let mut out = Vec::with_capacity(n);
for i in 0..n {
let Some(fmt) = fmts[i % fmts.len().max(1)].clone() else {
out.push(None);
continue;
};
let mut argi = 0usize;
let mut s = String::new();
let mut chars = fmt.chars().peekable();
while let Some(c) = chars.next() {
if c != '%' {
s.push(c);
continue;
}
if chars.peek() == Some(&'%') {
chars.next();
s.push('%');
continue;
}
let mut spec = String::new();
while let Some(&d) = chars.peek() {
spec.push(d);
chars.next();
if d.is_ascii_alphabetic() {
break;
}
}
let conv = spec.pop().unwrap_or('s');
if let Some(pos) = spec.find('*') {
let Some((_, wv)) = rest.get(argi).cloned() else {
return Err("too few arguments for sprintf format".into());
};
argi += 1;
let k = i % len(&wv).max(1);
let w = as_int(&wv).get(k).and_then(|e| *e).unwrap_or(0);
let repl = if spec[..pos].contains('.') {
w.max(0).to_string()
} else if w < 0 {
format!("-{}", w.unsigned_abs())
} else {
w.to_string()
};
spec.replace_range(pos..pos + 1, &repl);
}
let (flags, width, precision) = parse_spec(&spec);
let arg = rest.get(argi).map(|(_, v)| v.clone());
argi += 1;
let Some(arg) = arg else {
return Err("too few arguments for sprintf format".into());
};
let k = i % len(&arg).max(1);
let field = match conv {
'd' | 'i' => match as_int(&arg).get(k).and_then(|e| *e) {
Some(v) => num_field(v < 0, v.unsigned_abs().to_string(), width, &flags),
None => pad("NA", width, ""),
},
'f' | 'e' | 'E' | 'g' | 'G' => match as_dbl(&arg).get(k).and_then(|e| *e) {
Some(v) => {
let p = precision.unwrap_or(6);
let mag = if v.is_nan() {
"NaN".to_string()
} else if v.is_infinite() {
"Inf".to_string()
} else {
match conv {
'f' => format!("{:.p$}", v.abs()),
'e' | 'E' => fmt_exp(v.abs(), p, conv == 'E'),
_ => fmt_g(v.abs(), p, conv == 'G'),
}
};
num_field(v < 0.0, mag, width, &flags)
}
None => pad("NA", width, ""),
},
'x' | 'X' | 'o' => {
let v = as_int(&arg).get(k).and_then(|e| *e).unwrap_or(0);
let mag = match conv {
'x' => format!("{v:x}"),
'X' => format!("{v:X}"),
_ => format!("{v:o}"),
};
num_field(false, mag, width, &flags.replace(['+', ' '], ""))
}
_ => {
let v = as_str(&arg)
.get(k)
.cloned()
.flatten()
.unwrap_or_else(|| "NA".into());
let text: String = match precision {
Some(p) => {
let end = (0..=p.min(v.len())).rev().find(|&i| v.is_char_boundary(i));
v[..end.unwrap_or(0)].to_string()
}
None => v,
};
pad(&text, width, &flags.replace('0', ""))
}
};
s.push_str(&field);
}
out.push(Some(s));
}
Ok(mk_str(out))
}
fn format_c(a: &Args) -> Result<Value, String> {
let x = a.req(0, "x")?;
let digits = a.get(1, "digits").and_then(|v| num1(&v)).map(|d| d as i64);
let mut width = a.get(2, "width").and_then(|v| num1(&v)).map(|w| w as i64);
let flag = a.named("flag").and_then(|v| str1(&v)).unwrap_or_default();
let left = flag.contains('-');
let is_int = matches!(kind(&x), RKind::Int | RKind::Lgl);
let format = a
.get(3, "format")
.and_then(|v| str1(&v))
.unwrap_or_else(|| if is_int { "d".into() } else { "g".into() });
if kind(&x) == RKind::Str || format == "s" {
let w = width.unwrap_or(0);
let left = left || w < 0;
let w = w.unsigned_abs() as usize;
return Ok(mk_str(
as_str(&x)
.iter()
.map(|s| {
s.as_deref()
.map(|s| crate::strwidth::pad_display(s, w, left))
})
.collect(),
));
}
if width.is_none() && digits.is_none() {
width = Some(1);
}
let digits = match digits {
None => {
if format == "d" {
2
} else {
4
}
}
Some(d) if d < 0 => 6,
Some(d) => d,
};
let width = match width {
None => digits + 1,
Some(0) => digits,
Some(w) => w,
};
if format == "fg" {
let out = as_dbl(&x)
.iter()
.map(|v| {
let v = (*v)?;
if !v.is_finite() {
return Some(special_str(v));
}
let e = if v == 0.0 {
0
} else {
v.abs().log10().floor() as i64
};
let dec = (digits - 1 - e).max(0) as usize;
let mut t = format!("{:.dec$}", v);
if !flag.contains('#') && t.contains('.') {
t = t.trim_end_matches('0').trim_end_matches('.').to_string();
}
Some(t)
})
.collect::<Vec<_>>();
let w = width.unsigned_abs() as usize;
let left = left || width < 0;
return shaped_like(
mk_str(
out.into_iter()
.map(|s| s.map(|s| crate::strwidth::pad_display(&s, w, left)))
.collect(),
),
&x,
);
}
let xv = if format == "d" && !is_int {
mk_int(as_dbl(&x).iter().map(|v| v.map(|v| v as i64)).collect())
} else {
x.clone()
};
let mut spec = String::from("%");
spec.push_str(&flag);
spec.push_str(&width.to_string());
if format != "d" {
spec.push('.');
spec.push_str(&digits.to_string());
}
spec.push_str(&format);
let formatted = sprintf(&Args::new(vec![
(None, scalar_str(spec)),
(None, xv.clone()),
]))?;
let raw = as_dbl(&x);
if raw.iter().any(|v| !matches!(v, Some(v) if v.is_finite())) {
let specials: Vec<String> = raw
.iter()
.filter(|v| !matches!(v, Some(v) if v.is_finite()))
.map(|v| match v {
Some(v) => special_str(*v),
None => "NA".to_string(),
})
.collect();
let w = specials
.iter()
.map(|s| s.chars().count())
.max()
.unwrap_or(0)
.max(width.unsigned_abs() as usize);
let mut cur = as_str(&formatted);
for (i, v) in raw.iter().enumerate() {
if matches!(v, Some(v) if v.is_finite()) {
continue;
}
let text = match v {
Some(v) => special_str(*v),
None => "NA".to_string(),
};
cur[i] = Some(crate::strwidth::pad_display(&text, w, left));
}
return shaped_like(mk_str(big_marked(a, mk_str(cur))), &x);
}
let marked = big_marked(a, formatted.clone());
shaped_like(mk_str(marked), &x)
}
fn big_marked(a: &Args, v: Value) -> Vec<Option<String>> {
let mark = a
.named("big.mark")
.and_then(|v| str1(&v))
.unwrap_or_default();
let cur = as_str(&v);
if mark.is_empty() {
return cur;
}
cur.into_iter()
.map(|s| {
s.map(|s| {
let lead = s.len() - s.trim_start().len();
let marked = insert_big_mark(s.trim_start(), &mark);
let grew = marked.len() - (s.len() - lead);
format!("{}{marked}", " ".repeat(lead.saturating_sub(grew)))
})
})
.collect()
}
fn special_str(v: f64) -> String {
if v.is_nan() {
"NaN".into()
} else if v > 0.0 {
"Inf".into()
} else {
"-Inf".into()
}
}
fn centre_display(s: &str, w: usize) -> String {
let pad = w.saturating_sub(crate::strwidth::display_width(s));
format!("{}{s}{}", " ".repeat(pad / 2), " ".repeat(pad - pad / 2))
}
fn insert_big_mark(s: &str, mark: &str) -> String {
if mark.is_empty() {
return s.to_string();
}
let (sign, body) = match s.strip_prefix('-') {
Some(r) => ("-", r),
None => ("", s),
};
let (int_part, frac) = match body.split_once('.') {
Some((i, f)) => (i, Some(f)),
None => (body, None),
};
if !int_part.chars().all(|c| c.is_ascii_digit()) {
return s.to_string();
}
let digits: Vec<char> = int_part.chars().collect();
let mut grouped = String::new();
for (i, c) in digits.iter().enumerate() {
if i > 0 && (digits.len() - i) % 3 == 0 {
grouped.push_str(mark);
}
grouped.push(*c);
}
match frac {
Some(f) => format!("{sign}{grouped}.{f}"),
None => format!("{sign}{grouped}"),
}
}
fn str_abbrev(k: RKind) -> &'static str {
match k {
RKind::Lgl => "logi",
RKind::Int => "int",
RKind::Dbl => "num",
RKind::Str => "chr",
_ => "???",
}
}
fn str_vec_len(k: RKind) -> usize {
match k {
RKind::Lgl => 6,
RKind::Int | RKind::Dbl => 10,
_ => 4,
}
}
fn str_chr_count(encoded: &[String], nest: usize, prefix: &str) -> usize {
let budget = 80i64 - (4 + 5 * nest as i64 + prefix.chars().count() as i64);
let mut used = 0i64;
let mut n = 0;
for e in encoded {
used += 1 + e.chars().count() as i64;
if used >= budget {
break;
}
n += 1;
}
n.max(1)
}
fn str_num(x: f64) -> String {
if x.is_nan() {
return "NaN".into();
}
if x.is_infinite() {
return if x > 0.0 { "Inf" } else { "-Inf" }.into();
}
let r = signif(x, 3);
if r != 0.0 && (r.abs() >= 1e5 || r.abs() < 1e-4) {
crate::host::render_sci(r, crate::host::sci_decimals(r))
} else {
format!("{r}")
}
}
fn str_indent(nest: usize) -> String {
format!(" {}", " ..".repeat(nest))
}
fn str_dims(x: &Value, n: usize, has_names: bool, classed: bool) -> String {
if let Some(d) = with_host(|h| h.attr(x, "dim")) {
let dims: Vec<i64> = as_int(&d).into_iter().flatten().collect();
if dims.len() == 1 {
return format!(" [1:{}(1d)]", dims[0]);
}
let inner: Vec<String> = dims.iter().map(|k| format!("1:{k}")).collect();
return format!(" [{}]", inner.join(", "));
}
if n == 1 && !has_names && !classed {
String::new()
} else {
format!(" [1:{n}]")
}
}
fn str_lines(x: &Value, nest: usize) -> Vec<String> {
let ind = str_indent(nest);
let k = kind(x);
let classes = class_of(x);
if classes.iter().any(|c| c == "factor") {
let levels: Vec<String> = with_host(|h| h.attr(x, "levels"))
.map(|l| as_str(&l).into_iter().flatten().collect())
.unwrap_or_default();
let shown: Vec<String> = levels.iter().map(|l| format!("\"{l}\"")).collect();
let codes: Vec<String> = as_int(x)
.iter()
.map(|c| c.map_or("NA".into(), |i| i.to_string()))
.collect();
return vec![format!(
"{ind}Factor w/ {} level{} {}: {}",
levels.len(),
if levels.len() == 1 { "" } else { "s" },
shown.join(","),
codes.join(" ")
)];
}
if k == RKind::Null {
return vec![format!("{ind}NULL")];
}
if k == RKind::List {
let items = elements(x);
let names = names_of(x);
let mut out = vec![format!("{}List of {}", ind.trim_end(), items.len())];
for (i, it) in items.iter().enumerate() {
let name = names.get(i).cloned().flatten().unwrap_or_default();
let sub = str_lines(it, nest + 1);
let head = sub.first().cloned().unwrap_or_default();
let child_ind = str_indent(nest + 1);
let body = head
.strip_prefix(&child_ind[..])
.unwrap_or(&head)
.to_string();
let sep = if body.starts_with("List of") { "" } else { " " };
out.push(format!("{ind}$ {name}:{sep}{body}"));
out.extend(sub.into_iter().skip(1));
}
return out;
}
if !matches!(k, RKind::Lgl | RKind::Int | RKind::Dbl | RKind::Str) {
return vec![format!(
"{ind}{}",
classes.first().cloned().unwrap_or_default()
)];
}
let n = len(x);
let named = with_host(|h| h.attr(x, "names")).is_some();
let explicit = with_host(|h| h.attr(x, "class")).map(|c| {
as_str(&c)
.into_iter()
.flatten()
.map(|s| format!("'{s}' "))
.collect::<String>()
});
let prefix = format!(
"{ind}{}{}{}",
if named { "Named " } else { "" },
explicit.clone().unwrap_or_default(),
str_abbrev(k)
);
let dims = str_dims(x, n, named, explicit.is_some());
let encoded: Vec<String> = match k {
RKind::Str => as_str(x)
.into_iter()
.map(|s| s.map_or("NA".into(), |s| format!("\"{s}\"")))
.collect(),
RKind::Lgl => as_lgl(x)
.into_iter()
.map(|b| {
b.map_or("NA".into(), |b| {
if b {
"TRUE".to_string()
} else {
"FALSE".to_string()
}
})
})
.collect(),
RKind::Int => as_int(x)
.into_iter()
.map(|i| i.map_or("NA".into(), |i| i.to_string()))
.collect(),
_ => as_dbl(x)
.into_iter()
.map(|d| d.map_or("NA".into(), str_num))
.collect(),
};
let show = match k {
RKind::Str => str_chr_count(&encoded, nest, &format!("{prefix}{dims}")),
_ => str_vec_len(k),
}
.min(n);
let tail = if n > show { " ..." } else { "" };
let mut out = vec![format!(
"{prefix}{dims} {}{tail}",
encoded[..show].join(" ")
)];
for key in ["names", "dimnames"] {
if let Some(v) = with_host(|h| h.attr(x, key)) {
let sub = str_lines(&v, nest + 1);
let head = sub.first().cloned().unwrap_or_default();
let child_ind = str_indent(nest + 1);
let body = head
.strip_prefix(&child_ind[..])
.unwrap_or(&head)
.to_string();
let sep = if body.starts_with("List of") { "" } else { " " };
out.push(format!("{ind}- attr(*, \"{key}\")={sep}{body}"));
out.extend(sub.into_iter().skip(1));
}
}
out
}
fn char_pos(s: &str, byte: usize) -> usize {
s[..byte].chars().count()
}
fn substr_of(s: &str, start: usize, stop: usize) -> String {
let skip = start.saturating_sub(1);
s.chars()
.skip(skip)
.take(stop.saturating_sub(skip))
.collect()
}
fn expand_char_ranges(s: &str) -> Vec<char> {
let chars: Vec<char> = s.chars().collect();
let mut out = Vec::new();
let mut i = 0;
while i < chars.len() {
if i + 2 < chars.len() && chars[i + 1] == '-' && chars[i] <= chars[i + 2] {
for c in chars[i]..=chars[i + 2] {
out.push(c);
}
i += 3;
} else {
out.push(chars[i]);
i += 1;
}
}
out
}
pub(crate) fn encode_string(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\t' => out.push_str("\\t"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
_ => out.push(c),
}
}
out
}
fn r_strsplit(s: &str, re: ®ex::Regex) -> Vec<Option<String>> {
let mut out = Vec::new();
let mut rest = s;
while !rest.is_empty() {
match re.find(rest) {
Some(m) if m.start() != m.end() => {
out.push(Some(rest[..m.start()].to_string()));
rest = &rest[m.end()..];
}
Some(_) => {
let mut it = rest.char_indices();
let (_, c) = it.next().unwrap();
out.push(Some(c.to_string()));
let next = it.next().map(|(i, _)| i).unwrap_or(rest.len());
rest = &rest[next..];
}
None => {
out.push(Some(rest.to_string()));
break;
}
}
}
out
}
fn parse_spec(spec: &str) -> (String, Option<usize>, Option<usize>) {
let mut flags = String::new();
let mut rest = spec;
while let Some(c) = rest.chars().next() {
if "-+ 0#".contains(c) {
flags.push(c);
rest = &rest[1..];
} else {
break;
}
}
let (w, p) = match rest.split_once('.') {
Some((w, p)) => (w, p.parse::<usize>().ok()),
None => (rest, None),
};
(flags, w.parse::<usize>().ok(), p)
}
fn pad(text: &str, width: Option<usize>, flags: &str) -> String {
let Some(w) = width else {
return text.to_string();
};
if text.len() >= w {
return text.to_string();
}
let fill = w - text.len();
if flags.contains('-') {
format!("{text}{}", " ".repeat(fill))
} else if flags.contains('0') {
format!("{}{text}", "0".repeat(fill))
} else {
format!("{}{text}", " ".repeat(fill))
}
}
fn num_field(neg: bool, mag: String, width: Option<usize>, flags: &str) -> String {
let sign = if neg {
"-"
} else if flags.contains('+') {
"+"
} else if flags.contains(' ') {
" "
} else {
""
};
let core = sign.len() + mag.chars().count();
match width {
Some(w) if w > core => {
let fill = w - core;
if flags.contains('-') {
format!("{sign}{mag}{}", " ".repeat(fill))
} else if flags.contains('0') {
format!("{sign}{}{mag}", "0".repeat(fill))
} else {
format!("{}{sign}{mag}", " ".repeat(fill))
}
}
_ => format!("{sign}{mag}"),
}
}
fn fmt_exp(v: f64, p: usize, upper: bool) -> String {
let s = format!("{:.*e}", p, v);
let e = if upper { 'E' } else { 'e' };
match s.split_once('e') {
Some((mant, exp)) => {
let (esign, digits) = match exp.strip_prefix('-') {
Some(d) => ('-', d),
None => ('+', exp),
};
format!("{mant}{e}{esign}{digits:0>2}")
}
None => s,
}
}
fn fmt_g(v: f64, p: usize, upper: bool) -> String {
let p = p.max(1);
if v == 0.0 {
return "0".to_string();
}
let exp = v.log10().floor() as i32;
if exp < -4 || exp >= p as i32 {
let s = fmt_exp(v, p - 1, upper);
let (mant, rest) = s.split_once(['e', 'E']).unwrap_or((&s, ""));
let mant = strip_g_zeros(mant);
let e = if upper { 'E' } else { 'e' };
if rest.is_empty() {
mant
} else {
format!("{mant}{e}{rest}")
}
} else {
let prec = (p as i32 - 1 - exp).max(0) as usize;
strip_g_zeros(&format!("{v:.prec$}"))
}
}
fn strip_g_zeros(s: &str) -> String {
if !s.contains('.') {
return s.to_string();
}
let t = s.trim_end_matches('0');
t.trim_end_matches('.').to_string()
}
const INTERNAL_GENERICS: &[&str] = &[
"print",
"format",
"summary",
"toString",
"as.character",
"as.numeric",
"as.double",
"as.integer",
"as.logical",
"as.vector",
"as.list",
"length",
"levels",
"dim",
"dimnames",
"names",
"c",
"rev",
"sort",
"unique",
"mean",
"median",
"seq",
"rep",
"t",
"head",
"tail",
"all.equal",
"cbind",
"rbind",
"split",
];
fn s3_primitive_method(
name: &str,
args: &[(Option<String>, Value)],
) -> Option<Result<Value, String>> {
if !INTERNAL_GENERICS.contains(&name) {
return None;
}
let obj = args.iter().find(|(t, _)| t.is_none()).map(|(_, v)| v)?;
with_host(|h| h.attr(obj, "class"))?;
let mut classes = class_of(obj);
classes.push("default".to_string());
classes
.iter()
.any(|c| with_host(|h| h.lookup_function(&format!("{name}.{c}")).is_some()))
.then(|| dispatch_from(name, &classes, args.to_vec()))
}
fn mk_condition(message: &str, classes: &[&str], call: Option<String>) -> Value {
let call = match call.as_deref().and_then(|src| parse_one(src).ok()) {
Some(v) => v,
None => null(),
};
let out = mk_list(vec![scalar_str(message), call]);
set_names(
&out,
vec![Some("message".to_string()), Some("call".to_string())],
);
let cls = mk_str(classes.iter().map(|c| Some((*c).to_string())).collect());
with_host(|h| h.set_attr(&out, "class", cls));
out
}
enum Signalled {
Fell,
Unwind,
Muffled,
}
fn signal_to_handlers(cond: &Value, classes: &[String]) -> Result<Signalled, String> {
let mut i = with_host(|h| h.handlers.len());
while i > 0 {
i -= 1;
let (calling, skip, muffle, matched) = with_host(|h| {
let f = &h.handlers[i];
let matched: Vec<usize> = f
.handlers
.iter()
.enumerate()
.filter(|(_, (c, _))| classes.iter().any(|k| k == c))
.map(|(j, _)| j)
.collect();
(f.calling, f.disabled, f.muffle.clone(), matched)
});
if skip {
continue;
}
if let Some(m) = muffle {
if classes.contains(&m) {
return Ok(Signalled::Muffled);
}
continue;
}
if matched.is_empty() {
continue;
}
if !calling {
return Ok(Signalled::Unwind);
}
let saved: Vec<bool> = with_host(|h| {
let s = h.handlers[i..].iter().map(|f| f.disabled).collect();
h.handlers[i..].iter_mut().for_each(|f| f.disabled = true);
s
});
let mut out = Ok(());
let vis = with_host(|h| h.visible);
for j in matched {
let f = with_host(|h| h.handlers[i].handlers[j].1.clone());
if let Err(e) = call_value(&f, vec![(None, cond.clone())], None) {
out = Err(e);
break;
}
}
with_host(|h| {
h.visible = vis;
for (f, was) in h.handlers[i..].iter_mut().zip(saved) {
f.disabled = was;
}
});
out?;
}
Ok(Signalled::Fell)
}
fn require_numeric(x: &Value) -> Result<(), String> {
if is_factor(x) {
return Err("\u{2018}sqrt\u{2019} not meaningful for factors".into());
}
match kind(x) {
RKind::Lgl | RKind::Int | RKind::Dbl => Ok(()),
_ => Err("non-numeric argument to mathematical function".into()),
}
}
fn produced_nan(out: &[Option<f64>], input: &[Option<f64>]) -> bool {
out.iter()
.zip(input)
.any(|(o, i)| matches!((o, i), (Some(o), Some(i)) if o.is_nan() && !i.is_nan()))
}
fn nan_warning() -> Result<(), String> {
signal_warning("NaNs produced")
}
fn signal_warning(msg: &str) -> Result<(), String> {
signal_warning_in(msg, with_host(|h| h.current_call()))
}
fn signal_warning_in(msg: &str, call: Option<String>) -> Result<(), String> {
let classes: Vec<String> = ["simpleWarning", "warning", "condition"]
.iter()
.map(|s| s.to_string())
.collect();
match signal_condition_with_muffle(msg, &classes, "muffleWarning", call.clone())? {
Signalled::Fell => r_warning(msg, call),
Signalled::Muffled => {}
Signalled::Unwind => {
raise_condition(msg.to_string(), classes, call);
return Err(msg.to_string());
}
}
Ok(())
}
fn signal_condition_with_muffle(
msg: &str,
classes: &[String],
muffle: &str,
call: Option<String>,
) -> Result<Signalled, String> {
let cond = mk_condition(
msg,
&classes.iter().map(String::as_str).collect::<Vec<_>>(),
call,
);
let id = push_restarts(vec![(muffle.to_string(), String::new(), None)])[0];
let out = signal_to_handlers(&cond, classes);
with_host(|h| {
h.restarts.pop();
});
match out {
Err(e) => match with_host(|h| h.restart_invoke.take_if(|(t, _)| *t == id)) {
Some(_) => Ok(Signalled::Muffled),
None => Err(e),
},
Ok(v) => Ok(v),
}
}
const ABORT_RESTART: u64 = 0;
fn push_restarts(specs: Vec<(String, String, Option<Value>)>) -> Vec<u64> {
with_host(|h| {
let group: Vec<crate::host::RestartFrame> = specs
.into_iter()
.map(|(name, description, handler)| {
h.next_restart_id += 1;
crate::host::RestartFrame {
id: h.next_restart_id,
name,
description,
handler,
}
})
.collect();
let ids = group.iter().map(|r| r.id).collect();
h.restarts.push(group);
ids
})
}
fn visible_restarts() -> Vec<(u64, String, String)> {
with_host(|h| {
h.restarts
.iter()
.rev()
.flatten()
.map(|r| (r.id, r.name.clone(), r.description.clone()))
.collect()
})
}
fn mk_restart(id: u64, name: &str, description: &str) -> Value {
let out = mk_list(vec![
scalar_str(name),
scalar_dbl(id as f64),
null(),
scalar_str(description),
null(),
null(),
]);
set_names(
&out,
[
"name",
"exit",
"handler",
"description",
"test",
"interactive",
]
.iter()
.map(|s| Some((*s).to_string()))
.collect(),
);
let cls = scalar_str("restart");
with_host(|h| h.set_attr(&out, "class", cls));
out
}
fn mk_abort_restart() -> Value {
let out = mk_list(vec![scalar_str("abort"), null()]);
let cls = scalar_str("restart");
with_host(|h| h.set_attr(&out, "class", cls));
out
}
fn compute_restarts() -> Value {
let mut items: Vec<Value> = visible_restarts()
.into_iter()
.map(|(id, name, desc)| mk_restart(id, &name, &desc))
.collect();
items.push(mk_abort_restart());
mk_list(items)
}
fn invoke_restart(a: &Args) -> Result<Value, String> {
let r = a.req(0, "r")?;
let args = a.rest(1);
let named = str1(&r).unwrap_or_default();
let id = if class_of(&r).iter().any(|c| c == "restart") {
element_field(&r, "exit")
.and_then(|v| num1(&v))
.map(|v| v as u64)
.or(Some(ABORT_RESTART))
.filter(|id| *id == ABORT_RESTART || visible_restarts().iter().any(|(i, ..)| i == id))
} else if named == "abort" {
Some(ABORT_RESTART)
} else {
visible_restarts()
.into_iter()
.find(|(_, n, _)| *n == named)
.map(|(id, ..)| id)
};
let name = if named.is_empty() {
element_field(&r, "name")
.and_then(|v| str1(&v))
.unwrap_or_default()
} else {
named
};
let Some(id) = id else {
return Err(format!("no 'restart' '{name}' found"));
};
with_host(|h| h.restart_invoke = Some((id, args)));
Err(crate::host::RESTART_UNWIND.to_string())
}
fn with_restarts(a: &Args) -> Result<Value, String> {
let body = a.req(0, "expr")?;
let specs: Vec<(String, String, Option<Value>)> = a
.all
.iter()
.filter_map(|(t, v)| match t.as_deref() {
Some("expr") | None => None,
Some(name) => {
let (handler, description) = match (element_field(v, "handler"), str1(v)) {
(Some(h), _) => (
Some(h),
element_field(v, "description")
.and_then(|d| str1(&d))
.unwrap_or_default(),
),
(None, Some(desc)) if !with_host(|h| h.is_function(v)) => (None, desc),
_ => (Some(v.clone()), String::new()),
};
Some((name.to_string(), description, handler))
}
})
.collect();
let ids = push_restarts(specs);
let out = call_value(&body, Vec::new(), None);
let group = with_host(|h| h.restarts.pop()).unwrap_or_default();
let Err(e) = out else { return out };
let Some((id, args)) = with_host(|h| h.restart_invoke.take_if(|(t, _)| ids.contains(t))) else {
return Err(e);
};
match group
.into_iter()
.find(|r| r.id == id)
.and_then(|r| r.handler)
{
Some(f) => call_value(&f, args, None),
None => Ok(null()),
}
}
fn restart_in_flight() -> bool {
with_host(|h| h.restart_invoke.is_some())
}
fn raise_condition(msg: String, classes: Vec<String>, call: Option<String>) {
with_host(|h| {
if h.error.is_none() {
h.set_error_call(call);
h.error = Some(msg);
h.error_classes = classes;
}
});
}
fn try_catch(a: &Args) -> Result<Value, String> {
let body = a.req(0, "expr")?;
let finally = a.named("finally");
let handlers: Vec<(String, Value)> = a
.all
.iter()
.filter_map(|(t, v)| match t.as_deref() {
Some("finally") | Some("expr") | None => None,
Some(t) => Some((t.to_string(), v.clone())),
})
.collect();
with_host(|h| {
h.handlers.push(crate::host::HandlerFrame {
calling: false,
handlers: handlers.clone(),
disabled: false,
muffle: None,
})
});
let out = call_value(&body, Vec::new(), None);
let (raised, raised_call) = with_host(|h| {
h.handlers.pop();
let call = h.error_call.clone();
h.clear_error_call();
(std::mem::take(&mut h.error_classes), call)
});
let result = match out {
Ok(v) => Ok(v),
Err(msg) if restart_in_flight() => Err(msg),
Err(msg) => {
let classes: Vec<String> = if raised.is_empty() {
["simpleError", "error", "condition"]
.iter()
.map(|s| s.to_string())
.collect()
} else {
raised
};
match handlers
.iter()
.find(|(c, _)| classes.iter().any(|k| k == c))
{
Some((_, f)) => {
let cond = mk_condition(
&msg,
&classes.iter().map(String::as_str).collect::<Vec<_>>(),
raised_call.clone(),
);
call_value(f, vec![(None, cond)], None)
}
None => Err(msg),
}
}
};
if let Some(f) = finally {
let vis = with_host(|h| h.visible);
call_value(&f, Vec::new(), None)?;
with_host(|h| h.visible = vis);
}
result
}
fn with_calling_handlers(a: &Args) -> Result<Value, String> {
let body = a.req(0, "expr")?;
let handlers: Vec<(String, Value)> = a
.all
.iter()
.filter_map(|(t, v)| match t.as_deref() {
Some("expr") | None => None,
Some(t) => Some((t.to_string(), v.clone())),
})
.collect();
with_host(|h| {
h.handlers.push(crate::host::HandlerFrame {
calling: true,
handlers,
disabled: false,
muffle: None,
})
});
let out = call_value(&body, Vec::new(), None);
with_host(|h| {
h.handlers.pop();
});
out
}
fn suppress_conditions(a: &Args, class: &str) -> Result<Value, String> {
let body = a.req(0, "expr")?;
with_host(|h| {
h.handlers.push(crate::host::HandlerFrame {
calling: true,
handlers: Vec::new(),
disabled: false,
muffle: Some(class.to_string()),
})
});
let out = call_value(&body, Vec::new(), None);
with_host(|h| {
h.handlers.pop();
});
out
}
fn r_try(a: &Args) -> Result<Value, String> {
let body = a.req(0, "expr")?;
let silent = a.named("silent").and_then(|v| lgl1(&v)).unwrap_or(false);
match call_value(&body, Vec::new(), None) {
Ok(v) => Ok(v),
Err(msg) if restart_in_flight() => Err(msg),
Err(msg) => {
let (classes, raised_call) = with_host(|h| {
let call = h.error_call.clone();
h.clear_error_call();
(std::mem::take(&mut h.error_classes), call)
});
let text = match raised_call.as_deref().and_then(|c| c.lines().next()) {
Some(c) => format!("Error in {c} : {msg}\n"),
None => format!("Error : {msg}\n"),
};
if !silent {
eprint!("{text}");
}
let out = scalar_str(text);
let classes: Vec<&str> = if classes.is_empty() {
vec!["simpleError", "error", "condition"]
} else {
classes.iter().map(String::as_str).collect()
};
let cls = scalar_str("try-error");
let cond = mk_condition(&msg, &classes, raised_call);
with_host(|h| {
h.set_attr(&out, "class", cls);
h.set_attr(&out, "condition", cond);
h.visible = false;
});
Ok(out)
}
}
}
fn next_method() -> Result<Value, String> {
let (dispatch, args) = with_host(|h| {
let f = h.innermost_call();
(
f.and_then(|f| f.dispatch.clone()),
f.map(|f| f.args.clone()).unwrap_or_default(),
)
});
let args = crate::host::force_all(args)?;
let (generic, rest) =
dispatch.ok_or_else(|| "NextMethod called from outside a method".to_string())?;
dispatch_from(&generic, &rest, args)
}
fn dispatch_from(
generic: &str,
classes: &[String],
args: Vec<(Option<String>, Value)>,
) -> Result<Value, String> {
for (i, cls) in classes.iter().enumerate() {
let method = format!("{generic}.{cls}");
if let Some(f) = with_host(|h| h.lookup_function(&method)) {
with_host(|h| {
h.pending_dispatch = Some((generic.to_string(), classes[i + 1..].to_vec()))
});
let out = call_value(&f, args, Some(method));
with_host(|h| h.pending_dispatch = None);
return out;
}
}
with_host(|h| h.suppress_s3 = true);
call_primitive(generic, args)
}
fn use_method(a: &Args) -> Result<Value, String> {
let generic = str1(&a.req(0, "generic")?).unwrap_or_default();
let frame_args = crate::host::force_all(with_host(|h| {
h.innermost_call()
.map(|f| f.args.clone())
.unwrap_or_default()
}))?;
let obj = match a.get(1, "object") {
Some(v) => v,
None => frame_args
.first()
.map(|(_, v)| v.clone())
.ok_or_else(|| format!("UseMethod(\"{generic}\") applied to an object-less call"))?,
};
let mut classes = class_of(&obj);
classes.push("default".to_string());
if !classes
.iter()
.any(|c| with_host(|h| h.lookup_function(&format!("{generic}.{c}")).is_some()))
{
return Err(format!(
"no applicable method for '{generic}' applied to an object of class \"{}\"",
class_of(&obj).first().cloned().unwrap_or_default()
));
}
let out = dispatch_from(&generic, &classes, frame_args)?;
with_host(|h| h.signal = Some(Signal::Return(out.clone())));
Ok(out)
}
pub fn print_value(v: &Value) {
for line in format_value(v) {
crate::host::emit(&format!("{line}\n"));
}
}
pub fn format_value(v: &Value) -> Vec<String> {
let mut out = format_value_body(v);
out.extend(format_extra_attrs(v));
out
}
fn has_print_layout(v: &Value) -> bool {
class_of(v).iter().any(|c| {
matches!(
c.as_str(),
"factor" | "ordered" | "table" | "rle" | "condition" | "restart"
)
})
}
fn format_extra_attrs(v: &Value) -> Vec<String> {
const STRUCTURAL: [&str; 6] = ["names", "dim", "dimnames", "levels", "row.names", "tsp"];
let laid_out = has_print_layout(v);
let mut out = Vec::new();
for (k, val) in with_host(|h| h.attrs_of(v)) {
if STRUCTURAL.contains(&k.as_str()) || (k == "class" && laid_out) {
continue;
}
out.push(format!("attr(,\"{k}\")"));
out.extend(format_value(&val));
}
out
}
fn format_value_body(v: &Value) -> Vec<String> {
let classes = class_of(v);
if classes.iter().any(|c| c == "factor") {
return format_factor(v);
}
if classes.iter().any(|c| c == "table") {
let header = with_host(|h| h.attr(v, "dimnames"))
.map(|dn| names_of(&dn))
.and_then(|n| n.first().cloned().flatten())
.unwrap_or_default();
let mut out = vec![header];
out.extend(format_vector(v));
return out;
}
if classes.iter().any(|c| c == "rle") {
return format_rle(v);
}
if classes.iter().any(|c| c == "restart") {
let name = element_field(v, "name")
.and_then(|n| str1(&n))
.or_else(|| str1(&element_at(v, 0)))
.unwrap_or_default();
return vec![format!("<restart: {name} >")];
}
if classes.iter().any(|c| c == "condition") {
let msg = element_field(v, "message")
.and_then(|m| str1(&m))
.unwrap_or_default();
let call = element_field(v, "call").filter(|c| !is_null(c));
let head = classes.first().cloned().unwrap_or_default();
return match call {
Some(c) => vec![format!("<{head} in {}: {msg}>", deparse_value(&c))],
None => vec![format!("<{head}: {msg}>")],
};
}
match data(v) {
RData::Null => vec!["NULL".into()],
RData::Closure { .. } | RData::Builtin(_) | RData::Combinator { .. } => format_function(v),
#[cfg(not(target_arch = "wasm32"))]
RData::RForeign(ptr) => crate::rembed::print_foreign(ptr),
#[cfg(target_arch = "wasm32")]
RData::RForeign(_) => vec!["<R object>".into()],
RData::Environment(_) => vec!["<environment>".into()],
RData::Lang(e) => crate::deparse::deparse_all_lines(&e),
RData::Sym(n) => vec![match crate::deparse::is_syntactic_name(&n) {
true => n,
false => format!("`{n}`"),
}],
RData::Args(_) => format_list(v),
RData::List(_) => format_list(v),
_ => {
if let Some(dim) = with_host(|h| h.attr(v, "dim")) {
let d: Vec<usize> = as_int(&dim)
.iter()
.map(|e| e.unwrap_or(0) as usize)
.collect();
if d.len() == 2 {
return format_matrix(v, d[0], d[1]);
}
if d.len() >= 3 {
return format_array(v, &d);
}
}
format_vector(v)
}
}
}
fn format_array(v: &Value, dims: &[usize]) -> Vec<String> {
let (nr, nc) = (dims[0], dims[1]);
let plane = nr * nc;
let outer: Vec<usize> = dims[2..].to_vec();
let n_planes: usize = outer.iter().product::<usize>().max(1);
let dn = dimnames_of(v);
let margin = |d: usize| dn.get(d).cloned().flatten();
let mut out = Vec::new();
let mut oidx = vec![0usize; outer.len()];
for p in 0..n_planes {
let labels: Vec<String> = oidx
.iter()
.enumerate()
.map(|(k, i)| {
margin(k + 2)
.and_then(|l| l.get(*i).cloned().flatten())
.unwrap_or_else(|| (i + 1).to_string())
})
.collect();
out.push(format!(", , {}", labels.join(", ")));
out.push(String::new());
let base = p * plane;
let pos: Vec<Option<usize>> = (0..plane).map(|i| Some(base + i)).collect();
let slice = take_positions(v, &pos);
set_dimnames(&slice, margin(0), margin(1));
out.extend(format_matrix(&slice, nr, nc));
out.push(String::new());
for k in 0..outer.len() {
oidx[k] += 1;
if oidx[k] < outer[k] {
break;
}
oidx[k] = 0;
}
}
out
}
fn function_src(v: &Value) -> Option<Vec<String>> {
match data(v) {
RData::Builtin(name) => Some(vec![format!(".Primitive(\"{name}\")")]),
RData::Closure { .. } | RData::Combinator { .. } => Some(format_function(v)),
_ => None,
}
}
fn format_function(v: &Value) -> Vec<String> {
match data(v) {
RData::Builtin(name) => vec![format!("function (...) .Primitive(\"{name}\")")],
RData::Closure { id, .. } => with_host(|h| h.closures.get(id).map(|c| c.src.clone()))
.filter(|s| !s.is_empty())
.unwrap_or_else(|| vec!["function (...) ...".into()]),
_ => vec!["function".into()],
}
}
fn print_element(v: &Value, i: usize) -> String {
match data(v) {
RData::Str(xs) => match &xs[i] {
Some(s) => format!("\"{}\"", escape_string(s)),
None => "NA".into(),
},
RData::Lgl(xs) => match xs[i] {
Some(true) => "TRUE".into(),
Some(false) => "FALSE".into(),
None => "NA".into(),
},
RData::Int(xs) => match xs[i] {
Some(n) => n.to_string(),
None => "NA".into(),
},
RData::Dbl(xs) => match xs[i] {
Some(x) => x.to_string(),
None => "NA".into(),
},
_ => String::new(),
}
}
fn escape_string(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
_ => out.push(c),
}
}
out
}
fn format_elements(v: &Value) -> Vec<String> {
let n = len(v);
if let RData::Dbl(xs) = data(v) {
return format_dbl_run(&xs);
}
(0..n).map(|i| print_element(v, i)).collect()
}
fn format_dbl_run(xs: &[Option<f64>]) -> Vec<String> {
let finite: Vec<f64> = xs
.iter()
.flatten()
.copied()
.filter(|x| x.is_finite())
.collect();
let fixed_d = finite.iter().map(|x| fixed_decimals(*x)).max().unwrap_or(0);
let sci_d = finite.iter().map(|x| sci_decimals(*x)).max().unwrap_or(0);
let width = |f: &dyn Fn(f64) -> String| {
finite
.iter()
.map(|x| f(*x).chars().count())
.max()
.unwrap_or(0)
};
let use_sci = !crate::host::prefers_fixed(
width(&|x| render_fixed(x, fixed_d)),
width(&|x| render_sci(x, sci_d)),
);
let cells: Vec<String> = xs
.iter()
.map(|e| match e {
Some(x) if x.is_finite() && use_sci => render_sci(*x, sci_d),
Some(x) if x.is_finite() => render_fixed(*x, fixed_d),
Some(x) => render_fixed(*x, 0),
None => "NA".into(),
})
.collect();
if !use_sci {
return cells;
}
let exp_digits = cells
.iter()
.filter_map(|c| {
c.split_once(['e'])
.map(|(_, e)| e.trim_start_matches(['+', '-']).len())
})
.max()
.unwrap_or(2);
let neg = usize::from(cells.iter().any(|c| c.starts_with('-')));
let w = neg + 1 + if sci_d > 0 { sci_d + 1 } else { 0 } + 2 + exp_digits;
cells
.into_iter()
.map(|c| crate::strwidth::pad_display(&c, w, false))
.collect()
}
fn format_rle(v: &Value) -> Vec<String> {
let lengths = element_field(v, "lengths").unwrap_or_else(null);
let values = element_field(v, "values").unwrap_or_else(null);
let line = |field: &Value| -> String {
let n = len(field);
let abbr = match data(field) {
RData::Int(_) => "int",
RData::Dbl(_) => "num",
RData::Str(_) => "chr",
RData::Lgl(_) => "logi",
_ => "num",
};
let cells: Vec<String> = as_str(field)
.into_iter()
.map(|s| {
let s = s.unwrap_or_else(|| "NA".into());
if kind(field) == RKind::Str {
format!("\"{s}\"")
} else {
s
}
})
.collect();
if n > 1 {
format!("{abbr} [1:{n}] {}", cells.join(" "))
} else {
format!("{abbr} {}", cells.join(" "))
}
};
vec![
"Run Length Encoding".to_string(),
format!(" lengths: {}", line(&lengths)),
format!(" values : {}", line(&values)),
]
}
fn format_factor(v: &Value) -> Vec<String> {
let levels: Vec<String> = with_host(|h| h.attr(v, "levels"))
.map(|l| as_str(&l).into_iter().flatten().collect())
.unwrap_or_default();
let labels: Vec<String> = as_int(v)
.iter()
.map(|c| {
c.and_then(|i| levels.get((i - 1) as usize).cloned())
.unwrap_or_else(|| "<NA>".into())
})
.collect();
let ordered = class_of(v).iter().any(|c| c == "ordered");
let names = names_of(v);
let mut out = if labels.is_empty() {
vec![format!("{}()", if ordered { "ordered" } else { "factor" })]
} else if names.is_empty() {
layout_indexed(&labels, true)
} else {
layout_named(&names, &labels)
};
let sep = if ordered { " < " } else { " " };
out.push(format!("Levels: {}", levels.join(sep)));
out
}
fn layout_indexed(cells: &[String], left_align: bool) -> Vec<String> {
let n = cells.len();
const WIDTH: usize = 80;
let cell_w = cells.iter().map(|c| c.chars().count()).max().unwrap_or(1);
let idx_w = format!("[{n}]").len();
let per_line = ((WIDTH - idx_w) / (cell_w + 1)).max(1);
let mut out = Vec::new();
let mut i = 0;
while i < n {
let take = per_line.min(n - i);
let cells_row: Vec<String> = (i..i + take)
.map(|k| {
if left_align {
format!("{:<cell_w$}", cells[k])
} else {
format!("{:>cell_w$}", cells[k])
}
})
.collect();
out.push(format!(
"{:>idx_w$} {}",
format!("[{}]", i + 1),
cells_row.join(" ")
));
i += take;
}
out
}
fn layout_named(names: &[Option<String>], cells: &[String]) -> Vec<String> {
const WIDTH: usize = 80;
let n = cells.len();
let labels: Vec<String> = (0..n)
.map(|i| {
names
.get(i)
.cloned()
.flatten()
.unwrap_or_else(|| "<NA>".into())
})
.collect();
let w = labels
.iter()
.chain(cells.iter())
.map(|s| crate::strwidth::display_width(s))
.max()
.unwrap_or(1);
let per_line = (WIDTH / (w + 1)).max(1);
let mut out = Vec::new();
let mut i = 0;
while i < n {
let take = per_line.min(n - i);
let row = |src: &[String]| {
(i..i + take)
.map(|k| crate::strwidth::pad_display(&src[k], w, false))
.collect::<Vec<_>>()
.join(" ")
+ " "
};
out.push(row(&labels));
out.push(row(cells));
i += take;
}
out
}
fn format_vector(v: &Value) -> Vec<String> {
let n = len(v);
if n == 0 {
let kind = match data(v) {
RData::Str(_) => "character",
RData::Int(_) => "integer",
RData::Lgl(_) => "logical",
RData::List(_) => "list",
_ => "numeric",
};
let named = with_host(|h| h.attr(v, "names")).is_some_and(|n| !is_null(&n));
return vec![match named {
true => format!("named {kind}(0)"),
false => format!("{kind}(0)"),
}];
}
let cells = format_elements(v);
let names = names_of(v);
const WIDTH: usize = 80;
let left_align = kind(v) == RKind::Str && names.is_empty();
let justify = |cell: &str, w: usize| crate::strwidth::pad_display(cell, w, left_align);
if !names.is_empty() {
return layout_named(&names, &cells);
}
let cell_w = cells
.iter()
.map(|c| crate::strwidth::display_width(c))
.max()
.unwrap_or(1);
let idx_w = format!("[{n}]").len();
let per_line = ((WIDTH - idx_w) / (cell_w + 1)).max(1);
let mut out = Vec::new();
let mut i = 0;
while i < n {
let take = per_line.min(n - i);
let body = (i..i + take)
.map(|k| justify(&cells[k], cell_w))
.collect::<Vec<_>>()
.join(" ");
out.push(format!("{:>w$} {body}", format!("[{}]", i + 1), w = idx_w));
i += take;
}
out
}
fn format_matrix(v: &Value, nr: usize, nc: usize) -> Vec<String> {
if nr == 0 && nc == 0 {
return vec!["<0 x 0 matrix>".into()];
}
let cells = match data(v) {
RData::Dbl(xs) if nr > 0 => (0..nc)
.flat_map(|c| {
let lo = (c * nr).min(xs.len());
let hi = (lo + nr).min(xs.len());
format_dbl_run(&xs[lo..hi])
})
.collect(),
_ => format_elements(v),
};
let dn = dimnames_of(v);
let dn_at = |dim: usize, k: usize| -> Option<String> {
dn.get(dim)
.and_then(|o| o.as_ref())
.and_then(|names| names.get(k).cloned().flatten())
};
let row_labels: Vec<String> = (0..nr)
.map(|r| dn_at(0, r).unwrap_or_else(|| format!("[{},]", r + 1)))
.collect();
let row_names = dn.first().and_then(|o| o.as_ref()).is_some();
let col_labels: Vec<String> = (0..nc)
.map(|c| dn_at(1, c).unwrap_or_else(|| format!("[,{}]", c + 1)))
.collect();
let dw = |s: &str| crate::strwidth::display_width(s);
let label_w = match nr {
0 => "[1,]".len(),
_ => row_labels.iter().map(|s| dw(s)).max().unwrap_or(0),
};
let widths: Vec<usize> = (0..nc)
.map(|c| {
(0..nr)
.map(|r| cells.get(c * nr + r).map(|s| dw(s)).unwrap_or(2))
.chain(std::iter::once(dw(&col_labels[c])))
.max()
.unwrap_or(1)
})
.collect();
let left = kind(v) == RKind::Str;
let just = |s: &str, w: usize| crate::strwidth::pad_display(s, w, left);
let mut out = Vec::with_capacity(nr + 1);
let sep = if nc == 0 { "" } else { " " };
for (first, last) in column_blocks(&widths, label_w) {
let header = (first..last)
.map(|c| just(&col_labels[c], widths[c]))
.collect::<Vec<_>>()
.join(" ");
out.push(format!("{:w$}{sep}{header}", "", w = label_w));
for (r, label) in row_labels.iter().enumerate() {
let row = (first..last)
.map(|c| {
just(
&cells.get(c * nr + r).cloned().unwrap_or_default(),
widths[c],
)
})
.collect::<Vec<_>>()
.join(" ");
out.push(format!(
"{}{sep}{row}",
crate::strwidth::pad_display(label, label_w, row_names)
));
}
}
out
}
fn column_blocks(widths: &[usize], label_w: usize) -> Vec<(usize, usize)> {
if widths.is_empty() {
return vec![(0, 0)];
}
const WIDTH: usize = 80;
let mut blocks = Vec::new();
let mut first = 0;
while first < widths.len() {
let mut last = first;
let mut width = label_w;
loop {
width += widths[last] + 1;
last += 1;
if last >= widths.len() || width + widths[last] + 1 >= WIDTH {
break;
}
}
blocks.push((first, last));
first = last;
}
blocks
}
fn matrix_fill_warning(lendat: usize, nr: usize, nc: usize) -> Option<String> {
if lendat <= 1 {
return None;
}
let total = nr * nc;
if total == 0 {
return Some("non-empty data for zero-extent matrix".into());
}
if total % lendat == 0 {
return None;
}
let tiles = |extent: usize| lendat % extent == 0 || extent % lendat == 0;
if !tiles(nr) {
return Some(format!(
"data length [{lendat}] is not a sub-multiple or multiple of the number of rows [{nr}]"
));
}
if !tiles(nc) {
return Some(format!(
"data length [{lendat}] is not a sub-multiple or multiple of the number of columns [{nc}]"
));
}
(total != lendat)
.then(|| format!("data length differs from size of matrix: [{lendat} != {nr} x {nc}]"))
}
fn is_syntactic_name(n: &str) -> bool {
let mut chars = n.chars();
let first = match chars.next() {
Some(c) => c,
None => return false,
};
if !(first.is_ascii_alphabetic() || first == '.') {
return false;
}
if first == '.' {
if let Some(c2) = n.chars().nth(1) {
if c2.is_ascii_digit() {
return false;
}
}
}
if !n
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_')
{
return false;
}
!matches!(
n,
"if" | "else"
| "repeat"
| "while"
| "function"
| "for"
| "in"
| "next"
| "break"
| "TRUE"
| "FALSE"
| "NULL"
| "Inf"
| "NaN"
| "NA"
| "NA_integer_"
| "NA_real_"
| "NA_character_"
| "NA_complex_"
)
}
fn format_list(v: &Value) -> Vec<String> {
format_list_at(v, "")
}
fn is_plain_list(v: &Value) -> bool {
!has_print_layout(v) && matches!(kind(v), RKind::List | RKind::Args)
}
fn format_list_at(v: &Value, prefix: &str) -> Vec<String> {
let items = elements(v);
if items.is_empty() {
return vec!["list()".into()];
}
let names = names_of(v);
let mut out = Vec::new();
for (i, it) in items.iter().enumerate() {
let tag = match names.get(i) {
Some(Some(n)) if n.is_empty() => format!("[[{}]]", i + 1),
Some(Some(n)) if is_syntactic_name(n) => format!("${n}"),
Some(Some(n)) => format!("$`{n}`"),
Some(None) => "$<NA>".to_string(),
None => format!("[[{}]]", i + 1),
};
let path = format!("{prefix}{tag}");
out.push(path.clone());
if is_plain_list(it) {
out.extend(format_list_at(it, &path));
out.extend(format_extra_attrs(it));
} else {
out.extend(format_value(it));
}
out.push(String::new());
}
out
}
#[cfg(test)]
mod tests {
use crate::eval_to_string;
#[test]
fn arithmetic_recycles_and_keeps_integer_type() {
assert_eq!(eval_to_string("c(1L, 2L) + 1L").unwrap(), "[1] 2 3");
assert_eq!(eval_to_string("1:6 * c(1, 0)").unwrap(), "[1] 1 0 3 0 5 0");
}
#[test]
fn na_propagates_but_logic_stays_three_valued() {
assert_eq!(eval_to_string("NA + 1").unwrap(), "[1] NA");
assert_eq!(eval_to_string("NA & FALSE").unwrap(), "[1] FALSE");
assert_eq!(eval_to_string("NA | TRUE").unwrap(), "[1] TRUE");
}
#[test]
fn modulo_follows_the_sign_of_the_divisor() {
assert_eq!(eval_to_string("-5 %% 3").unwrap(), "[1] 1");
assert_eq!(eval_to_string("-5 %/% 3").unwrap(), "[1] -2");
}
#[test]
fn negative_subscripts_exclude() {
assert_eq!(eval_to_string("(1:5)[-1]").unwrap(), "[1] 2 3 4 5");
assert_eq!(
eval_to_string("(1:5)[c(TRUE, FALSE)]").unwrap(),
"[1] 1 3 5"
);
}
#[test]
fn doubles_share_a_decimal_width_when_printed() {
assert_eq!(eval_to_string("c(1, 2.5)").unwrap(), "[1] 1.0 2.5");
}
}