use crate::host::{
bigint_to_f64, num_cmp, CharTable, CtAscii, CtSlot, ElHashTable, ElispHost, MatchData, Num,
Obj, Resolved,
};
use fusevm::Value;
use num_bigint::BigInt;
use num_traits::ToPrimitive;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
type R = Result<Value, String>;
fn nil_or(b: bool) -> Value {
if b {
Value::Bool(true)
} else {
Value::Undef
}
}
fn is_nil(v: &Value) -> bool {
matches!(v, Value::Undef | Value::Bool(false))
}
fn as_num(h: &ElispHost, v: &Value) -> Result<(i64, f64, bool), String> {
match v {
Value::Int(n) => Ok((*n, *n as f64, false)),
Value::Float(f) => Ok((*f as i64, *f, true)),
_ => {
if let Some(b) = h.as_bigint(v) {
let f = bigint_to_f64(&b);
return Ok((f as i64, f, false));
}
match h.marker_position(v) {
Some(p) => Ok((p as i64, p as f64, false)),
None => Err(format!(
"wrong-type-argument: number-or-marker-p {}",
h.print(v, true)
)),
}
}
}
}
fn as_int(h: &ElispHost, v: &Value) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
Value::Float(f) => Ok(*f as i64),
_ => match h.marker_position(v) {
Some(p) => Ok(p as i64),
None => Err(format!(
"wrong-type-argument: integerp {}",
h.print(v, true)
)),
},
}
}
fn as_string(h: &ElispHost, v: &Value) -> Result<String, String> {
match h.str_text(v) {
Some(s) => Ok(s.to_string()),
None => Err(format!("wrong-type-argument: stringp {}", h.print(v, true))),
}
}
fn as_integer(h: &ElispHost, v: &Value) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ => Err(format!(
"wrong-type-argument: integerp {}",
h.print(v, true)
)),
}
}
const MOST_POSITIVE_FIXNUM: i64 = 2305843009213693951;
const MEMORY_EXHAUSTED: &str = "error: Memory exhausted--use C-x s then exit and restart Emacs";
fn check_array_len_val(h: &ElispHost, v: &Value) -> Result<usize, String> {
if h.is_bignum(v) {
return Err(format!(
"wrong-type-argument: wholenump {}",
h.print(v, true)
));
}
check_array_len(as_num(h, v)?.0)
}
fn check_fixnat(h: &ElispHost, v: &Value) -> Result<i64, String> {
match v {
Value::Int(n) if (0..=MOST_POSITIVE_FIXNUM).contains(n) => Ok(*n),
_ => Err(format!(
"wrong-type-argument: wholenump {}",
h.print(v, true)
)),
}
}
fn check_array_len(n: i64) -> Result<usize, String> {
if !(0..=MOST_POSITIVE_FIXNUM).contains(&n) {
return Err(format!("wrong-type-argument: wholenump {n}"));
}
Ok(n as usize)
}
fn as_fixnum_named(h: &mut ElispHost, v: &Value, pred: &str) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ => Err(h.signal_wrong_type(pred, v)),
}
}
fn as_int_or_marker(h: &mut ElispHost, v: &Value, pred: &str) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ => match h.marker_position(v) {
Some(p) => Ok(p as i64),
None => Err(h.signal_wrong_type(pred, v)),
},
}
}
fn as_char(h: &mut ElispHost, v: &Value) -> Result<u32, String> {
match v {
Value::Int(n) if (0..=0x3F_FFFF).contains(n) => Ok(*n as u32),
_ => Err(h.signal_wrong_type("characterp", v)),
}
}
fn as_number(h: &ElispHost, v: &Value) -> Result<Num, String> {
as_number_p(h, v, true)
}
fn as_number_p(h: &ElispHost, v: &Value, markers_ok: bool) -> Result<Num, String> {
match v {
Value::Int(n) => Ok(Num::Int(BigInt::from(*n))),
Value::Float(f) => Ok(Num::Float(*f)),
_ => {
if let Some(b) = h.as_bigint(v) {
return Ok(Num::Int(b));
}
if markers_ok {
if let Some(p) = h.marker_position(v) {
return Ok(Num::Int(BigInt::from(p)));
}
}
Err(format!(
"wrong-type-argument: {} {}",
if markers_ok {
"number-or-marker-p"
} else {
"numberp"
},
h.print(v, true)
))
}
}
}
fn fold_arith(
h: &mut ElispHost,
a: &[Value],
init: i64,
int_op: fn(BigInt, BigInt) -> BigInt,
float_op: fn(f64, f64) -> f64,
) -> R {
let mut acc = match a.first() {
Some(v) => as_number(h, v)?,
None => Num::Int(BigInt::from(init)),
};
for v in a.iter().skip(1) {
let n = as_number(h, v)?;
acc = match (acc, n) {
(Num::Int(x), Num::Int(y)) => Num::Int(int_op(x, y)),
(x, y) => Num::Float(float_op(x.to_f64(), y.to_f64())),
};
}
Ok(match acc {
Num::Int(i) => h.make_integer(i),
Num::Float(f) => Value::Float(f),
})
}
fn add(h: &mut ElispHost, a: &[Value]) -> R {
fold_arith(h, a, 0, |x, y| x + y, |x, y| x + y)
}
fn mul(h: &mut ElispHost, a: &[Value]) -> R {
fold_arith(h, a, 1, |x, y| x * y, |x, y| x * y)
}
fn sub(h: &mut ElispHost, a: &[Value]) -> R {
if a.is_empty() {
return Ok(Value::Int(0));
}
if a.len() == 1 {
return Ok(match as_number(h, &a[0])? {
Num::Int(x) => h.make_integer(-x),
Num::Float(f) => Value::Float(-f),
});
}
let mut acc = as_number(h, &a[0])?;
for v in &a[1..] {
let n = as_number(h, v)?;
acc = match (acc, n) {
(Num::Int(x), Num::Int(y)) => Num::Int(x - y),
(x, y) => Num::Float(x.to_f64() - y.to_f64()),
};
}
Ok(match acc {
Num::Int(i) => h.make_integer(i),
Num::Float(f) => Value::Float(f),
})
}
fn div(h: &mut ElispHost, a: &[Value]) -> R {
let first = as_number(h, &a[0])?;
let (mut acc, rest): (Num, &[Value]) = if a.len() == 1 {
(Num::Int(BigInt::from(1)), &a[0..1])
} else {
(first, &a[1..])
};
let mut nan_operand = matches!(acc, Num::Float(f) if f.is_nan());
for v in rest {
let n = as_number(h, v)?;
nan_operand |= matches!(n, Num::Float(f) if f.is_nan());
acc = match (acc, n) {
(Num::Int(x), Num::Int(y)) => {
if y == BigInt::from(0) {
return Err("arith-error: division by zero".to_string());
}
Num::Int(x / y)
}
(x, y) => Num::Float(x.to_f64() / y.to_f64()),
};
}
Ok(match acc {
Num::Int(i) => h.make_integer(i),
Num::Float(mut f) => {
if f.is_nan() && !nan_operand {
f = f.abs();
}
Value::Float(f)
}
})
}
fn modulo(h: &mut ElispHost, a: &[Value]) -> R {
let x = as_int_exact(h, &a[0])?;
let y = as_int_exact(h, &a[1])?;
if y == BigInt::from(0) {
return Err("arith-error: division by zero".to_string());
}
let r = x % y;
Ok(h.make_integer(r))
}
fn mod_fn(h: &mut ElispHost, a: &[Value]) -> R {
let xn = as_number(h, &a[0])?;
let yn = as_number(h, &a[1])?;
if matches!(xn, Num::Float(_)) || matches!(yn, Num::Float(_)) {
let (xf, yf) = (xn.to_f64(), yn.to_f64());
let mut r = xf % yf;
if if yf < 0.0 { r > 0.0 } else { r < 0.0 } {
r += yf;
}
if r.is_nan() && !(xf.is_nan() || yf.is_nan()) {
r = r.abs();
}
return Ok(Value::Float(r));
}
let x = as_int_exact(h, &a[0])?;
let y = as_int_exact(h, &a[1])?;
if y == BigInt::from(0) {
return Err("arith-error: division by zero".to_string());
}
let zero = BigInt::from(0);
let mut r = &x % &y;
if r != zero && (r < zero) != (y < zero) {
r += &y;
}
Ok(h.make_integer(r))
}
fn min_max(h: &mut ElispHost, a: &[Value], want_max: bool) -> R {
let coerce = |h: &mut ElispHost, v: &Value| -> Result<(Num, Value), String> {
let n = as_number(h, v)?;
let v = match h.marker_position(v) {
Some(p) => h.make_integer(BigInt::from(p)),
None => v.clone(),
};
Ok((n, v))
};
let (mut best, mut best_v) = coerce(h, &a[0])?;
for v in &a[1..] {
let (n, v) = coerce(h, v)?;
let better =
num_cmp(&n, &best).is_some_and(|o| if want_max { o.is_gt() } else { o.is_lt() });
if better {
best = n;
best_v = v;
} else if matches!(n, Num::Float(f) if f.is_nan()) {
return Ok(v);
}
}
Ok(best_v)
}
fn max_fn(h: &mut ElispHost, a: &[Value]) -> R {
min_max(h, a, true)
}
fn min_fn(h: &mut ElispHost, a: &[Value]) -> R {
min_max(h, a, false)
}
fn one_plus(h: &mut ElispHost, a: &[Value]) -> R {
Ok(match as_number(h, &a[0])? {
Num::Int(i) => h.make_integer(i + 1),
Num::Float(f) => Value::Float(f + 1.0),
})
}
fn one_minus(h: &mut ElispHost, a: &[Value]) -> R {
Ok(match as_number(h, &a[0])? {
Num::Int(i) => h.make_integer(i - 1),
Num::Float(f) => Value::Float(f - 1.0),
})
}
fn cmp(h: &ElispHost, a: &[Value], pred: fn(std::cmp::Ordering) -> bool, nan_val: bool) -> R {
for w in a.windows(2) {
let (x, y) = (as_number(h, &w[0])?, as_number(h, &w[1])?);
let ord = match num_cmp(&x, &y) {
Some(o) => o,
None => {
if nan_val {
continue;
}
return Ok(Value::Undef);
}
};
if !pred(ord) {
return Ok(Value::Undef);
}
}
Ok(Value::Bool(true))
}
fn num_eq(h: &mut ElispHost, a: &[Value]) -> R {
cmp(h, a, |o| o.is_eq(), false)
}
fn lt(h: &mut ElispHost, a: &[Value]) -> R {
cmp(h, a, |o| o.is_lt(), false)
}
fn gt(h: &mut ElispHost, a: &[Value]) -> R {
cmp(h, a, |o| o.is_gt(), false)
}
fn le(h: &mut ElispHost, a: &[Value]) -> R {
cmp(h, a, |o| o.is_le(), false)
}
fn ge(h: &mut ElispHost, a: &[Value]) -> R {
cmp(h, a, |o| o.is_ge(), false)
}
pub(crate) fn el_eq(h: &ElispHost, a: &Value, b: &Value) -> bool {
if is_nil(a) && is_nil(b) {
return true;
}
match (a, b) {
(Value::Int(x), Value::Int(y)) => x == y,
(Value::Obj(x), Value::Obj(y)) => x == y,
(Value::Bool(true), Value::Bool(true)) => true,
(Value::Str(x), Value::Str(y)) => {
std::sync::Arc::ptr_eq(x, y) || (x.is_empty() && y.is_empty())
}
_ => {
let _ = h;
false
}
}
}
fn el_eql(h: &ElispHost, a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Float(x), Value::Float(y)) => x.to_bits() == y.to_bits(),
(Value::Obj(_), Value::Obj(_)) => match (h.obj(a), h.obj(b)) {
(Some(Obj::Bignum(x)), Some(Obj::Bignum(y))) => x == y,
_ => el_eq(h, a, b),
},
_ => el_eq(h, a, b),
}
}
fn el_equal(h: &ElispHost, a: &Value, b: &Value) -> bool {
if el_eql(h, a, b) {
return true;
}
if let (Some(x), Some(y)) = (h.str_text(a), h.str_text(b)) {
return x == y;
}
match (a, b) {
(Value::Obj(_), Value::Obj(_)) => match (h.obj(a), h.obj(b)) {
(Some(Obj::Cons(a1, a2)), Some(Obj::Cons(b1, b2))) => {
el_equal(h, a1, b1) && el_equal(h, a2, b2)
}
(Some(Obj::Vector(va)), Some(Obj::Vector(vb)))
| (Some(Obj::Record(va)), Some(Obj::Record(vb))) => {
va.len() == vb.len() && va.iter().zip(vb).all(|(x, y)| el_equal(h, x, y))
}
(Some(Obj::BoolVector(ba)), Some(Obj::BoolVector(bb))) => ba == bb,
(Some(Obj::CharTable(ta)), Some(Obj::CharTable(tb))) => {
el_equal(h, &ta.default, &tb.default)
&& el_equal(h, &ta.parent, &tb.parent)
&& el_equal(h, &ta.subtype, &tb.subtype)
&& ta.extra.len() == tb.extra.len()
&& ta
.extra
.iter()
.zip(&tb.extra)
.all(|(x, y)| el_equal(h, x, y))
&& ct_slots_equal(h, &ta.contents, &tb.contents)
&& match (&ta.ascii, &tb.ascii) {
(CtAscii::Val(x), CtAscii::Val(y)) => el_equal(h, x, y),
(CtAscii::Tree, CtAscii::Tree) => true,
_ => false,
}
}
(Some(Obj::Marker(_)), Some(Obj::Marker(_))) => h.markers_equal(a, b),
(Some(Obj::Closure { .. }), Some(Obj::Closure { .. })) => {
match (h.closure_parts(a), h.closure_parts(b)) {
(Some((am, ad, aa, abody, aenv)), Some((bm, bd, ba, bbody, benv))) => {
am == bm
&& ad == bd
&& el_equal(h, &aa, &ba)
&& abody.len() == bbody.len()
&& abody.iter().zip(&bbody).all(|(x, y)| el_equal(h, x, y))
&& aenv.len() == benv.len()
&& aenv.iter().zip(&benv).all(|((s1, v1), (s2, v2))| {
s1 == s2
&& match (v1, v2) {
(Some(v1), Some(v2)) => el_equal(h, v1, v2),
(None, None) => true,
_ => false,
}
})
}
_ => false,
}
}
_ => false,
},
_ => false,
}
}
fn ct_slots_equal(h: &ElispHost, a: &[CtSlot], b: &[CtSlot]) -> bool {
a.len() == b.len()
&& a.iter().zip(b).all(|(x, y)| match (x, y) {
(CtSlot::Val(x), CtSlot::Val(y)) => el_equal(h, x, y),
(CtSlot::Sub(x), CtSlot::Sub(y)) => {
x.depth == y.depth
&& x.min_char == y.min_char
&& ct_slots_equal(h, &x.contents, &y.contents)
}
_ => false,
})
}
fn eq_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(el_eq(h, &a[0], &a[1])))
}
fn eql_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(el_eql(h, &a[0], &a[1])))
}
fn equal_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(el_equal(h, &a[0], &a[1])))
}
fn cons_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(h.cons(a[0].clone(), a[1].clone()))
}
fn car(h: &mut ElispHost, a: &[Value]) -> R {
match h.obj(&a[0]) {
Some(Obj::Cons(x, _)) => Ok(x.clone()),
_ if is_nil(&a[0]) => Ok(Value::Undef),
_ => Err(format!(
"wrong-type-argument: listp {}",
h.print(&a[0], true)
)),
}
}
fn cdr(h: &mut ElispHost, a: &[Value]) -> R {
match h.obj(&a[0]) {
Some(Obj::Cons(_, y)) => Ok(y.clone()),
_ if is_nil(&a[0]) => Ok(Value::Undef),
_ => Err(format!(
"wrong-type-argument: listp {}",
h.print(&a[0], true)
)),
}
}
fn setcar(h: &mut ElispHost, a: &[Value]) -> R {
if let Value::Obj(id) = &a[0] {
if let Some(Obj::Cons(c, _)) = h.arena.get_mut(*id as usize) {
*c = a[1].clone();
return Ok(a[1].clone());
}
}
Err(format!(
"wrong-type-argument: consp {}",
h.print(&a[0], true)
))
}
fn setcdr(h: &mut ElispHost, a: &[Value]) -> R {
if let Value::Obj(id) = &a[0] {
if let Some(Obj::Cons(_, d)) = h.arena.get_mut(*id as usize) {
*d = a[1].clone();
return Ok(a[1].clone());
}
}
Err(format!(
"wrong-type-argument: consp {}",
h.print(&a[0], true)
))
}
fn list_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(h.list_from(a.to_vec()))
}
fn append_fn(h: &mut ElispHost, a: &[Value]) -> R {
if a.is_empty() {
return Ok(Value::Undef);
}
let mut out = Vec::new();
for v in &a[..a.len() - 1] {
if is_nil(v) {
continue;
}
match h.str_text(v) {
Some(s) => out.extend(s.chars().map(|c| Value::Int(c as i64)).collect::<Vec<_>>()),
None => match h.obj(v) {
Some(Obj::Vector(items)) => out.extend(items.clone()),
_ => out.extend(h.seq_vec_checked(v)?),
},
}
}
let mut tail = a[a.len() - 1].clone();
for item in out.into_iter().rev() {
tail = h.cons(item, tail);
}
Ok(tail)
}
fn reverse_fn(h: &mut ElispHost, a: &[Value]) -> R {
if let Some(s) = h.str_text(&a[0]) {
let rev = s.chars().rev().collect::<String>();
return Ok(h.new_string(rev));
}
h.seq_vec_checked(&a[0])?;
let vec_items = match h.obj(&a[0]) {
Some(Obj::Vector(items)) => Some(items.clone()),
_ => None,
};
if let Some(mut items) = vec_items {
items.reverse();
return Ok(h.alloc(Obj::Vector(items)));
}
let mut v = h
.list_vec(&a[0])
.ok_or_else(|| format!("wrong-type-argument: sequencep {}", h.print(&a[0], true)))?;
v.reverse();
Ok(h.list_from(v))
}
fn simple_case(cp: i64, upper: bool) -> i64 {
if upper {
match cp {
223 => return 7838, 8064..=8071 | 8080..=8087 | 8096..=8103 => return cp + 8, 8115 | 8131 | 8179 => return cp + 9, _ => {}
}
}
let Some(ch) = u32::try_from(cp).ok().and_then(char::from_u32) else {
return cp;
};
let mut mapped: [char; 3] = ['\0'; 3];
let mut n = 0;
if upper {
for m in ch.to_uppercase() {
if n < 3 {
mapped[n] = m;
}
n += 1;
}
} else {
for m in ch.to_lowercase() {
if n < 3 {
mapped[n] = m;
}
n += 1;
}
}
if n == 1 {
mapped[0] as i64
} else {
cp
}
}
fn case_fold(h: &mut ElispHost, a: &[Value], upper: bool) -> R {
match &a[0] {
Value::Int(c) if *c < 0 => Err(h.signal_wrong_type("char-or-string-p", &a[0])),
Value::Int(c) if *c > 0x3F_FFFF => Ok(Value::Int(*c)),
Value::Int(c) => Ok(Value::Int(simple_case(*c, upper))),
_ if h.is_string(&a[0]) => {
let src = h.str_arc(&a[0]).expect("checked stringp");
let text = if upper {
src.to_uppercase()
} else {
src.to_lowercase()
};
let same_len = text.chars().count() == src.chars().count();
let (folded, out) = h.new_string_keyed(text);
if same_len {
h.string_carry_all(&out, &src);
}
Ok(folded)
}
v => {
let v = v.clone();
Err(h.signal_wrong_type("char-or-string-p", &v))
}
}
}
fn char_titlecase(h: &mut ElispHost, a: &[Value]) -> R {
match &a[0] {
Value::Int(c) if (0..=0x3F_FFFF).contains(c) => match char::from_u32(*c as u32) {
Some(ch) => Ok(h.new_string(titlecase_str(ch))),
None => Ok(h.new_string(String::new())),
},
v => Err(format!(
"wrong-type-argument: characterp {}",
h.print(v, true)
)),
}
}
fn titlecase_str(ch: char) -> String {
if let Some(t) = titlecase_char_only(ch) {
return t.to_string();
}
let mut out = String::new();
let mut seen_cased = false;
for u in ch.to_uppercase() {
if seen_cased {
if u == '\u{0399}' {
out.push('\u{0345}');
} else {
out.extend(u.to_lowercase());
}
} else {
out.push(u);
if u.to_lowercase().next() != Some(u) {
seen_cased = true;
}
}
}
out
}
fn titlecase_char_only(ch: char) -> Option<char> {
let c = ch as u32;
let t = match c {
0x01C4..=0x01C6 => 0x01C5,
0x01C7..=0x01C9 => 0x01C8,
0x01CA..=0x01CC => 0x01CB,
0x01F1..=0x01F3 => 0x01F2,
0x1F80..=0x1F87 => c + 8,
0x1F90..=0x1F97 => c + 8,
0x1FA0..=0x1FA7 => c + 8,
0x1FB3 => 0x1FBC,
0x1FC3 => 0x1FCC,
0x1FF3 => 0x1FFC,
0x1F88..=0x1F8F | 0x1F98..=0x1F9F | 0x1FA8..=0x1FAF => c,
0x1FBC | 0x1FCC | 0x1FFC => c,
0x10D0..=0x10FA | 0x10FD..=0x10FF => c,
_ => return None,
};
char::from_u32(t)
}
fn downcase_fn(h: &mut ElispHost, a: &[Value]) -> R {
case_fold(h, a, false)
}
fn upcase_fn(h: &mut ElispHost, a: &[Value]) -> R {
case_fold(h, a, true)
}
fn length_fn(h: &mut ElispHost, a: &[Value]) -> R {
if is_nil(&a[0]) {
return Ok(Value::Int(0));
}
if let Some(slots) = h.closure_slots(&a[0]) {
return Ok(Value::Int(slots.len() as i64));
}
if let Some(s) = h.str_text(&a[0]) {
return Ok(Value::Int(s.chars().count() as i64));
}
match &a[0] {
Value::Bool(_) | Value::Int(_) | Value::Float(_) => Err(format!(
"wrong-type-argument: sequencep {}",
h.print(&a[0], true)
)),
Value::Obj(_) => match h.obj(&a[0]) {
Some(Obj::Vector(items)) | Some(Obj::Record(items)) => {
Ok(Value::Int(items.len() as i64))
}
Some(Obj::BoolVector(bits)) => Ok(Value::Int(bits.len() as i64)),
Some(Obj::Cons(..)) => {
let mut n: i64 = 0;
let mut w = TailWalk::new(&a[0]);
while let Some((_, cdr)) = w.cons(h) {
n += 1;
if w.step(cdr) {
let tail = w.tail.clone();
return Err(h.signal_circular_list(&tail));
}
}
let tail = w.tail.clone();
check_list_end(h, &tail, &tail)?;
Ok(Value::Int(n))
}
Some(Obj::CharTable(_)) => Ok(Value::Int(MAX_CHAR + 1)),
_ => Err(h.signal_wrong_type("sequencep", &a[0])),
},
_ => Err(format!(
"wrong-type-argument: sequencep {}",
h.print(&a[0], true)
)),
}
}
fn check_list_end(h: &mut ElispHost, tail: &Value, list: &Value) -> Result<(), String> {
if is_nil(tail) {
Ok(())
} else {
Err(h.signal_wrong_type("listp", list))
}
}
fn nthcdr_fn(h: &mut ElispHost, a: &[Value]) -> R {
let list = a[1].clone();
let mut tail = list.clone();
if !h.is_integer(&a[0]) {
return Err(format!(
"wrong-type-argument: integerp {}",
h.print(&a[0], true)
));
}
const LARGE_NUM: i64 = i64::MAX;
const SMALL_LIST_LEN_MAX: i64 = 127;
let bignum: Option<BigInt> = match h.obj(&a[0]) {
Some(Obj::Bignum(b)) => Some(b.clone()),
_ => None,
};
let mut num: i64 = match (&a[0], &bignum) {
(Value::Int(n), _) => {
let mut num = *n;
if num <= SMALL_LIST_LEN_MAX {
while num > 0 {
match h.obj(&tail) {
Some(Obj::Cons(_, d)) => tail = d.clone(),
_ => {
check_list_end(h, &tail, &list)?;
return Ok(Value::Undef);
}
}
num -= 1;
}
return Ok(tail);
}
num
}
(_, Some(b)) => {
if b.sign() == num_bigint::Sign::Minus {
return Ok(tail);
}
LARGE_NUM
}
_ => return Ok(tail),
};
let mut tortoise = tail.clone();
let mut tortoise_num = num;
let mut saved_tail = tail.clone();
let mut period: i64 = 2;
let mut countdown: i64 = 2;
while let Some(Obj::Cons(_, d)) = h.obj(&tail) {
if value_eq_obj(&tail, &tortoise) {
tortoise_num = num;
}
saved_tail = d.clone();
num -= 1;
if num == 0 {
return Ok(saved_tail);
}
tail = saved_tail.clone();
countdown -= 1;
if countdown == 0 {
period <<= 1;
countdown = period;
tortoise = tail.clone();
} else if value_eq_obj(&tail, &tortoise) {
break;
}
}
tail = saved_tail;
if !matches!(h.obj(&tail), Some(Obj::Cons(..))) {
check_list_end(h, &tail, &list)?;
return Ok(Value::Undef);
}
let cycle_length = tortoise_num - num;
if let Some(b) = &bignum {
let m = BigInt::from(cycle_length);
let r = (b % &m).to_i64().unwrap_or(0);
num += r;
num += cycle_length - LARGE_NUM % cycle_length;
}
num = num.rem_euclid(cycle_length);
while num > 0 {
match h.obj(&tail) {
Some(Obj::Cons(_, d)) => tail = d.clone(),
_ => break,
}
num -= 1;
}
Ok(tail)
}
fn value_eq_obj(a: &Value, b: &Value) -> bool {
matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y)
}
pub struct TailWalk {
pub tail: Value,
tortoise: Value,
max: i64,
n: i64,
q: u16,
}
impl TailWalk {
pub fn new(list: &Value) -> Self {
Self {
tail: list.clone(),
tortoise: list.clone(),
max: 2,
n: 0,
q: 2,
}
}
pub fn cons(&self, h: &ElispHost) -> Option<(Value, Value)> {
match h.obj(&self.tail) {
Some(Obj::Cons(car, cdr)) => Some((car.clone(), cdr.clone())),
_ => None,
}
}
#[must_use]
pub fn step(&mut self, cdr: Value) -> bool {
self.tail = cdr;
self.q = self.q.wrapping_sub(1);
let advanced = if self.q != 0 {
true
} else {
self.n -= 1;
if self.n > 0 {
true
} else {
self.max <<= 1;
self.n = self.max;
self.q = (self.n & 0xffff) as u16;
self.n >>= 16;
self.tortoise = self.tail.clone();
false
}
};
advanced && value_eq_obj(&self.tail, &self.tortoise)
}
}
fn eq_comparable_value(h: &ElispHost, v: &Value) -> bool {
match v {
Value::Int(_) | Value::Bool(_) | Value::Undef => true,
Value::Obj(_) => matches!(h.obj(v), Some(Obj::Symbol(_))),
_ => false,
}
}
fn for_each_tail(
h: &mut ElispHost,
list: &Value,
mut hit: impl FnMut(&ElispHost, &Value, &Value) -> Option<Value>,
) -> R {
let mut w = TailWalk::new(list);
while let Some((car, cdr)) = w.cons(h) {
if let Some(found) = hit(h, &car, &w.tail) {
return Ok(found);
}
if w.step(cdr) {
return Err(h.signal_circular_list(&w.tail));
}
}
check_list_end(h, &w.tail, list)?;
Ok(Value::Undef)
}
fn memq_fn(h: &mut ElispHost, a: &[Value]) -> R {
let elt = a[0].clone();
for_each_tail(h, &a[1], |h, car, tail| {
el_eq(h, car, &elt).then(|| tail.clone())
})
}
fn memql_fn(h: &mut ElispHost, a: &[Value]) -> R {
let elt = a[0].clone();
let float = matches!(elt, Value::Float(_));
let bignum = matches!(h.obj(&elt), Some(Obj::Bignum(_)));
if !float && !bignum {
return memq_fn(h, a);
}
for_each_tail(h, &a[1], |h, car, tail| {
let same = if float {
matches!(car, Value::Float(_)) && el_eql(h, &elt, car)
} else {
matches!(h.obj(car), Some(Obj::Bignum(_))) && el_eql(h, &elt, car)
};
same.then(|| tail.clone())
})
}
fn member_fn(h: &mut ElispHost, a: &[Value]) -> R {
if eq_comparable_value(h, &a[0]) {
return memq_fn(h, a);
}
let elt = a[0].clone();
for_each_tail(h, &a[1], |h, car, tail| {
el_equal(h, &elt, car).then(|| tail.clone())
})
}
fn assq_fn(h: &mut ElispHost, a: &[Value]) -> R {
let key = a[0].clone();
for_each_tail(h, &a[1], |h, car, _| match h.obj(car) {
Some(Obj::Cons(k, _)) if el_eq(h, k, &key) => Some(car.clone()),
_ => None,
})
}
fn rassq_fn(h: &mut ElispHost, a: &[Value]) -> R {
let key = a[0].clone();
for_each_tail(h, &a[1], |h, car, _| match h.obj(car) {
Some(Obj::Cons(_, v)) if el_eq(h, v, &key) => Some(car.clone()),
_ => None,
})
}
pub fn eq_comparable(h: &ElispHost, v: &Value) -> bool {
eq_comparable_value(h, v)
}
pub fn assq(h: &mut ElispHost, a: &[Value]) -> R {
assq_fn(h, a)
}
pub fn equal_or_eq(h: &ElispHost, a: &Value, b: &Value) -> bool {
el_eq(h, a, b) || el_equal(h, a, b)
}
pub fn check_end(h: &mut ElispHost, tail: &Value, list: &Value) -> Result<(), String> {
check_list_end(h, tail, list)
}
pub fn concat(h: &mut ElispHost, a: &[Value]) -> R {
concat_fn(h, a)
}
fn rassoc_fn(h: &mut ElispHost, a: &[Value]) -> R {
if eq_comparable_value(h, &a[0]) {
return rassq_fn(h, a);
}
let key = a[0].clone();
for_each_tail(h, &a[1], |h, car, _| match h.obj(car) {
Some(Obj::Cons(_, v)) if el_eq(h, v, &key) || el_equal(h, v, &key) => Some(car.clone()),
_ => None,
})
}
fn nth_fn(h: &mut ElispHost, a: &[Value]) -> R {
let cur = nthcdr_fn(h, a)?;
match h.obj(&cur) {
Some(Obj::Cons(car, _)) => Ok(car.clone()),
_ if is_nil(&cur) => Ok(Value::Undef),
_ => Err(format!(
"wrong-type-argument: listp {}",
h.print(&cur, true)
)),
}
}
fn cxr(h: &mut ElispHost, a: &[Value], ops: &str) -> R {
let mut v = a[0].clone();
for op in ops.bytes().rev() {
v = if op == b'a' {
car(h, &[v])?
} else {
cdr(h, &[v])?
};
}
Ok(v)
}
macro_rules! cxr_subrs {
($($f:ident $ops:literal),* $(,)?) => {
$(fn $f(h: &mut ElispHost, a: &[Value]) -> R { cxr(h, a, $ops) })*
const CXR_SUBRS: &[(&str, crate::host::SubrFn)] =
&[$((concat!("c", $ops, "r"), $f)),*];
};
}
cxr_subrs!(
caar "aa", cadr "ad", cdar "da", cddr "dd",
caaar "aaa", caadr "aad", cadar "ada", caddr "add",
cdaar "daa", cdadr "dad", cddar "dda", cdddr "ddd",
caaaar "aaaa", caaadr "aaad", caadar "aada", caaddr "aadd",
cadaar "adaa", cadadr "adad", caddar "adda", cadddr "addd",
cdaaar "daaa", cdaadr "daad", cdadar "dada", cdaddr "dadd",
cddaar "ddaa", cddadr "ddad", cdddar "ddda", cddddr "dddd",
);
fn null_fn(_h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(is_nil(&a[0])))
}
fn consp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Cons(..)))))
}
fn listp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(
is_nil(&a[0]) || matches!(h.obj(&a[0]), Some(Obj::Cons(..))),
))
}
fn atom(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(!matches!(h.obj(&a[0]), Some(Obj::Cons(..)))))
}
fn symbolp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(
matches!(a[0], Value::Bool(_) | Value::Undef)
|| matches!(h.obj(&a[0]), Some(Obj::Symbol(_))),
))
}
fn stringp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(h.is_string(&a[0])))
}
fn natnump_fn(h: &mut ElispHost, a: &[Value]) -> R {
use num_traits::Signed;
let ok = match &a[0] {
Value::Int(n) => *n >= 0,
v => h.as_bigint(v).is_some_and(|b| !b.is_negative()),
};
Ok(nil_or(ok))
}
fn nlistp_fn(h: &mut ElispHost, a: &[Value]) -> R {
let is_list = is_nil(&a[0]) || matches!(h.obj(&a[0]), Some(Obj::Cons(..)));
Ok(nil_or(!is_list))
}
fn numberp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(h.is_number(&a[0])))
}
fn integerp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(h.is_integer(&a[0])))
}
fn fixnump(_h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(a[0], Value::Int(_))))
}
fn bignump(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(h.is_bignum(&a[0])))
}
fn floatp(_h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(a[0], Value::Float(_))))
}
fn vectorp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Vector(_)))))
}
fn vector_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(h.alloc(Obj::Vector(a.to_vec())))
}
fn make_list(h: &mut ElispHost, a: &[Value]) -> R {
let n = check_fixnat(h, &a[0])?;
let mut val = Value::Undef;
for _ in 0..n {
val = h.cons(a[1].clone(), val);
}
Ok(val)
}
fn make_vector(h: &mut ElispHost, a: &[Value]) -> R {
let n = check_array_len_val(h, &a[0])?;
let mut v: Vec<Value> = Vec::new();
v.try_reserve_exact(n)
.map_err(|_| MEMORY_EXHAUSTED.to_string())?;
v.resize(n, a[1].clone());
Ok(h.alloc(Obj::Vector(v)))
}
fn record_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(h.alloc(Obj::Record(a.to_vec())))
}
fn make_record(h: &mut ElispHost, a: &[Value]) -> R {
let slots = match &a[1] {
Value::Int(n) if *n >= 0 => *n as usize,
_ => {
return Err(format!(
"wrong-type-argument: wholenump {}",
h.print(&a[1], true)
))
}
};
let total = slots + 1;
if total > 4095 {
return Err(format!(
"Attempt to allocate a record of {total} slots; max is 4095"
));
}
let mut v: Vec<Value> = Vec::new();
v.try_reserve_exact(total)
.map_err(|_| MEMORY_EXHAUSTED.to_string())?;
v.resize(total, a[2].clone());
v[0] = a[0].clone();
Ok(h.alloc(Obj::Record(v)))
}
fn as_bool_vector(h: &ElispHost, v: &Value) -> Result<Vec<bool>, String> {
match h.obj(v) {
Some(Obj::BoolVector(bits)) => Ok(bits.clone()),
_ => Err(format!(
"wrong-type-argument: bool-vector-p {}",
h.print(v, true)
)),
}
}
fn make_bool_vector(h: &mut ElispHost, a: &[Value]) -> R {
let n = check_array_len_val(h, &a[0])?;
let bit = !is_nil(&a[1]);
let mut v: Vec<bool> = Vec::new();
v.try_reserve_exact(n)
.map_err(|_| MEMORY_EXHAUSTED.to_string())?;
v.resize(n, bit);
Ok(h.alloc(Obj::BoolVector(v)))
}
fn bool_vector_fn(h: &mut ElispHost, a: &[Value]) -> R {
let bits: Vec<bool> = a.iter().map(|x| !is_nil(x)).collect();
Ok(h.alloc(Obj::BoolVector(bits)))
}
fn bool_vector_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::BoolVector(_)))))
}
fn bool_vector_count_population(h: &mut ElispHost, a: &[Value]) -> R {
let bits = as_bool_vector(h, &a[0])?;
Ok(Value::Int(bits.iter().filter(|&&b| b).count() as i64))
}
fn bool_vector_subsetp(h: &mut ElispHost, a: &[Value]) -> R {
let ba = as_bool_vector(h, &a[0])?;
let bb = as_bool_vector(h, &a[1])?;
if ba.len() != bb.len() {
return Err(format!(
"wrong-length-argument: {} {} {}",
ba.len(),
bb.len(),
bb.len()
));
}
Ok(nil_or(ba.iter().zip(&bb).all(|(&x, &y)| !x || y)))
}
fn bool_vector_binop(h: &mut ElispHost, a: &[Value], op: fn(bool, bool) -> bool) -> R {
let ba = as_bool_vector(h, &a[0])?;
let bb = as_bool_vector(h, &a[1])?;
let dest = a.get(2).filter(|v| !is_nil(v)).cloned();
let wrong_length = |extra: Option<usize>| match extra {
Some(n) => format!("wrong-length-argument: {} {} {n}", ba.len(), bb.len()),
None => format!("wrong-length-argument: {} {}", ba.len(), bb.len()),
};
if bb.len() != ba.len() {
let extra = match &dest {
Some(d) => Some(as_bool_vector(h, d)?.len()),
None => None,
};
return Err(wrong_length(extra));
}
let out: Vec<bool> = ba.iter().zip(&bb).map(|(&x, &y)| op(x, y)).collect();
let Some(dest) = dest else {
return Ok(h.alloc(Obj::BoolVector(out)));
};
let bd = as_bool_vector(h, &dest)?;
if bd.len() != ba.len() {
return Err(wrong_length(Some(bd.len())));
}
if bd == out {
return Ok(Value::Undef);
}
if let Value::Obj(id) = &dest {
if let Some(Obj::BoolVector(bits)) = h.arena.get_mut(*id as usize) {
*bits = out;
}
}
Ok(dest)
}
fn bool_vector_exclusive_or(h: &mut ElispHost, a: &[Value]) -> R {
bool_vector_binop(h, a, |x, y| x ^ y)
}
fn bool_vector_union(h: &mut ElispHost, a: &[Value]) -> R {
bool_vector_binop(h, a, |x, y| x | y)
}
fn bool_vector_intersection(h: &mut ElispHost, a: &[Value]) -> R {
bool_vector_binop(h, a, |x, y| x & y)
}
fn bool_vector_set_difference(h: &mut ElispHost, a: &[Value]) -> R {
bool_vector_binop(h, a, |x, y| x & !y)
}
fn bool_vector_count_consecutive(h: &mut ElispHost, a: &[Value]) -> R {
let ba = as_bool_vector(h, &a[0])?;
let i = match &a[2] {
Value::Int(n) if *n >= 0 => *n as usize,
v => return Err(h.signal_wrong_type("wholenump", v)),
};
if i > ba.len() {
let (v, n) = (a[0].clone(), a[2].clone());
let data = h.list_from(vec![v, n]);
let sym = h.intern("args-out-of-range");
let obj = h.cons(sym, data);
let msg = format!("args-out-of-range: {}", h.print(&obj, true));
h.set_pending_error(&msg, obj);
return Err(msg);
}
let b = !is_nil(&a[1]);
Ok(Value::Int(
ba[i..].iter().take_while(|&&x| x == b).count() as i64
))
}
fn bool_vector_not(h: &mut ElispHost, a: &[Value]) -> R {
let ba = as_bool_vector(h, &a[0])?;
let out: Vec<bool> = ba.iter().map(|&x| !x).collect();
if a.len() > 1 && !is_nil(&a[1]) {
let bb = as_bool_vector(h, &a[1])?;
if bb.len() != ba.len() {
return Err(format!("wrong-length-argument: {} {}", ba.len(), bb.len()));
}
if let Value::Obj(id) = &a[1] {
if let Some(Obj::BoolVector(bits)) = h.arena.get_mut(*id as usize) {
bits.clear();
bits.extend_from_slice(&out);
}
}
return Ok(a[1].clone());
}
Ok(h.alloc(Obj::BoolVector(out)))
}
fn elt_fn(h: &mut ElispHost, a: &[Value]) -> R {
if is_nil(&a[0]) || matches!(h.obj(&a[0]), Some(Obj::Cons(..))) {
return nth_fn(h, &[a[1].clone(), a[0].clone()]);
}
if !matches!(
h.obj(&a[0]),
Some(Obj::Vector(_))
| Some(Obj::Str(_))
| Some(Obj::BoolVector(_))
| Some(Obj::CharTable(_))
) {
return Err(format!(
"wrong-type-argument: sequencep {}",
h.print(&a[0], true)
));
}
aref(h, a)
}
fn aref(h: &mut ElispHost, a: &[Value]) -> R {
if matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) {
let c = as_char(h, &a[1])?;
return Ok(h.char_table_ref(&a[0], c));
}
let idx = match &a[1] {
Value::Int(n) => *n,
v => return Err(format!("wrong-type-argument: fixnump {}", h.print(v, true))),
};
let oor = |h: &ElispHost| format!("args-out-of-range: {} {idx}", h.print(&a[0], true));
let get = |len: usize| -> Option<usize> { usize::try_from(idx).ok().filter(|i| *i < len) };
if let Some(slots) = h.closure_slots(&a[0]) {
return get(slots.len())
.map(|i| slots[i].clone())
.ok_or_else(|| oor(h));
}
match h.obj(&a[0]) {
Some(Obj::Vector(items)) | Some(Obj::Record(items)) => get(items.len())
.map(|i| items[i].clone())
.ok_or_else(|| oor(h)),
Some(Obj::BoolVector(bits)) => get(bits.len())
.map(|i| nil_or(bits[i]))
.ok_or_else(|| oor(h)),
_ => match h.str_text(&a[0]) {
Some(s) => get(s.chars().count())
.and_then(|i| s.chars().nth(i))
.map(|c| Value::Int(c as i64))
.ok_or_else(|| oor(h)),
None => Err(format!(
"wrong-type-argument: arrayp {}",
h.print(&a[0], true)
)),
},
}
}
fn note_compiler_macro(h: &mut ElispHost, a: &[Value]) -> R {
if let Value::Obj(id) = &a[0] {
h.compiler_macros.insert(*id);
}
Ok(a[0].clone())
}
fn aset(h: &mut ElispHost, a: &[Value]) -> R {
if matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) {
let c = as_char(h, &a[1])?;
if let Value::Obj(id) = &a[0] {
if let Some(Obj::CharTable(t)) = h.arena.get_mut(*id as usize) {
t.set_range(c, c, a[2].clone());
}
}
return Ok(a[2].clone());
}
let idx = as_num(h, &a[1])?.0;
if idx < 0 {
return Err(format!("args-out-of-range: {} {idx}", h.print(&a[0], true)));
}
let i = idx as usize;
let bit = !is_nil(&a[2]);
if let Value::Obj(id) = &a[0] {
match h.arena.get_mut(*id as usize) {
Some(Obj::Vector(items)) | Some(Obj::Record(items)) => {
if i < items.len() {
items[i] = a[2].clone();
return Ok(a[2].clone());
}
return Err(format!("args-out-of-range: {} {idx}", h.print(&a[0], true)));
}
Some(Obj::BoolVector(bits)) => {
if i < bits.len() {
bits[i] = bit;
return Ok(a[2].clone());
}
return Err(format!("args-out-of-range: {} {idx}", h.print(&a[0], true)));
}
_ => {}
}
}
if h.is_string(&a[0]) {
let mut chars: Vec<char> = h
.str_text(&a[0])
.expect("checked stringp")
.chars()
.collect();
if i >= chars.len() {
return Err(format!("args-out-of-range: {} {idx}", h.print(&a[0], true)));
}
let c = as_char(h, &a[2])?;
chars[i] = char::from_u32(c).unwrap_or('\u{fffd}');
let text: String = chars.into_iter().collect();
h.set_string_text(&a[0], text);
return Ok(a[2].clone());
}
Err(format!(
"wrong-type-argument: arrayp {}",
h.print(&a[0], true)
))
}
fn fillarray(h: &mut ElispHost, a: &[Value]) -> R {
if h.is_string(&a[0]) {
let n = h.str_text(&a[0]).expect("checked stringp").chars().count();
let c = as_char(h, &a[1])?;
let ch = char::from_u32(c).unwrap_or('\u{fffd}');
let text: String = std::iter::repeat_n(ch, n).collect();
h.set_string_text(&a[0], text);
return Ok(a[0].clone());
}
if let Value::Obj(id) = &a[0] {
if let Some(Obj::Vector(items)) = h.arena.get_mut(*id as usize) {
for x in items.iter_mut() {
*x = a[1].clone();
}
return Ok(a[0].clone());
}
}
Err(format!(
"wrong-type-argument: arrayp {}",
h.print(&a[0], true)
))
}
fn store_substring(h: &mut ElispHost, a: &[Value]) -> R {
if !h.is_string(&a[0]) {
return Err(h.signal_wrong_type("stringp", &a[0]));
}
let mut chars: Vec<char> = h
.str_text(&a[0])
.expect("checked stringp")
.chars()
.collect();
let idx = as_int(h, &a[1])?;
let incoming: Vec<char> = match h.str_text(&a[2]) {
Some(s) => s.chars().collect(),
None => vec![char::from_u32(as_char(h, &a[2])?).unwrap_or('\u{fffd}')],
};
for (k, c) in incoming.into_iter().enumerate() {
let pos = idx + k as i64;
if pos < 0 || pos as usize >= chars.len() {
let text: String = chars.into_iter().collect();
h.set_string_text(&a[0], text);
return Err(format!("args-out-of-range: {} {pos}", h.print(&a[0], true)));
}
chars[pos as usize] = c;
}
let text: String = chars.into_iter().collect();
h.set_string_text(&a[0], text);
Ok(a[0].clone())
}
fn clear_string(h: &mut ElispHost, a: &[Value]) -> R {
if !h.is_string(&a[0]) {
return Err(h.signal_wrong_type("stringp", &a[0]));
}
let n = h.str_text(&a[0]).expect("checked stringp").chars().count();
let text: String = std::iter::repeat_n('\0', n).collect();
h.set_string_text(&a[0], text);
Ok(Value::Undef)
}
fn make_char_table_new(h: &mut ElispHost, a: &[Value]) -> R {
let n = as_num(h, &a[2])?.0;
let n = if n < 0 { 0 } else { n as usize };
Ok(h.alloc(Obj::CharTable(CharTable::new(
a[0].clone(),
a[1].clone(),
n,
))))
}
fn char_table_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::CharTable(_)))))
}
fn char_table_subtype(h: &mut ElispHost, a: &[Value]) -> R {
match h.obj(&a[0]) {
Some(Obj::CharTable(t)) => Ok(t.subtype.clone()),
_ => Err(wrong_char_table(h, &a[0])),
}
}
fn char_table_parent(h: &mut ElispHost, a: &[Value]) -> R {
match h.obj(&a[0]) {
Some(Obj::CharTable(t)) => Ok(t.parent.clone()),
_ => Err(wrong_char_table(h, &a[0])),
}
}
fn set_char_table_parent(h: &mut ElispHost, a: &[Value]) -> R {
if let Value::Obj(id) = &a[0] {
if let Some(Obj::CharTable(t)) = h.arena.get_mut(*id as usize) {
t.parent = a[1].clone();
return Ok(a[1].clone());
}
}
Err(wrong_char_table(h, &a[0]))
}
fn char_table_extra_slot(h: &mut ElispHost, a: &[Value]) -> R {
let n = as_num(h, &a[1])?.0;
match h.obj(&a[0]) {
Some(Obj::CharTable(t)) => t
.extra
.get(n as usize)
.filter(|_| n >= 0)
.cloned()
.ok_or_else(|| format!("args-out-of-range: {} {n}", h.print(&a[0], true))),
_ => Err(wrong_char_table(h, &a[0])),
}
}
fn set_char_table_extra_slot(h: &mut ElispHost, a: &[Value]) -> R {
let n = as_num(h, &a[1])?.0;
if let Value::Obj(id) = &a[0] {
if let Some(Obj::CharTable(t)) = h.arena.get_mut(*id as usize) {
if n >= 0 && (n as usize) < t.extra.len() {
t.extra[n as usize] = a[2].clone();
return Ok(a[2].clone());
}
return Err(format!("args-out-of-range: {} {n}", h.print(&a[0], true)));
}
}
Err(wrong_char_table(h, &a[0]))
}
fn char_table_range(h: &mut ElispHost, a: &[Value]) -> R {
if !matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) {
return Err(wrong_char_table(h, &a[0]));
}
match &a[1] {
Value::Undef | Value::Bool(false) => match h.obj(&a[0]) {
Some(Obj::CharTable(t)) => Ok(t.default.clone()),
_ => unreachable!(),
},
Value::Bool(true) => {
Err("Invalid RANGE argument to \u{2018}char-table-range\u{2019}".to_string())
}
Value::Int(_) => {
let c = as_char(h, &a[1])?;
Ok(h.char_table_ref(&a[0], c))
}
_ => {
if let Some(Obj::Cons(from, _)) = h.obj(&a[1]) {
let from = from.clone();
let c = as_char(h, &from)?;
Ok(h.char_table_ref(&a[0], c))
} else {
Err("Invalid RANGE argument to \u{2018}char-table-range\u{2019}".to_string())
}
}
}
}
fn char_table_run_end(h: &mut ElispHost, a: &[Value]) -> R {
let from = as_char(h, &a[1])?;
let limit = as_char(h, &a[2])?;
let Some(Obj::CharTable(t)) = h.obj(&a[0]) else {
return Err(wrong_char_table(h, &a[0]));
};
let next = t
.runs()
.iter()
.map(|(start, _)| *start)
.find(|start| *start > from);
let end = next.map_or(crate::host::MAX_CHAR, |n| n - 1).min(limit);
Ok(Value::Int(end as i64))
}
fn set_char_table_range(h: &mut ElispHost, a: &[Value]) -> R {
let id = match &a[0] {
Value::Obj(id) if matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) => *id,
_ => return Err(wrong_char_table(h, &a[0])),
};
let val = a[2].clone();
match &a[1] {
Value::Undef | Value::Bool(false) => {
if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
t.default = val;
}
}
Value::Bool(true) => {
if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
t.set_all(val);
}
}
Value::Int(_) => {
let c = as_char(h, &a[1])?;
if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
t.set_range(c, c, val);
}
}
_ => {
let (from, to) = match h.obj(&a[1]) {
Some(Obj::Cons(f, t)) => (f.clone(), t.clone()),
_ => {
return Err(
"Invalid RANGE argument to \u{2018}set-char-table-range\u{2019}"
.to_string(),
)
}
};
let from = as_char(h, &from)?;
let to = as_char(h, &to)?;
if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
if from <= to {
t.set_range(from, to, val);
}
}
}
}
Ok(a[2].clone())
}
fn copy_char_table(h: &mut ElispHost, a: &[Value]) -> R {
let copy = match h.obj(&a[0]) {
Some(Obj::CharTable(t)) => t.copied(),
_ => return Err(wrong_char_table(h, &a[0])),
};
Ok(h.alloc(Obj::CharTable(copy)))
}
fn char_table_runs(h: &mut ElispHost, a: &[Value]) -> R {
if !matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) {
return Err(wrong_char_table(h, &a[0]));
}
let mut breaks: Vec<u32> = vec![0];
let mut cur = a[0].clone();
while let Some(Obj::CharTable(t)) = h.obj(&cur) {
breaks.extend(t.runs().iter().map(|(s, _)| *s));
cur = t.parent.clone();
}
breaks.sort_unstable();
breaks.dedup();
let mut runs: Vec<(u32, Value)> = Vec::new();
for b in breaks {
let v = h.char_table_ref(&a[0], b);
match runs.last() {
Some((_, last)) if h.values_eq(last, &v) => {}
_ => runs.push((b, v)),
}
}
let items = runs
.into_iter()
.map(|(s, v)| h.cons(Value::Int(i64::from(s)), v))
.collect();
Ok(h.list_from(items))
}
fn optimize_char_table(h: &mut ElispHost, a: &[Value]) -> R {
let id = match &a[0] {
Value::Obj(id) if matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) => *id,
_ => return Err(wrong_char_table(h, &a[0])),
};
let use_eq = a.get(1).and_then(|t| h.sym_name(t)).as_deref() == Some("eq");
let mut table = match h.obj(&a[0]) {
Some(Obj::CharTable(t)) => t.copied_exact(),
_ => unreachable!(),
};
let same = |x: &Value, y: &Value| {
if use_eq {
h.values_eq(x, y)
} else {
el_equal(h, x, y)
}
};
table.optimize(&same);
if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
*t = table;
}
Ok(Value::Undef)
}
fn wrong_char_table(h: &ElispHost, v: &Value) -> String {
format!("wrong-type-argument: char-table-p {}", h.print(v, true))
}
fn symbol_name(h: &mut ElispHost, a: &[Value]) -> R {
match h.sym_name(&a[0]) {
Some(s) => Ok(h.new_string(s)),
None => Err(format!(
"wrong-type-argument: symbolp {}",
h.print(&a[0], true)
)),
}
}
fn obarray_arg(h: &ElispHost, v: Option<&Value>) -> Result<Option<u32>, String> {
match v {
None | Some(Value::Undef) | Some(Value::Bool(false)) => Ok(None),
Some(ob) => match h.obj(ob) {
Some(Obj::Obarray(d)) if d.global => Ok(None),
Some(Obj::Obarray(_)) => match ob {
Value::Obj(id) => Ok(Some(*id)),
_ => Ok(None),
},
_ => Err(format!(
"wrong-type-argument: obarrayp {}",
h.print(ob, true)
)),
},
}
}
fn intern_fn(h: &mut ElispHost, a: &[Value]) -> R {
let name = match h.str_text(&a[0]) {
Some(s) => s.to_string(),
None => {
return Err(format!(
"wrong-type-argument: stringp {}",
h.print(&a[0], true)
))
}
};
match obarray_arg(h, a.get(1))? {
None if name == "nil" => Ok(Value::Undef),
None if name == "t" => Ok(Value::Bool(true)),
None => Ok(h.intern(&name)),
Some(id) => Ok(h.obarray_intern(id, &name)),
}
}
fn obarray_make_fn(h: &mut ElispHost, a: &[Value]) -> R {
if let Some(v) = a.first() {
match v {
Value::Int(n) if *n >= 0 => {}
Value::Undef | Value::Bool(false) => {}
_ => {
return Err(format!(
"wrong-type-argument: wholenump {}",
h.print(v, true)
))
}
}
}
Ok(h.alloc(Obj::Obarray(crate::host::ObarrayData {
symbols: std::collections::HashMap::new(),
global: false,
})))
}
fn obarrayp_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Obarray(_)))))
}
fn unintern_fn(h: &mut ElispHost, a: &[Value]) -> R {
let name = match h.str_text(&a[0]) {
Some(s) => s.to_string(),
None => h
.sym_name(&a[0])
.ok_or_else(|| format!("wrong-type-argument: stringp {}", h.print(&a[0], true)))?,
};
let removed = match obarray_arg(h, a.get(1))? {
None => h.obarray_unintern_global(&name),
Some(id) => h.obarray_unintern(id, &name),
};
Ok(nil_or(removed))
}
fn make_symbol_fn(h: &mut ElispHost, a: &[Value]) -> R {
match h.str_text(&a[0]).map(str::to_string) {
Some(s) => Ok(h.make_symbol(&s)),
None => Err(format!(
"wrong-type-argument: stringp {}",
h.print(&a[0], true)
)),
}
}
fn set_fn(h: &mut ElispHost, a: &[Value]) -> R {
h.set_dynamic_value(&a[0], a[1].clone())?;
Ok(a[1].clone())
}
fn keywordp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Bool(h.is_keyword(&a[0])))
}
fn symbol_value(h: &mut ElispHost, a: &[Value]) -> R {
if h.is_keyword(&a[0]) {
return Ok(a[0].clone());
}
h.get_dynamic_value(&a[0])
}
fn makunbound(h: &mut ElispHost, a: &[Value]) -> R {
h.unset_value(&a[0])?;
Ok(a[0].clone())
}
fn fset(h: &mut ElispHost, a: &[Value]) -> R {
h.set_function_value(&a[0], a[1].clone())?;
h.note_subr_alias(&a[0], &a[1]);
Ok(a[1].clone())
}
fn fmakunbound(h: &mut ElispHost, a: &[Value]) -> R {
if is_nil(&a[0]) || matches!(a[0], Value::Bool(true)) {
let name = if is_nil(&a[0]) { "nil" } else { "t" };
return Err(format!("setting-constant: {name}"));
}
h.set_function_value(&a[0], Value::Undef)?;
Ok(a[0].clone())
}
fn fboundp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(
h.resolve_function(&a[0]).is_ok() || h.introspect_function_cell(&a[0]).is_some(),
))
}
fn indirect_function(h: &mut ElispHost, a: &[Value]) -> R {
let mut cur = a[0].clone();
for _ in 0..64 {
if is_nil(&cur) || matches!(cur, Value::Bool(true)) {
return Ok(Value::Undef);
}
match h.obj(&cur) {
Some(Obj::Symbol(_)) => match h.introspect_function_cell(&cur) {
Some(def) => cur = def,
None => return Ok(Value::Undef),
},
_ => return Ok(cur),
}
}
Ok(cur)
}
fn defvaralias(h: &mut ElispHost, a: &[Value]) -> R {
h.defvaralias(&a[0], &a[1])
}
fn indirect_variable(h: &mut ElispHost, a: &[Value]) -> R {
match &a[0] {
Value::Obj(id) => {
let base = h.indirect_var(*id);
Ok(Value::Obj(base))
}
_ => Ok(a[0].clone()),
}
}
fn boundp(h: &mut ElispHost, a: &[Value]) -> R {
check_symbol(h, &a[0])?;
let bound =
is_nil(&a[0]) || matches!(a[0], Value::Bool(true)) || h.get_dynamic_value(&a[0]).is_ok();
Ok(nil_or(bound))
}
fn identity(_h: &mut ElispHost, a: &[Value]) -> R {
Ok(a[0].clone())
}
pub(crate) enum PrintDest {
Stdout,
Buffer(usize),
Marker(Value),
Function(Value),
}
pub(crate) fn print_dest(h: &ElispHost, pcf: Option<&Value>) -> Result<PrintDest, String> {
let mut v = pcf.cloned().unwrap_or(Value::Undef);
if is_nil(&v) {
v = h
.find_symbol("standard-output")
.and_then(|s| h.get_value(&s).ok())
.unwrap_or(Value::Bool(true));
}
if is_nil(&v) {
return Ok(PrintDest::Stdout);
}
if matches!(v, Value::Bool(true)) {
return Ok(PrintDest::Stdout);
}
match h.obj(&v) {
Some(Obj::Buffer(idx)) => {
if h.buffers.get(*idx).is_none_or(|b| b.name.is_none()) {
return Err("error: Selecting deleted buffer".to_string());
}
Ok(PrintDest::Buffer(*idx))
}
Some(Obj::Marker(m)) => {
if m.borrow().buffer.is_none() {
return Err("error: Marker does not point anywhere".to_string());
}
Ok(PrintDest::Marker(v.clone()))
}
_ => Ok(PrintDest::Function(v)),
}
}
pub(crate) fn print_to(h: &mut ElispHost, dest: &PrintDest, s: &str) -> Result<(), String> {
match dest {
PrintDest::Stdout => h.emit(s),
PrintDest::Buffer(idx) => {
let old = h.current;
h.current = *idx;
h.cur_insert(s.chars().collect(), true);
h.current = old;
}
PrintDest::Marker(mv) => {
let Some(Obj::Marker(m)) = h.obj(mv) else {
unreachable!("print_dest only yields markers here")
};
let m = m.clone();
let (bi, pos) = {
let md = m.borrow();
(md.buffer.expect("checked in print_dest"), md.pos)
};
let old = h.current;
h.current = bi;
let (begv, zv, old_point) = {
let b = h.cur_buf_ref();
(b.begv, b.zv, b.point)
};
if pos < begv || pos > zv {
h.current = old;
return Err(
h.signal_error_arg("Marker is outside the accessible part of the buffer", mv)
);
}
h.cur_buf().point = pos;
let n = s.chars().count();
h.cur_insert(s.chars().collect(), true);
m.borrow_mut().pos = pos + n;
h.cur_buf().point = if old_point >= pos {
old_point + n
} else {
old_point
};
h.current = old;
}
PrintDest::Function(_) => {
unreachable!("function destinations are driven by host::call_function")
}
}
Ok(())
}
pub(crate) fn print_text(
h: &mut ElispHost,
name: &str,
a: &[Value],
) -> Result<Option<String>, String> {
Ok(Some(match name {
"princ" if !a.is_empty() => h.print_checked(&a[0], false)?,
"prin1" if !a.is_empty() => h.print_checked(&a[0], true)?,
"print" if !a.is_empty() => format!("\n{}\n", h.print_checked(&a[0], true)?),
"terpri" => "\n".to_string(),
"write-char" if !a.is_empty() => {
let c = write_char_code(h, &a[0])?;
char::from_u32(c).unwrap_or('\u{fffd}').to_string()
}
_ => return Ok(None),
}))
}
fn backquote_process_fn(h: &mut ElispHost, a: &[Value]) -> R {
let level = match a.get(1) {
Some(Value::Int(n)) => *n,
Some(v) if !is_nil(v) => return Err(h.signal_wrong_type("number-or-marker-p", v)),
_ => 0,
};
let (tag, code) = crate::backquote::process(h, &a[0], level)?;
Ok(h.cons(Value::Int(tag as i64), code))
}
fn write_char_code(h: &mut ElispHost, v: &Value) -> Result<u32, String> {
match v {
Value::Int(n) => Ok(*n as u32),
_ => Err(h.signal_wrong_type("fixnump", v)),
}
}
fn at_bol(text: &[char], begv: usize, pos: usize) -> bool {
pos <= begv || text[pos - 2] == '\n'
}
fn terpri(h: &mut ElispHost, a: &[Value]) -> R {
let dest = print_dest(h, a.first())?;
let ensure = a.get(1).is_some_and(|v| !is_nil(v));
let needed = if !ensure {
true
} else {
match &dest {
PrintDest::Stdout => h.stdout_last != '\n',
PrintDest::Buffer(idx) => {
let b = &h.buffers[*idx];
!at_bol(&b.text, b.begv, b.point)
}
PrintDest::Marker(mv) => match h.obj(mv) {
Some(Obj::Marker(m)) => {
let md = m.borrow();
let b = &h.buffers[md.buffer.expect("checked in print_dest")];
!at_bol(&b.text, b.begv, md.pos)
}
_ => true,
},
PrintDest::Function(f) => {
let f = f.clone();
return Err(h.signal_error_arg("Unsupported function argument", &f));
}
}
};
if needed {
print_to(h, &dest, "\n")?;
}
Ok(nil_or(needed))
}
fn print_fn(h: &mut ElispHost, a: &[Value]) -> R {
let dest = print_dest(h, a.get(1))?;
let s = h.print_checked(&a[0], true)?;
print_to(h, &dest, &format!("\n{s}\n"))?;
Ok(a[0].clone())
}
fn write_char_fn(h: &mut ElispHost, a: &[Value]) -> R {
let c = write_char_code(h, &a[0])?;
let dest = print_dest(h, a.get(1))?;
print_to(
h,
&dest,
&char::from_u32(c).unwrap_or('\u{fffd}').to_string(),
)?;
Ok(a[0].clone())
}
fn prin1_to_string(h: &mut ElispHost, a: &[Value]) -> R {
let readable = a.get(1).is_none_or(is_nil);
Ok(h.new_string(h.print_checked(&a[0], readable)?))
}
fn throw_fn(h: &mut ElispHost, a: &[Value]) -> R {
let tag = a[0].clone();
let val = a.get(1).cloned().unwrap_or(Value::Undef);
let tags = h.catch_tags.clone();
if tags.iter().any(|t| h.values_eq(t, &tag)) {
h.pending_throw = Some((tag, val));
Err("--throw--".to_string())
} else {
let sym = h.intern("no-catch");
let data = h.list_from(vec![tag, val]);
let display = h.print(&data, true);
let obj = h.cons(sym, data);
let msg = format!("no-catch: {display}");
h.set_pending_error(&msg, obj);
Err(msg)
}
}
fn curve_quotes(h: &ElispHost, fmt: &str) -> String {
let style = h
.find_symbol("text-quoting-style")
.and_then(|s| match h.obj(&s) {
Some(Obj::Symbol(d)) => d.value.clone(),
_ => None,
})
.and_then(|v| h.sym_name(&v));
fmt.chars()
.map(|c| match (c, style.as_deref()) {
(_, Some("grave")) => c,
('`', Some("straight")) => '\'',
(_, Some("straight")) => c,
('`', _) => '\u{2018}',
('\'', _) => '\u{2019}',
_ => c,
})
.collect()
}
fn el_format_message(h: &mut ElispHost, a: &[Value]) -> Result<String, String> {
match a
.first()
.and_then(|v| h.str_text(v))
.map(|t| curve_quotes(h, t))
{
Some(curved) => {
let mut args = a.to_vec();
args[0] = h.new_string(curved);
el_format(h, &args)
}
None => el_format(h, a),
}
}
fn error_fn(h: &mut ElispHost, a: &[Value]) -> R {
let msg = el_format_message(h, a)?;
let esym = h.intern("error");
let mstr = h.new_string(msg.clone());
let data = h.list_from(vec![mstr]);
let obj = h.cons(esym, data);
let full = format!("error: {msg}");
h.set_pending_error(&full, obj);
Err(full)
}
fn user_error_fn(h: &mut ElispHost, a: &[Value]) -> R {
let msg = el_format_message(h, a)?;
let esym = h.intern("user-error");
let mstr = h.new_string(msg.clone());
let data = h.list_from(vec![mstr]);
let obj = h.cons(esym, data);
let full = format!("user-error: {msg}");
h.set_pending_error(&full, obj);
Err(full)
}
fn symbol_get(h: &mut ElispHost, sym: &Value, prop: &str) -> Value {
let table_sym = h.intern("symbol-plist--table");
let Ok(table) = h.get_dynamic_value(&table_sym) else {
return Value::Undef;
};
let plist = gethash(h, &[sym.clone(), table]).unwrap_or(Value::Undef);
let prop = h.intern(prop);
h.plist_get_eq(&plist, &prop)
}
fn signal_fn(h: &mut ElispHost, a: &[Value]) -> R {
let (mut symv, mut data) = (a[0].clone(), a.get(1).cloned().unwrap_or(Value::Undef));
let whole_error = match h.obj(&symv) {
Some(Obj::Cons(car, cdr)) if is_nil(&data) => Some((car.clone(), cdr.clone())),
_ => None,
};
if let Some((car, cdr)) = whole_error {
symv = car;
data = cdr;
} else if is_nil(&symv) {
match h.obj(&data) {
Some(Obj::Cons(car, cdr)) => {
let (car, cdr) = (car.clone(), cdr.clone());
symv = car;
data = cdr;
}
_ => symv = h.intern("error"),
}
}
let is_symbol =
matches!(symv, Value::Bool(true)) || matches!(h.obj(&symv), Some(Obj::Symbol(_)));
if !is_symbol {
return Err(format!(
"wrong-type-argument: symbolp {}",
h.print(&symv, true)
));
}
let conditions = symbol_get(h, &symv, "error-conditions");
if is_nil(&conditions) {
let msg = h.new_string("Invalid error symbol");
let err = h.intern("error");
let obj = h.list_from(vec![err, msg, symv.clone()]);
let text = format!("error: Invalid error symbol: {}", h.print(&symv, true));
h.set_pending_error(&text, obj);
return Err(text);
}
if !matches!(h.obj(&conditions), Some(Obj::Cons(..))) {
return Err(format!(
"wrong-type-argument: listp {}",
h.print(&conditions, true)
));
}
let sym = h.sym_name(&symv).unwrap_or_else(|| "error".to_string());
let display = h.print(&data, true);
let obj = h.cons(symv, data);
let msg = format!("{sym}: {display}");
h.set_pending_error(&msg, obj);
Err(msg)
}
fn concat_fn(h: &mut ElispHost, a: &[Value]) -> R {
let mut out = String::new();
let mut pieces: Vec<(Option<std::sync::Arc<String>>, usize, usize)> = Vec::new();
let mut carried = 0usize;
let push_char = |h: &ElispHost, out: &mut String, it: &Value| -> Result<(), String> {
match it {
Value::Int(c) if (0..=0x3F_FFFF).contains(c) => {
out.push(char::from_u32(*c as u32).unwrap_or('\u{FFFD}'));
Ok(())
}
_ => Err(format!(
"wrong-type-argument: characterp {}",
h.print(it, true)
)),
}
};
for v in a {
if is_nil(v) {
continue;
}
match h.str_arc(v) {
Some(s) => {
let n = s.chars().count();
out.push_str(&s);
pieces.push((Some(s), 0, n));
carried += n;
}
None => match h.obj(v) {
Some(Obj::Vector(items)) => {
for it in items.clone() {
push_char(h, &mut out, &it)?;
}
}
Some(Obj::Cons(..)) => {
for it in h.seq_vec_checked(v)? {
push_char(h, &mut out, &it)?;
}
}
_ => {
return Err(format!(
"wrong-type-argument: sequencep {}",
h.print(v, true)
))
}
},
}
let so_far = out.chars().count();
if so_far > carried {
pieces.push((None, 0, so_far - carried));
carried = so_far;
}
}
let (out, key) = h.new_string_keyed(out);
h.string_copy_props(&key, &pieces);
Ok(out)
}
struct FmtSpec {
left: bool,
zero: bool,
plus: bool,
space: bool,
alt: bool,
width: usize,
prec: Option<usize>,
conv: char,
}
enum IntArg {
Fixnum(BigInt),
FloatD(f64),
Bignum(BigInt),
}
fn format_integer(arg: IntArg, spec: &FmtSpec) -> String {
use num_traits::{Signed, Zero};
let conv = spec.conv;
let sharp = spec.alt && !matches!(conv, 'd' | 'i');
let plus = spec.plus;
let space = spec.space && !plus;
let zero_flag = spec.zero && !spec.left && spec.prec.is_none();
let radix = match conv {
'o' => 8,
'x' | 'X' => 16,
_ => 10,
};
let digits = |n: &BigInt| {
let s = n.abs().to_str_radix(radix);
if conv == 'X' {
s.to_uppercase()
} else {
s
}
};
let sign_char = |negative: bool| {
if negative {
"-"
} else if plus {
"+"
} else if space {
" "
} else {
""
}
};
let printf_digits = |n: &BigInt| match spec.prec {
Some(0) if n.is_zero() => String::new(),
Some(p) => {
let d = digits(n);
format!("{}{d}", "0".repeat(p.saturating_sub(d.len())))
}
None => digits(n),
};
let mut prefix = String::new();
let (p, excess) = match arg {
IntArg::Fixnum(n) => {
let mut d = printf_digits(&n);
if sharp && conv == 'o' && !d.starts_with('0') {
d.insert(0, '0');
}
if sharp && radix == 16 && !n.is_zero() {
d.insert_str(0, if conv == 'X' { "0X" } else { "0x" });
}
(format!("{}{d}", sign_char(n.is_negative())), 0)
}
IntArg::FloatD(x) => {
let t = x.trunc();
let n = <BigInt as num_traits::FromPrimitive>::from_f64(t).unwrap_or_default();
let p = format!("{}{}", sign_char(n.is_negative()), digits(&n));
let signedp = usize::from(!p.starts_with(|c: char| c.is_ascii_digit()));
let len = p.len() - signedp;
(p, spec.prec.map_or(0, |pr| pr.saturating_sub(len)))
}
IntArg::Bignum(n) => {
let negative = n.is_negative();
let p = format!("{}{}", if negative { "-" } else { "" }, digits(&n));
if !negative && (plus || space) {
prefix.push(if plus { '+' } else { ' ' });
}
if sharp && radix == 16 {
prefix.push('0');
prefix.push(conv);
}
let len = p.len();
(p, spec.prec.map_or(0, |pr| pr.saturating_sub(len)))
}
};
let pb = p.as_bytes();
let mut leading_zeros = excess;
let numwidth = prefix.len() + p.len() + excess;
let mut padding = spec.width.saturating_sub(numwidth);
let signedp = usize::from(matches!(pb.first(), Some(b'-' | b'+' | b' ')));
let beglen = signedp
+ if pb.get(signedp) == Some(&b'0') && pb.get(signedp + 1) == Some(&(conv as u8)) {
2
} else {
0
};
if zero_flag && pb.get(beglen).is_some_and(u8::is_ascii_hexdigit) {
leading_zeros += padding;
padding = 0;
}
if leading_zeros == 0 && sharp && conv == 'o' && pb.get(beglen) != Some(&b'0') {
leading_zeros += 1;
padding -= usize::from(padding != 0);
}
let (lead, trail) = if spec.left {
(0, padding)
} else {
(padding, 0)
};
format!(
"{}{}{prefix}{}{}{}",
" ".repeat(lead),
&p[..beglen],
"0".repeat(leading_zeros),
&p[beglen..],
" ".repeat(trail)
)
}
const FMT_PREC_CAP: usize = 65535;
const FMT_G_CAP: usize = 1100;
fn format_fixed(v: f64, prec: usize) -> String {
if prec <= FMT_PREC_CAP {
format!("{:.*}", prec, v)
} else {
let mut s = format!("{:.*}", FMT_PREC_CAP, v);
s.push_str(&"0".repeat(prec - FMT_PREC_CAP));
s
}
}
fn format_g(v: f64, prec: usize, alt: bool) -> String {
let p = prec.clamp(1, FMT_G_CAP);
let strip = |mant: &str| -> String {
if mant.contains('.') {
mant.trim_end_matches('0').trim_end_matches('.').to_string()
} else {
mant.to_string()
}
};
let x: i32 = if v == 0.0 {
0
} else {
let es = format!("{:.*e}", p - 1, v);
es[es.find('e').unwrap() + 1..].parse().unwrap_or(0)
};
if x >= -4 && x < p as i32 {
let prec_f = (p as i32 - 1 - x).max(0) as usize;
let s = format!("{:.*}", prec_f, v);
if alt {
s
} else {
strip(&s)
}
} else {
let body = format_e(v, p - 1);
if alt {
body
} else {
match body.find('e') {
Some(ep) => format!("{}{}", strip(&body[..ep]), &body[ep..]),
None => strip(&body),
}
}
}
}
fn with_decimal_point(s: String) -> String {
if s.contains('.') {
return s;
}
match s.find('e') {
Some(ep) => format!("{}.{}", &s[..ep], &s[ep..]),
None => s + ".",
}
}
fn format_e(v: f64, prec: usize) -> String {
let s = if prec <= FMT_PREC_CAP {
format!("{:.*e}", prec, v)
} else {
let capped = format!("{:.*e}", FMT_PREC_CAP, v);
match capped.find('e') {
Some(epos) => {
let mut m = capped[..epos].to_string();
m.push_str(&"0".repeat(prec - FMT_PREC_CAP));
m.push_str(&capped[epos..]);
m
}
None => capped,
}
};
match s.find('e') {
Some(epos) => {
let (mant, rest) = s.split_at(epos);
let exp = &rest[1..];
let (sign, digits) = match exp.strip_prefix('-') {
Some(d) => ('-', d),
None => ('+', exp.strip_prefix('+').unwrap_or(exp)),
};
format!("{mant}e{sign}{digits:0>2}")
}
None => s,
}
}
fn apply_sign(body: String, spec: &FmtSpec) -> String {
if body.starts_with('-') {
body
} else if spec.plus {
format!("+{body}")
} else if spec.space {
format!(" {body}")
} else {
body
}
}
pub fn char_display_width(c: u32) -> usize {
match c {
0x0A => 0, 0x09 => 8, 0..=0x1F | 0x7F => 2, 0x0300..=0x036F => 0, 0x200B..=0x200F => 0, 0x1100..=0x115F | 0x2E80..=0x303E | 0x3041..=0x33FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xA000..=0xA4CF | 0xAC00..=0xD7A3 | 0xF900..=0xFAFF | 0xFF00..=0xFF60 | 0xFFE0..=0xFFE6
| 0x1F300..=0x1F64F | 0x1F900..=0x1F9FF | 0x1FA70..=0x1FAFF | 0x20000..=0x3FFFD => 2, _ => 1,
}
}
pub fn string_display_width(s: &str) -> usize {
s.chars().map(|c| char_display_width(c as u32)).sum()
}
fn truncate_to_columns(s: &str, cols: usize) -> String {
let mut used = 0;
let mut out = String::new();
for c in s.chars() {
let w = char_display_width(c as u32);
if used + w > cols {
break;
}
used += w;
out.push(c);
}
out
}
fn pad(body: String, spec: &FmtSpec) -> String {
let body_cols = string_display_width(&body);
if body_cols >= spec.width {
return body;
}
let fill = spec.width - body_cols;
if spec.left {
format!("{body}{}", " ".repeat(fill))
} else if spec.zero && matches!(spec.conv, 'd' | 'o' | 'x' | 'X' | 'e' | 'f' | 'g') {
let mut p = 0;
if matches!(body.chars().next(), Some('-' | '+' | ' ')) {
p = 1;
}
if body[p..].starts_with("0x") || body[p..].starts_with("0X") {
p += 2;
}
format!("{}{}{}", &body[..p], "0".repeat(fill), &body[p..])
} else {
format!("{}{body}", " ".repeat(fill))
}
}
struct FmtField {
fbeg: usize,
fend: usize,
fstart: usize,
text_start: usize,
out_end: usize,
carries: Option<std::sync::Arc<String>>,
}
fn el_format(h: &ElispHost, a: &[Value]) -> Result<String, String> {
el_format_pieces(h, a).map(|(s, _)| s)
}
fn el_format_pieces(h: &ElispHost, a: &[Value]) -> Result<(String, Vec<FmtField>), String> {
let fmt = match h.str_text(&a[0]) {
Some(s) => s.to_string(),
None => {
return Err(format!(
"wrong-type-argument: stringp {}",
h.print(&a[0], true)
))
}
};
let mut fields: Vec<FmtField> = Vec::new();
let fmt_len = fmt.chars().count();
let mut out = String::new();
let mut ai = 1;
let mut chars = fmt.chars().peekable();
while let Some(c) = chars.next() {
if c != '%' {
out.push(c);
continue;
}
let fbeg = fmt_len - chars.clone().count() - 1;
if chars.peek() == Some(&'%') {
chars.next();
let at = out.chars().count();
out.push('%');
fields.push(FmtField {
fbeg,
fend: fbeg + 2,
fstart: at,
text_start: at,
out_end: at + 1,
carries: None,
});
continue;
}
let mut field: Option<usize> = None;
let mut width = 0usize;
let mut width_done = false;
if matches!(chars.peek(), Some('1'..='9')) {
let mut num = 0usize;
while let Some(&d) = chars.peek() {
if d.is_ascii_digit() {
num = num * 10 + (d as usize - '0' as usize);
chars.next();
} else {
break;
}
}
if chars.peek() == Some(&'$') {
chars.next();
field = Some(num);
} else {
width = num;
width_done = true;
}
}
let (mut left, mut zero, mut plus, mut space, mut alt) =
(false, false, false, false, false);
if !width_done {
while let Some(&f) = chars.peek() {
match f {
'-' => left = true,
'0' => zero = true,
'+' => plus = true,
' ' => space = true,
'#' => alt = true,
_ => break,
}
chars.next();
}
}
if !width_done {
while let Some(&d) = chars.peek() {
if d.is_ascii_digit() {
width = width * 10 + (d as usize - '0' as usize);
chars.next();
} else {
break;
}
}
}
let mut prec = None;
if chars.peek() == Some(&'.') {
chars.next();
let mut p = 0usize;
while let Some(&d) = chars.peek() {
if d.is_ascii_digit() {
p = p * 10 + (d as usize - '0' as usize);
chars.next();
} else {
break;
}
}
prec = Some(p);
}
let Some(conv) = chars.next() else {
return Err("Format string ends in middle of format specifier".to_string());
};
if conv == '%' {
if let Some(f) = field {
ai = f;
}
let at = out.chars().count();
out.push('%');
fields.push(FmtField {
fbeg,
fend: fmt_len - chars.clone().count(),
fstart: at,
text_start: at,
out_end: at + 1,
carries: None,
});
continue;
}
let mut spec = FmtSpec {
left,
zero,
plus,
space,
alt,
width,
prec,
conv,
};
const NOT_ENOUGH: &str = "Not enough arguments for format string";
const BAD_TYPE: &str = "Format specifier doesn\u{2019}t match argument type";
let idx = field.unwrap_or(ai);
let numf = |idx: usize| -> Result<(i64, f64, bool), String> {
let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
as_num(h, arg).map_err(|_| BAD_TYPE.to_string())
};
let bigf = |idx: usize| -> Result<BigInt, String> {
let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
match arg {
Value::Float(f) => <BigInt as num_traits::FromPrimitive>::from_f64(f.trunc())
.ok_or_else(|| BAD_TYPE.to_string()),
_ => as_int_exact(h, arg).map_err(|_| BAD_TYPE.to_string()),
}
};
let int_arg = |idx: usize| -> Result<IntArg, String> {
let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
Ok(match arg {
Value::Float(f) if matches!(conv, 'd' | 'i') => IntArg::FloatD(*f),
Value::Float(f) if f.abs() < 18446744073709551616.0 => IntArg::Fixnum(bigf(idx)?),
Value::Float(_) => IntArg::Bignum(bigf(idx)?),
_ if h.is_bignum(arg) => IntArg::Bignum(bigf(idx)?),
_ => IntArg::Fixnum(bigf(idx)?),
})
};
let carries: Option<std::sync::Arc<String>> = match conv {
's' => a.get(idx).and_then(|v| h.str_arc(v)),
_ => None,
};
let body = match conv {
's' => {
let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
let s = h.print_checked(arg, false)?;
match spec.prec {
Some(p) => truncate_to_columns(&s, p),
None => s,
}
}
'S' => {
let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
let s = h.print_checked(arg, true)?;
match spec.prec {
Some(p) => truncate_to_columns(&s, p),
None => s,
}
}
'd' | 'i' => match a.get(idx) {
Some(Value::Float(f)) if !f.is_finite() => {
spec.zero = false;
if f.is_nan() {
"nan".to_string()
} else if *f < 0.0 {
"-inf".to_string()
} else {
apply_sign("inf".to_string(), &spec)
}
}
_ => format_integer(int_arg(idx)?, &spec),
},
'o' | 'x' | 'X' => {
if let Some(Value::Float(f)) = a.get(idx) {
if !f.is_finite() {
return Err("overflow-error".to_string());
}
}
format_integer(int_arg(idx)?, &spec)
}
'c' => {
let (i, _, is_float) = numf(idx)?;
if is_float {
return Err(BAD_TYPE.to_string());
}
if !(0..=0x3F_FFFF).contains(&i) {
return Err(format!("wrong-type-argument: characterp {i}"));
}
char::from_u32(i as u32)
.map(String::from)
.unwrap_or_default()
}
'e' | 'f' | 'g' => {
let v = numf(idx)?.1;
if v.is_finite() {
let raw = match conv {
'e' => format_e(v, spec.prec.unwrap_or(6)),
'f' => format_fixed(v, spec.prec.unwrap_or(6)),
_ => format_g(v, spec.prec.unwrap_or(6), spec.alt),
};
let raw = if spec.alt {
with_decimal_point(raw)
} else {
raw
};
apply_sign(raw, &spec)
} else {
spec.zero = false;
if v.is_nan() {
"nan".to_string()
} else if v < 0.0 {
"-inf".to_string()
} else {
apply_sign("inf".to_string(), &spec)
}
}
}
other => {
if a.get(idx).is_none() {
return Err(NOT_ENOUGH.to_string());
}
return Err(format!("Invalid format operation %{other}"));
}
};
ai = idx + 1;
let out_start = out.chars().count();
let body_len = body.chars().count();
let padded = pad(body, &spec);
out.push_str(&padded);
let pad_len = padded.chars().count() - body_len;
let text_start = if spec.left {
out_start
} else {
out_start + pad_len
};
fields.push(FmtField {
fbeg,
fend: fmt_len - chars.clone().count(),
fstart: out_start,
text_start,
out_end: out_start + body_len + pad_len,
carries: carries.clone(),
});
}
Ok((out, fields))
}
fn format_position(fields: &[FmtField], p: usize) -> usize {
let (mut out, mut fpos) = (0usize, 0usize);
for f in fields {
if p <= f.fbeg {
return out + (p - fpos);
}
out = f.out_end;
fpos = f.fend;
if p < f.fend {
return out;
}
}
out + (p - fpos)
}
fn apply_format_props(
h: &mut ElispHost,
key: &std::sync::Arc<String>,
fmt: &Value,
fields: &[FmtField],
) {
let replace = crate::textprop::SetType::Replace;
let mut field_start = false;
if let Some(farc) = h.str_arc(fmt) {
let intervals = h.string_intervals(&farc);
field_start = !intervals.is_empty();
for (rs, re, plist) in intervals {
if is_nil(&plist) {
continue;
}
let (os, oe) = (format_position(fields, rs), format_position(fields, re));
if oe > os {
let pairs = each_prop_pair(h, &plist);
h.string_add_props(key, os, oe, &pairs, replace);
}
}
}
for f in fields {
let Some(src) = &f.carries else { continue };
let len = src.chars().count();
let start = if field_start { f.fstart } else { f.text_start };
let new_len = f.out_end - start;
for (rs, re, plist) in h.string_intervals(src) {
if is_nil(&plist) || rs >= new_len {
continue;
}
let mut end = re;
if (end == len && end != new_len) || end > new_len {
end = new_len;
}
let pairs = each_prop_pair(h, &plist);
h.string_add_props(key, start + rs, start + end, &pairs, replace);
}
}
}
fn format_fn(h: &mut ElispHost, a: &[Value]) -> R {
if let Some(fmt) = h.str_text(&a[0]) {
if !fmt.contains('%') {
return Ok(a[0].clone());
}
if fmt == "%s" && a.len() == 2 && h.str_text(&a[1]).is_some() {
let plain = h
.str_arc(&a[0])
.is_none_or(|f| h.string_intervals(&f).is_empty());
if plain {
return Ok(a[1].clone());
}
}
}
let (s, fields) = el_format_pieces(h, a)?;
let (out, key) = h.new_string_keyed(s);
apply_format_props(h, &key, &a[0], &fields);
Ok(out)
}
fn message_fn(h: &mut ElispHost, a: &[Value]) -> R {
let blank = match a.first() {
Some(v) if is_nil(v) => true,
Some(v) => h.str_text(v).is_some_and(str::is_empty),
None => false,
};
let text = if blank {
None
} else {
Some(el_format_message(h, a)?)
};
if h.need_newline {
h.need_newline = false;
eprintln!();
}
match text {
Some(s) => {
eprintln!("{s}");
Ok(h.new_string(s))
}
None => {
eprintln!();
Ok(a.first().cloned().unwrap_or(Value::Undef))
}
}
}
fn princ_fn(h: &mut ElispHost, a: &[Value]) -> R {
let dest = print_dest(h, a.get(1))?;
let s = h.print_checked(&a[0], false)?;
print_to(h, &dest, &s)?;
Ok(a[0].clone())
}
fn prin1_fn(h: &mut ElispHost, a: &[Value]) -> R {
let dest = print_dest(h, a.get(1))?;
let s = h.print_checked(&a[0], true)?;
print_to(h, &dest, &s)?;
Ok(a[0].clone())
}
fn number_to_string(h: &mut ElispHost, a: &[Value]) -> R {
as_number_p(h, &a[0], false)?;
Ok(h.new_string(h.print(&a[0], false)))
}
fn hash_eq(h: &ElispHost, test: u8, a: &Value, b: &Value) -> bool {
match test {
2 => el_equal(h, a, b),
1 => el_eql(h, a, b),
_ => el_eq(h, a, b),
}
}
const HASH_DEPTH_LIMIT: u32 = 8;
fn hash_key(h: &ElispHost, test: u8, v: &Value) -> u64 {
use std::hash::Hasher;
let mut st = std::collections::hash_map::DefaultHasher::new();
hash_into(h, test, v, 0, &mut st);
st.finish()
}
fn hash_into(h: &ElispHost, test: u8, v: &Value, depth: u32, st: &mut impl std::hash::Hasher) {
use std::hash::Hash;
if is_nil(v) {
st.write_u8(0);
return;
}
if depth > HASH_DEPTH_LIMIT {
st.write_u8(0xFF);
return;
}
match v {
Value::Int(n) => {
st.write_u8(1);
st.write_i64(*n);
}
Value::Float(f) => {
st.write_u8(2);
st.write_u64(f.to_bits());
}
Value::Bool(b) => {
st.write_u8(3);
st.write_u8(u8::from(*b));
}
Value::Str(txt) => {
st.write_u8(4);
txt.as_str().hash(st);
}
Value::Obj(_) if h.is_string(v) => {
st.write_u8(4);
h.str_text(v).unwrap_or_default().hash(st);
}
Value::Obj(id) => match h.arena.get(*id as usize) {
Some(Obj::Bignum(b)) => {
st.write_u8(5);
b.to_string().hash(st);
}
Some(Obj::Cons(a, d)) if test == 2 => {
st.write_u8(6);
hash_into(h, test, a, depth + 1, st);
hash_into(h, test, d, depth + 1, st);
}
Some(Obj::Vector(items)) | Some(Obj::Record(items)) if test == 2 => {
st.write_u8(7);
st.write_usize(items.len());
for it in items.iter() {
hash_into(h, test, it, depth + 1, st);
}
}
Some(Obj::BoolVector(bits)) if test == 2 => {
st.write_u8(8);
bits.hash(st);
}
Some(Obj::Marker(_)) if test == 2 => st.write_u8(9),
Some(Obj::Closure { .. }) if test == 2 => {
st.write_u8(12);
if let Some((is_macro, dynamic, arglist, body, captures)) = h.closure_parts(v) {
st.write_u8(u8::from(is_macro));
st.write_u8(u8::from(dynamic));
hash_into(h, test, &arglist, depth + 1, st);
st.write_usize(body.len());
for form in &body {
hash_into(h, test, form, depth + 1, st);
}
st.write_usize(captures.len());
for (sym, val) in &captures {
st.write_u32(*sym);
if let Some(val) = val {
hash_into(h, test, val, depth + 1, st);
}
}
}
}
_ => {
st.write_u8(10);
st.write_u32(*id);
}
},
_ => st.write_u8(11),
}
}
pub(crate) fn ht_ref<'a>(h: &'a ElispHost, v: &Value) -> Result<&'a ElHashTable, String> {
match h.obj(v) {
Some(Obj::HashTable(t)) => Ok(t),
_ => Err(format!(
"wrong-type-argument: hash-table-p {}",
h.print(v, true)
)),
}
}
fn ht_mut<'a>(h: &'a mut ElispHost, v: &Value) -> Option<&'a mut ElHashTable> {
match v {
Value::Obj(id) => match h.arena.get_mut(*id as usize) {
Some(Obj::HashTable(t)) => Some(t),
_ => None,
},
_ => None,
}
}
fn ht_ensure_index(h: &mut ElispHost, v: &Value) -> Result<(), String> {
let t = ht_ref(h, v)?;
if !t.needs_index() {
return Ok(());
}
let test = t.test;
let keys: Vec<(u32, Value)> = t
.slots
.iter()
.enumerate()
.filter_map(|(i, slot)| slot.as_ref().map(|(k, _)| (i as u32, k.clone())))
.collect();
let hashes: Vec<(u32, u64)> = keys
.iter()
.map(|(i, k)| (*i, hash_key(h, test, k)))
.collect();
if let Some(t) = ht_mut(h, v) {
t.reindex(&hashes);
}
Ok(())
}
fn ht_find(h: &mut ElispHost, table: &Value, key: &Value) -> Result<(u64, Option<u32>), String> {
ht_ensure_index(h, table)?;
let t = ht_ref(h, table)?;
let test = t.test;
let hk = hash_key(h, test, key);
let t = ht_ref(h, table)?;
let slot = t
.candidates(hk)
.iter()
.copied()
.find(|&i| t.key_at(i).is_some_and(|k| hash_eq(h, test, key, k)));
Ok((hk, slot))
}
pub(crate) struct HashTableKeywords {
pub test: Option<Value>,
pub size: Option<Value>,
pub weakness: Option<Value>,
}
pub(crate) fn hash_table_keywords(
h: &mut ElispHost,
a: &[Value],
) -> Result<HashTableKeywords, String> {
if a.len() % 2 == 1 {
return Err("error: Odd number of arguments".to_string());
}
let mut kw = HashTableKeywords {
test: None,
size: None,
weakness: None,
};
let mut bad: Option<Value> = None;
for pair in a.chunks(2) {
let name = h.sym_name(&pair[0]);
let slot = match name.as_deref() {
Some(":test") => &mut kw.test,
Some(":size") => &mut kw.size,
Some(":weakness") => &mut kw.weakness,
Some(":purecopy") | Some(":rehash-size") | Some(":rehash-threshold") => continue,
_ => {
bad = Some(pair[0].clone());
continue;
}
};
if slot.is_none() {
*slot = Some(pair[1].clone());
}
}
if let Some(k) = bad {
return Err(h.signal_error_arg("Invalid keyword argument", &k));
}
Ok(kw)
}
pub(crate) fn make_hash_table_with(
h: &mut ElispHost,
a: &[Value],
user: Option<(Value, Value, Value)>,
) -> R {
let kw = hash_table_keywords(h, a)?;
let test = match &kw.test {
None => 1u8, Some(v) => match h.sym_name(v).as_deref() {
Some("eq") => 0,
Some("equal") => 2,
Some(other) if other != "eql" && user.is_some() => 3,
_ => 1,
},
};
let size = match &kw.size {
None => 0usize,
Some(v) => match v {
v if crate::host::el_nil(v) => 0,
Value::Int(n) if *n >= 0 => *n as usize,
v => {
let v = v.clone();
return Err(h.signal_error_arg("Invalid hash table size", &v));
}
},
};
let weakness = match &kw.weakness {
None => Value::Undef,
Some(w) => {
let w = w.clone();
hash_table_weakness_arg(h, &w)?
}
};
let mut t = ElHashTable::new(test, size, weakness);
if test == 3 {
t.user_test = user;
}
Ok(h.alloc(Obj::HashTable(t)))
}
pub(crate) fn hash_table_weakness_arg(h: &mut ElispHost, w: &Value) -> R {
if matches!(w, Value::Bool(true)) {
return Ok(h.intern("key-and-value"));
}
let named = h.sym_name(w);
let ok = crate::host::el_nil(w)
|| matches!(
named.as_deref(),
Some("key") | Some("value") | Some("key-or-value") | Some("key-and-value")
);
if !ok {
return Err(h.signal_error_arg("Invalid hash table weakness", w));
}
Ok(w.clone())
}
pub(crate) fn ht_user_test(table: &Value) -> Option<(Value, Value, Value)> {
crate::host::with_host(|h| ht_ref(h, table).ok().and_then(|t| t.user_test.clone()))
}
pub(crate) fn ht_find_user(
table: &Value,
key: &Value,
testfn: &Value,
hashfn: &Value,
) -> Result<(u64, Option<u32>), String> {
use crate::host::{call_function, with_host};
let hv = call_function(hashfn, std::slice::from_ref(key))?;
let hk = with_host(|h| hash_key(h, 2, &hv));
let cands: Vec<(u32, Value)> = with_host(|h| {
let t = ht_ref(h, table)?;
Ok::<_, String>(
t.candidates(hk)
.iter()
.filter_map(|&i| t.key_at(i).map(|k| (i, k.clone())))
.collect(),
)
})?;
for (i, k) in cands {
if crate::host::el_truthy(&call_function(testfn, &[key.clone(), k])?) {
return Ok((hk, Some(i)));
}
}
Ok((hk, None))
}
pub(crate) fn gethash_user(a: &[Value], t: &(Value, Value, Value)) -> R {
let (_, slot) = ht_find_user(&a[1], &a[0], &t.1, &t.2)?;
crate::host::with_host(|h| match slot {
Some(i) => Ok(ht_ref(h, &a[1])?
.value_at(i)
.cloned()
.unwrap_or(Value::Undef)),
None => Ok(a.get(2).cloned().unwrap_or(Value::Undef)),
})
}
pub(crate) fn puthash_user(a: &[Value], t: &(Value, Value, Value)) -> R {
let (hk, slot) = ht_find_user(&a[2], &a[0], &t.1, &t.2)?;
crate::host::with_host(|h| {
if let Some(tbl) = ht_mut(h, &a[2]) {
match slot {
Some(i) => tbl.set_value_at(i, a[1].clone()),
None => tbl.insert(hk, a[0].clone(), a[1].clone()),
}
}
});
Ok(a[1].clone())
}
pub(crate) fn remhash_user(a: &[Value], t: &(Value, Value, Value)) -> R {
let (hk, slot) = ht_find_user(&a[1], &a[0], &t.1, &t.2)?;
crate::host::with_host(|h| {
if let (Some(i), Some(tbl)) = (slot, ht_mut(h, &a[1])) {
tbl.remove(hk, i);
}
});
Ok(Value::Undef)
}
pub(crate) fn gethash(h: &mut ElispHost, a: &[Value]) -> R {
let (_, slot) = ht_find(h, &a[1], &a[0])?;
match slot {
Some(i) => Ok(ht_ref(h, &a[1])?
.value_at(i)
.cloned()
.unwrap_or(Value::Undef)),
None => Ok(a.get(2).cloned().unwrap_or(Value::Undef)),
}
}
pub(crate) fn puthash(h: &mut ElispHost, a: &[Value]) -> R {
let (hk, slot) = ht_find(h, &a[2], &a[0])?;
if let Some(t) = ht_mut(h, &a[2]) {
match slot {
Some(i) => t.set_value_at(i, a[1].clone()),
None => t.insert(hk, a[0].clone(), a[1].clone()),
}
}
Ok(a[1].clone())
}
pub(crate) fn remhash(h: &mut ElispHost, a: &[Value]) -> R {
let (hk, slot) = ht_find(h, &a[1], &a[0])?;
if let (Some(i), Some(t)) = (slot, ht_mut(h, &a[1])) {
t.remove(hk, i);
}
Ok(Value::Undef) }
fn clrhash(h: &mut ElispHost, a: &[Value]) -> R {
if let Some(t) = ht_mut(h, &a[0]) {
t.clear();
}
Ok(a[0].clone())
}
fn hash_table_count(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Int(ht_ref(h, &a[0])?.count() as i64))
}
fn hash_table_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::HashTable(_)))))
}
fn hash_table_test(h: &mut ElispHost, a: &[Value]) -> R {
let t = ht_ref(h, &a[0])?;
if let Some((name, _, _)) = &t.user_test {
return Ok(name.clone());
}
let name = match t.test {
0 => "eq",
1 => "eql",
_ => "equal",
};
Ok(h.intern(name))
}
fn hash_table_size(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Int(ht_ref(h, &a[0])?.size as i64))
}
fn hash_table_weakness(h: &mut ElispHost, a: &[Value]) -> R {
Ok(ht_ref(h, &a[0])?.weakness.clone())
}
fn hash_table_keys(h: &mut ElispHost, a: &[Value]) -> R {
let mut keys: Vec<Value> = ht_ref(h, &a[0])?.pairs().map(|(k, _)| k.clone()).collect();
keys.reverse();
Ok(h.list_from(keys))
}
fn hash_table_values(h: &mut ElispHost, a: &[Value]) -> R {
let mut vals: Vec<Value> = ht_ref(h, &a[0])?.pairs().map(|(_, v)| v.clone()).collect();
vals.reverse();
Ok(h.list_from(vals))
}
fn copy_hash_table(h: &mut ElispHost, a: &[Value]) -> R {
ht_ensure_index(h, &a[0])?;
let copy = ht_ref(h, &a[0])?.clone();
Ok(h.alloc(Obj::HashTable(copy)))
}
fn copy_string(h: &mut ElispHost, a: &[Value]) -> R {
let Some(text) = h.str_text(&a[0]).map(str::to_string) else {
return Err(format!(
"wrong-type-argument: stringp {}",
h.print(&a[0], true)
));
};
let src = h.str_arc(&a[0]);
let (out, dst) = h.new_string_keyed(text);
if let Some(src) = src {
h.string_carry_all(&dst, &src);
}
Ok(out)
}
fn substring_no_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
if !h.is_string(&a[0]) {
return Err(format!(
"wrong-type-argument: stringp {}",
h.print(&a[0], true)
));
}
let out = substring(h, a)?;
if let Some(s) = h.str_arc(&out) {
h.string_clear_props(&s);
}
Ok(out)
}
fn substring(h: &mut ElispHost, a: &[Value]) -> R {
enum Seq {
Str(Vec<char>),
Vec(Vec<Value>),
}
let seq = match h.str_text(&a[0]) {
Some(s) => Seq::Str(s.chars().collect()),
None => match h.obj(&a[0]) {
Some(Obj::Vector(items)) => Seq::Vec(items.clone()),
_ => {
return Err(format!(
"wrong-type-argument: arrayp {}",
h.print(&a[0], true)
));
}
},
};
for idx in a.iter().skip(1) {
if !is_nil(idx) && !matches!(idx, Value::Int(_)) {
return Err(format!(
"wrong-type-argument: integerp {}",
h.print(idx, true)
));
}
}
let len = match &seq {
Seq::Str(c) => c.len() as i64,
Seq::Vec(v) => v.len() as i64,
};
let adj = |i: i64| -> i64 {
if i < 0 {
len + i
} else {
i
}
};
let start = match a.get(1) {
Some(v) if !is_nil(v) => adj(as_int(h, v)?),
_ => 0,
};
let end = match a.get(2) {
Some(v) if !is_nil(v) => adj(as_int(h, v)?),
_ => len,
};
if start < 0 || end > len || start > end {
let from = a
.get(1)
.map(|v| h.print(v, true))
.unwrap_or_else(|| "nil".to_string());
let to = a
.get(2)
.map(|v| h.print(v, true))
.unwrap_or_else(|| "nil".to_string());
return Err(format!(
"args-out-of-range: {} {from} {to}",
h.print(&a[0], true)
));
}
match seq {
Seq::Str(c) => {
let text = c[start as usize..end as usize].iter().collect::<String>();
let src = h.str_arc(&a[0]);
let (out, dst) = h.new_string_keyed(text);
if let Some(src) = src {
h.string_copy_props(&dst, &[(Some(src), start as usize, (end - start) as usize)]);
}
Ok(out)
}
Seq::Vec(v) => Ok(h.alloc(Obj::Vector(v[start as usize..end as usize].to_vec()))),
}
}
pub(crate) const SPLIT_STRING_DEFAULT_SEPARATORS: &str = "[ \u{c}\t\n\r\u{b}]+";
fn match_end_0(h: &mut ElispHost) -> Result<i64, String> {
let end = match_end(h, &[Value::Int(0)])?;
as_int(h, &end)
}
fn split_string(h: &mut ElispHost, a: &[Value]) -> R {
let nil = Value::Undef;
let arg = |i: usize| a.get(i).cloned().unwrap_or(Value::Undef);
let string = arg(0);
let separators = arg(1);
let trim = arg(3);
let keep_empty = !is_nil(&separators) && is_nil(&arg(2));
let len = emacs_length(h, &string)?;
let anchored = |h: &mut ElispHost, head: &str, tail: &str| -> R {
concat_fn(
h,
&[
Value::str(head.to_string()),
trim.clone(),
Value::str(tail.to_string()),
],
)
};
let (trim_left_re, trim_right_re) = if is_nil(&trim) {
(nil.clone(), nil.clone())
} else {
(
anchored(h, "\\`\\(?:", "\\)")?,
anchored(h, "\\(?:", "\\)\\'")?,
)
};
let sep_re = if is_nil(&separators) {
match h
.find_symbol("split-string-default-separators")
.and_then(|s| h.get_value(&s).ok())
{
Some(v) if !is_nil(&v) => v,
_ => Value::str(SPLIT_STRING_DEFAULT_SEPARATORS.to_string()),
}
} else {
separators
};
let trim_item = |h: &mut ElispHost, item: Value| -> Result<(Value, i64, i64), String> {
let hit = string_match(h, &[trim_left_re.clone(), item.clone(), Value::Int(0)])?;
let beg = if is_nil(&hit) { 0 } else { match_end_0(h)? };
let item_len = emacs_length(h, &item)?;
let end = match string_match_p(h, &[trim_right_re.clone(), item.clone(), Value::Int(beg)])?
{
Value::Int(n) => n,
_ => item_len,
};
if beg > 0 || end < item_len {
let item = substring(h, &[item, Value::Int(beg), Value::Int(end)])?;
return Ok((item, beg, end));
}
Ok((item, beg, end))
};
let mut acc: Vec<Value> = Vec::new();
let (mut next, mut start) = (0i64, 0i64);
loop {
let sep = string_match(h, &[sep_re.clone(), string.clone(), Value::Int(next)])?;
let Value::Int(sep) = sep else { break };
let sep_end = match_end_0(h)?;
if keep_empty || start < sep {
let item = substring(h, &[string.clone(), Value::Int(start), Value::Int(sep)])?;
if is_nil(&trim) {
acc.push(item);
} else {
let (item, beg, end) = trim_item(h, item)?;
if keep_empty || beg < end {
acc.push(item);
}
}
}
next = (next + 1).max(sep_end);
start = sep_end;
if start >= len {
break;
}
}
let mut item = if start == 0 {
string
} else {
substring(h, &[string, Value::Int(start)])?
};
if !is_nil(&trim) {
item = trim_item(h, item)?.0;
}
if keep_empty || !el_equal(h, &item, &Value::str(String::new())) {
acc.push(item);
}
Ok(h.list_from(acc))
}
fn emacs_length(h: &mut ElispHost, v: &Value) -> Result<i64, String> {
match length_fn(h, std::slice::from_ref(v))? {
Value::Int(n) => Ok(n),
_ => Ok(0), }
}
fn cs_fold(ignore_case: bool) -> impl Fn(char) -> char {
move |c| {
if ignore_case {
c.to_lowercase().next().unwrap_or(c)
} else {
c
}
}
}
fn string_prefix_p(h: &mut ElispHost, a: &[Value]) -> R {
let plen = emacs_length(h, &a[0])?;
let slen = emacs_length(h, &a[1])?;
if plen > slen {
return Ok(Value::Undef);
}
let pre = as_string(h, &a[0])?;
let s = as_string(h, &a[1])?;
let fold = cs_fold(a.get(2).is_some_and(|v| !is_nil(v)));
Ok(nil_or(
pre.chars()
.map(&fold)
.eq(s.chars().take(plen as usize).map(&fold)),
))
}
fn string_suffix_p(h: &mut ElispHost, a: &[Value]) -> R {
let slen = emacs_length(h, &a[1])?;
let suflen = emacs_length(h, &a[0])?;
if slen < suflen {
return Ok(Value::Undef);
}
let suf = as_string(h, &a[0])?;
let s = as_string(h, &a[1])?;
let fold = cs_fold(a.get(2).is_some_and(|v| !is_nil(v)));
Ok(nil_or(
suf.chars()
.map(&fold)
.eq(s.chars().skip((slen - suflen) as usize).map(&fold)),
))
}
fn string_empty_p(h: &mut ElispHost, a: &[Value]) -> R {
match &a[0] {
v if h.is_string(v) => Ok(nil_or(h.str_text(v).is_some_and(str::is_empty))),
v if is_nil(v) => Ok(Value::Undef), v => match h.sym_name(v) {
Some(name) => Ok(nil_or(name.is_empty())),
None => Err(format!("wrong-type-argument: stringp {}", h.print(v, true))),
},
}
}
fn string_join(h: &mut ElispHost, a: &[Value]) -> R {
emacs_length(h, &a[0])?;
let items = h
.seq_vec(&a[0])
.ok_or_else(|| format!("wrong-type-argument: sequencep {}", h.print(&a[0], true)))?;
let sep = a.get(1).cloned().unwrap_or(Value::Undef);
let mut parts: Vec<Value> = Vec::with_capacity(items.len() * 2);
for (i, it) in items.into_iter().enumerate() {
if i > 0 && !is_nil(&sep) {
parts.push(sep.clone());
}
parts.push(it);
}
concat_fn(h, &parts)
}
fn char_to_string(h: &mut ElispHost, a: &[Value]) -> R {
let n = as_char(h, &a[0])?;
Ok(h.new_string(char::from_u32(n).map(|c| c.to_string()).unwrap_or_default()))
}
fn string_to_char(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Int(
as_string(h, &a[0])?
.chars()
.next()
.map(|c| c as i64)
.unwrap_or(0),
))
}
fn make_string(h: &mut ElispHost, a: &[Value]) -> R {
let n = check_array_len_val(h, &a[0])?;
let c = char::from_u32(as_char(h, &a[1])?).unwrap_or(' ');
let bytes = n
.checked_mul(c.len_utf8())
.ok_or_else(|| MEMORY_EXHAUSTED.to_string())?;
let mut s = String::new();
s.try_reserve_exact(bytes)
.map_err(|_| MEMORY_EXHAUSTED.to_string())?;
for _ in 0..n {
s.push(c);
}
Ok(h.new_string(s))
}
fn string_fn(h: &mut ElispHost, a: &[Value]) -> R {
let mut s = String::new();
for v in a {
let c = as_char(h, v)?;
if let Some(c) = char::from_u32(c) {
s.push(c);
}
}
Ok(h.new_string(s))
}
fn string_to_list(h: &mut ElispHost, a: &[Value]) -> R {
match h
.str_text(&a[0])
.map(|st| st.chars().map(|c| Value::Int(c as i64)).collect())
{
Some(items) => Ok(h.list_from(items)),
None => match h.seq_vec(&a[0]) {
Some(items) => Ok(h.list_from(items)),
None => Err(format!(
"wrong-type-argument: sequencep {}",
h.print(&a[0], true)
)),
},
}
}
fn string_search(h: &mut ElispHost, a: &[Value]) -> R {
let needle = as_string(h, &a[0])?;
let hay = as_string(h, &a[1])?;
let hay_len = hay.chars().count() as i64;
let start_char = match a.get(2) {
Some(v) if !is_nil(v) => {
let n = as_int(h, v)?;
if n < 0 || n > hay_len {
return Err(format!("args-out-of-range: {n}"));
}
n as usize
}
_ => 0,
};
let start_byte = hay
.char_indices()
.nth(start_char)
.map(|(b, _)| b)
.unwrap_or(hay.len());
Ok(match hay[start_byte..].find(&needle) {
Some(off) => Value::Int(hay[..start_byte + off].chars().count() as i64),
None => Value::Undef,
})
}
fn byte_of_char(s: &str, char_idx: usize) -> usize {
s.char_indices()
.nth(char_idx)
.map(|(b, _)| b)
.unwrap_or(s.len())
}
pub(crate) fn char_of_byte(s: &str, byte_idx: usize) -> usize {
s[..byte_idx].chars().count()
}
struct HostSyntax<'a> {
host: &'a ElispHost,
used_syntax: std::cell::Cell<bool>,
used_category: std::cell::Cell<bool>,
point: Option<usize>,
}
impl crate::regexp::SyntaxLookup for HostSyntax<'_> {
fn ranges(&self, class: char) -> Vec<(u32, u32)> {
self.used_syntax.set(true);
self.host.syntax_class_ranges(class)
}
fn category_ranges(&self, category: u8) -> Vec<(u32, u32)> {
self.used_category.set(true);
self.host.category_ranges(category)
}
fn at_dot(&self) -> String {
match self.point {
None => crate::regexp::NEVER_MATCHES.to_string(),
Some(0) => r"\A".to_string(),
Some(p) => format!(r"(?<=\A[\s\S]{{{p}}})"),
}
}
}
pub(crate) struct CompiledRe {
re: fancy_regex::Regex,
emacs_groups: Option<Vec<u32>>,
}
impl std::ops::Deref for CompiledRe {
type Target = fancy_regex::Regex;
fn deref(&self) -> &fancy_regex::Regex {
&self.re
}
}
type ReCacheMap = HashMap<String, (Option<(TablesRead, u64)>, Result<Rc<CompiledRe>, String>)>;
type TablesRead = (bool, bool);
fn tables_fingerprint(h: &ElispHost, tables: TablesRead) -> u64 {
let syntax = if tables.0 { h.syntax_fingerprint() } else { 0 };
let category = if tables.1 {
h.category_fingerprint()
} else {
0
};
syntax.rotate_left(1) ^ category
}
thread_local! {
static RE_CACHE: RefCell<[ReCacheMap; 4]> =
RefCell::new([HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new()]);
}
const RE_CACHE_MAX: usize = 1024;
pub(crate) fn compile_cf(
h: &ElispHost,
pat: &str,
case_insensitive: bool,
) -> Result<Rc<CompiledRe>, String> {
compile_cf_in(h, pat, case_insensitive, None)
}
pub(crate) fn compile_cf_buf(
h: &ElispHost,
pat: &str,
case_insensitive: bool,
) -> Result<Rc<CompiledRe>, String> {
let b = h.cur_buf_ref();
compile_cf_in(h, pat, case_insensitive, Some(b.point - b.begv))
}
fn compile_cf_in(
h: &ElispHost,
pat: &str,
case_insensitive: bool,
point: Option<usize>,
) -> Result<Rc<CompiledRe>, String> {
let slot = usize::from(case_insensitive) + 2 * usize::from(point.is_some());
let key = match point {
Some(p) if pat.contains("\\=") => format!("{p}\0{pat}"),
_ => pat.to_string(),
};
if let Some((stamp, hit)) = RE_CACHE.with(|c| c.borrow()[slot].get(&key).cloned()) {
if stamp.is_none_or(|(tables, s)| s == tables_fingerprint(h, tables)) {
return hit;
}
}
let syntax = HostSyntax {
host: h,
used_syntax: std::cell::Cell::new(false),
used_category: std::cell::Cell::new(false),
point,
};
let compiled = compile_uncached(pat, case_insensitive, &syntax);
let tables = (syntax.used_syntax.get(), syntax.used_category.get());
let stamp = (tables.0 || tables.1).then(|| (tables, tables_fingerprint(h, tables)));
RE_CACHE.with(|c| {
let mut maps = c.borrow_mut();
if maps[slot].len() >= RE_CACHE_MAX {
maps[slot].clear();
}
maps[slot].insert(key, (stamp, compiled.clone()));
});
compiled
}
fn compile_uncached(
pat: &str,
case_insensitive: bool,
syntax: &HostSyntax<'_>,
) -> Result<Rc<CompiledRe>, String> {
let (translated, groups) =
crate::regexp::translate_groups(pat, syntax).map_err(|e| format!("invalid-regexp: {e}"))?;
let flags = if case_insensitive { "(?mi)" } else { "(?m)" };
let full = format!("{flags}{translated}");
let re = fancy_regex::Regex::new(&full).map_err(|e| format!("invalid-regexp: {e}"))?;
let identity = groups.iter().enumerate().all(|(i, &g)| g as usize == i + 1);
Ok(Rc::new(CompiledRe {
re,
emacs_groups: (!identity).then_some(groups),
}))
}
pub fn clear_regexp_cache() {
RE_CACHE.with(|c| {
let mut maps = c.borrow_mut();
maps.iter_mut().for_each(HashMap::clear);
});
}
pub(crate) fn case_fold_search(h: &ElispHost) -> bool {
match h.find_symbol("case-fold-search") {
Some(sym) => h
.get_value(&sym)
.map(|v| !matches!(v, Value::Undef | Value::Bool(false)))
.unwrap_or(true),
None => true,
}
}
fn run_match(re: &CompiledRe, subject: &str, start: usize) -> Option<Vec<Option<(usize, usize)>>> {
let start_byte = byte_of_char(subject, start);
let caps = re.captures_from_pos(subject, start_byte).ok().flatten()?;
let spans: Vec<Option<(usize, usize)>> = (0..caps.len())
.map(|i| {
caps.get(i).map(|m| {
(
char_of_byte(subject, m.start()),
char_of_byte(subject, m.end()),
)
})
})
.collect();
let Some(map) = &re.emacs_groups else {
return Some(spans);
};
let width = map.iter().copied().max().unwrap_or(0) as usize + 1;
let mut out = vec![None; width];
out[0] = spans.first().copied().flatten();
for (i, &g) in map.iter().enumerate() {
let Some(span) = spans.get(i + 1).copied().flatten() else {
continue;
};
out[g as usize] = Some(span);
}
Some(out)
}
fn string_match(h: &mut ElispHost, a: &[Value]) -> R {
let pat = as_string(h, &a[0])?;
let subject = as_string(h, &a[1])?;
let start = match a.get(2) {
Some(Value::Undef) | Some(Value::Bool(false)) | None => 0,
Some(v) => {
let raw = as_int(h, v)?;
let len = subject.chars().count() as i64;
let pos = if raw < 0 { len + raw } else { raw };
if pos < 0 || pos > len {
return Err(format!("args-out-of-range: {} {raw}", h.print(&a[1], true)));
}
pos as usize
}
};
let re = compile_cf(h, &pat, case_fold_search(h))?;
match run_match(&re, &subject, start) {
Some(spans) => {
let begin = spans[0].map(|(b, _)| b as i64).unwrap_or(0);
h.match_data = Some(MatchData {
subject,
spans,
from_buffer: false,
buffer: None,
});
Ok(Value::Int(begin))
}
None => Ok(Value::Undef),
}
}
fn string_match_p(h: &mut ElispHost, a: &[Value]) -> R {
let saved = h.match_data.take();
let result = string_match(h, a);
h.match_data = saved;
result
}
fn match_edge(h: &mut ElispHost, a: &[Value], end: bool) -> R {
let n = as_int(h, &a[0])?.max(0) as usize;
let edge = h
.match_data
.as_ref()
.and_then(|m| m.spans.get(n).copied().flatten())
.map(|(b, e)| if end { e } else { b });
Ok(match edge {
Some(pos) => Value::Int(pos as i64),
None => Value::Undef,
})
}
fn match_beginning(h: &mut ElispHost, a: &[Value]) -> R {
match_edge(h, a, false)
}
fn match_end(h: &mut ElispHost, a: &[Value]) -> R {
match_edge(h, a, true)
}
fn match_string(h: &mut ElispHost, a: &[Value]) -> R {
let n = as_int(h, &a[0])?.max(0) as usize;
let Some(md) = h.match_data.as_ref() else {
return Ok(Value::Undef);
};
let span = md.spans.get(n).copied().flatten();
let explicit = a.get(1).and_then(|v| h.str_text(v)).map(str::to_string);
if md.from_buffer && explicit.is_none() {
return Ok(match span {
Some((b, e)) => {
let t = &h.cur_buf().text;
let (lo, hi) = ((b - 1).min(t.len()), (e - 1).min(t.len()));
let text = t[lo..hi].iter().collect::<String>();
h.new_string(text)
}
None => Value::Undef,
});
}
let Some(md) = h.match_data.as_ref() else {
return Ok(Value::Undef);
};
let subject = match explicit {
Some(s) => s,
None => md.subject.clone(),
};
match span {
Some((b, e)) => {
let bb = byte_of_char(&subject, b);
let eb = byte_of_char(&subject, e);
Ok(h.new_string(subject.get(bb..eb).unwrap_or("").to_string()))
}
None => Ok(Value::Undef),
}
}
fn match_data_fn(h: &mut ElispHost, a: &[Value]) -> R {
let integers = a.first().is_some_and(|v| !is_nil(v));
let reuse = a.get(1).cloned().unwrap_or(Value::Undef);
if a.get(2).is_some_and(|v| !is_nil(v)) {
let mut tail = reuse.clone();
while let Some(Obj::Cons(car, cdr)) = h.obj(&tail).cloned() {
if h.is_marker(&car) {
h.set_marker_to(&car, None, 0)?;
setcar(h, &[tail.clone(), Value::Undef])?;
}
tail = cdr;
}
}
let Some(md) = h.match_data.clone() else {
return Ok(Value::Undef);
};
let live = md.buffer.filter(|&bi| h.buffers[bi].name.is_some());
let mut data = Vec::with_capacity(md.spans.len() * 2 + 1);
let mut len = 0;
for span in &md.spans {
match *span {
Some((b, e)) => {
if md.buffer.is_none() || integers {
data.push(Value::Int(b as i64));
data.push(Value::Int(e as i64));
} else {
data.push(h.alloc_marker(live, if live.is_some() { b } else { 0 }, false));
data.push(h.alloc_marker(live, if live.is_some() { e } else { 0 }, false));
}
len = data.len();
}
None => {
data.push(Value::Undef);
data.push(Value::Undef);
}
}
}
data.truncate(len);
if let (Some(bi), true) = (md.buffer, integers) {
data.push(h.buffer_object(bi));
}
if !matches!(h.obj(&reuse), Some(Obj::Cons(..))) {
return Ok(h.list_from(data));
}
let mut items = data.into_iter();
let mut tail = reuse.clone();
let mut prev = tail.clone();
while let Some(Obj::Cons(_, cdr)) = h.obj(&tail).cloned() {
setcar(h, &[tail.clone(), items.next().unwrap_or(Value::Undef)])?;
prev = tail;
tail = cdr;
}
let rest: Vec<Value> = items.collect();
if !rest.is_empty() {
let rest = h.list_from(rest);
setcdr(h, &[prev, rest])?;
}
Ok(reuse)
}
fn set_match_data(h: &mut ElispHost, a: &[Value]) -> R {
let list = a[0].clone();
if !is_nil(&list) && !matches!(h.obj(&list), Some(Obj::Cons(..))) {
return Err(h.signal_wrong_type("listp", &list));
}
let reseat = a.get(1).is_some_and(|v| !is_nil(v));
let flat = h.list_vec(&list).unwrap_or_default();
let pairs = flat.len() / 2;
let mut buffer: Option<usize> = None;
let mut spans: Vec<Option<(usize, usize)>> = Vec::with_capacity(pairs);
let pos = |h: &mut ElispHost, v: &Value, buffer: &mut Option<usize>| -> Result<i64, String> {
if h.is_marker(v) {
let p = match h.marker_buffer(v) {
Some(bv) => {
if let Some(Obj::Buffer(bi)) = h.obj(&bv) {
*buffer = Some(*bi);
}
h.marker_position(v).unwrap_or(0) as i64
}
None => 0,
};
if reseat {
h.set_marker_to(v, None, 0)?;
}
return Ok(p);
}
as_int_or_marker(h, v, "integer-or-marker-p")
};
let mut i = 0;
while i < flat.len() {
if let Some(Obj::Buffer(bi)) = h.obj(&flat[i]) {
buffer = Some(*bi);
break;
}
if spans.len() >= pairs {
break;
}
if is_nil(&flat[i]) {
spans.push(None);
i += 2;
continue;
}
let from = pos(h, &flat[i], &mut buffer)?;
let Some(end_v) = flat.get(i + 1).cloned() else {
break;
};
let to = pos(h, &end_v, &mut buffer)?;
spans.push(Some((from.max(0) as usize, to.max(0) as usize)));
i += 2;
}
while spans.last().is_some_and(|s| s.is_none()) {
spans.pop();
}
if spans.is_empty() {
h.match_data = None;
return Ok(Value::Undef);
}
let subject = h
.match_data
.as_ref()
.map(|m| m.subject.clone())
.unwrap_or_default();
h.match_data = Some(MatchData {
subject,
spans,
from_buffer: buffer.is_some(),
buffer,
});
Ok(Value::Undef)
}
fn regexp_quote(h: &mut ElispHost, a: &[Value]) -> R {
let s = as_string(h, &a[0])?;
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(c, '.' | '*' | '+' | '?' | '[' | '^' | '$' | '\\') {
out.push('\\');
}
out.push(c);
}
Ok(h.new_string(out))
}
fn adapt_replacement_case(matched: &str, rep: String) -> String {
let (mut upper, mut lower, mut first_upper) = (0u32, 0u32, None);
for c in matched.chars() {
if c.is_alphabetic() {
if c.is_uppercase() {
upper += 1;
} else {
lower += 1;
}
if first_upper.is_none() {
first_upper = Some(c.is_uppercase());
}
}
}
if upper > 0 && lower == 0 {
rep.to_uppercase()
} else if first_upper == Some(true) {
let mut out = String::with_capacity(rep.len());
let mut prev_word = false;
for c in rep.chars() {
if c.is_alphabetic() && !prev_word {
out.extend(c.to_uppercase());
} else {
out.push(c);
}
prev_word = c.is_alphanumeric();
}
out
} else {
rep
}
}
#[derive(Clone, Copy)]
enum Rm {
Floor,
Ceil,
Trunc,
Round,
}
fn quotient(h: &mut ElispHost, a: &[Value], rm: Rm) -> R {
let xn = as_number_p(h, &a[0], false)?;
match a.get(1) {
Some(d) if !is_nil(d) => {
let dn = as_number_p(h, d, false)?;
if let (Num::Int(x), Num::Int(y)) = (&xn, &dn) {
if *y == BigInt::from(0) {
return Err("arith-error: division by zero".to_string());
}
let q = big_div(x, y, rm);
return Ok(h.make_integer(q));
}
let df = dn.to_f64();
if df == 0.0 {
return Err("arith-error: division by zero".to_string());
}
if matches!(xn, Num::Float(f) if !f.is_finite()) {
return Err("overflow-error".to_string());
}
if df.is_nan() {
return Err("overflow-error".to_string());
}
if df.is_infinite() {
return Ok(Value::Int(0));
}
let (xnum, xden) = exact_ratio(&xn);
let (dnum, dden) = exact_ratio(&dn);
Ok(h.make_integer(big_div(&(xnum * dden), &(xden * dnum), rm)))
}
_ => match xn {
Num::Int(i) => Ok(h.make_integer(i)),
Num::Float(f) => {
if !f.is_finite() {
return Err("overflow-error".to_string());
}
Ok(float_to_integer(h, apply_rm(f, rm)))
}
},
}
}
fn big_div(x: &BigInt, y: &BigInt, rm: Rm) -> BigInt {
use num_integer::Integer;
let zero = BigInt::from(0);
let (q, r) = x.div_rem(y);
match rm {
Rm::Trunc => q,
Rm::Floor if r != zero && (r < zero) != (*y < zero) => q - 1,
Rm::Ceil if r != zero && (r < zero) == (*y < zero) => q + 1,
Rm::Round => {
use num_traits::Signed;
let twice: BigInt = (&r * BigInt::from(2)).abs();
let mag = y.abs();
let away = match twice.cmp(&mag) {
std::cmp::Ordering::Greater => true,
std::cmp::Ordering::Equal => q.is_odd(),
std::cmp::Ordering::Less => false,
};
let toward = if (r < zero) != (*y < zero) { -1 } else { 1 };
if away {
q + toward
} else {
q
}
}
_ => q,
}
}
fn exact_ratio(n: &Num) -> (BigInt, BigInt) {
let one = BigInt::from(1);
let f = match n {
Num::Int(i) => return (i.clone(), one),
Num::Float(f) => *f,
};
let bits = f.to_bits();
let biased = ((bits >> 52) & 0x7ff) as i64;
let frac = bits & ((1u64 << 52) - 1);
let (mantissa, exp) = if biased == 0 {
(frac, -1074)
} else {
(frac | (1u64 << 52), biased - 1075)
};
let mut num = BigInt::from(mantissa);
if bits >> 63 == 1 {
num = -num;
}
if exp >= 0 {
(num << exp as usize, one)
} else {
(num, one << (-exp) as usize)
}
}
fn float_to_integer(h: &mut ElispHost, f: f64) -> Value {
use num_traits::ToPrimitive;
match f.to_i64() {
Some(i) => h.make_integer(BigInt::from(i)),
None => match <BigInt as num_traits::FromPrimitive>::from_f64(f) {
Some(b) => h.make_integer(b),
None => Value::Float(f),
},
}
}
fn apply_rm(f: f64, rm: Rm) -> f64 {
match rm {
Rm::Floor => f.floor(),
Rm::Ceil => f.ceil(),
Rm::Trunc => f.trunc(),
Rm::Round => f.round_ties_even(),
}
}
fn floor_fn(h: &mut ElispHost, a: &[Value]) -> R {
quotient(h, a, Rm::Floor)
}
fn ceiling_fn(h: &mut ElispHost, a: &[Value]) -> R {
quotient(h, a, Rm::Ceil)
}
fn round_fn(h: &mut ElispHost, a: &[Value]) -> R {
quotient(h, a, Rm::Round)
}
fn truncate_fn(h: &mut ElispHost, a: &[Value]) -> R {
quotient(h, a, Rm::Trunc)
}
fn float_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64()))
}
fn as_int_exact(h: &ElispHost, v: &Value) -> Result<BigInt, String> {
as_int_exact_p(h, v, true)
}
fn as_int_bitop(h: &ElispHost, v: &Value, first: bool) -> Result<BigInt, String> {
if !first && !h.is_number(v) && h.marker_position(v).is_none() {
return Err(format!(
"wrong-type-argument: number-or-marker-p {}",
h.print(v, true)
));
}
as_int_exact(h, v)
}
fn as_int_exact_p(h: &ElispHost, v: &Value, markers_ok: bool) -> Result<BigInt, String> {
match v {
Value::Int(n) => Ok(BigInt::from(*n)),
_ => {
if let Some(b) = h.as_bigint(v) {
return Ok(b);
}
if markers_ok {
if let Some(p) = h.marker_position(v) {
return Ok(BigInt::from(p));
}
}
Err(format!(
"wrong-type-argument: {} {}",
if markers_ok {
"integer-or-marker-p"
} else {
"integerp"
},
h.print(v, true)
))
}
}
}
fn logand_fn(h: &mut ElispHost, a: &[Value]) -> R {
let mut r = BigInt::from(-1);
for (i, v) in a.iter().enumerate() {
r &= as_int_bitop(h, v, i == 0)?;
}
Ok(h.make_integer(r))
}
fn logior_fn(h: &mut ElispHost, a: &[Value]) -> R {
let mut r = BigInt::from(0);
for (i, v) in a.iter().enumerate() {
r |= as_int_bitop(h, v, i == 0)?;
}
Ok(h.make_integer(r))
}
fn logxor_fn(h: &mut ElispHost, a: &[Value]) -> R {
let mut r = BigInt::from(0);
for (i, v) in a.iter().enumerate() {
r ^= as_int_bitop(h, v, i == 0)?;
}
Ok(h.make_integer(r))
}
fn lognot_fn(h: &mut ElispHost, a: &[Value]) -> R {
let n = as_int_exact_p(h, &a[0], false)?;
Ok(h.make_integer(!n))
}
fn integer_width(h: &ElispHost) -> u64 {
h.find_symbol("integer-width")
.and_then(|s| h.get_value(&s).ok())
.and_then(|v| match v {
Value::Int(n) if n > 0 => Some(n as u64),
_ => None,
})
.unwrap_or(65536)
}
fn ash_fn(h: &mut ElispHost, a: &[Value]) -> R {
use num_traits::{Signed, ToPrimitive};
let n = as_int_exact_p(h, &a[0], false)?;
let cb = as_int_exact_p(h, &a[1], false)?;
let c = match cb.to_i64() {
Some(c) => c,
None if cb.is_negative() => {
return Ok(h.make_integer(if n.is_negative() {
BigInt::from(-1)
} else {
BigInt::from(0)
}))
}
None => return Err("overflow-error".to_string()),
};
let r = if c >= 0 {
let width = integer_width(h);
if n.sign() != num_bigint::Sign::NoSign && n.bits().saturating_add(c as u64) > width {
return Err("overflow-error".to_string());
}
n << (c as u64)
} else {
let sh = c.unsigned_abs();
if sh > 1 << 30 {
if n.sign() == num_bigint::Sign::Minus {
BigInt::from(-1)
} else {
BigInt::from(0)
}
} else {
n >> sh
}
};
Ok(h.make_integer(r))
}
fn lsh_fn(h: &mut ElispHost, a: &[Value]) -> R {
const FIXNUM_MASK: u64 = (1u64 << 62) - 1;
if as_number_p(h, &a[0], true).is_err() {
let v = a[0].clone();
return Err(h.signal_wrong_type("number-or-marker-p", &v));
}
if let Ok(c) = as_integer(h, &a[1]) {
if c >= 0 {
let n = as_int_exact_p(h, &a[0], false)?;
if c > 1 << 30 {
return Err("overflow-error".to_string());
}
let r = n << (c as u64);
return Ok(h.make_integer(r));
}
}
let n = as_integer(h, &a[0])?;
let c = as_integer(h, &a[1])?;
Ok(Value::Int(if c >= 0 {
n.wrapping_shl(c as u32)
} else {
let sh = (-c) as u32;
if sh >= 62 {
0
} else {
(((n as u64) & FIXNUM_MASK) >> sh) as i64
}
}))
}
fn expt_fn(h: &mut ElispHost, a: &[Value]) -> R {
let base = as_number_p(h, &a[0], false)?;
let exp = as_number_p(h, &a[1], false)?;
if let (Num::Int(b), Num::Int(e)) = (&base, &exp) {
use num_traits::{Signed, ToPrimitive};
if !e.is_negative() {
let e_u32 = e.to_u32().ok_or_else(|| "overflow-error".to_string())?;
if e_u32 > 1 << 24 {
return Err("overflow-error".to_string());
}
let r = num_traits::Pow::pow(b.clone(), e_u32);
return Ok(h.make_integer(r));
}
}
Ok(Value::Float(base.to_f64().powf(exp.to_f64())))
}
fn sqrt_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().sqrt()))
}
fn exp_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().exp()))
}
fn log_fn(h: &mut ElispHost, a: &[Value]) -> R {
let x = as_number_p(h, &a[0], false)?.to_f64();
Ok(Value::Float(match a.get(1) {
Some(b) => {
let base = as_num(h, b)?.1;
if base == 10.0 {
x.log10()
} else if base == 2.0 {
x.log2()
} else {
x.ln() / base.ln()
}
}
None => x.ln(),
}))
}
fn sin_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().sin()))
}
fn cos_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().cos()))
}
fn tan_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().tan()))
}
fn asin_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().asin()))
}
fn acos_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().acos()))
}
fn atan_fn(h: &mut ElispHost, a: &[Value]) -> R {
let y = as_number_p(h, &a[0], false)?.to_f64();
Ok(Value::Float(match a.get(1) {
Some(x) => {
let xv = as_number_p(h, x, false)
.map_err(|_| format!("wrong-type-argument: numberp {}", h.print(x, true)))?;
y.atan2(xv.to_f64())
}
None => y.atan(),
}))
}
pub(crate) fn scalbn(x: f64, mut n: i64) -> f64 {
let two_1023 = 2f64.powi(1023);
let two_m1022 = f64::MIN_POSITIVE; let two_53 = (1u64 << 53) as f64; let mut y = x;
if n > 1023 {
y *= two_1023;
n -= 1023;
if n > 1023 {
y *= two_1023;
n -= 1023;
if n > 1023 {
n = 1023;
}
}
} else if n < -1022 {
y *= two_m1022 * two_53;
n += 1022 - 53;
if n < -1022 {
y *= two_m1022 * two_53;
n += 1022 - 53;
if n < -1022 {
n = -1022;
}
}
}
y * f64::from_bits(((0x3ff + n) as u64) << 52)
}
fn ldexp_fn(h: &mut ElispHost, a: &[Value]) -> R {
let m = as_number_p(h, &a[0], false)?.to_f64();
let e = as_num(h, &a[1])?.0;
Ok(Value::Float(scalbn(m, e)))
}
fn copysign_fn(h: &mut ElispHost, a: &[Value]) -> R {
let f = |h: &mut ElispHost, v: &Value| -> Result<f64, String> {
match v {
Value::Float(x) => Ok(*x),
_ => Err(h.signal_wrong_type("floatp", v)),
}
};
let x = f(h, &a[0])?;
let y = f(h, &a[1])?;
Ok(Value::Float(x.copysign(y)))
}
fn frexp_parts(x: f64) -> (f64, i64) {
let bits = x.to_bits();
let ee = (bits >> 52) & 0x7ff;
if ee == 0 {
if x == 0.0 {
(x, 0) } else {
let (m, e) = frexp_parts(x * 2f64.powi(64));
(m, e - 64)
}
} else if ee == 0x7ff {
(x, 0) } else {
let e = ee as i64 - 0x3fe;
let m = f64::from_bits((bits & 0x800f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000);
(m, e)
}
}
fn frexp_fn(h: &mut ElispHost, a: &[Value]) -> R {
let (m, e) = frexp_parts(as_number_p(h, &a[0], false)?.to_f64());
Ok(h.cons(Value::Float(m), Value::Int(e)))
}
fn isnan_fn(h: &mut ElispHost, a: &[Value]) -> R {
match a[0] {
Value::Float(f) => Ok(nil_or(f.is_nan())),
_ => Err(format!(
"wrong-type-argument: floatp {}",
h.print(&a[0], true)
)),
}
}
fn as_float_strict(h: &ElispHost, v: &Value) -> Result<f64, String> {
match v {
Value::Float(f) => Ok(*f),
_ => Err(format!("wrong-type-argument: floatp {}", h.print(v, true))),
}
}
fn fround_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_float_strict(h, &a[0])?.round_ties_even()))
}
fn ffloor_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_float_strict(h, &a[0])?.floor()))
}
fn fceiling_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_float_strict(h, &a[0])?.ceil()))
}
fn ftruncate_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(as_float_strict(h, &a[0])?.trunc()))
}
fn string_to_number(h: &mut ElispHost, a: &[Value]) -> R {
let raw = as_string(h, &a[0])?;
let s = raw.trim_start_matches([' ', '\t']);
if let Some(bv) = a.get(1) {
if !is_nil(bv) {
let base_i = match bv {
Value::Int(n) => *n,
v => {
return Err(format!("wrong-type-argument: fixnump {}", h.print(v, true)));
}
};
if !(2..=16).contains(&base_i) {
return Err(format!("args-out-of-range: {base_i}"));
}
if base_i != 10 {
let base = base_i as u32;
let mut chars = s.chars().peekable();
let mut sign = 1i64;
match chars.peek() {
Some('+') => {
chars.next();
}
Some('-') => {
sign = -1;
chars.next();
}
_ => {}
}
let (mut n, mut seen) = (BigInt::from(0), false);
for c in chars {
match c.to_digit(base) {
Some(d) => {
n = n * base as i64 + d as i64;
seen = true;
}
None => break,
}
}
return Ok(if seen {
h.make_integer(n * sign)
} else {
Value::Int(0)
});
}
}
}
let b: Vec<char> = s.chars().collect();
let (mut i, n) = (0usize, b.len());
let start = i;
if i < n && (b[i] == '+' || b[i] == '-') {
i += 1;
}
let (mut has_digit, mut is_float) = (false, false);
while i < n && b[i].is_ascii_digit() {
i += 1;
has_digit = true;
}
let mut dot_pos = None;
if i < n && b[i] == '.' {
dot_pos = Some(i);
i += 1;
while i < n && b[i].is_ascii_digit() {
i += 1;
has_digit = true;
is_float = true;
}
}
let mut nonfinite: Option<f64> = None;
if has_digit && i < n && (b[i] == 'e' || b[i] == 'E') {
let mut j = i + 1;
let plus = j < n && b[j] == '+';
if j < n && (b[j] == '+' || b[j] == '-') {
j += 1;
}
if j < n && b[j].is_ascii_digit() {
is_float = true;
i = j;
while i < n && b[i].is_ascii_digit() {
i += 1;
}
} else if plus && b[j..].starts_with(&['I', 'N', 'F']) {
is_float = true;
nonfinite = Some(f64::INFINITY);
i = j + 3;
} else if plus && b[j..].starts_with(&['N', 'a', 'N']) {
is_float = true;
let mant: String = b[start..i].iter().collect();
nonfinite = Some(crate::reader::nan_with_payload(
crate::reader::leading_integer(&mant),
false,
));
i = j + 3;
}
}
if !has_digit {
return Ok(Value::Int(0));
}
if is_float {
if let Some(v) = nonfinite {
return Ok(Value::Float(if b[start] == '-' { -v } else { v }));
}
let tok: String = b[start..i].iter().collect();
Ok(Value::Float(tok.parse().unwrap_or(0.0)))
} else {
let end = dot_pos.unwrap_or(i);
let tok: String = b[start..end].iter().collect();
match tok.parse::<BigInt>() {
Ok(n) => Ok(h.make_integer(n)),
Err(_) => Ok(Value::Int(0)),
}
}
}
const SXHASH_MAX_DEPTH: u32 = 3;
const SXHASH_MAX_LEN: usize = 7;
const INTMASK: u64 = (1 << 62) - 1;
fn hash_mix(acc: u64, x: u64) -> u64 {
(acc ^ x)
.wrapping_mul(0x100000001b3)
.wrapping_add(0x9e3779b97f4a7c15)
}
fn hash_bytes(s: &str) -> u64 {
let mut acc = 0xcbf29ce484222325u64;
for b in s.bytes() {
acc = hash_mix(acc, b as u64);
}
acc
}
fn sxhash_combine(x: u64, y: u64) -> u64 {
(x << 4).wrapping_add(x >> 60).wrapping_add(y)
}
fn hash_char_array(p: &[u8]) -> u64 {
let len = p.len();
let mut hash = len as u64;
let word = |i: usize| u64::from_ne_bytes(p[i..i + 8].try_into().unwrap());
if len >= 8 {
let step = 8.max(len >> 3);
let mut i = 0;
while i + 8 <= len {
hash = sxhash_combine(hash, word(i));
i += step;
}
hash = sxhash_combine(hash, word(len - 8));
} else {
let mut tail = 0u64;
let mut i = 0;
if len - i >= 4 {
tail = (tail << 32) + u32::from_ne_bytes(p[i..i + 4].try_into().unwrap()) as u64;
i += 4;
}
if len - i >= 2 {
tail = (tail << 16) + u16::from_ne_bytes(p[i..i + 2].try_into().unwrap()) as u64;
i += 2;
}
if i < len {
tail = (tail << 8) + p[i] as u64;
}
hash = sxhash_combine(hash, tail);
}
hash
}
fn sxhash_obj(h: &ElispHost, v: &Value, depth: u32) -> u64 {
if depth > SXHASH_MAX_DEPTH {
return 0;
}
if let Some(b) = h.as_bigint(v).filter(|_| h.is_bignum(v)) {
let mut hash = u64::from(b.sign() == num_bigint::Sign::Minus);
for limb in b.magnitude().iter_u64_digits() {
hash = sxhash_combine(hash, limb);
}
return hash;
}
match v {
Value::Int(n) => (*n as u64) & INTMASK,
Value::Float(f) => sxhash_combine(0, f.to_bits()),
Value::Str(s) => hash_char_array(s.as_bytes()),
Value::Bool(false) | Value::Undef => 0,
Value::Bool(true) => 1,
Value::Obj(_) => match h.obj(v) {
Some(Obj::Str(s)) => hash_char_array(s.as_bytes()),
Some(Obj::Symbol(s)) => hash_mix(0x5111, hash_bytes(&s.name)) & ((1 << 47) - 1),
Some(Obj::Cons(..)) => {
let mut hash = 0u64;
let mut list = v.clone();
if depth < SXHASH_MAX_DEPTH {
let mut i = 0;
while let Some(Obj::Cons(car, cdr)) = h.obj(&list) {
if i >= SXHASH_MAX_LEN {
break;
}
let (car, cdr) = (car.clone(), cdr.clone());
hash = sxhash_combine(hash, sxhash_obj(h, &car, depth + 1));
list = cdr;
i += 1;
}
}
if !matches!(list, Value::Undef | Value::Bool(false)) {
hash = sxhash_combine(hash, sxhash_obj(h, &list, depth + 1));
}
hash
}
Some(Obj::Vector(items)) => {
let mut hash = items.len() as u64;
for it in items.iter().take(SXHASH_MAX_LEN) {
hash = sxhash_combine(hash, sxhash_obj(h, it, depth + 1));
}
hash
}
Some(Obj::BoolVector(bits)) => {
let mut hash = bits.len() as u64;
for chunk in bits.chunks(64).take(SXHASH_MAX_LEN) {
let word =
chunk
.iter()
.enumerate()
.fold(0u64, |w, (i, &b)| if b { w | (1 << i) } else { w });
hash = sxhash_combine(hash, word);
}
hash
}
_ => 0x6,
},
_ => 0x8,
}
}
fn sxhash_eq(v: &Value) -> u64 {
match v {
Value::Int(n) => ((*n as u64) & INTMASK) ^ if n & 1 == 0 { 2 } else { 6 },
Value::Float(f) => f.to_bits(),
Value::Bool(false) | Value::Undef => 0,
Value::Bool(true) => 1,
Value::Str(s) => hash_bytes(s),
Value::Obj(id) => hash_mix(0xab, *id as u64),
_ => 0x8,
}
}
fn sxhash_fixnum(x: u64) -> Value {
let r = (x ^ (x >> 2)) & INTMASK;
Value::Int(((r << 2) as i64) >> 2)
}
fn sxhash_equal_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(sxhash_fixnum(sxhash_obj(h, &a[0], 0)))
}
fn sxhash_eq_fn(_h: &mut ElispHost, a: &[Value]) -> R {
Ok(sxhash_fixnum(sxhash_eq(&a[0])))
}
fn sxhash_eql_fn(h: &mut ElispHost, a: &[Value]) -> R {
let x = match &a[0] {
Value::Float(_) => sxhash_obj(h, &a[0], 0),
other if h.is_bignum(other) => sxhash_obj(h, other, 0),
other => sxhash_eq(other),
};
Ok(sxhash_fixnum(x))
}
fn type_of(h: &mut ElispHost, a: &[Value]) -> R {
if let Some(Obj::Record(items)) = h.obj(&a[0]) {
let slot0 = items.first().cloned();
return match slot0 {
Some(t) => Ok(t),
None => Ok(h.intern("record")),
};
}
let name = match &a[0] {
Value::Int(_) => "integer",
Value::Float(_) => "float",
Value::Str(_) => "string",
_ if h.is_string(&a[0]) => "string",
Value::Bool(_) | Value::Undef => "symbol",
Value::Obj(_) => match h.obj(&a[0]) {
Some(Obj::Cons(..)) => "cons",
Some(Obj::Overlay(_)) => "overlay",
Some(Obj::Window(_)) => "window",
Some(Obj::Frame(_)) => "frame",
Some(Obj::WindowConfig(_)) => "window-configuration",
Some(Obj::Bignum(_)) => "integer",
Some(Obj::Symbol(_)) => "symbol",
Some(Obj::Vector(_)) => "vector",
Some(Obj::Record(_)) => "record",
Some(Obj::BoolVector(_)) => "bool-vector",
Some(Obj::Str(_)) => "string",
Some(Obj::Subr { .. }) => "subr",
Some(Obj::Closure { is_macro, .. }) => {
if *is_macro {
"cons"
} else {
"interpreted-function"
}
}
Some(Obj::HashTable(_)) => "hash-table",
Some(Obj::CharTable(_)) => "char-table",
Some(Obj::Buffer(_)) => "buffer",
Some(Obj::Marker(_)) => "marker",
Some(Obj::Obarray(_)) => "obarray",
None => "symbol",
},
_ => "symbol",
};
Ok(h.intern(name))
}
fn recordp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Record(_)))))
}
fn prelude_closure_p_fn(h: &mut ElispHost, a: &[Value]) -> R {
let macro_cell = matches!(h.obj(&a[0]), Some(Obj::Closure { is_macro: true, .. }));
Ok(nil_or(
h.is_closure(&a[0]) && !macro_cell && h.is_prelude_object(&a[0]),
))
}
fn closurep_fn(h: &mut ElispHost, a: &[Value]) -> R {
let macro_cell = matches!(h.obj(&a[0]), Some(Obj::Closure { is_macro: true, .. }));
Ok(nil_or(h.is_closure(&a[0]) && !macro_cell))
}
fn oclosure_fix_type(h: &mut ElispHost, a: &[Value]) -> R {
let closure = a[3].clone();
if !h.is_closure(&closure) {
return Err("cl-assertion-failed: (closurep oclosure)".to_string());
}
let ty = h
.as_sym_handle(&a[0])
.ok_or("oclosure--fix-type: type is not a symbol")?;
let slot_vals = h
.list_vec(&a[1])
.ok_or("oclosure--fix-type: slots is not a proper list")?;
let mut slots = Vec::with_capacity(slot_vals.len());
for s in &slot_vals {
slots.push(
h.as_sym_handle(s)
.ok_or("oclosure--fix-type: slot name is not a symbol")?,
);
}
h.oclosure_set_meta(&closure, ty, slots);
Ok(closure)
}
fn oclosure_type_fn(h: &mut ElispHost, a: &[Value]) -> R {
match h.oclosure_type_of(&a[0]) {
Some(id) => Ok(Value::Obj(id)),
None => Ok(Value::Undef),
}
}
fn oclosure_get_fn(h: &mut ElispHost, a: &[Value]) -> R {
if !h.is_closure(&a[0]) {
return Err("cl-assertion-failed: (closurep oclosure)".to_string());
}
let idx = as_int(h, &a[1])? as usize;
h.oclosure_get(&a[0], idx)
.ok_or_else(|| "oclosure--get: slot index out of range".to_string())
}
fn oclosure_set_fn(h: &mut ElispHost, a: &[Value]) -> R {
if !h.is_closure(&a[1]) {
return Err("cl-assertion-failed: (closurep oclosure)".to_string());
}
let idx = as_int(h, &a[2])? as usize;
if h.oclosure_set(&a[1], idx, &a[0]) {
Ok(a[0].clone())
} else {
Err("oclosure--set: slot index out of range".to_string())
}
}
fn oclosure_copy_fn(h: &mut ElispHost, a: &[Value]) -> R {
if !h.is_closure(&a[0]) {
return Err("cl-assertion-failed: (closurep oclosure)".to_string());
}
let args: Vec<Value> = a[2..].to_vec();
h.oclosure_copy(&a[0], &args)
.ok_or_else(|| "oclosure--copy: not an OClosure".to_string())
}
fn functionp(h: &mut ElispHost, a: &[Value]) -> R {
if let Some(Obj::Subr { name, .. }) = h.obj(&a[0]) {
if SPECIAL_FORMS.iter().any(|(sf, _)| *sf == name.as_str()) {
return Ok(Value::Bool(false));
}
}
if h.indirect_lambda_list(&a[0]).is_some() {
return Ok(Value::Bool(true));
}
let mut cur = a[0].clone();
for _ in 0..64 {
match h.obj(&cur) {
Some(Obj::Symbol(s)) => match &s.function {
Some(def) => cur = def.clone(),
None => break,
},
_ => break,
}
}
if let Some(items) = h.list_vec(&cur) {
if items.first().and_then(|c| h.sym_name(c)).as_deref() == Some("autoload")
&& matches!(h.obj(&a[0]), Some(Obj::Symbol(_)))
{
return Ok(nil_or(!items.get(4).is_some_and(crate::host::el_truthy)));
}
}
let ok = match h.resolve_function(&a[0]) {
Ok(Resolved::Subr { .. }) => true,
Ok(Resolved::Closure { is_macro, .. }) => !is_macro,
Err(_) => false,
};
Ok(nil_or(ok))
}
fn char_or_string_p(_h: &mut ElispHost, a: &[Value]) -> R {
let ok = match &a[0] {
Value::Int(n) => (0..=0x3F_FFFF).contains(n),
v => _h.is_string(v),
};
Ok(nil_or(ok))
}
fn char_width_fn(h: &mut ElispHost, a: &[Value]) -> R {
let c = as_char(h, &a[0])?;
Ok(Value::Int(char_display_width(c) as i64))
}
fn char_equal(h: &mut ElispHost, a: &[Value]) -> R {
let (c1, c2) = (as_char(h, &a[0])? as i64, as_char(h, &a[1])? as i64);
if c1 == c2 {
return Ok(Value::Bool(true));
}
if case_fold_search(h) {
if let (Some(x), Some(y)) = (char::from_u32(c1 as u32), char::from_u32(c2 as u32)) {
let eq = x.to_lowercase().eq(y.to_lowercase());
return Ok(nil_or(eq));
}
}
Ok(Value::Bool(false))
}
fn symbol_function(h: &mut ElispHost, a: &[Value]) -> R {
Ok(h.introspect_function_cell(&a[0]).unwrap_or(Value::Undef))
}
pub(crate) fn intercepted_subr(_h: &mut ElispHost, _a: &[Value]) -> R {
Err(
"internal: an intercepted higher-order primitive was called through its \
subr body; host::call_function should have matched it by name"
.to_string(),
)
}
fn set_intrinsic_macro_cell(h: &mut ElispHost, a: &[Value]) -> R {
h.set_intrinsic_macro_cell(&a[0], a[1].clone());
Ok(a[0].clone())
}
fn intern_soft(h: &mut ElispHost, a: &[Value]) -> R {
let name = match &a[0] {
v if h.is_string(v) => h.str_text(v).unwrap_or_default().to_string(),
Value::Bool(true) => "t".to_string(),
v if is_nil(v) => "nil".to_string(),
v => h
.sym_name(v)
.ok_or_else(|| format!("wrong-type-argument: stringp {}", h.print(v, true)))?,
};
match obarray_arg(h, a.get(1))? {
None => match name.as_str() {
"t" => Ok(Value::Bool(true)),
"nil" => Ok(Value::Undef),
_ => Ok(h.find_symbol(&name).unwrap_or(Value::Undef)),
},
Some(id) => Ok(h.obarray_intern_soft(id, &name)),
}
}
fn subrp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Subr { .. }))))
}
fn set_subr_intspec(h: &mut ElispHost, a: &[Value]) -> R {
match h.introspect_function_cell(&a[0]) {
Some(Value::Obj(id)) if matches!(h.obj(&Value::Obj(id)), Some(Obj::Subr { .. })) => {
h.subr_intspecs.insert(id, a[1].clone());
Ok(a[0].clone())
}
_ => Err(h.signal_wrong_type("subrp", &a[0])),
}
}
fn subr_intspec(h: &mut ElispHost, a: &[Value]) -> R {
Ok(match &a[0] {
Value::Obj(id) => h.subr_intspecs.get(id).cloned().unwrap_or(Value::Undef),
_ => Value::Undef,
})
}
const INTRINSIC_MACROS: &[(&str, i64)] = &[
("lambda", 0),
("when", 1),
("unless", 1),
("defun", 2),
("defmacro", 2),
];
const SPECIAL_FORMS: &[(&str, i64)] = &[
("and", 0),
("catch", 1),
("cond", 0),
("condition-case", 2),
("defconst", 2),
("defvar", 1),
("function", 1),
("if", 2),
("inline", 0),
("interactive", 0),
("let", 1),
("let*", 1),
("or", 0),
("prog1", 1),
("progn", 0),
("quote", 1),
("save-current-buffer", 0),
("save-excursion", 0),
("save-restriction", 0),
("setq", 0),
("unwind-protect", 1),
("while", 1),
];
fn macrop(h: &mut ElispHost, a: &[Value]) -> R {
if matches!(
h.resolve_function(&a[0]),
Ok(Resolved::Closure { is_macro: true, .. })
) {
return Ok(Value::Bool(true));
}
let ok = h
.sym_name(&a[0])
.is_some_and(|n| INTRINSIC_MACROS.iter().any(|(m, _)| *m == n.as_str()));
Ok(nil_or(ok))
}
fn special_form_p(h: &mut ElispHost, a: &[Value]) -> R {
let name = match h.obj(&a[0]) {
Some(Obj::Subr { name, .. }) => Some(name.clone()),
_ => h.sym_name(&a[0]),
};
let ok = name.is_some_and(|n| SPECIAL_FORMS.iter().any(|(sf, _)| *sf == n.as_str()));
Ok(nil_or(ok))
}
fn char_uppercase_p(h: &mut ElispHost, a: &[Value]) -> R {
let c = char::from_u32(as_int(h, &a[0])? as u32);
Ok(nil_or(c.is_some_and(|c| c.is_uppercase())))
}
fn string_distance(h: &mut ElispHost, a: &[Value]) -> R {
let a0 = as_string(h, &a[0])?;
let a1 = as_string(h, &a[1])?;
let bytewise = a.len() > 2 && !is_nil(&a[2]);
let (s1, s2): (Vec<u32>, Vec<u32>) = if bytewise {
(
a0.bytes().map(|b| b as u32).collect(),
a1.bytes().map(|b| b as u32).collect(),
)
} else {
(
a0.chars().map(|c| c as u32).collect(),
a1.chars().map(|c| c as u32).collect(),
)
};
let m = s2.len();
let mut prev: Vec<usize> = (0..=m).collect();
let mut cur = vec![0usize; m + 1];
for (i, c1) in s1.iter().enumerate() {
cur[0] = i + 1;
for (j, c2) in s2.iter().enumerate() {
let cost = if c1 == c2 { 0 } else { 1 };
cur[j + 1] = (prev[j + 1] + 1).min(cur[j] + 1).min(prev[j] + cost);
}
std::mem::swap(&mut prev, &mut cur);
}
Ok(Value::Int(prev[m] as i64))
}
fn vconcat_fn(h: &mut ElispHost, a: &[Value]) -> R {
let mut out = Vec::new();
for v in a {
if is_nil(v) {
continue;
}
match h.obj(v) {
Some(Obj::Vector(items)) => out.extend(items.clone()),
_ => match h
.str_text(v)
.map(|s| s.chars().map(|c| Value::Int(c as i64)).collect::<Vec<_>>())
{
Some(chars) => out.extend(chars),
_ => out.extend(h.seq_vec_checked(v)?),
},
}
}
Ok(h.alloc(Obj::Vector(out)))
}
fn abs_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(match as_number_p(h, &a[0], false)? {
Num::Int(n) => {
use num_traits::Signed;
h.make_integer(n.abs())
}
Num::Float(f) => Value::Float(f.abs()),
})
}
fn logcount_fn(h: &mut ElispHost, a: &[Value]) -> R {
use num_traits::Signed;
let n = as_int_exact_p(h, &a[0], false)?;
let counted = if n.is_negative() { !n } else { n };
let bits: u64 = counted
.to_bytes_le()
.1
.iter()
.map(|b| b.count_ones() as u64)
.sum();
Ok(Value::Int(bits as i64))
}
fn sha1_bytes(msg: &[u8]) -> Vec<u8> {
let mut h: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
let ml = (msg.len() as u64).wrapping_mul(8);
let mut data = msg.to_vec();
data.push(0x80);
while data.len() % 64 != 56 {
data.push(0);
}
data.extend_from_slice(&ml.to_be_bytes());
for chunk in data.chunks(64) {
let mut w = [0u32; 80];
for (i, wi) in w.iter_mut().enumerate().take(16) {
*wi = u32::from_be_bytes([
chunk[i * 4],
chunk[i * 4 + 1],
chunk[i * 4 + 2],
chunk[i * 4 + 3],
]);
}
for i in 16..80 {
w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
}
let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]);
for (i, &wi) in w.iter().enumerate() {
let (f, k) = match i {
0..=19 => ((b & c) | ((!b) & d), 0x5A827999u32),
20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
_ => (b ^ c ^ d, 0xCA62C1D6),
};
let tmp = a
.rotate_left(5)
.wrapping_add(f)
.wrapping_add(e)
.wrapping_add(k)
.wrapping_add(wi);
e = d;
d = c;
c = b.rotate_left(30);
b = a;
a = tmp;
}
h[0] = h[0].wrapping_add(a);
h[1] = h[1].wrapping_add(b);
h[2] = h[2].wrapping_add(c);
h[3] = h[3].wrapping_add(d);
h[4] = h[4].wrapping_add(e);
}
h.iter().flat_map(|x| x.to_be_bytes()).collect()
}
fn sha2_32(msg: &[u8], iv: [u32; 8], out_len: usize) -> Vec<u8> {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut h = iv;
let ml = (msg.len() as u64).wrapping_mul(8);
let mut data = msg.to_vec();
data.push(0x80);
while data.len() % 64 != 56 {
data.push(0);
}
data.extend_from_slice(&ml.to_be_bytes());
for chunk in data.chunks(64) {
let mut w = [0u32; 64];
for (i, wi) in w.iter_mut().enumerate().take(16) {
*wi = u32::from_be_bytes([
chunk[i * 4],
chunk[i * 4 + 1],
chunk[i * 4 + 2],
chunk[i * 4 + 3],
]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let mut v = h;
for i in 0..64 {
let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
let ch = (v[4] & v[5]) ^ ((!v[4]) & v[6]);
let t1 = v[7]
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
let t2 = s0.wrapping_add(maj);
v = [
t1.wrapping_add(t2),
v[0],
v[1],
v[2],
v[3].wrapping_add(t1),
v[4],
v[5],
v[6],
];
}
for (hi, vi) in h.iter_mut().zip(v.iter()) {
*hi = hi.wrapping_add(*vi);
}
}
let full: Vec<u8> = h.iter().flat_map(|x| x.to_be_bytes()).collect();
full[..out_len].to_vec()
}
fn sha256_bytes(msg: &[u8]) -> Vec<u8> {
sha2_32(
msg,
[
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
],
32,
)
}
fn sha224_bytes(msg: &[u8]) -> Vec<u8> {
sha2_32(
msg,
[
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7,
0xbefa4fa4,
],
28,
)
}
fn sha2_64(msg: &[u8], iv: [u64; 8], out_len: usize) -> Vec<u8> {
const K: [u64; 80] = [
0x428a2f98d728ae22,
0x7137449123ef65cd,
0xb5c0fbcfec4d3b2f,
0xe9b5dba58189dbbc,
0x3956c25bf348b538,
0x59f111f1b605d019,
0x923f82a4af194f9b,
0xab1c5ed5da6d8118,
0xd807aa98a3030242,
0x12835b0145706fbe,
0x243185be4ee4b28c,
0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f,
0x80deb1fe3b1696b1,
0x9bdc06a725c71235,
0xc19bf174cf692694,
0xe49b69c19ef14ad2,
0xefbe4786384f25e3,
0x0fc19dc68b8cd5b5,
0x240ca1cc77ac9c65,
0x2de92c6f592b0275,
0x4a7484aa6ea6e483,
0x5cb0a9dcbd41fbd4,
0x76f988da831153b5,
0x983e5152ee66dfab,
0xa831c66d2db43210,
0xb00327c898fb213f,
0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2,
0xd5a79147930aa725,
0x06ca6351e003826f,
0x142929670a0e6e70,
0x27b70a8546d22ffc,
0x2e1b21385c26c926,
0x4d2c6dfc5ac42aed,
0x53380d139d95b3df,
0x650a73548baf63de,
0x766a0abb3c77b2a8,
0x81c2c92e47edaee6,
0x92722c851482353b,
0xa2bfe8a14cf10364,
0xa81a664bbc423001,
0xc24b8b70d0f89791,
0xc76c51a30654be30,
0xd192e819d6ef5218,
0xd69906245565a910,
0xf40e35855771202a,
0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8,
0x1e376c085141ab53,
0x2748774cdf8eeb99,
0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63,
0x4ed8aa4ae3418acb,
0x5b9cca4f7763e373,
0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc,
0x78a5636f43172f60,
0x84c87814a1f0ab72,
0x8cc702081a6439ec,
0x90befffa23631e28,
0xa4506cebde82bde9,
0xbef9a3f7b2c67915,
0xc67178f2e372532b,
0xca273eceea26619c,
0xd186b8c721c0c207,
0xeada7dd6cde0eb1e,
0xf57d4f7fee6ed178,
0x06f067aa72176fba,
0x0a637dc5a2c898a6,
0x113f9804bef90dae,
0x1b710b35131c471b,
0x28db77f523047d84,
0x32caab7b40c72493,
0x3c9ebe0a15c9bebc,
0x431d67c49c100d4c,
0x4cc5d4becb3e42b6,
0x597f299cfc657e2a,
0x5fcb6fab3ad6faec,
0x6c44198c4a475817,
];
let mut h = iv;
let bitlen = (msg.len() as u128).wrapping_mul(8);
let mut data = msg.to_vec();
data.push(0x80);
while data.len() % 128 != 112 {
data.push(0);
}
data.extend_from_slice(&bitlen.to_be_bytes());
for chunk in data.chunks(128) {
let mut w = [0u64; 80];
for (i, wi) in w.iter_mut().enumerate().take(16) {
*wi = u64::from_be_bytes([
chunk[i * 8],
chunk[i * 8 + 1],
chunk[i * 8 + 2],
chunk[i * 8 + 3],
chunk[i * 8 + 4],
chunk[i * 8 + 5],
chunk[i * 8 + 6],
chunk[i * 8 + 7],
]);
}
for i in 16..80 {
let s0 = w[i - 15].rotate_right(1) ^ w[i - 15].rotate_right(8) ^ (w[i - 15] >> 7);
let s1 = w[i - 2].rotate_right(19) ^ w[i - 2].rotate_right(61) ^ (w[i - 2] >> 6);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let mut v = h;
for i in 0..80 {
let s1 = v[4].rotate_right(14) ^ v[4].rotate_right(18) ^ v[4].rotate_right(41);
let ch = (v[4] & v[5]) ^ ((!v[4]) & v[6]);
let t1 = v[7]
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let s0 = v[0].rotate_right(28) ^ v[0].rotate_right(34) ^ v[0].rotate_right(39);
let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
let t2 = s0.wrapping_add(maj);
v = [
t1.wrapping_add(t2),
v[0],
v[1],
v[2],
v[3].wrapping_add(t1),
v[4],
v[5],
v[6],
];
}
for (hi, vi) in h.iter_mut().zip(v.iter()) {
*hi = hi.wrapping_add(*vi);
}
}
let full: Vec<u8> = h.iter().flat_map(|x| x.to_be_bytes()).collect();
full[..out_len].to_vec()
}
fn sha512_bytes(msg: &[u8]) -> Vec<u8> {
sha2_64(
msg,
[
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1,
0x510e527fade682d1,
0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b,
0x5be0cd19137e2179,
],
64,
)
}
fn sha384_bytes(msg: &[u8]) -> Vec<u8> {
sha2_64(
msg,
[
0xcbbb9d5dc1059ed8,
0x629a292a367cd507,
0x9159015a3070dd17,
0x152fecd8f70e5939,
0x67332667ffc00b31,
0x8eb44a8768581511,
0xdb0c2e0d64f98fa7,
0x47b5481dbefa4fa4,
],
48,
)
}
fn md5_bytes(msg: &[u8]) -> Vec<u8> {
const S: [u32; 64] = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5,
9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10,
15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
];
const K: [u32; 64] = [
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
0xeb86d391,
];
let (mut a0, mut b0, mut c0, mut d0) =
(0x67452301u32, 0xefcdab89u32, 0x98badcfeu32, 0x10325476u32);
let ml = (msg.len() as u64).wrapping_mul(8);
let mut data = msg.to_vec();
data.push(0x80);
while data.len() % 64 != 56 {
data.push(0);
}
data.extend_from_slice(&ml.to_le_bytes());
for chunk in data.chunks(64) {
let mut m = [0u32; 16];
for (i, mi) in m.iter_mut().enumerate() {
*mi = u32::from_le_bytes([
chunk[i * 4],
chunk[i * 4 + 1],
chunk[i * 4 + 2],
chunk[i * 4 + 3],
]);
}
let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
for i in 0..64 {
let (f, g) = match i {
0..=15 => ((b & c) | ((!b) & d), i),
16..=31 => ((d & b) | ((!d) & c), (5 * i + 1) % 16),
32..=47 => (b ^ c ^ d, (3 * i + 5) % 16),
_ => (c ^ (b | (!d)), (7 * i) % 16),
};
let f = f.wrapping_add(a).wrapping_add(K[i]).wrapping_add(m[g]);
a = d;
d = c;
c = b;
b = b.wrapping_add(f.rotate_left(S[i]));
}
a0 = a0.wrapping_add(a);
b0 = b0.wrapping_add(b);
c0 = c0.wrapping_add(c);
d0 = d0.wrapping_add(d);
}
[a0, b0, c0, d0]
.iter()
.flat_map(|x| x.to_le_bytes())
.collect()
}
fn to_hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
s.push_str(&format!("{b:02x}"));
}
s
}
fn hash_input(h: &mut ElispHost, a: &[Value], obj_idx: usize) -> Result<Vec<u8>, String> {
let s = match as_string(h, &a[obj_idx]) {
Ok(s) => s,
Err(_) => {
let v = a[obj_idx].clone();
return Err(h.signal_error_with("Invalid object argument", &v));
}
};
let bytes = s.as_bytes();
let len = bytes.len() as i64;
let idx = |h: &mut ElispHost, v: &Value| -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ if as_integer(h, v).is_ok() => as_integer(h, v),
_ => Err(h.signal_wrong_type("integerp", v)),
}
};
let raw_start = match a.get(obj_idx + 1) {
Some(v) if !is_nil(v) => Some(idx(h, &v.clone())?),
_ => None,
};
let raw_end = match a.get(obj_idx + 2) {
Some(v) if !is_nil(v) => Some(idx(h, &v.clone())?),
_ => None,
};
let adj = |n: i64| if n < 0 { n + len } else { n };
let start = raw_start.map_or(0, adj);
let end = raw_end.map_or(len, adj);
if start < 0 || end > len || start > end {
let obj = h.print(&a[obj_idx], true);
let sv = raw_start.map_or("nil".to_string(), |n| n.to_string());
let ev = raw_end.map_or("nil".to_string(), |n| n.to_string());
return Err(format!("args-out-of-range: {obj} {sv} {ev}"));
}
Ok(bytes[start as usize..end as usize].to_vec())
}
fn sha1_fn(h: &mut ElispHost, a: &[Value]) -> R {
let digest = to_hex(&sha1_bytes(&hash_input(h, a, 0)?));
Ok(h.new_string(digest))
}
fn md5_fn(h: &mut ElispHost, a: &[Value]) -> R {
let digest = to_hex(&md5_bytes(&hash_input(h, a, 0)?));
Ok(h.new_string(digest))
}
fn secure_hash(h: &mut ElispHost, a: &[Value]) -> R {
let algo = h
.sym_name(&a[0])
.or_else(|| as_string(h, &a[0]).ok())
.unwrap_or_default();
let bytes = hash_input(h, a, 1)?;
let digest = match algo.as_str() {
"md5" => md5_bytes(&bytes),
"sha1" => sha1_bytes(&bytes),
"sha224" => sha224_bytes(&bytes),
"sha256" => sha256_bytes(&bytes),
"sha384" => sha384_bytes(&bytes),
"sha512" => sha512_bytes(&bytes),
other => return Err(format!("error: Invalid algorithm arg: {other}")),
};
if a.get(4).is_some_and(|v| !is_nil(v)) {
Ok(h.new_string(digest.iter().map(|&b| b as char).collect::<String>()))
} else {
Ok(h.new_string(to_hex(&digest)))
}
}
fn secure_hash_algorithms(h: &mut ElispHost, _a: &[Value]) -> R {
let syms = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]
.iter()
.map(|n| h.intern(n))
.collect();
Ok(h.list_from(syms))
}
const B64_STD: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64_URL: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
fn b64_encode(input: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
let mut out = String::new();
for chunk in input.chunks(3) {
let b = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | (b[2] as u32);
out.push(alphabet[((n >> 18) & 63) as usize] as char);
out.push(alphabet[((n >> 12) & 63) as usize] as char);
if chunk.len() > 1 {
out.push(alphabet[((n >> 6) & 63) as usize] as char);
} else if pad {
out.push('=');
}
if chunk.len() > 2 {
out.push(alphabet[(n & 63) as usize] as char);
} else if pad {
out.push('=');
}
}
out
}
fn b64_wrap(s: &str) -> String {
let mut out = String::with_capacity(s.len() + s.len() / 76);
for (i, c) in s.chars().enumerate() {
if i > 0 && i % 76 == 0 {
out.push('\n');
}
out.push(c);
}
out
}
const INVALID_B64: &str = "error: Invalid base64 data";
fn b64_decode(input: &str, url: bool) -> Result<Vec<u8>, String> {
let val = |c: u8| -> Option<u32> {
match c {
b'A'..=b'Z' => Some((c - b'A') as u32),
b'a'..=b'z' => Some((c - b'a' + 26) as u32),
b'0'..=b'9' => Some((c - b'0' + 52) as u32),
b'+' if !url => Some(62),
b'/' if !url => Some(63),
b'-' if url => Some(62),
b'_' if url => Some(63),
_ => None,
}
};
let chars: Vec<u8> = input.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
let mut out = Vec::with_capacity(chars.len() / 4 * 3);
if !url && !chars.len().is_multiple_of(4) {
return Err(INVALID_B64.into());
}
for quad in chars.chunks(4) {
if quad.len() < 4 {
if quad.len() < 2 || quad.contains(&b'=') {
return Err(INVALID_B64.into());
}
let mut v = [0u32; 3];
for (i, &c) in quad.iter().enumerate() {
v[i] = val(c).ok_or(INVALID_B64)?;
}
out.push(((v[0] << 2) | (v[1] >> 4)) as u8);
if quad.len() == 3 {
out.push((((v[1] & 0x0F) << 4) | (v[2] >> 2)) as u8);
}
continue;
}
let mut v = [0u32; 4];
let mut n = 0usize;
let mut padded = false;
for (i, &c) in quad.iter().enumerate() {
if c == b'=' {
padded = true;
continue;
}
if padded {
return Err(INVALID_B64.into());
}
v[i] = val(c).ok_or(INVALID_B64)?;
n += 1;
}
if n < 2 {
return Err(INVALID_B64.into());
}
out.push(((v[0] << 2) | (v[1] >> 4)) as u8);
if n >= 3 {
out.push((((v[1] & 0x0F) << 4) | (v[2] >> 2)) as u8);
}
if n == 4 {
out.push((((v[2] & 0x03) << 6) | v[3]) as u8);
}
}
Ok(out)
}
fn b64_input_bytes(s: &str) -> Result<Vec<u8>, String> {
s.chars()
.map(|c| {
u8::try_from(c as u32)
.map_err(|_| "error: Multibyte character in data for base64 encoding".to_string())
})
.collect()
}
fn bytes_to_str(h: &mut ElispHost, bytes: &[u8]) -> Value {
let text = bytes.iter().map(|&b| b as char).collect::<String>();
h.new_string(text)
}
fn base64_encode_string(h: &mut ElispHost, a: &[Value]) -> R {
let raw = b64_encode(&b64_input_bytes(&as_string(h, &a[0])?)?, B64_STD, true);
let no_break = a.get(1).is_some_and(|v| !is_nil(v));
Ok(h.new_string(if no_break { raw } else { b64_wrap(&raw) }))
}
fn base64_decode_string(h: &mut ElispHost, a: &[Value]) -> R {
let url = a.get(1).is_some_and(|v| !is_nil(v));
let bytes = b64_decode(&as_string(h, &a[0])?, url)?;
Ok(bytes_to_str(h, &bytes))
}
fn base64url_encode_string(h: &mut ElispHost, a: &[Value]) -> R {
let no_pad = a.get(1).is_some_and(|v| !is_nil(v));
Ok(h.new_string(b64_encode(
&b64_input_bytes(&as_string(h, &a[0])?)?,
B64_URL,
!no_pad,
)))
}
fn base64url_decode_string(h: &mut ElispHost, a: &[Value]) -> R {
let bytes = b64_decode(&as_string(h, &a[0])?, true)?;
Ok(bytes_to_str(h, &bytes))
}
fn url_hexify_string(h: &mut ElispHost, a: &[Value]) -> R {
let src = match h.str_text(&a[0]).map(str::to_string) {
Some(s) => s,
None => {
let v = &a[0];
let items = h
.seq_vec(v)
.ok_or_else(|| h.signal_wrong_type("sequencep", v))?;
let mut acc = String::new();
for it in &items {
match char::from_u32(as_char(h, it)?) {
Some(c) => acc.push(c),
None => return Err(h.signal_wrong_type("characterp", it)),
}
}
acc
}
};
let mut out = String::new();
for b in src.as_bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
out.push(*b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
Ok(h.new_string(out))
}
fn url_unhex_string(h: &mut ElispHost, a: &[Value]) -> R {
let s = as_string(h, &a[0])?;
let chars: Vec<char> = s.chars().collect();
let hex = |c: char| c.is_ascii_hexdigit();
let mut out = String::with_capacity(s.len());
let mut i = 0;
while i < chars.len() {
if chars[i] == '%' && i + 2 < chars.len() && hex(chars[i + 1]) && hex(chars[i + 2]) {
let pair: String = chars[i + 1..i + 3].iter().collect();
if let Ok(v) = u8::from_str_radix(&pair, 16) {
out.push(v as char);
i += 3;
continue;
}
}
out.push(chars[i]);
i += 1;
}
Ok(h.new_string(out))
}
fn string_to_vector(h: &mut ElispHost, a: &[Value]) -> R {
let items = h
.seq_vec(&a[0])
.ok_or_else(|| format!("wrong-type-argument: sequencep {}", h.print(&a[0], true)))?;
Ok(h.alloc(Obj::Vector(items)))
}
fn logb_fn(h: &mut ElispHost, a: &[Value]) -> R {
let n = as_number_p(h, &a[0], false)?;
if let crate::host::Num::Int(i) = &n {
let bits = i.bits();
if bits > 0 {
return Ok(Value::Int(bits as i64 - 1));
}
}
let f = n.to_f64();
if f.is_finite() && f != 0.0 {
return Ok(Value::Int(f.abs().log2().floor() as i64));
}
let val = if f.is_nan() {
f
} else if f == 0.0 {
f64::NEG_INFINITY
} else {
f64::INFINITY
};
Ok(Value::Float(val))
}
fn max_char(_h: &mut ElispHost, a: &[Value]) -> R {
let unicode = a.first().map(|v| !is_nil(v)).unwrap_or(false);
Ok(Value::Int(if unicode { 0x10_FFFF } else { 0x3F_FFFF }))
}
fn byteorder(_h: &mut ElispHost, _a: &[Value]) -> R {
Ok(Value::Int(if cfg!(target_endian = "little") {
108
} else {
66
}))
}
const CHAR_ALT: i64 = 0x0400000;
const CHAR_SUPER: i64 = 0x0800000;
const CHAR_HYPER: i64 = 0x1000000;
const CHAR_SHIFT: i64 = 0x2000000;
const CHAR_CTL: i64 = 0x4000000;
const CHAR_META: i64 = 0x8000000;
const CHAR_MODIFIER_MASK: i64 =
CHAR_ALT | CHAR_SUPER | CHAR_HYPER | CHAR_SHIFT | CHAR_CTL | CHAR_META;
const MAX_CHAR: i64 = 0x3F_FFFF;
const MAX_5_BYTE_CHAR: i64 = 0x3F_FF7F;
fn ascii_char_p(c: i64) -> bool {
(0..0x80).contains(&c)
}
fn check_character(h: &ElispHost, v: &Value) -> Result<i64, String> {
let c = as_int(h, v)?;
if (0..=MAX_CHAR).contains(&c) {
Ok(c)
} else {
Err(format!("wrong-type-argument: characterp {c}"))
}
}
fn char_resolve_modifiers(h: &mut ElispHost, a: &[Value]) -> R {
let mut c = as_int(h, &a[0])?;
if !ascii_char_p(c & !CHAR_MODIFIER_MASK) {
return Ok(Value::Int(c));
}
if c & CHAR_SHIFT != 0 {
let base = c & 0o377;
if (b'A' as i64..=b'Z' as i64).contains(&base) {
c &= !CHAR_SHIFT;
} else if (b'a' as i64..=b'z' as i64).contains(&base) {
c = (c & !CHAR_SHIFT) - (b'a' as i64 - b'A' as i64);
} else if (c & !CHAR_MODIFIER_MASK) <= 0x20 {
c &= !CHAR_SHIFT;
}
}
if c & CHAR_CTL != 0 {
let base = c & 0o377;
if base == b' ' as i64 {
c &= !0o177 & !CHAR_CTL;
} else if base == b'?' as i64 {
c = 0o177 | (c & !0o177 & !CHAR_CTL);
} else if (0o101..=0o132).contains(&(c & 0o137)) || (0o100..=0o137).contains(&(c & 0o177)) {
c &= 0o37 | (!0o177 & !CHAR_CTL);
}
}
Ok(Value::Int(c))
}
fn text_char_description(h: &mut ElispHost, a: &[Value]) -> R {
let c = check_character(h, &a[0])?;
if ascii_char_p(c) {
let s = if c < 0o40 {
format!("^{}", (c as u8 + 64) as char)
} else if c == 0o177 {
"^?".to_string()
} else {
(c as u8 as char).to_string()
};
Ok(h.new_string(s))
} else {
Ok(h.new_string(
char::from_u32(c as u32)
.map(|c| c.to_string())
.unwrap_or_default(),
))
}
}
fn unibyte_char_to_multibyte(h: &mut ElispHost, a: &[Value]) -> R {
let c = check_character(h, &a[0])?;
if c >= 256 {
return Err(format!("error: Not a unibyte character: {c}"));
}
Ok(Value::Int(if c < 0x80 { c } else { c + 0x3F_FF00 }))
}
fn multibyte_char_to_unibyte(h: &mut ElispHost, a: &[Value]) -> R {
let c = check_character(h, &a[0])?;
let byte = if c < 256 {
c
} else if c > MAX_5_BYTE_CHAR {
c - 0x3F_FF00
} else {
-1
};
Ok(Value::Int(byte))
}
fn decode_char_code_point(h: &ElispHost, v: &Value) -> Result<i64, String> {
if let Some(Obj::Cons(hi, lo)) = h.obj(v) {
let hi = as_int(h, &hi.clone())?;
let lo = as_int(h, &lo.clone())?;
return Ok((hi << 16) | lo);
}
as_int(h, v)
}
fn decode_char(h: &mut ElispHost, a: &[Value]) -> R {
let name = h
.sym_name(&a[0])
.filter(|n| {
matches!(
n.as_str(),
"ascii" | "eight-bit" | "iso-8859-1" | "ucs" | "unicode" | "unicode-bmp"
)
})
.ok_or_else(|| format!("wrong-type-argument: charsetp {}", h.print(&a[0], true)))?;
let code = decode_char_code_point(h, &a[1])?;
if !(0..=0xFFFF_FFFF).contains(&code) {
return Err(
"error: Not an in-range integer, integral float, or cons of integers".to_string(),
);
}
let ch = match name.as_str() {
"ascii" => (0..=0x7F).contains(&code).then_some(code),
"eight-bit" => (0x80..=0xFF).contains(&code).then_some(0x3F_FF00 + code),
"iso-8859-1" => (0..=0xFF).contains(&code).then_some(code),
"unicode-bmp" => (0..=0xFFFF).contains(&code).then_some(code),
_ => (0..=0x10_FFFF).contains(&code).then_some(code),
};
Ok(ch.map(Value::Int).unwrap_or(Value::Undef))
}
fn emacs_pid(_h: &mut ElispHost, _a: &[Value]) -> R {
Ok(Value::Int(std::process::id() as i64))
}
fn load_average(h: &mut ElispHost, a: &[Value]) -> R {
let use_floats = a.first().map(|v| !is_nil(v)).unwrap_or(false);
let mut loads = [0f64; 3];
let n = unsafe { libc::getloadavg(loads.as_mut_ptr(), 3) };
if n < 0 {
return Err("error: load-average not implemented for this operating system".to_string());
}
let items = loads[..n as usize]
.iter()
.map(|&l| {
if use_floats {
Value::Float(l)
} else {
Value::Int((100.0 * l) as i64)
}
})
.collect();
Ok(h.list_from(items))
}
fn bare_symbol_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(
matches!(a[0], Value::Bool(true))
|| is_nil(&a[0])
|| matches!(h.obj(&a[0]), Some(Obj::Symbol(_))),
))
}
fn car_less_than_car(h: &mut ElispHost, a: &[Value]) -> R {
let car_of = |h: &ElispHost, v: &Value| -> Result<Value, String> {
match h.obj(v) {
Some(Obj::Cons(x, _)) => Ok(x.clone()),
_ if is_nil(v) => Ok(Value::Undef),
_ => Err(format!("wrong-type-argument: listp {}", h.print(v, true))),
}
};
let a0 = car_of(h, &a[0])?;
let b0 = car_of(h, &a[1])?;
Ok(nil_or(as_num(h, &a0)?.1 < as_num(h, &b0)?.1))
}
fn subr_name(h: &mut ElispHost, a: &[Value]) -> R {
match h.obj(&a[0]) {
Some(Obj::Subr { name, .. }) => Ok(h.new_string(name.clone())),
_ => Err(format!(
"wrong-type-argument: subrp {}",
h.print(&a[0], true)
)),
}
}
fn default_boundp(h: &mut ElispHost, a: &[Value]) -> R {
check_symbol(h, &a[0])?;
let bound = is_nil(&a[0]) || matches!(a[0], Value::Bool(true)) || h.default_boundp_raw(&a[0]);
Ok(nil_or(bound))
}
fn default_toplevel_value(h: &mut ElispHost, a: &[Value]) -> R {
h.raw_global_value(&a[0])
}
fn read_fn(h: &mut ElispHost, a: &[Value]) -> R {
let stream = a.first().cloned().unwrap_or(Value::Undef);
let (bi, marker) = match h.obj(&stream) {
Some(Obj::Buffer(idx)) => (*idx, None),
Some(Obj::Marker(m)) => match m.borrow().buffer {
Some(idx) => (idx, Some(m.clone())),
None => return Err("error: Marker does not point anywhere".to_string()),
},
_ => {
let s = as_string(h, &stream)?;
return crate::reader::read_one(h, &s, 0).map(|(form, _)| form);
}
};
let (start, text) = {
let b = &h.buffers[bi];
let start = marker.as_ref().map_or(b.point, |m| m.borrow().pos);
let start = start.clamp(b.begv, b.zv);
(
start,
b.text[start - 1..b.zv - 1].iter().collect::<String>(),
)
};
let r = crate::reader::read_one(h, &text, 0);
let end = match &r {
Ok((_, end)) => start + end,
Err(e) if e == "end-of-file" => start + text.chars().count(),
Err(_) => start,
};
let from_buffer = marker.is_none();
match marker {
Some(m) => m.borrow_mut().pos = end,
None => h.buffers[bi].point = end,
}
match r {
Err(e) if e == "end-of-file" && from_buffer => {
let sym = h.intern("end-of-file");
let obj = h.list_from(vec![sym, stream]);
h.set_pending_error(&e, obj);
Err(e)
}
r => r.map(|(form, _)| form),
}
}
fn read_from_minibuffer(h: &mut ElispHost, a: &[Value]) -> R {
use std::io::Read;
let prompt = as_string(h, &a[0])?;
h.write_stdout(&prompt);
let mut line = Vec::new();
let mut ended = false;
let mut byte = [0u8; 1];
while let Ok(1) = h.stdin.read(&mut byte) {
if matches!(byte[0], b'\n' | b'\r') {
ended = true;
break;
}
line.push(byte[0]);
}
if line.is_empty() && !ended {
let msg = h.new_string("Error reading from stdin");
return Err(signal_with_data(h, "end-of-file", vec![msg]));
}
let text = String::from_utf8_lossy(&line).into_owned();
if a.get(3).is_none_or(is_nil) {
return Ok(h.new_string(text));
}
string_to_object(h, text, a.get(5))
}
fn string_to_object(h: &mut ElispHost, text: String, default: Option<&Value>) -> R {
let mut val = h.new_string(text);
if h.str_text(&val).is_some_and(str::is_empty) {
let default = default.cloned().unwrap_or(Value::Undef);
let car = match h.obj(&default) {
Some(Obj::Cons(car, _)) => car.clone(),
_ => Value::Undef,
};
if h.str_text(&default).is_some() {
val = default;
} else if h.str_text(&car).is_some() {
val = car;
}
}
let read = read_from_string(h, std::slice::from_ref(&val))?;
let Some(Obj::Cons(obj, end)) = h.obj(&read).cloned() else {
unreachable!("read-from-string returns (OBJECT . END)")
};
let rest: String = as_string(h, &val)?
.chars()
.skip(usize::try_from(as_integer(h, &end)?).unwrap_or(0))
.collect();
if rest.chars().any(|c| !matches!(c, ' ' | '\t' | '\n')) {
let msg = h.new_string("Trailing garbage following expression");
return Err(signal_with_data(h, "invalid-read-syntax", vec![msg]));
}
Ok(obj)
}
fn read_string(h: &mut ElispHost, a: &[Value]) -> R {
let get = |i: usize| a.get(i).cloned().unwrap_or(Value::Undef);
let default = get(3);
let val = read_from_minibuffer(
h,
&[
get(0),
get(1),
Value::Undef,
Value::Undef,
get(2),
default.clone(),
get(4),
],
)?;
if h.str_text(&val).is_some_and(str::is_empty) && !is_nil(&default) {
return Ok(match h.obj(&default) {
Some(Obj::Cons(car, _)) => car.clone(),
_ => default,
});
}
Ok(val)
}
fn signal_with_data(h: &mut ElispHost, symbol: &str, data: Vec<Value>) -> String {
let data = h.list_from(data);
let msg = format!("{symbol}: {}", h.print(&data, true));
let sym = h.intern(symbol);
let obj = h.cons(sym, data);
h.set_pending_error(&msg, obj);
msg
}
fn read_from_string(h: &mut ElispHost, a: &[Value]) -> R {
let s = as_string(h, &a[0])?;
let size = s.chars().count() as i64;
let adj = |v: Option<&Value>, default: i64| -> i64 {
match v {
Some(Value::Int(n)) => {
if *n < 0 {
n + size
} else {
*n
}
}
_ => default,
}
};
let from = adj(a.get(1), 0);
let to = adj(a.get(2), size);
if !(0 <= from && from <= to && to <= size) {
let disp = |v: Option<&Value>| match v {
None | Some(Value::Undef) | Some(Value::Bool(false)) => "nil".to_string(),
Some(v) => h.print(v, true),
};
return Err(format!(
"args-out-of-range: {} {} {}",
h.print(&a[0], true),
disp(a.get(1)),
disp(a.get(2))
));
}
let limited: String = s.chars().take(to as usize).collect();
let (form, end) = crate::reader::read_one(h, &limited, from as usize)?;
Ok(h.cons(form, Value::Int(end as i64)))
}
fn validate_subarray(
h: &ElispHost,
array: &Value,
from: &Value,
to: Option<&Value>,
size: usize,
) -> Result<(usize, usize), String> {
let to = to.cloned().unwrap_or(Value::Undef);
let to = match to {
Value::Int(n) if n > size as i64 => Value::Int(size as i64),
other => other,
};
let resolve = |v: &Value, default: i64| -> Result<i64, String> {
match v {
Value::Int(n) => Ok(if *n < 0 { n + size as i64 } else { *n }),
_ if is_nil(v) => Ok(default),
_ => Err(format!(
"wrong-type-argument: integerp {}",
h.print(v, true)
)),
}
};
let f = resolve(from, 0)?;
let t = resolve(&to, size as i64)?;
if !(0 <= f && f <= t && t <= size as i64) {
return Err(format!(
"args-out-of-range: {} {} {}",
h.print(array, true),
h.print(from, true),
h.print(&to, true)
));
}
Ok((f as usize, t as usize))
}
fn compare_strings(h: &mut ElispHost, a: &[Value]) -> R {
let s1: Vec<char> = as_string(h, &a[0])?.chars().collect();
let s2: Vec<char> = as_string(h, &a[3])?.chars().collect();
let (start1, end1) = validate_subarray(h, &a[0], &a[1], a.get(2), s1.len())?;
let (start2, end2) = validate_subarray(h, &a[3], &a[4], a.get(5), s2.len())?;
let ignore_case = a.get(6).is_some_and(|v| !is_nil(v));
let sub1 = &s1[start1..end1];
let sub2 = &s2[start2..end2];
let fold = |c: char| {
if ignore_case {
c.to_lowercase().next().unwrap_or(c)
} else {
c
}
};
let n = sub1.len().min(sub2.len());
for i in 0..n {
let (x, y) = (fold(sub1[i]), fold(sub2[i]));
if x != y {
let idx = (i + 1) as i64;
return Ok(Value::Int(if x < y { -idx } else { idx }));
}
}
match sub1.len().cmp(&sub2.len()) {
std::cmp::Ordering::Less => Ok(Value::Int(-((n + 1) as i64))),
std::cmp::Ordering::Greater => Ok(Value::Int((n + 1) as i64)),
std::cmp::Ordering::Equal => Ok(Value::Bool(true)),
}
}
fn member_ignore_case(h: &mut ElispHost, a: &[Value]) -> R {
let elt = a[0].clone();
let mut cur = a[1].clone();
loop {
let (car, cdr) = match h.obj(&cur) {
Some(Obj::Cons(car, cdr)) => (car.clone(), cdr.clone()),
_ if is_nil(&cur) => return Ok(Value::Undef),
_ => return Err(h.signal_wrong_type("listp", &cur)),
};
if h.is_string(&car) {
let cmp = compare_strings(
h,
&[
elt.clone(),
Value::Int(0),
Value::Undef,
car,
Value::Int(0),
Value::Undef,
Value::Bool(true),
],
)?;
if matches!(cmp, Value::Bool(true)) {
return Ok(cur);
}
}
cur = cdr;
}
}
fn now_secs() -> f64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0)
}
thread_local! {
static RNG_STATE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
fn rng_seed() -> u64 {
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0x9e3779b97f4a7c15);
nanos | 1
}
pub(crate) fn rng_next() -> u64 {
RNG_STATE.with(|s| {
let mut x = s.get();
if x == 0 {
x = rng_seed();
}
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
s.set(x);
x
})
}
fn random_fixnum() -> i64 {
((rng_next() << 2) as i64) >> 2
}
fn random_fn(h: &mut ElispHost, a: &[Value]) -> R {
let limit = a.first().cloned().unwrap_or(Value::Undef);
match &limit {
Value::Bool(true) => RNG_STATE.with(|s| s.set(rng_seed())),
Value::Int(n) => {
if *n <= 0 {
return Err(args_out_of_range_values(h, vec![limit.clone()]));
}
return Ok(Value::Int((rng_next() % *n as u64) as i64));
}
_ => {
if let Some(Obj::Bignum(b)) = h.obj(&limit) {
let b = b.clone();
if b.sign() != num_bigint::Sign::Plus {
return Err(args_out_of_range_values(h, vec![limit.clone()]));
}
let words = b.bits() / 64 + 2;
let mut r = BigInt::from(0u8);
for _ in 0..words {
r = (r << 64) + BigInt::from(rng_next());
}
return Ok(h.make_integer(r % b));
}
if h.is_string(&limit) {
let s = as_string(h, &limit)?;
let seed = s.bytes().fold(0xcbf2_9ce4_8422_2325u64, |acc, c| {
(acc ^ c as u64).wrapping_mul(0x0100_0000_01b3)
});
RNG_STATE.with(|st| st.set(seed | 1));
}
}
}
Ok(Value::Int(random_fixnum()))
}
fn time_arg_secs(h: &ElispHost, v: Option<&Value>) -> Result<f64, String> {
crate::timefns::float_seconds(h, v)
}
fn time_arg_split(h: &ElispHost, v: Option<&Value>) -> Result<(i64, i64), String> {
use num_integer::Integer;
let t = crate::timefns::decode(h, v, false)?;
let (secs, frac) = t.ticks.div_mod_floor(&t.hz);
let secs = num_traits::ToPrimitive::to_i64(&secs).ok_or_else(crate::timefns::overflow)?;
let nanos = (frac * BigInt::from(1_000_000_000)).div_floor(&t.hz);
Ok((secs, num_traits::ToPrimitive::to_i64(&nanos).unwrap_or(0)))
}
enum TimeZone {
Local,
Utc,
Fixed(i64, String),
Named(String),
}
const MAX_ZONE_OFFSET: i64 = 7 * 24 * 3600;
fn time_zone_arg(h: &mut ElispHost, zone: Option<&Value>) -> Result<TimeZone, String> {
let Some(z) = zone else {
return Ok(TimeZone::Local);
};
let invalid = |h: &mut ElispHost| {
let z = z.clone();
Err(h.signal_error_with("Invalid time zone specification", &z))
};
match z {
Value::Undef | Value::Bool(false) => return Ok(TimeZone::Local),
Value::Bool(true) => return Ok(TimeZone::Utc),
Value::Int(off) => return Ok(fixed_time_zone(*off, None)),
_ => {}
}
if h.is_string(z) {
let tz = as_string(h, z)?;
return Ok(TimeZone::Named(tz));
}
match h.obj(z) {
Some(Obj::Symbol(s)) if s.name == "wall" => Ok(TimeZone::Local),
Some(Obj::Cons(car, cdr)) => {
let (car, cdr) = (car.clone(), cdr.clone());
let name = match h.obj(&cdr) {
Some(Obj::Cons(name, _)) => name.clone(),
_ => return invalid(h),
};
let Value::Int(off) = car else {
return invalid(h);
};
if !h.is_string(&name) {
return Err(h.signal_wrong_type("stringp", &name));
}
let abbr = as_string(h, &name)?;
Ok(fixed_time_zone(off, Some(abbr)))
}
_ => invalid(h),
}
}
fn fixed_time_zone(off: i64, abbr: Option<String>) -> TimeZone {
if off.abs() >= MAX_ZONE_OFFSET {
return TimeZone::Utc;
}
if let Some(abbr) = abbr {
return TimeZone::Fixed(off, abbr);
}
if off == 0 {
return TimeZone::Utc;
}
let a = off.abs();
let (hh, mm, ss) = (a / 3600, (a % 3600) / 60, a % 60);
let sign = if off < 0 { '-' } else { '+' };
let name = match (mm, ss) {
(0, 0) => format!("{sign}{hh:02}"),
(_, 0) => format!("{sign}{hh:02}{mm:02}"),
_ => format!("{sign}{hh:02}{mm:02}{ss:02}"),
};
TimeZone::Fixed(off, name)
}
static TZ_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn with_tz_env<T>(tz: &str, f: impl FnOnce() -> T) -> T {
extern "C" {
fn tzset();
}
let _guard = TZ_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let saved = std::env::var_os("TZ");
std::env::set_var("TZ", tz);
unsafe { tzset() };
let out = f();
match saved {
Some(v) => std::env::set_var("TZ", v),
None => std::env::remove_var("TZ"),
}
unsafe { tzset() };
out
}
struct DecodedTime {
tm: libc::tm,
_zone_name: Option<std::ffi::CString>,
}
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y.rem_euclid(400);
let mp = (m + 9) % 12;
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
fn civil_from_days(z: i64) -> (i64, i64, i64) {
let z = z + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
(y, m, d)
}
fn civil_tm(secs: i64) -> Option<libc::tm> {
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
let (y, m, d) = civil_from_days(days);
let mut tm: libc::tm = unsafe { std::mem::zeroed() };
tm.tm_year = libc::c_int::try_from(y - 1900).ok()?;
tm.tm_mon = (m - 1) as libc::c_int;
tm.tm_mday = d as libc::c_int;
tm.tm_hour = (rem / 3600) as libc::c_int;
tm.tm_min = (rem % 3600 / 60) as libc::c_int;
tm.tm_sec = (rem % 60) as libc::c_int;
tm.tm_wday = (days + 4).rem_euclid(7) as libc::c_int;
tm.tm_yday = (days - days_from_civil(y, 1, 1)) as libc::c_int;
Some(tm)
}
fn civil_secs(tm: &libc::tm) -> i64 {
let months = i64::from(tm.tm_year) * 12 + i64::from(tm.tm_mon);
let year = 1900 + months.div_euclid(12);
let mon = months.rem_euclid(12) + 1;
let days = days_from_civil(year, mon, 1) + i64::from(tm.tm_mday) - 1;
days * 86_400 + i64::from(tm.tm_hour) * 3600 + i64::from(tm.tm_min) * 60 + i64::from(tm.tm_sec)
}
#[allow(clippy::useless_conversion)]
fn zone_mktime(tm: &mut libc::tm) -> i64 {
let probe = *tm;
let r = unsafe { libc::mktime(tm) } as i64;
if r != -1 {
return r;
}
let wall = civil_secs(&probe);
let mut guess = wall;
for _ in 0..4 {
let mut out: libc::tm = unsafe { std::mem::zeroed() };
let t = guess as libc::time_t;
if unsafe { libc::localtime_r(&t, &mut out) }.is_null() {
break;
}
let next = wall - i64::from(out.tm_gmtoff);
if next == guess {
break;
}
guess = next;
}
guess
}
fn time_decompose(secs: i64, zone: &TimeZone) -> Result<DecodedTime, String> {
let t = secs as libc::time_t;
let mut tm: libc::tm = unsafe { std::mem::zeroed() };
let mut name: Option<std::ffi::CString> = None;
match zone {
TimeZone::Local => {
let _guard = TZ_LOCK.lock().unwrap_or_else(|e| e.into_inner());
if unsafe { libc::localtime_r(&t, &mut tm) }.is_null() {
return Err(crate::timefns::overflow());
}
}
TimeZone::Utc => {
tm = civil_tm(secs).ok_or_else(crate::timefns::overflow)?;
name = Some(std::ffi::CString::new("UTC").expect("no NUL"));
}
TimeZone::Fixed(off, abbr) => {
let shifted = secs
.checked_add(*off)
.ok_or_else(crate::timefns::overflow)?;
tm = civil_tm(shifted).ok_or_else(crate::timefns::overflow)?;
tm.tm_gmtoff = *off as libc::c_long;
name = Some(std::ffi::CString::new(abbr.replace('\0', "")).expect("NUL removed"));
}
TimeZone::Named(tz) => {
let ok = with_tz_env(tz, || {
if unsafe { libc::localtime_r(&t, &mut tm) }.is_null() {
return false;
}
if !tm.tm_zone.is_null() {
let s = unsafe { std::ffi::CStr::from_ptr(tm.tm_zone) };
name = Some(s.to_owned());
}
true
});
if !ok {
return Err(crate::timefns::overflow());
}
}
}
if let Some(n) = &name {
tm.tm_zone = n.as_ptr() as *mut libc::c_char;
}
Ok(DecodedTime {
tm,
_zone_name: name,
})
}
fn fmt_time_string(
h: &mut ElispHost,
fmt: &str,
tm: &libc::tm,
secs: i64,
nanos: i64,
) -> Result<Value, String> {
let bytes = crate::strftime::format(fmt.as_bytes(), tm, secs, nanos)
.map_err(|_| crate::timefns::overflow())?;
Ok(h.new_string(String::from_utf8_lossy(&bytes).into_owned()))
}
fn float_time(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Float(time_arg_secs(h, a.first())?))
}
fn sleep_for(h: &mut ElispHost, a: &[Value]) -> R {
let mut duration = as_number_p(h, &a[0], false)?.to_f64();
if let Some(ms) = a.get(1).filter(|v| !is_nil(v)) {
duration += as_fixnum_named(h, ms, "fixnump")? as f64 / 1000.0;
}
if duration > 0.0 {
std::thread::sleep(std::time::Duration::from_secs_f64(duration));
}
Ok(Value::Undef)
}
fn current_time(_h: &mut ElispHost, _a: &[Value]) -> R {
let secs = now_secs();
let isec = secs.floor() as i64;
let usec = ((secs - secs.floor()) * 1.0e6) as i64;
Ok(_h.list_from(vec![
Value::Int(isec >> 16),
Value::Int(isec & 0xffff),
Value::Int(usec),
Value::Int(0),
]))
}
fn build_time(h: &mut ElispHost, _a: &[Value]) -> R {
use std::os::unix::fs::MetadataExt;
let (isec, nsec) = std::env::current_exe()
.ok()
.and_then(|p| std::fs::metadata(p).ok())
.map(|m| (m.mtime(), m.mtime_nsec()))
.unwrap_or((0, 0));
Ok(h.list_from(vec![
Value::Int(isec >> 16),
Value::Int(isec & 0xffff),
Value::Int(nsec / 1000),
Value::Int(0),
]))
}
fn format_time_string(h: &mut ElispHost, a: &[Value]) -> R {
let fmt = as_string(h, &a[0])?;
let (secs, nanos) = time_arg_split(h, a.get(1))?;
let zone = time_zone_arg(h, a.get(2))?;
let decoded = time_decompose(secs, &zone)?;
fmt_time_string(h, &fmt, &decoded.tm, secs, nanos)
}
fn current_time_string(h: &mut ElispHost, a: &[Value]) -> R {
let (secs, nanos) = time_arg_split(h, a.first())?;
let zone = time_zone_arg(h, a.get(1))?;
let decoded = time_decompose(secs, &zone)?;
fmt_time_string(h, "%a %b %e %H:%M:%S %Y", &decoded.tm, secs, nanos)
}
#[allow(clippy::useless_conversion)]
fn decode_time(h: &mut ElispHost, a: &[Value]) -> R {
let exact = if matches!(a.get(2), Some(Value::Bool(true))) {
Some(crate::timefns::decode(h, a.first(), false)?)
} else {
None
};
let secs = match &exact {
Some(t) => crate::timefns::floor_seconds(t)?,
None => crate::timefns::seconds_argument(h, a.first())?,
};
let zone = time_zone_arg(h, a.get(1))?;
let decoded = time_decompose(secs, &zone)?;
let tm = decoded.tm;
let dst = match tm.tm_isdst {
0 => Value::Undef,
n if n > 0 => Value::Bool(true),
_ => Value::Int(-1),
};
let sec = match exact {
Some(t) if t.hz != BigInt::from(1) => {
use num_integer::Integer;
let ticks = t.ticks.mod_floor(&t.hz) + &t.hz * BigInt::from(tm.tm_sec);
let ticks = h.make_integer(ticks);
let hz = h.make_integer(t.hz);
h.cons(ticks, hz)
}
_ => Value::Int(tm.tm_sec as i64),
};
Ok(h.list_from(vec![
sec,
Value::Int(tm.tm_min as i64),
Value::Int(tm.tm_hour as i64),
Value::Int(tm.tm_mday as i64),
Value::Int(tm.tm_mon as i64 + 1),
Value::Int(tm.tm_year as i64 + 1900),
Value::Int(tm.tm_wday as i64),
dst,
Value::Int(i64::from(tm.tm_gmtoff)),
]))
}
fn encode_time(h: &mut ElispHost, a: &[Value]) -> R {
let mut isdst: libc::c_int = -1;
let (fields, zone): (Vec<Value>, Value) = if a.len() == 1 {
let mut fields = Vec::with_capacity(6);
let mut tail = a[0].clone();
for _ in 0..6 {
let Some(Obj::Cons(car, cdr)) = h.obj(&tail) else {
return Err(h.signal_wrong_type("consp", &tail));
};
fields.push(car.clone());
tail = cdr.clone();
}
let mut zone = Value::Undef;
if !is_nil(&tail) {
let Some(Obj::Cons(_, rest)) = h.obj(&tail) else {
return Err(h.signal_wrong_type("consp", &tail));
};
let rest = rest.clone();
let Some(Obj::Cons(dstflag, rest2)) = h.obj(&rest) else {
return Err(h.signal_wrong_type("consp", &rest));
};
let (dstflag, rest2) = (dstflag.clone(), rest2.clone());
let Some(Obj::Cons(z, _)) = h.obj(&rest2) else {
return Err(h.signal_wrong_type("consp", &rest2));
};
zone = z.clone();
let is_symbol = is_nil(&dstflag)
|| matches!(dstflag, Value::Bool(true))
|| h.sym_name(&dstflag).is_some();
let zone_fixnum_or_cons =
matches!(zone, Value::Int(_)) || matches!(h.obj(&zone), Some(Obj::Cons(..)));
if is_symbol && !zone_fixnum_or_cons {
isdst = libc::c_int::from(!is_nil(&dstflag));
}
}
(fields, zone)
} else if a.len() < 6 {
let f = h.intern("encode-time");
let n = h.list_from(vec![f, Value::Int(a.len() as i64)]);
let sym = h.intern("wrong-number-of-arguments");
let obj = h.cons(sym, n);
let msg = format!("wrong-number-of-arguments: encode-time {}", a.len());
h.set_pending_error(&msg, obj);
return Err(msg);
} else {
let zone = if a.len() > 6 {
a[a.len() - 1].clone()
} else {
Value::Undef
};
(a[..6].to_vec(), zone)
};
let t = crate::timefns::decode(h, Some(&fields[0]), false)?;
let (sec, subsec) = {
use num_integer::Integer;
t.ticks.div_mod_floor(&t.hz)
};
let member = |h: &mut ElispHost, v: &Value, offset: i64| -> Result<libc::c_int, String> {
let Value::Int(n) = v else {
return Err(h.signal_wrong_type("fixnump", v));
};
libc::c_int::try_from(n - offset).map_err(|_| crate::timefns::overflow())
};
let sec_v = h.make_integer(sec);
let mut tm: libc::tm = unsafe { std::mem::zeroed() };
tm.tm_sec = member(h, &sec_v, 0)?;
tm.tm_min = member(h, &fields[1], 0)?;
tm.tm_hour = member(h, &fields[2], 0)?;
tm.tm_mday = member(h, &fields[3], 0)?;
tm.tm_mon = member(h, &fields[4], 1)?;
tm.tm_year = member(h, &fields[5], 1900)?;
tm.tm_isdst = isdst;
let tz = time_zone_arg(h, Some(&zone))?;
if civil_tm(civil_secs(&tm)).is_none() {
return Err(crate::timefns::overflow());
}
let value: i64 = match &tz {
TimeZone::Fixed(off, _) => civil_secs(&tm) - *off,
TimeZone::Local => {
let _guard = TZ_LOCK.lock().unwrap_or_else(|e| e.into_inner());
zone_mktime(&mut tm)
}
TimeZone::Utc => civil_secs(&tm),
TimeZone::Named(name) => with_tz_env(name, || zone_mktime(&mut tm)),
};
if t.hz == BigInt::from(1) {
return Ok(h.list_from(vec![Value::Int(value >> 16), Value::Int(value & 0xffff)]));
}
let ticks = BigInt::from(value) * &t.hz + subsec;
let ticks = h.make_integer(ticks);
let hz = h.make_integer(t.hz);
Ok(h.cons(ticks, hz))
}
fn env_entries(h: &ElispHost, env: &Value, stop_at_non_string: bool) -> Vec<String> {
let mut out = Vec::new();
let mut cur = env.clone();
while let Some(Obj::Cons(car, cdr)) = h.obj(&cur) {
match h.str_text(car) {
Some(s) => out.push(s.to_string()),
None if stop_at_non_string => break,
None => {}
}
cur = cdr.clone();
}
out
}
fn env_lookup(entries: &[String], var: &str) -> Option<Option<String>> {
entries.iter().find_map(|entry| {
let rest = entry.strip_prefix(var)?;
match rest.strip_prefix('=') {
Some(value) => Some(Some(value.to_string())),
None if rest.is_empty() => Some(None),
None => None,
}
})
}
fn symbol_value_or_nil(h: &mut ElispHost, name: &str) -> Value {
let sym = h.intern(name);
h.get_value(&sym).unwrap_or(Value::Undef)
}
fn getenv_internal(h: &mut ElispHost, a: &[Value]) -> R {
let Some(var) = h.str_text(&a[0]).map(str::to_string) else {
return Err(format!(
"wrong-type-argument: stringp {}",
h.print(&a[0], true)
));
};
let env = a.get(1).cloned().unwrap_or(Value::Undef);
if matches!(h.obj(&env), Some(Obj::Cons(..))) {
let entries = env_entries(h, &env, false);
return Ok(match env_lookup(&entries, &var) {
Some(Some(value)) => h.new_string(value),
Some(None) => Value::Bool(true),
None => Value::Undef,
});
}
let process_env = symbol_value_or_nil(h, "process-environment");
let mut found = env_lookup(&env_entries(h, &process_env, false), &var);
if found.is_none() && var == "DISPLAY" {
let initial = symbol_value_or_nil(h, "initial-environment");
found = env_lookup(&env_entries(h, &initial, false), &var);
}
Ok(match found {
Some(Some(value)) => h.new_string(value),
_ => Value::Undef,
})
}
pub(crate) fn egetenv(h: &mut ElispHost, var: &str) -> Option<String> {
let process_env = symbol_value_or_nil(h, "process-environment");
env_lookup(&env_entries(h, &process_env, false), var).flatten()
}
fn set_time_zone_rule(h: &mut ElispHost, a: &[Value]) -> R {
let tz = a[0].clone();
if !is_nil(&tz) {
time_zone_arg(h, Some(&tz))?;
}
let offset_rule = |off: i64, abbr: Option<String>| {
let abszone = off.abs();
let (hour, rem) = (abszone / 3600, abszone % 3600);
let (min, sec) = (rem / 60, rem % 60);
let sign = if off < 0 { "" } else { "-" };
let name = abbr.unwrap_or_else(|| {
let (mut prec, mut numzone) = (2, hour);
if rem != 0 {
prec += 2;
numzone = 100 * numzone + min;
if sec != 0 {
prec += 2;
numzone = 100 * numzone + sec;
}
}
let numzone = if off < 0 { -numzone } else { numzone };
format!("{numzone:+0width$}", width = prec + 1)
});
format!("<{name}>{sign}{hour}:{min:02}:{sec:02}")
};
let rule: Option<String> = match &tz {
Value::Undef | Value::Bool(false) => None,
Value::Bool(true) | Value::Int(0) => Some("UTC0".to_string()),
Value::Int(off) => Some(offset_rule(*off, None)),
_ if h.is_string(&tz) => Some(as_string(h, &tz)?),
_ => match h.obj(&tz) {
Some(Obj::Cons(Value::Int(off), rest)) => {
let (off, rest) = (*off, rest.clone());
let abbr = match h.obj(&rest) {
Some(Obj::Cons(abbr, _)) => abbr.clone(),
_ => Value::Undef,
};
Some(offset_rule(off, Some(as_string(h, &abbr)?)))
}
_ => None,
},
};
extern "C" {
fn tzset();
}
let _guard = TZ_LOCK.lock().unwrap_or_else(|e| e.into_inner());
match rule {
Some(rule) => std::env::set_var("TZ", rule),
None => std::env::remove_var("TZ"),
}
unsafe { tzset() };
Ok(Value::Undef)
}
fn child_environment(h: &mut ElispHost, current_dir: &str) -> Vec<(String, String)> {
let process_env = symbol_value_or_nil(h, "process-environment");
let entries = env_entries(h, &process_env, true);
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut out = Vec::new();
if let Some(Some(_)) = env_lookup(&env_entries(h, &process_env, false), "PWD") {
let mut pwd = current_dir.to_string();
while pwd.len() > 2 && pwd.ends_with('/') {
pwd.pop();
}
seen.insert("PWD".to_string());
out.push(("PWD".to_string(), pwd));
}
let mentions_display = entries
.iter()
.any(|e| e == "DISPLAY" || e.starts_with("DISPLAY="));
if !mentions_display {
let initial = symbol_value_or_nil(h, "initial-environment");
if let Some(Some(display)) = env_lookup(&env_entries(h, &initial, false), "DISPLAY") {
seen.insert("DISPLAY".to_string());
out.push(("DISPLAY".to_string(), display));
}
}
for entry in entries {
let (name, value) = match entry.split_once('=') {
Some((n, v)) => (n.to_string(), Some(v.to_string())),
None => (entry.clone(), None),
};
if seen.insert(name.clone()) {
if let Some(value) = value {
out.push((name, value));
}
}
}
out
}
fn subprocess_directory(h: &mut ElispHost) -> Result<String, String> {
let curdir = symbol_value_or_nil(h, "default-directory");
let dir = if h.is_string(&curdir) {
curdir.clone()
} else {
h.new_string("~")
};
let expanded = crate::fileio::expand_file_name(h, &[dir])?;
let file = crate::fileio::directory_file_name(h, &[expanded])?;
let dir = remove_slash_colon(&as_string(h, &file)?).to_string();
if let Err(e) = accessible_directory(&dir) {
let shown = h.str_text(&curdir).map(str::to_string);
let shown = shown.unwrap_or_else(|| h.print(&curdir, false));
return Err(report_file_errno(
h,
"Setting current directory",
&[&shown],
&e,
));
}
Ok(dir)
}
fn accessible_directory(dir: &str) -> std::io::Result<()> {
let probe = if dir.ends_with('/') {
dir.to_string()
} else {
format!("{dir}/")
};
let c = std::ffi::CString::new(probe)
.map_err(|_| std::io::Error::from_raw_os_error(libc::ENOENT))?;
if unsafe { libc::access(c.as_ptr(), libc::F_OK) } == 0 {
Ok(())
} else {
Err(std::io::Error::last_os_error())
}
}
fn find_program(h: &mut ElispHost, program: &str) -> Result<String, String> {
let dirs = if program.starts_with('/') || program.starts_with('~') {
vec![Value::Undef]
} else {
let path = symbol_value_or_nil(h, "exec-path");
h.list_vec(&path).unwrap_or_default()
};
let suffixes_v = symbol_value_or_nil(h, "exec-suffixes");
let mut suffixes: Vec<String> = h
.list_vec(&suffixes_v)
.unwrap_or_default()
.iter()
.filter_map(|s| h.str_text(s).map(str::to_string))
.collect();
if suffixes.is_empty() {
suffixes.push(String::new());
}
for dir in dirs {
let dir = if is_nil(&dir) {
symbol_value_or_nil(h, "default-directory")
} else {
dir
};
if !is_nil(&dir) && !h.is_string(&dir) {
continue;
}
for suffix in &suffixes {
let name = h.new_string(format!("{program}{suffix}"));
let full = crate::fileio::expand_file_name(h, &[name, dir.clone()])?;
let full = as_string(h, &full)?;
let is_file = std::fs::metadata(&full).is_ok_and(|m| !m.is_dir());
if is_file && fs_access(std::path::Path::new(&full), libc::X_OK) {
return Ok(full);
}
}
}
let e = std::io::Error::from_raw_os_error(libc::ENOENT);
Err(report_file_errno(
h,
"Searching for program",
&[program],
&e,
))
}
pub(crate) fn install_exec_path(h: &mut ElispHost) {
let path = egetenv(h, "PATH").unwrap_or_default();
let mut dirs: Vec<Value> = path
.split(':')
.map(|d| h.new_string(if d.is_empty() { "." } else { d }))
.collect();
let exec_dir = symbol_value_or_nil(h, "exec-directory");
if h.is_string(&exec_dir) {
if let Ok(d) = crate::fileio::directory_file_name(h, &[exec_dir]) {
dirs.push(d);
}
}
let exec_path = h.list_from(dirs);
let sym = h.intern("exec-path");
let _ = h.set_value(&sym, exec_path);
let shell = egetenv(h, "SHELL").unwrap_or_else(|| "/bin/sh".to_string());
let shell = h.new_string(shell);
let sym = h.intern("shell-file-name");
let _ = h.set_value(&sym, shell);
}
fn special_variable_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(h.symbol_special(&a[0])))
}
fn func_arity(h: &mut ElispHost, a: &[Value]) -> R {
if let Some(name) = h.sym_name(&a[0]) {
let name = name.as_str().to_owned();
if let Some((_, min)) = SPECIAL_FORMS.iter().find(|(sf, _)| *sf == name) {
let unevalled = h.intern("unevalled");
return Ok(h.cons(Value::Int(*min), unevalled));
}
if let Some((_, min)) = INTRINSIC_MACROS.iter().find(|(m, _)| *m == name) {
let many = h.intern("many");
return Ok(h.cons(Value::Int(*min), many));
}
}
if let Some(fun) = h.indirect_lambda_list(&a[0]) {
let arglist = match h.obj(&fun) {
Some(Obj::Cons(_, rest)) => match h.obj(rest) {
Some(Obj::Cons(args, _)) => args.clone(),
_ => return Err(h.signal_invalid_function(&fun)),
},
_ => return Err(h.signal_invalid_function(&fun)),
};
let (mut min, mut max, mut optional) = (0i64, 0i64, false);
let mut cur = arglist;
while let Some(Obj::Cons(next, rest)) = h.obj(&cur) {
let (next, rest) = (next.clone(), rest.clone());
match h.sym_name(&next).as_deref() {
None => return Err(h.signal_invalid_function(&fun)),
Some("&rest") => {
let many = h.intern("many");
return Ok(h.cons(Value::Int(min), many));
}
Some("&optional") => optional = true,
Some(_) => {
if !optional {
min += 1;
}
max += 1;
}
}
cur = rest;
}
if !matches!(cur, Value::Undef | Value::Bool(false)) {
return Err(h.signal_invalid_function(&fun));
}
return Ok(h.cons(Value::Int(min), Value::Int(max)));
}
let (min, max) = {
match h.resolve_function(&a[0])? {
Resolved::Subr { min, max, .. } => (min as i64, max.map(|m| m as i64)),
Resolved::Closure { params, .. } => {
let mn = params.required.len() as i64;
if params.rest.is_some() {
(mn, None)
} else {
(mn, Some(mn + params.optional.len() as i64))
}
}
}
};
let maxv = match max {
Some(m) => Value::Int(m),
None => h.intern("many"),
};
Ok(h.cons(Value::Int(min), maxv))
}
fn current_directory(h: &mut ElispHost, _a: &[Value]) -> R {
use std::os::unix::fs::MetadataExt;
let same_file =
|a: &std::fs::Metadata, b: &std::fs::Metadata| a.dev() == b.dev() && a.ino() == b.ino();
let from_pwd = std::env::var("PWD").ok().filter(|pwd| {
pwd.starts_with('/')
&& match (std::fs::metadata(pwd), std::fs::metadata(".")) {
(Ok(p), Ok(d)) => same_file(&p, &d),
_ => false,
}
});
Ok(h.new_string(from_pwd.unwrap_or_else(|| {
std::env::current_dir()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| "/".to_string())
})))
}
fn system_type(h: &mut ElispHost, _a: &[Value]) -> R {
let sym = match std::env::consts::OS {
"macos" => "darwin",
"linux" => "gnu/linux",
"windows" => "windows-nt",
"freebsd" | "openbsd" | "netbsd" | "dragonfly" => "berkeley-unix",
"android" => "android",
_ => "gnu/linux",
};
Ok(h.intern(sym))
}
fn system_name(h: &mut ElispHost, _a: &[Value]) -> R {
let mut buf = [0u8; 256];
let rc = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) };
if rc != 0 {
return Ok(h.new_string("unknown"));
}
let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
if end == 0 {
return Ok(h.new_string("unknown"));
}
Ok(h.new_string(String::from_utf8_lossy(&buf[..end]).into_owned()))
}
fn uid_arg(h: &ElispHost, v: &Value) -> Result<u32, String> {
const MSG: &str = "error: Not an in-range integer, integral float, or cons of integers";
let n = match v {
Value::Int(n) => Some(*n),
Value::Float(f) if f.fract() == 0.0 && *f >= 0.0 && *f <= u32::MAX as f64 => {
Some(*f as i64)
}
_ => cons_parts(h, v).and_then(|(hi, lo)| {
let lo = cons_parts(h, &lo).map_or(lo, |(car, _)| car);
match (hi, lo) {
(Value::Int(hi), Value::Int(lo)) if hi >= 0 && (0..1 << 16).contains(&lo) => {
hi.checked_mul(1 << 16).map(|v| v + lo)
}
_ => None,
}
}),
};
n.and_then(|n| u32::try_from(n).ok())
.ok_or_else(|| MSG.to_string())
}
fn login_name_from_env() -> String {
std::env::var("LOGNAME")
.or_else(|_| std::env::var("USER"))
.ok()
.or_else(|| id_name(unsafe { libc::geteuid() }, false))
.unwrap_or_else(|| "unknown".to_string())
}
fn user_login_name(h: &mut ElispHost, a: &[Value]) -> R {
match a.first().filter(|v| !is_nil(v)) {
Some(uid) => {
let uid = uid_arg(h, uid)?;
Ok(id_name(uid, false).map_or(Value::Undef, |s| h.new_string(s)))
}
None => Ok(h.new_string(login_name_from_env())),
}
}
fn user_real_login_name(h: &mut ElispHost, _a: &[Value]) -> R {
let name = id_name(unsafe { libc::getuid() }, false).unwrap_or_else(|| "unknown".to_string());
Ok(h.new_string(name))
}
fn user_uid(_h: &mut ElispHost, _a: &[Value]) -> R {
Ok(Value::Int(unsafe { libc::geteuid() } as i64))
}
fn user_real_uid(_h: &mut ElispHost, _a: &[Value]) -> R {
Ok(Value::Int(unsafe { libc::getuid() } as i64))
}
fn temp_directory(h: &mut ElispHost, _a: &[Value]) -> R {
if let Ok(v) = std::env::var("TMPDIR") {
return Ok(h.new_string(v));
}
#[cfg(target_os = "macos")]
{
let mut buf = [0u8; 1024];
let n = unsafe {
libc::confstr(
libc::_CS_DARWIN_USER_TEMP_DIR,
buf.as_mut_ptr() as *mut libc::c_char,
buf.len(),
)
};
if n > 1 && n <= buf.len() {
if let Ok(s) = std::str::from_utf8(&buf[..n - 1]) {
return Ok(h.new_string(s.to_string()));
}
}
}
Ok(h.new_string("/tmp/".to_string()))
}
pub(crate) fn report_file_errno(
h: &mut ElispHost,
string: &str,
names: &[&str],
err: &std::io::Error,
) -> String {
let errno = err.raw_os_error();
let shown = err.to_string();
let errstring = match shown.rfind(" (os error ") {
Some(i) if errno.is_some() => shown[..i].to_string(),
_ => shown,
};
let condition = match errno {
Some(libc::EEXIST) => "file-already-exists",
Some(libc::ENOENT) => "file-missing",
Some(libc::EACCES) => "permission-denied",
_ => "file-error",
};
let mut data = Vec::with_capacity(names.len() + 2);
if errno != Some(libc::EEXIST) {
data.push(h.new_string(string.to_string()));
}
data.push(h.new_string(errstring));
data.extend(names.iter().map(|n| h.new_string(n.to_string())));
let sym = h.intern(condition);
let data = h.list_from(data);
let obj = h.cons(sym, data);
let msg = format!("{condition}: {}", h.print(&obj, true));
h.set_pending_error(&msg, obj);
msg
}
fn fs_expand(s: &str) -> std::path::PathBuf {
std::path::PathBuf::from(remove_slash_colon(s))
}
fn remove_slash_colon(s: &str) -> &str {
match s.strip_prefix("/:") {
Some("") => "/",
Some(rest) => rest,
None => s,
}
}
fn fs_access(p: &std::path::Path, mode: libc::c_int) -> bool {
use std::os::unix::ffi::OsStrExt;
match std::ffi::CString::new(p.as_os_str().as_bytes()) {
Ok(c) => unsafe { libc::access(c.as_ptr(), mode) == 0 },
Err(_) => false,
}
}
fn file_exists_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(fs_expand(&as_string(h, &a[0])?).exists()))
}
fn file_directory_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(fs_expand(&as_string(h, &a[0])?).is_dir()))
}
fn file_regular_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(fs_expand(&as_string(h, &a[0])?).is_file()))
}
fn file_readable_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(fs_access(
&fs_expand(&as_string(h, &a[0])?),
libc::R_OK,
)))
}
fn file_writable_p(h: &mut ElispHost, a: &[Value]) -> R {
let p = fs_expand(&as_string(h, &a[0])?);
let target = if p.exists() {
p.clone()
} else {
p.parent().map(|x| x.to_path_buf()).unwrap_or(p)
};
Ok(nil_or(fs_access(&target, libc::W_OK)))
}
fn file_symlink_p(h: &mut ElispHost, a: &[Value]) -> R {
match std::fs::read_link(fs_expand(&as_string(h, &a[0])?)) {
Ok(t) => Ok(h.new_string(t.to_string_lossy().into_owned())),
Err(_) => Ok(Value::Undef),
}
}
fn file_attribute_errno(h: &mut ElispHost, file: &str, err: &std::io::Error) -> R {
match err.raw_os_error() {
Some(libc::ENOENT) | Some(libc::ENOTDIR) => Ok(Value::Undef),
_ => Err(report_file_errno(h, "Getting attributes", &[file], err)),
}
}
fn lisp_timestamp(h: &mut ElispHost, sec: i64, nsec: i64) -> Value {
h.list_from(vec![
Value::Int(sec >> 16),
Value::Int(sec & 0xffff),
Value::Int(nsec / 1000),
Value::Int(nsec % 1000 * 1000),
])
}
fn mode_bits<T: Into<u32>>(m: T) -> u32 {
m.into()
}
fn file_mode_string(mode: u32) -> String {
let kind = match mode & mode_bits(libc::S_IFMT) {
m if m == mode_bits(libc::S_IFREG) => '-',
m if m == mode_bits(libc::S_IFDIR) => 'd',
m if m == mode_bits(libc::S_IFBLK) => 'b',
m if m == mode_bits(libc::S_IFCHR) => 'c',
m if m == mode_bits(libc::S_IFLNK) => 'l',
m if m == mode_bits(libc::S_IFIFO) => 'p',
m if m == mode_bits(libc::S_IFSOCK) => 's',
_ => '?',
};
let bit = |mask: u32, c: char| if mode & mask != 0 { c } else { '-' };
let exec =
|x: u32, special: u32, set: char, unset: char| match (mode & x != 0, mode & special != 0) {
(true, true) => set,
(false, true) => unset,
(true, false) => 'x',
(false, false) => '-',
};
[
kind,
bit(0o400, 'r'),
bit(0o200, 'w'),
exec(0o100, 0o4000, 's', 'S'),
bit(0o040, 'r'),
bit(0o020, 'w'),
exec(0o010, 0o2000, 's', 'S'),
bit(0o004, 'r'),
bit(0o002, 'w'),
exec(0o001, 0o1000, 't', 'T'),
]
.iter()
.collect()
}
fn id_name(id: u32, group: bool) -> Option<String> {
unsafe {
let name = if group {
let gr = libc::getgrgid(id);
if gr.is_null() {
return None;
}
(*gr).gr_name
} else {
let pw = libc::getpwuid(id);
if pw.is_null() {
return None;
}
(*pw).pw_name
};
if name.is_null() {
return None;
}
Some(
std::ffi::CStr::from_ptr(name)
.to_string_lossy()
.into_owned(),
)
}
}
fn file_attributes(h: &mut ElispHost, a: &[Value]) -> R {
use std::os::unix::fs::MetadataExt;
let Some(name) = h.str_text(&a[0]).map(str::to_string) else {
return Ok(Value::Undef);
};
let path = fs_expand(&name);
let st = match std::fs::symlink_metadata(&path) {
Ok(st) => st,
Err(e) => return file_attribute_errno(h, &name, &e),
};
let ft = st.file_type();
let kind = if ft.is_dir() {
Value::Bool(true)
} else if ft.is_symlink() {
match std::fs::read_link(&path) {
Ok(t) => h.new_string(t.to_string_lossy().into_owned()),
Err(e) => return file_attribute_errno(h, &name, &e),
}
} else {
Value::Undef
};
let by_name = match a.get(1) {
Some(v) if !is_nil(v) => h.sym_name(v).is_none_or(|n| n.as_str() != "integer"),
_ => false,
};
let id =
|h: &mut ElispHost, n: u32, group: bool| match by_name.then(|| id_name(n, group)).flatten()
{
Some(s) => h.new_string(s),
None => Value::Int(n as i64),
};
let uid = id(h, st.uid(), false);
let gid = id(h, st.gid(), true);
let size = h.make_integer(BigInt::from(st.size()));
let atime = lisp_timestamp(h, st.atime(), st.atime_nsec());
let mtime = lisp_timestamp(h, st.mtime(), st.mtime_nsec());
let ctime = lisp_timestamp(h, st.ctime(), st.ctime_nsec());
let modes = h.new_string(file_mode_string(st.mode()));
let inode = h.make_integer(BigInt::from(st.ino()));
let device = h.make_integer(BigInt::from(st.dev()));
Ok(h.list_from(vec![
kind,
Value::Int(st.nlink() as i64),
uid,
gid,
atime,
mtime,
ctime,
size,
modes,
Value::Bool(true),
inode,
device,
]))
}
fn nofollow_flag(h: &ElispHost, flag: Option<&Value>) -> bool {
flag.and_then(|v| h.sym_name(v))
.is_some_and(|n| n.as_str() == "nofollow")
}
fn file_modes(h: &mut ElispHost, a: &[Value]) -> R {
use std::os::unix::fs::MetadataExt;
let name = as_string(h, &a[0])?;
let path = fs_expand(&name);
let st = if nofollow_flag(h, a.get(1)) {
std::fs::symlink_metadata(&path)
} else {
std::fs::metadata(&path)
};
match st {
Ok(st) => Ok(Value::Int((st.mode() & 0o7777) as i64)),
Err(e) => file_attribute_errno(h, &name, &e),
}
}
fn set_file_modes(h: &mut ElispHost, a: &[Value]) -> R {
let name = as_string(h, &a[0])?;
let mode = as_fixnum_named(h, &a[1], "fixnump")?;
let flags = if nofollow_flag(h, a.get(2)) {
libc::AT_SYMLINK_NOFOLLOW
} else {
0
};
let Ok(c) = std::ffi::CString::new(remove_slash_colon(&name)) else {
let e = std::io::Error::from_raw_os_error(libc::EINVAL);
return Err(report_file_errno(h, "Doing chmod", &[&name], &e));
};
if unsafe { libc::fchmodat(libc::AT_FDCWD, c.as_ptr(), mode as libc::mode_t, flags) } != 0 {
let e = std::io::Error::last_os_error();
return Err(report_file_errno(h, "Doing chmod", &[&name], &e));
}
Ok(Value::Undef)
}
fn file_newer_than_file_p(h: &mut ElispHost, a: &[Value]) -> R {
let mut names = Vec::with_capacity(2);
for v in &a[..2] {
as_string(h, v)?;
let file = crate::fileio::directory_file_name(h, std::slice::from_ref(v))?;
names.push(as_string(h, &file)?);
}
let mtime = |n: &str| {
use std::os::unix::fs::MetadataExt;
std::fs::metadata(fs_expand(n)).map(|m| (m.mtime(), m.mtime_nsec()))
};
let t1 = match mtime(&names[0]) {
Ok(t) => t,
Err(e) => return file_attribute_errno(h, &names[0], &e),
};
match mtime(&names[1]) {
Ok(t2) => Ok(nil_or(t1 > t2)),
Err(e) => {
file_attribute_errno(h, &names[1], &e)?;
Ok(Value::Bool(true))
}
}
}
fn file_accessible_directory_p(h: &mut ElispHost, a: &[Value]) -> R {
let name = as_string(h, &a[0])?;
let dir = remove_slash_colon(&name);
let probe = if dir.ends_with('/') {
format!("{dir}.")
} else {
format!("{dir}/.")
};
Ok(nil_or(fs_access(std::path::Path::new(&probe), libc::F_OK)))
}
fn delete_directory_internal(h: &mut ElispHost, a: &[Value]) -> R {
let name = as_string(h, &a[0])?;
std::fs::remove_dir(fs_expand(&name))
.map_err(|e| report_file_errno(h, "Removing directory", &[&name], &e))?;
Ok(Value::Undef)
}
fn cp_target(file: &str, newname: &str) -> String {
if newname.ends_with('/') {
let base = file.rsplit('/').next().unwrap_or(file);
format!("{newname}{base}")
} else {
newname.to_string()
}
}
fn make_link(
h: &mut ElispHost,
string: &str,
names: &[&str],
ok_if_exists: Option<&Value>,
make: impl Fn() -> std::io::Result<()>,
) -> Result<(), String> {
let newname = names[names.len() - 1];
let mut result = make();
if matches!(&result, Err(e) if e.raw_os_error() == Some(libc::EEXIST)) {
let replace = ok_if_exists.is_some_and(|v| !is_nil(v) && !matches!(v, Value::Int(_)));
if !replace {
let sym = h.intern("file-already-exists");
let data = vec![
h.new_string("File already exists".to_string()),
h.new_string(newname.to_string()),
];
let data = h.list_from(data);
let obj = h.cons(sym, data);
let msg = format!("file-already-exists: {}", h.print(&obj, true));
h.set_pending_error(&msg, obj);
return Err(msg);
}
let _ = std::fs::remove_file(fs_expand(newname));
result = make();
}
result.map_err(|e| report_file_errno(h, string, names, &e))
}
fn make_symbolic_link(h: &mut ElispHost, a: &[Value]) -> R {
let target = as_string(h, &a[0])?;
let link = cp_target(&target, &as_string(h, &a[1])?);
let path = fs_expand(&link);
make_link(
h,
"Making symbolic link",
&[&target, &link],
a.get(2),
|| std::os::unix::fs::symlink(&target, &path),
)?;
Ok(Value::Undef)
}
fn add_name_to_file(h: &mut ElispHost, a: &[Value]) -> R {
let file = as_string(h, &a[0])?;
let newname = cp_target(&file, &as_string(h, &a[1])?);
let (from, to) = (fs_expand(&file), fs_expand(&newname));
make_link(h, "Adding new name", &[&file, &newname], a.get(2), || {
std::fs::hard_link(&from, &to)
})?;
Ok(Value::Undef)
}
fn file_executable_p(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(fs_access(
&fs_expand(&as_string(h, &a[0])?),
libc::X_OK,
)))
}
fn invocation_file(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(h.new_string(
std::env::current_exe()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| "elisp".to_string()),
))
}
fn directory_files_raw(h: &mut ElispHost, a: &[Value]) -> R {
let raw = as_string(h, &a[0])?;
let match_re = match a.get(1) {
Some(v) if !is_nil(v) => Some(compile_cf(h, &as_string(h, v)?, false)?),
_ => None,
};
let nosort = a.get(2).is_some_and(|v| !is_nil(v));
let rd = std::fs::read_dir(fs_expand(&raw))
.map_err(|e| report_file_errno(h, "Opening directory", &[&raw], &e))?;
let mut names: Vec<String> = vec![".".into(), "..".into()];
for e in rd.flatten() {
names.push(e.file_name().to_string_lossy().into_owned());
}
if let Some(re) = match_re {
names.retain(|n| re.is_match(n).unwrap_or(false));
}
if !nosort {
names.sort();
}
Ok(h.list_from(names.into_iter().map(Value::str).collect()))
}
fn bufferp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Buffer(_)))))
}
fn current_buffer_fn(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(h.current_buffer())
}
fn set_buffer_fn(h: &mut ElispHost, a: &[Value]) -> R {
h.set_buffer(&a[0])
}
fn get_buffer(h: &mut ElispHost, a: &[Value]) -> R {
match h.get_buffer(&a[0])? {
Some(idx) => Ok(h.buffers[idx].self_obj.clone()),
None => Ok(Value::Undef),
}
}
fn get_buffer_create(h: &mut ElispHost, a: &[Value]) -> R {
if matches!(h.obj(&a[0]), Some(Obj::Buffer(_))) {
return Ok(a[0].clone());
}
let name = as_string(h, &a[0])?;
check_buffer_name(&name)?;
let existed = h.find_buffer_by_name(&name).is_some();
let buffer = h.get_buffer_create(&name);
if !existed && a.get(1).is_some_and(|v| !is_nil(v)) {
let idx = h.resolve_buffer(&buffer).expect("fresh buffer");
h.buffers[idx].inhibit_hooks = true;
}
Ok(buffer)
}
fn check_buffer_name(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err("error: Empty string for buffer name is not allowed".to_string());
}
Ok(())
}
fn generate_new_buffer(h: &mut ElispHost, a: &[Value]) -> R {
let base = as_string(h, &a[0])?;
check_buffer_name(&base)?;
let name = h.generate_new_buffer_name(&base, None);
let buffer = h.get_buffer_create(&name);
if a.get(1).is_some_and(|v| !is_nil(v)) {
let idx = h.resolve_buffer(&buffer).expect("fresh buffer");
h.buffers[idx].inhibit_hooks = true;
}
Ok(buffer)
}
fn generate_new_buffer_name(h: &mut ElispHost, a: &[Value]) -> R {
let base = as_string(h, &a[0])?;
let ignore = match a.get(1) {
Some(v) if !is_nil(v) => Some(as_string(h, v)?),
_ => None,
};
Ok(h.new_string(h.generate_new_buffer_name(&base, ignore.as_deref())))
}
fn buffer_name(h: &mut ElispHost, a: &[Value]) -> R {
let idx = match a.first() {
Some(v) if !is_nil(v) => match h.resolve_buffer(v) {
Some(i) => i,
None => return Ok(Value::Undef),
},
_ => h.current,
};
Ok(match &h.buffers[idx].name {
Some(n) => h.new_string(n.clone()),
None => Value::Undef,
})
}
fn buffer_live_p(h: &mut ElispHost, a: &[Value]) -> R {
let ok = matches!(h.obj(&a[0]), Some(Obj::Buffer(idx))
if h.buffers.get(*idx).is_some_and(|b| b.name.is_some()));
Ok(nil_or(ok))
}
fn kill_buffer(h: &mut ElispHost, a: &[Value]) -> R {
Ok(h.kill_buffer(a.first()))
}
fn get_buffer_process(h: &mut ElispHost, a: &[Value]) -> R {
if !is_nil(&a[0]) && h.resolve_buffer(&a[0]).is_none() && !h.is_string(&a[0]) {
return Err(h.signal_wrong_type("stringp", &a[0]));
}
Ok(Value::Undef)
}
fn rename_buffer(h: &mut ElispHost, a: &[Value]) -> R {
let newname = as_string(h, &a[0])?;
let unique = a.get(1).is_some_and(|v| !is_nil(v));
h.rename_buffer(&newname, unique)
}
fn buffer_list(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(h.buffer_list())
}
fn mark_marker_fn(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(h.mark_marker())
}
fn region_limit(h: &mut ElispHost, beginningp: bool) -> R {
let var = |h: &mut ElispHost, name: &str| {
let sym = h.intern(name);
h.get_dynamic_value(&sym)
.map(|v| !is_nil(&v))
.unwrap_or(false)
};
if var(h, "transient-mark-mode") && !var(h, "mark-even-if-inactive") && !var(h, "mark-active") {
return Err("mark-inactive".to_string());
}
let m = h
.mark_pos()
.ok_or("error: The mark is not set now, so there is no region")?;
let b = h.cur_buf_ref();
Ok(Value::Int(if (b.point < m) == beginningp {
b.point
} else {
m.clamp(b.begv, b.zv)
} as i64))
}
fn region_beginning(h: &mut ElispHost, _a: &[Value]) -> R {
region_limit(h, true)
}
fn region_end(h: &mut ElispHost, _a: &[Value]) -> R {
region_limit(h, false)
}
fn narrow_to_region(h: &mut ElispHost, a: &[Value]) -> R {
let (lo, hi) = narrow_bounds(h, &a[0], &a[1])?;
h.narrow(lo, hi);
Ok(Value::Undef)
}
fn narrow_bounds(h: &mut ElispHost, b: &Value, e: &Value) -> Result<(usize, usize), String> {
let (s0, e0) = (fix_position(h, b)?, fix_position(h, e)?);
let (lo, hi) = if e0 < s0 { (e0, s0) } else { (s0, e0) };
let z = h.cur_buf_ref().text.len() as i64 + 1;
if lo < 1 || hi > z {
return Err(args_out_of_range_values(h, vec![b.clone(), e.clone()]));
}
Ok((lo as usize, hi as usize))
}
fn widen_fn(h: &mut ElispHost, _a: &[Value]) -> R {
h.widen();
Ok(Value::Undef)
}
fn se_push(h: &mut ElispHost, _a: &[Value]) -> R {
let p = h.cur_buf().point;
h.cur_buf().se_markers.push(p);
Ok(Value::Undef)
}
fn se_pop(h: &mut ElispHost, _a: &[Value]) -> R {
let buf = h.cur_buf();
if let Some(m) = buf.se_markers.pop() {
buf.point = m.clamp(buf.begv, buf.zv);
}
Ok(Value::Undef)
}
fn save_restriction_push(h: &mut ElispHost, _a: &[Value]) -> R {
let buf = h.cur_buf();
let (lo, hi) = (buf.begv, buf.zv);
buf.restrict_stack.push((lo, hi));
Ok(Value::Undef)
}
fn restore_restriction(h: &mut ElispHost, _a: &[Value]) -> R {
let buf = h.cur_buf();
if let Some((lo, hi)) = buf.restrict_stack.pop() {
let maxzv = buf.text.len() + 1;
buf.begv = lo.clamp(1, maxzv);
buf.zv = hi.clamp(1, maxzv);
buf.point = buf.point.clamp(buf.begv, buf.zv);
}
Ok(Value::Undef)
}
fn make_local_variable(h: &mut ElispHost, a: &[Value]) -> R {
h.make_local_variable(&a[0])
}
fn make_variable_buffer_local(h: &mut ElispHost, a: &[Value]) -> R {
h.make_variable_buffer_local(&a[0])
}
fn check_symbol(h: &mut ElispHost, v: &Value) -> Result<(), String> {
if !is_nil(&symbolp(h, std::slice::from_ref(v))?) {
Ok(())
} else {
Err(h.signal_wrong_type("symbolp", v))
}
}
fn local_variable_p(h: &mut ElispHost, a: &[Value]) -> R {
let bi = decode_buffer(h, a.get(1))?;
check_symbol(h, &a[0])?;
Ok(nil_or(h.local_variable_p(&a[0], bi)))
}
fn local_variable_if_set_p(h: &mut ElispHost, a: &[Value]) -> R {
check_symbol(h, &a[0])?;
if h.is_auto_local_var(&a[0]) {
return Ok(Value::Bool(true));
}
if !h.has_any_local(&a[0]) {
return Ok(Value::Undef);
}
let bi = decode_buffer(h, a.get(1))?;
Ok(nil_or(h.local_variable_p(&a[0], bi)))
}
fn kill_local_variable(h: &mut ElispHost, a: &[Value]) -> R {
h.kill_local_variable(&a[0])
}
fn buffer_local_symbols_fn(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(h.buffer_local_symbols())
}
fn make_always_local_fn(h: &mut ElispHost, a: &[Value]) -> R {
let init = match h.sym_name(&a[1]).as_deref() {
Some(":inherit") => crate::host::SlotInit::Inherit,
Some(":undo-list") => crate::host::SlotInit::UndoList,
_ => crate::host::SlotInit::Value(a[1].clone()),
};
h.make_always_local(&a[0], init)
}
fn early_declarations_fn(h: &mut ElispHost, _a: &[Value]) -> R {
let forms = std::mem::take(&mut h.early_declarations);
Ok(h.list_from(forms))
}
fn defvar_declare_fn(h: &mut ElispHost, a: &[Value]) -> R {
h.declare_special_locally(&a[0]);
Ok(a[0].clone())
}
fn declare_special_fn(h: &mut ElispHost, a: &[Value]) -> R {
h.set_special(&a[0]);
Ok(Value::Undef)
}
fn buffer_local_value_fn(h: &mut ElispHost, a: &[Value]) -> R {
let idx = match a.get(1) {
Some(v) if !is_nil(v) => h
.resolve_buffer(v)
.ok_or_else(|| format!("wrong-type-argument: bufferp {}", h.print(v, true)))?,
_ => h.current,
};
h.buffer_local_or_default(&a[0], idx)
}
fn default_value_fn(h: &mut ElispHost, a: &[Value]) -> R {
h.raw_global_value(&a[0])
}
fn set_default_fn(h: &mut ElispHost, a: &[Value]) -> R {
h.set_raw_global(&a[0], a[1].clone())?;
Ok(a[1].clone())
}
fn use_local_map_fn(h: &mut ElispHost, a: &[Value]) -> R {
h.use_local_map(a[0].clone());
Ok(Value::Undef)
}
fn current_local_map_fn(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(h.current_local_map())
}
fn insert_chars(h: &ElispHost, v: &Value) -> Result<Vec<char>, String> {
if let Some(s) = h.str_text(v) {
return Ok(s.chars().collect());
}
match v {
Value::Int(n) => Ok(vec![char::from_u32(*n as u32).unwrap_or('\u{fffd}')]),
_ => Err(format!(
"wrong-type-argument: char-or-string-p {}",
h.print(v, true)
)),
}
}
fn insert_fn(h: &mut ElispHost, a: &[Value]) -> R {
for v in a {
let start = h.cur_buf_ref().point; let chars = insert_chars(h, v)?;
if !chars.is_empty() {
h.barf_if_read_only()?;
}
let n = chars.len();
h.cur_insert(chars, true);
if let Some(arc) = h.str_arc(v) {
h.buffer_graft_string_props(&arc, start - 1, n);
}
}
Ok(Value::Undef)
}
fn insert_before_markers_fn(h: &mut ElispHost, a: &[Value]) -> R {
let chunks = insert_chars(h, &a[0])?;
if !chunks.is_empty() {
h.barf_if_read_only()?;
}
h.cur_insert_before_markers(chunks);
Ok(Value::Undef)
}
fn buffer_string(h: &mut ElispHost, _a: &[Value]) -> R {
let (begv, zv) = {
let b = h.cur_buf_ref();
(b.begv, b.zv)
};
let text: String = h.cur_buf_ref().text[(begv - 1)..(zv - 1)].iter().collect();
let (out, arc) = h.new_string_keyed(text);
h.string_from_buffer_props(&arc, begv - 1, zv - 1);
Ok(out)
}
fn buffer_size(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(Value::Int(h.cur_buf().text.len() as i64))
}
fn point_fn(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(Value::Int(h.cur_buf().point as i64))
}
fn point_min(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(Value::Int(h.cur_buf().begv as i64))
}
fn point_max(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(Value::Int(h.cur_buf().zv as i64))
}
fn goto_char(h: &mut ElispHost, a: &[Value]) -> R {
let arg = as_int_or_marker(h, &a[0], "integer-or-marker-p")?;
let buf = h.cur_buf();
buf.point = arg.clamp(buf.begv as i64, buf.zv as i64) as usize;
Ok(a[0].clone())
}
fn position_bytes(h: &mut ElispHost, a: &[Value]) -> R {
let pos = fix_position(h, &a[0])?;
let text = &h.cur_buf_ref().text;
if !(1 <= pos && pos <= text.len() as i64 + 1) {
return Ok(Value::Undef);
}
let bytes: usize = text[..pos as usize - 1].iter().map(|c| c.len_utf8()).sum();
Ok(Value::Int(bytes as i64 + 1))
}
fn byte_to_position(h: &mut ElispHost, a: &[Value]) -> R {
let want = as_fixnum_named(h, &a[0], "fixnump")?;
if want < 1 {
return Ok(Value::Undef);
}
let mut byte = 1i64;
for (i, c) in h.cur_buf_ref().text.iter().enumerate() {
let next = byte + c.len_utf8() as i64;
if want < next {
return Ok(Value::Int(i as i64 + 1));
}
byte = next;
}
Ok(if want == byte {
Value::Int(h.cur_buf_ref().text.len() as i64 + 1)
} else {
Value::Undef
})
}
fn decode_buffer(h: &mut ElispHost, v: Option<&Value>) -> Result<usize, String> {
match v {
None => Ok(h.current),
Some(v) if is_nil(v) => Ok(h.current),
Some(v) => match h.obj(v) {
Some(Obj::Buffer(idx)) => Ok(*idx),
_ => Err(h.signal_wrong_type("bufferp", v)),
},
}
}
fn buffer_modified_p(h: &mut ElispHost, a: &[Value]) -> R {
let bi = decode_buffer(h, a.first())?;
let m = h.buffers[bi].mods;
Ok(if m.save_modiff >= m.modiff {
Value::Undef
} else if m.autosave_modiff == m.modiff {
h.intern("autosaved")
} else {
Value::Bool(true)
})
}
fn restore_buffer_modified_p(h: &mut ElispHost, a: &[Value]) -> R {
let flag = a[0].clone();
let autosaved = h
.find_symbol("autosaved")
.is_some_and(|s| h.values_eq(&s, &flag));
let m = &mut h.cur_buf().mods;
if is_nil(&flag) {
m.save_modiff = m.modiff;
} else {
if m.save_modiff >= m.modiff {
m.save_modiff = m.modiff;
m.incr(1);
}
if autosaved {
m.autosave_modiff = m.modiff;
}
}
Ok(flag)
}
fn set_buffer_modified_p(h: &mut ElispHost, a: &[Value]) -> R {
restore_buffer_modified_p(h, a)?;
Ok(Value::Undef)
}
fn buffer_modified_tick(h: &mut ElispHost, a: &[Value]) -> R {
let bi = decode_buffer(h, a.first())?;
Ok(Value::Int(h.buffers[bi].mods.modiff))
}
fn buffer_chars_modified_tick(h: &mut ElispHost, a: &[Value]) -> R {
let bi = decode_buffer(h, a.first())?;
Ok(Value::Int(h.buffers[bi].mods.chars_modiff))
}
fn erase_buffer(h: &mut ElispHost, _a: &[Value]) -> R {
let len = h.cur_buf().text.len();
if len > 0 {
h.barf_if_read_only()?;
}
h.cur_delete(1, len + 1);
h.widen();
h.cur_buf().point = 1;
Ok(Value::Undef)
}
fn char_after(h: &mut ElispHost, a: &[Value]) -> R {
let arg = match a.first() {
Some(v) if !is_nil(v) => Some(fix_position(h, v)?),
_ => None,
};
let buf = h.cur_buf();
let pos = arg.unwrap_or(buf.point as i64);
Ok(if pos >= buf.begv as i64 && pos < buf.zv as i64 {
Value::Int(buf.text[pos as usize - 1] as i64)
} else {
Value::Undef
})
}
fn args_out_of_range_in_buffer(h: &mut ElispHost, start: i64, end: i64) -> String {
let buf = h.current_buffer();
let sym = h.intern("args-out-of-range");
let data = h.list_from(vec![buf.clone(), Value::Int(start), Value::Int(end)]);
let obj = h.cons(sym, data);
let msg = format!("args-out-of-range: {} {start} {end}", h.print(&buf, true));
h.set_pending_error(&msg, obj);
msg
}
fn buffer_substring_core(h: &mut ElispHost, a: &[Value], with_props: bool) -> R {
let s0 = as_int_or_marker(h, &a[0], "integer-or-marker-p")?;
let e0 = as_int_or_marker(h, &a[1], "integer-or-marker-p")?;
let buf = h.cur_buf_ref();
let (lo0, hi0) = (buf.begv as i64, buf.zv as i64);
let (lo, hi) = if s0 <= e0 { (s0, e0) } else { (e0, s0) };
if lo < lo0 || hi > hi0 {
return Err(args_out_of_range_in_buffer(h, s0, e0));
}
let text: String = buf.text[(lo - 1) as usize..(hi - 1) as usize]
.iter()
.collect();
let (out, arc) = h.new_string_keyed(text);
if with_props {
let plists: Vec<Value> = ((lo - 1) as usize..(hi - 1) as usize)
.map(|i| {
h.cur_buf_ref()
.props
.get(i)
.cloned()
.unwrap_or(Value::Undef)
})
.collect();
if plists.iter().any(|p| !is_nil(p)) {
let plists = h.copy_plist_runs(plists);
h.string_set_props_vec(&arc, plists);
}
}
Ok(out)
}
fn buffer_substring(h: &mut ElispHost, a: &[Value]) -> R {
buffer_substring_core(h, a, true)
}
fn buffer_substring_no_properties(h: &mut ElispHost, a: &[Value]) -> R {
buffer_substring_core(h, a, false)
}
fn make_marker(h: &mut ElispHost, _a: &[Value]) -> R {
Ok(h.alloc_marker(None, 0, false))
}
fn insert_buffer_substring(h: &mut ElispHost, a: &[Value]) -> R {
let Some(bi) = h.get_buffer(&a[0])? else {
return Err(h.nsberror(&a[0]));
};
if h.buffers[bi].name.is_none() {
return Err("error: Selecting deleted buffer".to_string());
}
let (begv, zv) = (h.buffers[bi].begv as i64, h.buffers[bi].zv as i64);
let b = match a.get(1) {
Some(v) if !is_nil(v) => fix_position(h, v)?,
_ => begv,
};
let e = match a.get(2) {
Some(v) if !is_nil(v) => fix_position(h, v)?,
_ => zv,
};
let (lo, hi) = if b > e { (e, b) } else { (b, e) };
if !(begv <= lo && hi <= zv) {
let data = vec![
a.get(1).cloned().unwrap_or(Value::Undef),
a.get(2).cloned().unwrap_or(Value::Undef),
];
return Err(args_out_of_range_values(h, data));
}
let cur = h.current;
h.current = bi;
let text = buffer_substring_core(h, &[Value::Int(lo), Value::Int(hi)], true);
h.current = cur;
insert_fn(h, &[text?])?;
Ok(Value::Undef)
}
fn point_min_marker(h: &mut ElispHost, _a: &[Value]) -> R {
let (bi, p) = (h.current, h.cur_buf_ref().begv);
Ok(h.alloc_marker(Some(bi), p, false))
}
fn point_max_marker(h: &mut ElispHost, _a: &[Value]) -> R {
let (bi, p) = (h.current, h.cur_buf_ref().zv);
Ok(h.alloc_marker(Some(bi), p, false))
}
fn delete_and_extract_region(h: &mut ElispHost, a: &[Value]) -> R {
let (lo, hi) = validate_region(h, &a[0], &a[1])?;
if lo == hi {
return Ok(h.new_string(String::new()));
}
let text = buffer_substring_core(h, &[Value::Int(lo as i64), Value::Int(hi as i64)], true)?;
h.barf_if_read_only()?;
h.cur_delete(lo, hi);
Ok(text)
}
fn point_marker(h: &mut ElispHost, _a: &[Value]) -> R {
let p = h.cur_buf_ref().point;
let bi = h.current;
Ok(h.alloc_marker(Some(bi), p, false))
}
fn markerp_fn(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(h.is_marker(&a[0])))
}
fn require_marker(h: &ElispHost, v: &Value) -> Result<(), String> {
if h.is_marker(v) {
Ok(())
} else {
Err(format!("wrong-type-argument: markerp {}", h.print(v, true)))
}
}
fn marker_position_fn(h: &mut ElispHost, a: &[Value]) -> R {
require_marker(h, &a[0])?;
Ok(match h.marker_position(&a[0]) {
Some(p) => Value::Int(p as i64),
None => Value::Undef,
})
}
fn marker_buffer_fn(h: &mut ElispHost, a: &[Value]) -> R {
require_marker(h, &a[0])?;
Ok(h.marker_buffer(&a[0]).unwrap_or(Value::Undef))
}
fn marker_insertion_type_fn(h: &mut ElispHost, a: &[Value]) -> R {
require_marker(h, &a[0])?;
Ok(nil_or(h.marker_insertion_type(&a[0]).unwrap_or(false)))
}
fn set_marker_insertion_type_fn(h: &mut ElispHost, a: &[Value]) -> R {
require_marker(h, &a[0])?;
h.set_marker_insertion_type(&a[0], !is_nil(&a[1]));
Ok(a[1].clone())
}
fn set_marker_fn(h: &mut ElispHost, a: &[Value]) -> R {
require_marker(h, &a[0])?;
let pos_arg = a.get(1).cloned().unwrap_or(Value::Undef);
if is_nil(&pos_arg) {
h.set_marker_to(&a[0], None, 0)?;
return Ok(a[0].clone());
}
let pos = as_int(h, &pos_arg)?;
let bi = match a.get(2) {
Some(v) if !is_nil(v) => h
.resolve_buffer(v)
.ok_or("error: Marker does not point anywhere")?,
_ => h.current,
};
h.set_marker_to(&a[0], Some(bi), pos.max(1) as usize)?;
Ok(a[0].clone())
}
fn copy_marker_fn(h: &mut ElispHost, a: &[Value]) -> R {
let itype = a.get(1).is_some_and(|v| !is_nil(v));
let arg = a.first().cloned().unwrap_or(Value::Undef);
if is_nil(&arg) {
return Ok(h.alloc_marker(None, 0, itype));
}
if h.is_marker(&arg) {
if let (Some(p), Some(bufv)) = (h.marker_position(&arg), h.marker_buffer(&arg)) {
let bi = h.resolve_buffer(&bufv).unwrap_or(h.current);
return Ok(h.alloc_marker(Some(bi), p, itype));
}
return Ok(h.alloc_marker(None, 0, itype));
}
let pos = as_int(h, &arg)?;
let bi = h.current;
let size = h.cur_buf_ref().text.len();
let p = (pos.max(1) as usize).min(size + 1);
Ok(h.alloc_marker(Some(bi), p, itype))
}
enum PropObj {
Str(std::sync::Arc<String>),
Buf(usize),
}
fn prop_object(h: &ElispHost, obj: Option<&Value>) -> Result<PropObj, String> {
match obj {
Some(v) if h.is_string(v) => Ok(PropObj::Str(h.str_arc(v).expect("checked stringp"))),
None | Some(Value::Undef) | Some(Value::Bool(false)) => Ok(PropObj::Buf(h.current)),
Some(v) => match h.resolve_buffer(v) {
Some(bi) => Ok(PropObj::Buf(bi)),
None => Err(format!(
"wrong-type-argument: buffer-or-string-p {}",
h.print(v, true)
)),
},
}
}
fn plist_at_pos(h: &ElispHost, obj: &PropObj, pos: i64) -> Result<Value, String> {
match obj {
PropObj::Str(s) => {
let len = s.chars().count() as i64;
if pos < 0 || pos > len {
return Err(format!("args-out-of-range: {pos} {pos}"));
}
if pos == len {
return Ok(Value::Undef);
}
Ok(h.string_plist_at(s, pos as usize))
}
PropObj::Buf(bi) => {
let (begv, zv) = h.buffer_begv_zv(*bi);
if pos < begv as i64 || pos > zv as i64 {
return Err(format!("args-out-of-range: {pos} {pos}"));
}
if pos == zv as i64 {
return Ok(Value::Undef);
}
Ok(h.buffer_plist_at_idx(*bi, (pos - 1) as usize))
}
}
}
fn get_text_property_fn(h: &mut ElispHost, a: &[Value]) -> R {
let pos = as_int(h, &a[0])?;
let obj = prop_object(h, a.get(2))?;
let plist = plist_at_pos(h, &obj, pos)?;
Ok(h.plist_get_eq(&plist, &a[1]))
}
fn text_properties_at_fn(h: &mut ElispHost, a: &[Value]) -> R {
let pos = as_int(h, &a[0])?;
let obj = prop_object(h, a.get(1))?;
plist_at_pos(h, &obj, pos)
}
fn prop_range(
obj: &PropObj,
start: i64,
end: i64,
h: &ElispHost,
) -> Result<(usize, usize), String> {
let (lo, hi) = if start <= end {
(start, end)
} else {
(end, start)
};
let (min, max, base) = match obj {
PropObj::Str(s) => (0, s.chars().count() as i64, 0),
PropObj::Buf(bi) => {
let (begv, zv) = h.buffer_begv_zv(*bi);
(begv as i64, zv as i64, 1)
}
};
if lo < min || hi > max {
return Err(format!("args-out-of-range: {lo} {hi}"));
}
Ok(((lo - base) as usize, (hi - base) as usize))
}
fn with_buffer<T>(h: &mut ElispHost, bi: usize, f: impl FnOnce(&mut ElispHost) -> T) -> T {
let saved = h.current;
h.current = bi;
let r = f(h);
h.current = saved;
r
}
fn put_text_property_fn(h: &mut ElispHost, a: &[Value]) -> R {
let start = as_int(h, &a[0])?;
let end = as_int(h, &a[1])?;
let (prop, val) = (a[2].clone(), a[3].clone());
let obj = prop_object(h, a.get(4))?;
let (lo, hi) = prop_range(&obj, start, end, h)?;
let changed = props_would_change(h, &obj, lo, hi, &[(prop.clone(), val.clone())], true);
match obj {
PropObj::Str(s) => h.string_put_prop(&s, lo, hi, &prop, &val),
PropObj::Buf(bi) => {
if changed {
let pair = [(prop.clone(), val.clone())];
record_prop_undo(h, bi, lo, hi, PropUndo::Add(&pair));
}
with_buffer(h, bi, |h| h.buffer_put_prop(lo, hi, &prop, &val));
if changed {
h.note_prop_change(bi);
}
}
}
Ok(Value::Undef)
}
fn set_text_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
let start = as_int(h, &a[0])?;
let end = as_int(h, &a[1])?;
let plist = a[2].clone();
let obj = prop_object(h, a.get(3))?;
let (lo, hi) = prop_range(&obj, start, end, h)?;
let has_props = |h: &ElispHost| match &obj {
PropObj::Str(s) => h
.string_props_vec(s)
.is_some_and(|v| v.iter().any(|p| !is_nil(p))),
PropObj::Buf(bi) => h.buffers[*bi].has_intervals,
};
if lo == hi {
return Ok(Value::Undef);
}
if is_nil(&plist) && !has_props(h) {
return Ok(Value::Undef);
}
match obj {
PropObj::Str(s) => h.string_set_props(&s, lo, hi, &plist),
PropObj::Buf(bi) => {
record_prop_undo(h, bi, lo, hi, PropUndo::Set(&plist));
with_buffer(h, bi, |h| h.buffer_set_props(lo, hi, &plist));
if lo < hi {
h.note_prop_change(bi);
}
}
}
Ok(Value::Bool(true))
}
fn each_prop_pair(h: &ElispHost, props: &Value) -> Vec<(Value, Value)> {
let mut out = Vec::new();
let mut cur = props.clone();
while let Some(Obj::Cons(k, d)) = h.obj(&cur) {
let k = k.clone();
let rest = d.clone();
match h.obj(&rest) {
Some(Obj::Cons(v, d2)) => {
out.push((k, v.clone()));
cur = d2.clone();
}
_ => break,
}
}
out
}
fn plist_lookup(h: &ElispHost, plist: &Value, prop: &Value) -> Option<Value> {
let mut cur = plist.clone();
while let Some(Obj::Cons(k, d)) = h.obj(&cur) {
let (k, d) = (k.clone(), d.clone());
let Some(Obj::Cons(v, rest)) = h.obj(&d) else {
return None;
};
if h.values_eq(&k, prop) {
return Some(v.clone());
}
cur = rest.clone();
}
None
}
fn props_would_change(
h: &ElispHost,
obj: &PropObj,
lo: usize,
hi: usize,
pairs: &[(Value, Value)],
add: bool,
) -> bool {
(lo..hi).any(|i| {
let plist = match obj {
PropObj::Str(s) => h.string_plist_at(s, i),
PropObj::Buf(bi) => h.buffer_plist_at_idx(*bi, i),
};
pairs
.iter()
.any(|(prop, val)| match plist_lookup(h, &plist, prop) {
Some(old) => !add || !h.values_eq(&old, val),
None => add,
})
})
}
fn add_text_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
let start = as_int(h, &a[0])?;
let end = as_int(h, &a[1])?;
let obj = prop_object(h, a.get(3))?;
let (lo, hi) = prop_range(&obj, start, end, h)?;
let pairs = each_prop_pair(h, &a[2]);
let changed = props_would_change(h, &obj, lo, hi, &pairs, true);
match &obj {
PropObj::Str(s) => {
h.string_add_props(s, lo, hi, &pairs, crate::textprop::SetType::Replace);
}
PropObj::Buf(bi) => {
let bi = *bi;
record_prop_undo(h, bi, lo, hi, PropUndo::Add(&pairs));
with_buffer(h, bi, |h| {
h.buffer_add_props(lo, hi, &pairs, crate::textprop::SetType::Replace)
});
}
}
if let (true, PropObj::Buf(bi)) = (changed, &obj) {
h.note_prop_change(*bi);
}
Ok(Value::Bool(changed))
}
fn remove_text_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
let start = as_int(h, &a[0])?;
let end = as_int(h, &a[1])?;
let obj = prop_object(h, a.get(3))?;
let (lo, hi) = prop_range(&obj, start, end, h)?;
let pairs = each_prop_pair(h, &a[2]);
let changed = props_would_change(h, &obj, lo, hi, &pairs, false);
match &obj {
PropObj::Str(s) => {
let names: Vec<Value> = pairs.iter().map(|(k, _)| k.clone()).collect();
h.string_remove_props(s, lo, hi, &names);
}
PropObj::Buf(bi) => {
let bi = *bi;
let names: Vec<Value> = pairs.iter().map(|(k, _)| k.clone()).collect();
record_prop_undo(h, bi, lo, hi, PropUndo::Remove(&names));
with_buffer(h, bi, |h| h.buffer_remove_props(lo, hi, &names));
}
}
if let (true, PropObj::Buf(bi)) = (changed, &obj) {
h.note_prop_change(*bi);
}
Ok(Value::Bool(changed))
}
fn replace_chars_in_place_fn(h: &mut ElispHost, a: &[Value]) -> R {
let (lo, hi) = validate_region(h, &a[0], &a[1])?;
let new: Vec<char> = as_string(h, &a[2])?.chars().collect();
if new.len() != hi - lo {
return Ok(Value::Undef);
}
if lo < hi {
h.barf_if_read_only()?;
h.record_change(lo, hi - lo);
h.note_text_change(hi - lo);
h.cur_buf().text[lo - 1..hi - 1].copy_from_slice(&new);
}
Ok(Value::Bool(true))
}
fn transpose_regions_fn(h: &mut ElispHost, a: &[Value]) -> R {
let (mut start1, mut end1) = validate_region(h, &a[0], &a[1])?;
let (mut start2, mut end2) = validate_region(h, &a[2], &a[3])?;
let (arg_start1, arg_end2) = (start1, end2);
let leave_markers = a.get(4).is_some_and(|v| !is_nil(v));
if start2 < end1 {
std::mem::swap(&mut start1, &mut start2);
std::mem::swap(&mut end1, &mut end2);
}
if start2 < end1 {
return Err("error: Transposed regions overlap".to_string());
}
if (start1 == end1 || start2 == end2) && end1 == start2 {
return Ok(Value::Undef);
}
h.barf_if_read_only()?;
let (len1, len2) = (end1 - start1, end2 - start2);
if len1 == len2 && end1 != start2 {
h.record_change(start1, len1);
h.record_change(start2, len2);
} else {
h.record_change(start1, end2 - start1);
}
h.note_text_change(end2 - start1);
let (s1, e1, s2, e2) = (start1 - 1, end1 - 1, start2 - 1, end2 - 1);
let moved = |p: usize| {
if p < s1 || p >= e2 {
p
} else if p < e1 {
p + (e2 - s2) + (s2 - e1)
} else if p < s2 {
p + (e2 - s2) - (e1 - s1)
} else {
p - ((e1 - s1) + (s2 - e1))
}
};
fn rearrange<T: Clone>(v: &mut Vec<T>, s1: usize, e1: usize, s2: usize, e2: usize) {
let mut span: Vec<T> = v[s2..e2].to_vec();
span.extend_from_slice(&v[e1..s2]);
span.extend_from_slice(&v[s1..e1]);
v.splice(s1..e2, span);
}
let b = h.cur_buf();
rearrange(&mut b.text, s1, e1, s2, e2);
rearrange(&mut b.props, s1, e1, s2, e2);
if b.has_intervals {
let cleared: Vec<(usize, usize)> = if len1 == len2 {
vec![(s1, e1), (s2, e2)]
} else {
vec![(arg_start1.min(arg_end2) - 1, arg_start1.max(arg_end2) - 1)]
};
let inside_cleared = |p: usize| cleared.iter().any(|&(lo, hi)| p > lo && p < hi);
let mut bounds: Vec<u32> = b
.prop_bounds
.iter()
.copied()
.filter(|&p| !inside_cleared(p as usize))
.collect();
let mut split = |p: usize| bounds.push(p as u32);
for &(lo, hi) in &cleared {
split(lo);
split(hi);
}
let mut pieces = vec![(s2, e2, s1), (s1, e1, e2 - len1)];
if len1 != len2 {
pieces.push((e1, s2, s1 + len2));
}
for (from, to, at) in pieces {
split(at);
split(at + (to - from));
for &p in &b.prop_bounds {
let p = p as usize;
if p > from && p < to {
split(p - from + at);
}
}
}
bounds.retain(|&p| p != 0 && (p as usize) < b.text.len());
bounds.sort_unstable();
bounds.dedup();
b.prop_bounds = bounds;
}
if !leave_markers {
let pt = b.point - 1;
b.point = moved(pt) + 1;
for mk in &b.markers {
let mut md = mk.borrow_mut();
md.pos = moved(md.pos - 1) + 1;
}
}
Ok(Value::Undef)
}
fn carry_text_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
let (Some(src), Some(dst)) = (h.str_arc(&a[0]), h.str_arc(&a[1])) else {
return Ok(a[1].clone());
};
if src.chars().count() == dst.chars().count() {
h.string_carry_all(&dst, &src);
}
Ok(a[1].clone())
}
fn propertize_fn(h: &mut ElispHost, a: &[Value]) -> R {
if a.len().is_multiple_of(2) {
let name = h.intern("propertize");
return Err(h.signal_wrong_nargs_subject(name, a.len()));
}
let base = as_string(h, &a[0])?;
let len = base.chars().count();
let (out, arc) = h.new_string_keyed(base);
let mut flat: Vec<(Value, Value)> = Vec::new();
for pair in a[1..].chunks(2).rev() {
match flat.iter_mut().find(|(k, _)| el_eq(h, k, &pair[0])) {
Some(slot) => slot.1 = pair[1].clone(),
None => flat.insert(0, (pair[0].clone(), pair[1].clone())),
}
}
if !flat.is_empty() {
let items = flat.into_iter().flat_map(|(k, v)| [k, v]).collect();
let plist = h.list_from(items);
h.string_set_props(&arc, 0, len, &plist);
}
Ok(out)
}
fn fix_position(h: &mut ElispHost, v: &Value) -> Result<i64, String> {
if let Some(Obj::Bignum(b)) = h.obj(v) {
return Ok(if b.sign() == num_bigint::Sign::Minus {
-MOST_POSITIVE_FIXNUM - 1
} else {
MOST_POSITIVE_FIXNUM
});
}
as_int_or_marker(h, v, "integer-or-marker-p")
}
fn args_out_of_range_values(h: &mut ElispHost, data: Vec<Value>) -> String {
let sym = h.intern("args-out-of-range");
let rendered: Vec<String> = data.iter().map(|v| h.print(v, true)).collect();
let data = h.list_from(data);
let obj = h.cons(sym, data);
let msg = format!("args-out-of-range: {}", rendered.join(" "));
h.set_pending_error(&msg, obj);
msg
}
pub(crate) fn validate_region(
h: &mut ElispHost,
b: &Value,
e: &Value,
) -> Result<(usize, usize), String> {
let (s0, e0) = (fix_position(h, b)?, fix_position(h, e)?);
let (lo, hi) = if e0 < s0 { (e0, s0) } else { (s0, e0) };
let buf = h.cur_buf_ref();
if !(buf.begv as i64 <= lo && hi <= buf.zv as i64) {
let cur = h.current_buffer();
return Err(args_out_of_range_values(h, vec![cur, b.clone(), e.clone()]));
}
Ok((lo as usize, hi as usize))
}
pub(crate) fn delete_region(h: &mut ElispHost, a: &[Value]) -> R {
let (lo, hi) = validate_region(h, &a[0], &a[1])?;
if lo < hi {
h.barf_if_read_only()?;
}
h.cur_delete(lo, hi);
Ok(Value::Undef)
}
fn insert_file_contents(h: &mut ElispHost, a: &[Value]) -> R {
let raw = as_string(h, &a[0])?;
let mut file = std::fs::File::open(fs_expand(&raw))
.map_err(|e| report_file_errno(h, "Opening input file", &[&raw], &e))?;
let mut content = String::new();
std::io::Read::read_to_string(&mut file, &mut content)
.map_err(|e| report_file_errno(h, "Read error", &[&raw], &e))?;
let chars: Vec<char> = content.chars().collect();
let n = chars.len() as i64;
h.cur_insert(chars, false); let raw = h.new_string(raw);
Ok(h.list_from(vec![raw, Value::Int(n)]))
}
fn move_point_by(h: &mut ElispHost, delta: i64) -> R {
let buf = h.cur_buf();
let target = buf.point as i64 + delta;
if target < buf.begv as i64 {
buf.point = buf.begv;
return Err("beginning-of-buffer".to_string());
}
if target > buf.zv as i64 {
buf.point = buf.zv;
return Err("end-of-buffer".to_string());
}
buf.point = target as usize;
Ok(Value::Undef)
}
fn forward_char(h: &mut ElispHost, a: &[Value]) -> R {
let n = match a.first() {
Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
_ => 1,
};
move_point_by(h, n)
}
fn backward_char(h: &mut ElispHost, a: &[Value]) -> R {
let n = match a.first() {
Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
_ => 1,
};
move_point_by(h, -n)
}
fn find_newline(t: &[char], start: usize, count: i64, begv: usize, zv: usize) -> (usize, i64) {
let mut p = start;
let mut found = 0i64;
if count > 0 {
while p < zv {
p += 1;
if t[p - 2] == '\n' {
found += 1;
if found == count {
return (p, found);
}
}
}
(zv, found)
} else {
while p > begv {
if t[p - 2] == '\n' {
found += 1;
if found == -count {
return (p, -found);
}
}
p -= 1;
}
(begv, -found)
}
}
fn scan_newline_from_point(buf: &crate::host::EditBuffer, count: i64) -> (usize, i64) {
let cnt = if count <= 0 { count - 1 } else { count };
find_newline(&buf.text, buf.point, cnt, buf.begv, buf.zv)
}
fn line_count_arg(h: &ElispHost, a: &[Value], default: i64) -> Result<i64, String> {
const HUGE: i64 = i64::MAX / 4;
match a.first() {
None => Ok(default),
Some(v) if is_nil(v) => Ok(default),
Some(v) => match h.obj(v) {
Some(Obj::Bignum(b)) => Ok(if b.sign() == num_bigint::Sign::Minus {
-HUGE
} else {
HUGE
}),
_ => as_integer(h, v),
},
}
}
fn bol_n(h: &mut ElispHost, a: &[Value]) -> Result<usize, String> {
let n = line_count_arg(h, a, 1)?;
Ok(scan_newline_from_point(h.cur_buf(), n.saturating_sub(1)).0)
}
fn eol_n(h: &mut ElispHost, a: &[Value]) -> Result<usize, String> {
let n = line_count_arg(h, a, 1)?;
let cnt = n - (n <= 0) as i64;
let buf = h.cur_buf();
let (pos, counted) = find_newline(&buf.text, buf.point, cnt, buf.begv, buf.zv);
Ok(if counted == cnt { pos - 1 } else { pos })
}
fn check_line_motion_arg(h: &mut ElispHost, a: &[Value]) -> Result<(), String> {
match a.first() {
Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump").map(|_| ()),
_ => Ok(()),
}
}
fn beginning_of_line(h: &mut ElispHost, a: &[Value]) -> R {
check_line_motion_arg(h, a)?;
let p = bol_n(h, a)?;
h.cur_buf().point = p;
Ok(Value::Undef)
}
fn end_of_line(h: &mut ElispHost, a: &[Value]) -> R {
check_line_motion_arg(h, a)?;
let p = eol_n(h, a)?;
h.cur_buf().point = p;
Ok(Value::Undef)
}
fn line_beginning_position(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Int(bol_n(h, a)? as i64))
}
fn line_end_position(h: &mut ElispHost, a: &[Value]) -> R {
Ok(Value::Int(eol_n(h, a)? as i64))
}
fn bolp(h: &mut ElispHost, _a: &[Value]) -> R {
let buf = h.cur_buf();
Ok(nil_or(
buf.point == buf.begv || buf.text[buf.point - 2] == '\n',
))
}
fn eolp(h: &mut ElispHost, _a: &[Value]) -> R {
let buf = h.cur_buf();
Ok(nil_or(
buf.point == buf.zv || buf.text[buf.point - 1] == '\n',
))
}
fn bobp(h: &mut ElispHost, _a: &[Value]) -> R {
let buf = h.cur_buf();
Ok(nil_or(buf.point == buf.begv))
}
fn eobp(h: &mut ElispHost, _a: &[Value]) -> R {
let buf = h.cur_buf();
Ok(nil_or(buf.point == buf.zv))
}
fn forward_line(h: &mut ElispHost, a: &[Value]) -> R {
let count = line_count_arg(h, a, 1)?;
let buf = h.cur_buf();
let opoint = buf.point;
let (pos, counted) = scan_newline_from_point(buf, count);
buf.point = pos;
let mut shortage = count - (count <= 0) as i64 - counted;
if shortage != 0 {
shortage -= if count <= 0 {
-1
} else {
(buf.begv < buf.zv && pos != opoint && buf.text[pos - 2] != '\n') as i64
};
}
match a.first().and_then(|v| h.obj(v)).and_then(|o| match o {
Obj::Bignum(b) => Some(b.clone()),
_ => None,
}) {
Some(n) => Ok(h.make_integer(n + (shortage - count))),
None => Ok(Value::Int(shortage)),
}
}
fn set_buf_match(h: &mut ElispHost, spans0: &[Option<(usize, usize)>]) {
let spans = spans0
.iter()
.map(|o| o.map(|(b, e)| (b + 1, e + 1)))
.collect();
h.match_data = Some(MatchData {
subject: String::new(),
spans,
from_buffer: true,
buffer: Some(h.current),
});
}
fn search_with_count(
h: &mut ElispHost,
a: &[Value],
forward: bool,
fwd: SearchStep,
bwd: SearchStep,
) -> R {
let noerror = a.get(2).cloned().unwrap_or(Value::Undef);
let count = match a.get(3) {
Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
_ => 1,
};
let n = if forward { count } else { -count };
let pat = as_string(h, &a[0])?;
let (point, begv, zv) = {
let b = h.cur_buf_ref();
(b.point, b.begv, b.zv)
};
let lim = match a.get(1) {
Some(v) if !is_nil(v) => {
let lim = fix_position(h, v)?;
if if n > 0 {
lim < point as i64
} else {
lim > point as i64
} {
return Err("error: Invalid search bound (wrong side of point)".to_string());
}
lim.clamp(begv as i64, zv as i64) as usize
}
_ if n > 0 => zv,
_ => begv,
};
if n == 0 {
return Ok(Value::Int(point as i64));
}
let step = if count > 0 { fwd } else { bwd };
let mut last = None;
for _ in 0..count.unsigned_abs() {
match step(h, &pat, lim)? {
Some(p) => last = Some(p),
None => {
h.cur_buf().point = point;
if is_nil(&noerror) {
return Err(format!("search-failed: {pat}"));
}
if !matches!(noerror, Value::Bool(true)) {
h.cur_buf().point = lim;
}
return Ok(Value::Undef);
}
}
}
Ok(Value::Int(last.unwrap_or(point as i64)))
}
type SearchStep = fn(&mut ElispHost, &str, usize) -> Result<Option<i64>, String>;
fn search_forward(h: &mut ElispHost, a: &[Value]) -> R {
search_with_count(h, a, true, search_forward_once, search_backward_once)
}
fn search_backward(h: &mut ElispHost, a: &[Value]) -> R {
search_with_count(h, a, false, search_backward_once, search_forward_once)
}
fn re_search_forward(h: &mut ElispHost, a: &[Value]) -> R {
search_with_count(h, a, true, re_search_forward_once, re_search_backward_once)
}
fn re_search_backward(h: &mut ElispHost, a: &[Value]) -> R {
search_with_count(h, a, false, re_search_backward_once, re_search_forward_once)
}
fn literal_regexp(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(c, '.' | '*' | '+' | '?' | '[' | '^' | '$' | '\\') {
out.push('\\');
}
out.push(c);
}
out
}
fn search_forward_once(h: &mut ElispHost, s: &str, lim: usize) -> Result<Option<i64>, String> {
re_search_forward_once(h, &literal_regexp(s), lim)
}
fn search_backward_once(h: &mut ElispHost, s: &str, lim: usize) -> Result<Option<i64>, String> {
re_search_backward_once(h, &literal_regexp(s), lim)
}
fn accessible_text(h: &ElispHost) -> (String, usize) {
let b = h.cur_buf_ref();
(b.text[b.begv - 1..b.zv - 1].iter().collect(), b.begv - 1)
}
fn match_within(
re: &CompiledRe,
text: &str,
s: usize,
stop: usize,
anchored: bool,
) -> Option<Spans> {
let ok = |spans: &Spans| match spans[0] {
Some((b, e)) => (!anchored || b == s) && e <= stop,
None => false,
};
let m = run_match(re, text, s)?;
if ok(&m) {
return Some(m);
}
let first = m[0]?.0;
if anchored && first != s || first > stop {
return None;
}
let cut = &text[..byte_of_char(text, stop)];
run_match(re, cut, s).filter(ok)
}
type Spans = Vec<Option<(usize, usize)>>;
pub(crate) fn match_at(re: &CompiledRe, text: &str, s: usize, stop: usize) -> Option<Spans> {
match_within(re, text, s, stop, true)
}
fn record_buf_match(h: &mut ElispHost, spans: Spans, off: usize) -> Spans {
let spans: Spans = spans
.into_iter()
.map(|o| o.map(|(b, e)| (b + off, e + off)))
.collect();
set_buf_match(h, &spans);
spans
}
fn re_search_forward_once(h: &mut ElispHost, pat: &str, lim: usize) -> Result<Option<i64>, String> {
let re = compile_cf_buf(h, pat, case_fold_search(h))?;
let (text, off) = accessible_text(h);
let p = h.cur_buf_ref().point - 1 - off;
let Some(m) = match_within(&re, &text, p, lim - 1 - off, false) else {
return Ok(None);
};
let spans = record_buf_match(h, m, off);
let end = spans[0].map_or(p + off, |(_, e)| e) + 1;
h.cur_buf().point = end;
Ok(Some(end as i64))
}
fn re_search_backward_once(
h: &mut ElispHost,
pat: &str,
lim: usize,
) -> Result<Option<i64>, String> {
let re = compile_cf_buf(h, pat, case_fold_search(h))?;
let (text, off) = accessible_text(h);
let p = h.cur_buf_ref().point - 1 - off;
let lower = lim - 1 - off;
let mut s = p + 1;
while s > lower {
s -= 1;
if let Some(m) = match_within(&re, &text, s, p, true) {
let spans = record_buf_match(h, m, off);
let begin = spans[0].map_or(s + off, |(b, _)| b) + 1;
h.cur_buf().point = begin;
return Ok(Some(begin as i64));
}
}
Ok(None)
}
fn looking_at(h: &mut ElispHost, a: &[Value]) -> R {
let re = compile_cf_buf(h, &as_string(h, &a[0])?, case_fold_search(h))?;
let (text, off) = accessible_text(h);
let p = h.cur_buf_ref().point - 1 - off;
let stop = text.chars().count();
match match_within(&re, &text, p, stop, true) {
Some(m) => {
record_buf_match(h, m, off);
Ok(Value::Bool(true))
}
None => Ok(Value::Undef),
}
}
fn looking_at_p(h: &mut ElispHost, a: &[Value]) -> R {
let saved = h.match_data.take();
let r = looking_at(h, a);
h.match_data = saved;
r
}
fn expand_repl(
newtext: &str,
gt: &dyn Fn(usize) -> String,
in_string: bool,
) -> Result<String, String> {
const BAD: &str = "error: Invalid use of ‘\\’ in replacement text";
let chars: Vec<char> = newtext.chars().collect();
let mut out = String::new();
let mut i = 0;
while i < chars.len() {
if chars[i] == '\\' {
let Some(&c) = chars.get(i + 1) else {
return Err(BAD.to_string());
};
match c {
'&' => out.push_str(>(0)),
'0'..='9' => out.push_str(>(c as usize - '0' as usize)),
'\\' => out.push(c),
'?' if in_string => out.push_str("\\?"),
_ => return Err(BAD.to_string()),
}
i += 2;
} else {
out.push(chars[i]);
i += 1;
}
}
Ok(out)
}
fn no_such_subexp(h: &mut ElispHost, subexp: usize) -> String {
let sym = h.intern("error");
let text = h.new_string("replace-match subexpression does not exist");
let data = h.list_from(vec![text, Value::Int(subexp as i64)]);
let obj = h.cons(sym, data);
let msg = format!("error: replace-match subexpression does not exist: {subexp}");
h.set_pending_error(&msg, obj);
msg
}
fn match_data_translate(h: &mut ElispHost, a: &[Value]) -> R {
let n = as_fixnum_named(h, &a[0], "fixnump")?;
if let Some(md) = h.match_data.as_mut() {
for (b, e) in md.spans.iter_mut().flatten() {
*b = (*b as i64 + n).max(0) as usize;
*e = (*e as i64 + n).max(0) as usize;
}
}
Ok(Value::Undef)
}
fn replace_match(h: &mut ElispHost, a: &[Value]) -> R {
let newtext = as_string(h, &a[0])?;
let fixedcase = !matches!(
a.get(1),
Some(Value::Undef) | Some(Value::Bool(false)) | None
);
let literal = !matches!(
a.get(2),
Some(Value::Undef) | Some(Value::Bool(false)) | None
);
let subexp = match a.get(4) {
Some(v) if !is_nil(v) => as_int(h, v)?.max(0) as usize,
_ => 0,
};
let spans = {
let md = h
.match_data
.as_ref()
.ok_or("args-out-of-range: no match data".to_string())?;
md.spans.clone()
};
if let Some(s) = a.get(3).and_then(|v| h.str_text(v)).map(str::to_string) {
let subject: Vec<char> = s.chars().collect();
let Some((b, e)) = spans.get(subexp).copied().flatten() else {
return Err(no_such_subexp(h, subexp));
};
if e > subject.len() || b > e {
return Err(format!("args-out-of-range: {b} {e}"));
}
let gt = |n: usize| -> String {
spans
.get(n)
.copied()
.flatten()
.filter(|(gb, ge)| *ge <= subject.len() && gb <= ge)
.map(|(gb, ge)| subject[gb..ge].iter().collect::<String>())
.unwrap_or_default()
};
let matched = gt(subexp);
let rep = if literal {
newtext
} else {
expand_repl(&newtext, >, true)?
};
let rep = if fixedcase {
rep
} else {
adapt_replacement_case(&matched, rep)
};
let mut out: String = subject[..b].iter().collect();
out.push_str(&rep);
out.extend(&subject[e..]);
let rep_len = rep.chars().count();
let (new_arc, subj_arc) = (h.str_arc(&a[0]), a.get(3).and_then(|v| h.str_arc(v)));
let (res, key) = h.new_string_keyed(out);
if new_arc.is_some() || subj_arc.is_some() {
let mut pieces: Vec<(Option<std::sync::Arc<String>>, usize, usize)> = Vec::new();
pieces.push((subj_arc.clone(), 0, b));
let mut produced = 0;
if literal {
pieces.push((new_arc.clone(), 0, rep_len));
produced = rep_len;
} else if let Some(na) = &new_arc {
let nc: Vec<char> = na.chars().collect();
let mut i = 0;
while i < nc.len() {
if nc[i] == '\\' && i + 1 < nc.len() {
let c = nc[i + 1];
let group = match c {
'&' => Some(0),
'0'..='9' => Some(c as usize - '0' as usize),
_ => None,
};
match group {
Some(g) => {
if let Some((gb, ge)) = spans.get(g).copied().flatten() {
if ge <= subject.len() && gb <= ge {
pieces.push((subj_arc.clone(), gb, ge - gb));
produced += ge - gb;
}
}
}
None => {
let len = if c == '?' { 2 } else { 1 };
pieces.push((Some(na.clone()), i + 2 - len, len));
produced += len;
}
}
i += 2;
} else {
pieces.push((Some(na.clone()), i, 1));
produced += 1;
i += 1;
}
}
}
pieces.push((subj_arc, e, subject.len() - e));
if produced == rep_len {
h.string_carry_props(&key, &pieces);
}
}
return Ok(res);
}
let text: Vec<char> = h.cur_buf().text.clone();
let (begv, zv) = (h.cur_buf().begv, h.cur_buf().zv);
let Some((b, e)) = spans.get(subexp).copied().flatten() else {
return Err(no_such_subexp(h, subexp));
};
if b < begv || e > zv || b > e {
return Err(format!("args-out-of-range: {b} {e}"));
}
let gt = |n: usize| -> String {
spans
.get(n)
.copied()
.flatten()
.filter(|(gb, ge)| *gb >= begv && *ge <= zv && gb <= ge)
.map(|(gb, ge)| text[(gb - 1)..(ge - 1)].iter().collect::<String>())
.unwrap_or_default()
};
let matched = gt(subexp);
let rep = if literal {
newtext
} else {
expand_repl(&newtext, >, false)?
};
let rep = if fixedcase {
rep
} else {
adapt_replacement_case(&matched, rep)
};
let rep_chars: Vec<char> = rep.chars().collect();
h.barf_if_read_only()?;
h.cur_buf().point = b;
h.cur_delete(b, e);
h.cur_insert(rep_chars, true);
Ok(Value::Undef)
}
fn ov_rc(h: &ElispHost, v: &Value) -> Option<Rc<RefCell<crate::host::OverlayData>>> {
match h.obj(v) {
Some(Obj::Overlay(o)) => Some(o.clone()),
_ => None,
}
}
fn ov_of(h: &mut ElispHost, v: &Value) -> Result<Rc<RefCell<crate::host::OverlayData>>, String> {
ov_rc(h, v).ok_or_else(|| h.signal_wrong_type("overlayp", v))
}
fn overlayp(h: &mut ElispHost, a: &[Value]) -> R {
Ok(nil_or(ov_rc(h, &a[0]).is_some()))
}
fn make_overlay(h: &mut ElispHost, a: &[Value]) -> R {
let bi = match a.get(2) {
Some(v) if !is_nil(v) => h
.resolve_buffer(v)
.ok_or_else(|| h.signal_wrong_type("buffer-or-string-p", v))?,
_ => h.current,
};
let z = h.buffers[bi].text.len() as i64 + 1;
let clamp = |n: i64| n.clamp(1, z) as usize;
let b0 = clamp(as_int(h, &a[0])?);
let e0 = clamp(as_int(h, &a[1])?);
let (start, end) = if b0 <= e0 { (b0, e0) } else { (e0, b0) };
let od = Rc::new(RefCell::new(crate::host::OverlayData {
buffer: Some(bi),
start,
end,
front_advance: a.get(3).is_some_and(|v| !is_nil(v)),
rear_advance: a.get(4).is_some_and(|v| !is_nil(v)),
props: Vec::new(),
}));
h.buffers[bi].overlays.push(od.clone());
Ok(h.alloc(Obj::Overlay(od)))
}
fn overlay_start(h: &mut ElispHost, a: &[Value]) -> R {
let od = ov_of(h, &a[0])?;
let od = od.borrow();
Ok(match od.buffer {
Some(_) => Value::Int(od.start as i64),
None => Value::Undef,
})
}
fn overlay_end(h: &mut ElispHost, a: &[Value]) -> R {
let od = ov_of(h, &a[0])?;
let od = od.borrow();
Ok(match od.buffer {
Some(_) => Value::Int(od.end as i64),
None => Value::Undef,
})
}
fn overlay_buffer(h: &mut ElispHost, a: &[Value]) -> R {
let od = ov_of(h, &a[0])?;
let bi = od.borrow().buffer;
Ok(match bi {
Some(i) => h.buffer_object(i),
None => Value::Undef,
})
}
fn overlay_get(h: &mut ElispHost, a: &[Value]) -> R {
let od = ov_of(h, &a[0])?;
let od = od.borrow();
Ok(od
.props
.iter()
.find(|(k, _)| el_eq(h, k, &a[1]))
.map(|(_, v)| v.clone())
.unwrap_or(Value::Undef))
}
fn overlay_put(h: &mut ElispHost, a: &[Value]) -> R {
let od = ov_of(h, &a[0])?;
let existing = od
.borrow()
.props
.iter()
.position(|(k, _)| el_eq(h, k, &a[1]));
let mut od = od.borrow_mut();
match existing {
Some(i) => od.props[i].1 = a[2].clone(),
None => od.props.insert(0, (a[1].clone(), a[2].clone())),
}
Ok(a[2].clone())
}
fn overlay_properties(h: &mut ElispHost, a: &[Value]) -> R {
let od = ov_of(h, &a[0])?;
let flat: Vec<Value> = od
.borrow()
.props
.iter()
.flat_map(|(k, v)| [k.clone(), v.clone()])
.collect();
Ok(h.list_from(flat))
}
fn delete_overlay(h: &mut ElispHost, a: &[Value]) -> R {
let od = ov_of(h, &a[0])?;
let was = od.borrow().buffer;
if let Some(bi) = was {
h.buffers[bi].overlays.retain(|o| !Rc::ptr_eq(o, &od));
}
od.borrow_mut().buffer = None;
Ok(Value::Undef)
}
fn move_overlay(h: &mut ElispHost, a: &[Value]) -> R {
let od = ov_of(h, &a[0])?;
let old = od.borrow().buffer;
let bi = match a.get(3) {
Some(v) if !is_nil(v) => h
.resolve_buffer(v)
.ok_or_else(|| h.signal_wrong_type("buffer-or-string-p", v))?,
_ => old.unwrap_or(h.current),
};
let z = h.buffers[bi].text.len() as i64 + 1;
let clamp = |n: i64| n.clamp(1, z) as usize;
let b0 = clamp(as_int(h, &a[1])?);
let e0 = clamp(as_int(h, &a[2])?);
if old != Some(bi) {
if let Some(o) = old {
h.buffers[o].overlays.retain(|x| !Rc::ptr_eq(x, &od));
}
h.buffers[bi].overlays.push(od.clone());
}
{
let mut m = od.borrow_mut();
m.buffer = Some(bi);
m.start = b0.min(e0);
m.end = b0.max(e0);
}
Ok(a[0].clone())
}
fn overlays_where(
h: &mut ElispHost,
keep: impl Fn(usize, usize) -> bool,
) -> Vec<Rc<RefCell<crate::host::OverlayData>>> {
h.buffers[h.current]
.overlays
.iter()
.filter(|o| {
let od = o.borrow();
keep(od.start, od.end)
})
.cloned()
.collect()
}
fn overlays_to_list(h: &mut ElispHost, ovs: Vec<Rc<RefCell<crate::host::OverlayData>>>) -> R {
let items: Vec<Value> = ovs.into_iter().map(|o| h.alloc(Obj::Overlay(o))).collect();
Ok(h.list_from(items))
}
fn overlays_at(h: &mut ElispHost, a: &[Value]) -> R {
let pos = as_int(h, &a[0])? as usize;
let ovs = overlays_where(h, |s, e| s <= pos && pos < e);
overlays_to_list(h, ovs)
}
fn overlays_in(h: &mut ElispHost, a: &[Value]) -> R {
let beg = as_int(h, &a[0])? as usize;
let end = as_int(h, &a[1])? as usize;
let ovs = overlays_where(h, |s, e| {
if s == e {
beg <= s && s <= end
} else {
s < end && e > beg
}
});
overlays_to_list(h, ovs)
}
fn next_overlay_change(h: &mut ElispHost, a: &[Value]) -> R {
let pos = as_int(h, &a[0])? as usize;
let zv = h.cur_buf_ref().zv;
let mut best = zv;
for o in h.buffers[h.current].overlays.iter() {
let od = o.borrow();
for p in [od.start, od.end] {
if p > pos && p < best {
best = p;
}
}
}
Ok(Value::Int(best as i64))
}
fn previous_overlay_change(h: &mut ElispHost, a: &[Value]) -> R {
let pos = as_int(h, &a[0])? as usize;
let begv = h.cur_buf_ref().begv;
let mut best = begv;
for o in h.buffers[h.current].overlays.iter() {
let od = o.borrow();
for p in [od.start, od.end] {
if p < pos && p > best {
best = p;
}
}
}
Ok(Value::Int(best as i64))
}
fn write_region(h: &mut ElispHost, a: &[Value]) -> R {
let append = a.get(3).is_some_and(|v| !is_nil(v));
let content: String = match h.str_text(&a[0]).map(str::to_string) {
Some(s) => s,
None => {
let len = h.cur_buf_ref().text.len() as i64;
let s = as_int(h, &a[0])?.clamp(1, len + 1);
let e = match a.get(1) {
Some(v) if !is_nil(v) => as_int(h, v)?.clamp(1, len + 1),
_ => len + 1,
};
let buf = h.cur_buf();
let (lo, hi) = if s <= e { (s, e) } else { (e, s) };
buf.text[(lo - 1) as usize..(hi - 1) as usize]
.iter()
.collect()
}
};
let filename = as_string(h, &a[2])?;
let path = fs_expand(&filename);
let res = if append {
use std::io::Write;
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.and_then(|mut f| f.write_all(content.as_bytes()))
} else {
std::fs::write(&path, content.as_bytes())
};
res.map_err(|e| report_file_errno(h, "Opening output file", &[&filename], &e))?;
Ok(Value::Undef)
}
fn delete_file_internal(h: &mut ElispHost, a: &[Value]) -> R {
let f = as_string(h, &a[0])?;
match std::fs::remove_file(fs_expand(&f)) {
Err(e) if e.raw_os_error() != Some(libc::ENOENT) => {
Err(report_file_errno(h, "Removing old name", &[&f], &e))
}
_ => Ok(Value::Undef),
}
}
fn make_directory_internal(h: &mut ElispHost, a: &[Value]) -> R {
let f = as_string(h, &a[0])?;
std::fs::create_dir(fs_expand(&f))
.map_err(|e| report_file_errno(h, "Creating directory", &[&f], &e))?;
Ok(Value::Undef)
}
fn rename_file(h: &mut ElispHost, a: &[Value]) -> R {
let (o, n) = (as_string(h, &a[0])?, as_string(h, &a[1])?);
std::fs::rename(fs_expand(&o), fs_expand(&n))
.map_err(|e| report_file_errno(h, "Renaming", &[&o, &n], &e))?;
Ok(Value::Undef)
}
fn copy_file(h: &mut ElispHost, a: &[Value]) -> R {
let (o, n) = (as_string(h, &a[0])?, as_string(h, &a[1])?);
let ok_if_exists = a
.get(2)
.is_some_and(|v| !is_nil(v) && !matches!(v, Value::Int(_)));
if !ok_if_exists && std::fs::symlink_metadata(fs_expand(&n)).is_ok() {
let sym = h.intern("file-already-exists");
let data = vec![
h.new_string("File already exists".to_string()),
h.new_string(n.clone()),
];
let data = h.list_from(data);
let obj = h.cons(sym, data);
let msg = format!("file-already-exists: {}", h.print(&obj, true));
h.set_pending_error(&msg, obj);
return Err(msg);
}
std::fs::File::open(fs_expand(&o))
.map_err(|e| report_file_errno(h, "Opening input file", &[&o], &e))?;
std::fs::copy(fs_expand(&o), fs_expand(&n))
.map_err(|e| report_file_errno(h, "Opening output file", &[&n], &e))?;
Ok(Value::Undef)
}
pub(crate) enum ProcOutput {
Discard,
NoWait,
Buffer(Value),
File(String),
}
pub(crate) enum ProcStderr {
Discard,
Mix,
File(String),
}
fn cons_parts(h: &ElispHost, v: &Value) -> Option<(Value, Value)> {
match h.obj(v) {
Some(Obj::Cons(a, d)) => Some((a.clone(), d.clone())),
_ => None,
}
}
pub(crate) fn process_destination(
h: &mut ElispHost,
dest: Option<&Value>,
) -> Result<(ProcOutput, ProcStderr), String> {
let Some(dest) = dest.cloned() else {
return Ok((ProcOutput::Discard, ProcStderr::Mix));
};
let mut stderr = ProcStderr::Mix;
let mut buffer = dest.clone();
if let Some((car, cdr)) = cons_parts(h, &dest) {
if h.sym_name(&car).is_some_and(|n| n.as_str() == ":file") {
let file = cons_parts(h, &cdr).map(|(file, _)| file);
let file = file.unwrap_or(Value::Undef);
let file = crate::fileio::expand_file_name(h, &[file])?;
return Ok((ProcOutput::File(as_string(h, &file)?), stderr));
}
if let Some((err, _)) = cons_parts(h, &cdr) {
stderr = if is_nil(&err) {
ProcStderr::Discard
} else if matches!(err, Value::Bool(true)) {
ProcStderr::Mix
} else {
let file = crate::fileio::expand_file_name(h, &[err])?;
ProcStderr::File(as_string(h, &file)?)
};
}
buffer = car;
}
let out = match buffer {
Value::Undef => ProcOutput::Discard,
Value::Bool(false) => ProcOutput::Discard,
Value::Bool(true) => ProcOutput::Buffer(h.cur_buf_ref().self_obj.clone()),
Value::Int(_) => ProcOutput::NoWait,
v => {
let b = get_buffer_create(h, &[v])?;
if h.resolve_buffer(&b)
.is_none_or(|i| h.buffers[i].name.is_none())
{
return Err("error: Selecting deleted buffer".to_string());
}
ProcOutput::Buffer(b)
}
};
Ok((out, stderr))
}
fn exit_value(h: &mut ElispHost, status: std::process::ExitStatus) -> Value {
use std::os::unix::process::ExitStatusExt;
if let Some(sig) = status.signal() {
let text = unsafe {
let p = libc::strsignal(sig);
if p.is_null() {
"unknown".to_string()
} else {
std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned()
}
};
return h.new_string(text);
}
Value::Int(status.code().unwrap_or(0) as i64)
}
fn create_output_file(
h: &mut ElispHost,
file: &str,
string: &str,
) -> Result<std::fs::File, String> {
std::fs::File::create(fs_expand(file)).map_err(|e| report_file_errno(h, string, &[file], &e))
}
pub(crate) fn run_process(
h: &mut ElispHost,
program: &Value,
infile: Option<&Value>,
dest: Option<&Value>,
args: &[Value],
) -> R {
use std::process::Stdio;
let infile = match infile {
Some(v) if !is_nil(v) => {
let f = crate::fileio::expand_file_name(h, std::slice::from_ref(v))?;
Some(as_string(h, &f)?)
}
_ => None,
};
let program = as_string(h, program)?;
let args: Vec<String> = args
.iter()
.map(|v| as_string(h, v))
.collect::<Result<_, _>>()?;
let (out, stderr) = process_destination(h, dest)?;
let cwd = subprocess_directory(h)?;
let stdin = match &infile {
Some(f) => Stdio::from(
std::fs::File::open(fs_expand(f))
.map_err(|e| report_file_errno(h, "Opening process input file", &[f], &e))?,
),
None => Stdio::null(),
};
let path = find_program(h, &program)?;
let mut cmd = std::process::Command::new(path);
cmd.args(&args)
.current_dir(&cwd)
.env_clear()
.envs(child_environment(h, &cwd))
.stdin(stdin);
let mut reader = None;
let stdout_file = match &out {
ProcOutput::File(f) => Some(create_output_file(h, f, "Opening process output file")?),
_ => None,
};
let stderr_file = match &stderr {
ProcStderr::File(f) => Some(create_output_file(h, f, "Cannot redirect stderr")?),
_ => None,
};
let to_stdout: Stdio = match (&out, &stdout_file) {
(ProcOutput::Buffer(_), _) => {
let (r, w) = std::io::pipe().map_err(|e| e.to_string())?;
reader = Some(r);
if matches!(stderr, ProcStderr::Mix) {
cmd.stderr(w.try_clone().map_err(|e| e.to_string())?);
}
w.into()
}
(_, Some(f)) => {
if matches!(stderr, ProcStderr::Mix) {
cmd.stderr(f.try_clone().map_err(|e| e.to_string())?);
}
f.try_clone().map_err(|e| e.to_string())?.into()
}
_ => Stdio::null(),
};
cmd.stdout(to_stdout);
match (stderr_file, &stderr) {
(Some(f), _) => {
cmd.stderr(f);
}
(None, ProcStderr::Discard) => {
cmd.stderr(Stdio::null());
}
(None, _) if reader.is_none() && stdout_file.is_none() => {
cmd.stderr(Stdio::null());
}
_ => {}
}
let mut child = cmd
.spawn()
.map_err(|e| report_file_errno(h, "Searching for program", &[&program], &e))?;
drop(cmd);
if matches!(out, ProcOutput::NoWait) {
return Ok(Value::Undef);
}
let mut bytes = Vec::new();
if let Some(mut r) = reader {
std::io::Read::read_to_end(&mut r, &mut bytes)
.map_err(|e| report_file_errno(h, "Read error", &[&program], &e))?;
}
let status = child.wait().map_err(|e| e.to_string())?;
if let ProcOutput::Buffer(buffer) = &out {
if !bytes.is_empty() {
let saved = h.cur_buf_ref().self_obj.clone();
h.set_buffer(buffer)?;
let inserted = h.barf_if_read_only().map(|()| {
let chars: Vec<char> = String::from_utf8_lossy(&bytes).chars().collect();
h.cur_insert(chars, true);
});
h.set_buffer(&saved)?;
inserted?;
}
}
Ok(exit_value(h, status))
}
fn shell_command_to_string(h: &mut ElispHost, a: &[Value]) -> R {
as_string(h, &a[0])?;
let shell = symbol_value_or_nil(h, "shell-file-name");
let switch = symbol_value_or_nil(h, "shell-command-switch");
let saved = h.cur_buf_ref().self_obj.clone();
let name = h.generate_new_buffer_name(" *temp*", None);
let temp = h.get_buffer_create(&name);
if let Some(i) = h.resolve_buffer(&temp) {
h.buffers[i].inhibit_hooks = true;
}
let dest = Value::Bool(true);
h.set_buffer(&temp)?;
let result = run_process(h, &shell, None, Some(&dest), &[switch, a[0].clone()]);
let text: String = h.cur_buf_ref().text.iter().collect();
h.set_buffer(&saved)?;
h.kill_buffer(Some(&temp));
result?;
Ok(h.new_string(text))
}
fn call_process(h: &mut ElispHost, a: &[Value]) -> R {
run_process(h, &a[0], a.get(1), a.get(2), a.get(4..).unwrap_or(&[]))
}
fn char_before(h: &mut ElispHost, a: &[Value]) -> R {
let arg = match a.first() {
Some(v) if !is_nil(v) => Some(fix_position(h, v)?),
_ => None,
};
let buf = h.cur_buf();
let pos = arg.unwrap_or(buf.point as i64);
Ok(if pos > buf.begv as i64 && pos <= buf.zv as i64 {
Value::Int(buf.text[pos as usize - 2] as i64)
} else {
Value::Undef
})
}
fn delete_char(h: &mut ElispHost, a: &[Value]) -> R {
let n = as_fixnum_named(h, &a[0], "fixnump")?;
let (point, begv, zv) = {
let b = h.cur_buf_ref();
(b.point as i64, b.begv as i64, b.zv as i64)
};
let pos = point + n;
let (lo, hi) = if n < 0 {
if pos < begv {
return Err("beginning-of-buffer".to_string());
}
(pos, point)
} else {
if pos > zv {
return Err("end-of-buffer".to_string());
}
(point, pos)
};
if lo < hi {
h.barf_if_read_only()?;
}
h.cur_delete(lo as usize, hi as usize);
Ok(Value::Undef)
}
pub(crate) fn insert_char(h: &mut ElispHost, a: &[Value]) -> R {
let c = char::from_u32(as_int(h, &a[0])? as u32).unwrap_or('\u{fffd}');
let count = match a.get(1) {
Some(v) if !is_nil(v) => as_int(h, v)?.max(0) as usize,
_ => 1,
};
if count > 0 {
h.barf_if_read_only()?;
}
h.cur_insert(vec![c; count], true);
Ok(Value::Undef)
}
fn count_lines(h: &mut ElispHost, a: &[Value]) -> R {
let (lo, hi) = narrow_bounds(h, &a[0], &a[1])?;
let buf = h.cur_buf();
let region = &buf.text[lo - 1..hi - 1];
let nl = region.iter().filter(|&&c| c == '\n').count();
let extra = if !region.is_empty() && region[region.len() - 1] != '\n' {
1
} else {
0
};
Ok(Value::Int((nl + extra) as i64))
}
fn line_number_at_pos(h: &mut ElispHost, a: &[Value]) -> R {
let arg = match a.first() {
Some(v) if !is_nil(v) => Some(as_int(h, v)? as usize),
_ => None,
};
let buf = h.cur_buf();
let pos = arg.unwrap_or(buf.point);
let upto = (pos.saturating_sub(1)).min(buf.text.len());
let n = buf.text[..upto].iter().filter(|&&c| c == '\n').count();
Ok(Value::Int(n as i64 + 1))
}
fn sane_tab_width(h: &ElispHost) -> i64 {
match h
.find_symbol("tab-width")
.and_then(|s| h.get_value(&s).ok())
{
Some(Value::Int(n)) if (1..=1000).contains(&n) => n,
_ => 8,
}
}
fn advance_column(c: char, col: i64, tab_width: i64) -> i64 {
if c == '\t' {
(col / tab_width + 1) * tab_width
} else {
col + char_display_width(c as u32) as i64
}
}
pub(crate) fn scan_for_column(h: &ElispHost, end: usize, goal: i64) -> (usize, i64, usize, i64) {
let tab_width = sane_tab_width(h);
let buf = h.cur_buf_ref();
let mut pos = find_newline(&buf.text, buf.point, -1, buf.begv, buf.zv).0;
let (mut col, mut prev_pos, mut prev_col) = (0i64, pos, 0i64);
while pos < end {
if col >= goal {
break;
}
let c = buf.text[pos - 1];
if c == '\n' {
break;
}
prev_pos = pos;
prev_col = col;
col = advance_column(c, col, tab_width);
pos += 1;
}
(pos, col, prev_pos, prev_col)
}
fn current_column(h: &mut ElispHost, _a: &[Value]) -> R {
let point = h.cur_buf_ref().point;
Ok(Value::Int(scan_for_column(h, point, i64::MAX).1))
}
fn current_indentation(h: &mut ElispHost, _a: &[Value]) -> R {
let tab_width = sane_tab_width(h);
let buf = h.cur_buf_ref();
let mut pos = find_newline(&buf.text, buf.point, -1, buf.begv, buf.zv).0;
let mut col = 0i64;
while pos < buf.zv && matches!(buf.text[pos - 1], ' ' | '\t') {
col = advance_column(buf.text[pos - 1], col, tab_width);
pos += 1;
}
Ok(Value::Int(col))
}
pub(crate) fn indent_to_plan(
h: &mut ElispHost,
a: &[Value],
) -> Result<(i64, usize, usize), String> {
let column = as_fixnum_named(h, &a[0], "fixnump")?;
let minimum = match a.get(1) {
Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
_ => 0,
};
let tab_width = sane_tab_width(h);
let point = h.cur_buf_ref().point;
let mut fromcol = scan_for_column(h, point, i64::MAX).1;
let mincol = (fromcol + minimum).max(column);
if fromcol == mincol {
return Ok((mincol, 0, 0));
}
h.barf_if_read_only()?;
let tabs_mode = h
.find_symbol("indent-tabs-mode")
.and_then(|s| h.get_value(&s).ok())
.is_some_and(|v| !is_nil(&v));
let mut tabs = 0;
if tabs_mode {
let n = mincol / tab_width - fromcol / tab_width;
if n != 0 {
tabs = n.max(0) as usize;
fromcol = (mincol / tab_width) * tab_width;
}
}
Ok((mincol, tabs, (mincol - fromcol).max(0) as usize))
}
pub(crate) fn indent_to(h: &mut ElispHost, a: &[Value]) -> R {
let (mincol, tabs, spaces) = indent_to_plan(h, a)?;
h.cur_insert(vec!['\t'; tabs], true);
h.cur_insert(vec![' '; spaces], true);
Ok(Value::Int(mincol))
}
fn move_to_column(h: &mut ElispHost, a: &[Value]) -> R {
let goal = match &a[0] {
Value::Int(n) if *n >= 0 => *n,
other => return Err(h.signal_wrong_type("wholenump", other)),
};
let force = a.get(1).cloned().unwrap_or(Value::Undef);
let zv = h.cur_buf_ref().zv;
let (pos, mut col, prev_pos, prev_col) = scan_for_column(h, zv, goal);
h.cur_buf().point = pos;
if !is_nil(&force) && col > goal {
let c = h.cur_buf_ref().text[prev_pos - 1];
if c == '\t' && prev_col < goal && prev_pos < pos {
h.cur_buf().point = prev_pos;
h.cur_insert(vec![' '; (goal - prev_col) as usize], true);
let at = h.cur_buf_ref().point;
h.cur_delete(at, at + 1);
indent_to(h, &[Value::Int(col)])?;
h.cur_buf().point = at;
col = goal;
}
}
if col < goal && matches!(force, Value::Bool(true)) {
col = goal;
indent_to(h, &[Value::Int(col)])?;
}
Ok(Value::Int(col))
}
enum SkipItem {
Range(char, char),
Class(Rc<CompiledRe>),
}
struct SkipSet {
negate: bool,
items: Vec<SkipItem>,
}
impl SkipSet {
fn parse(h: &ElispHost, spec: &str) -> Result<SkipSet, String> {
let chars: Vec<char> = spec.chars().collect();
let negate = chars.first() == Some(&'^');
let mut i = usize::from(negate);
let mut items = Vec::new();
while i < chars.len() {
let mut c = chars[i];
i += 1;
if c == '[' && chars.get(i) == Some(&':') {
let beg = i + 1;
let mut end = beg;
while end + 1 < chars.len()
&& !(chars[end] as u32 >= 0o200
|| chars[end] as u32 <= 0o40
|| (chars[end] == ':' && chars[end + 1] == ']'))
{
end += 1;
}
if end > beg && chars.get(end) == Some(&':') && chars.get(end + 1) == Some(&']') {
let name: String = chars[beg..end].iter().collect();
if !crate::regexp::is_class_name(&name) {
return Err("error: Invalid ISO C character class".to_string());
}
items.push(SkipItem::Class(compile_cf(
h,
&format!("[[:{name}:]]"),
false,
)?));
i = end + 2;
continue;
}
}
if c == '\\' {
match chars.get(i) {
Some(&q) => {
c = q;
i += 1;
}
None => break,
}
}
if i + 1 < chars.len() && chars[i] == '-' {
let mut c2 = chars[i + 1];
i += 2;
if c2 == '\\' && i < chars.len() {
c2 = chars[i];
i += 1;
}
if c <= c2 {
items.push(SkipItem::Range(c, c2));
}
} else {
items.push(SkipItem::Range(c, c));
}
}
Ok(SkipSet { negate, items })
}
fn contains(&self, c: char) -> bool {
let hit = self.items.iter().any(|item| match item {
SkipItem::Range(a, b) => (*a..=*b).contains(&c),
SkipItem::Class(re) => re.is_match(c.encode_utf8(&mut [0; 4])).unwrap_or(false),
});
hit != self.negate
}
}
fn skip_chars(h: &mut ElispHost, a: &[Value], forward: bool) -> R {
let set = SkipSet::parse(h, &as_string(h, &a[0])?)?;
let lim = match a.get(1) {
Some(v) if !is_nil(v) => Some(as_int_or_marker(h, v, "integer-or-marker-p")?),
_ => None,
};
let buf = h.cur_buf();
let (begv, zv) = (buf.begv as i64, buf.zv as i64);
let lim = lim
.unwrap_or(if forward { zv } else { begv })
.clamp(begv, zv) as usize;
let start = buf.point;
if forward {
while buf.point < lim && set.contains(buf.text[buf.point - 1]) {
buf.point += 1;
}
} else {
while buf.point > lim && set.contains(buf.text[buf.point - 2]) {
buf.point -= 1;
}
}
Ok(Value::Int(buf.point as i64 - start as i64))
}
fn skip_chars_forward(h: &mut ElispHost, a: &[Value]) -> R {
skip_chars(h, a, true)
}
fn skip_chars_backward(h: &mut ElispHost, a: &[Value]) -> R {
skip_chars(h, a, false)
}
fn scan_words(h: &ElispHost, from: usize, mut count: i64) -> Option<usize> {
let escapes = h
.find_symbol("words-include-escapes")
.and_then(|s| h.get_value(&s).ok())
.is_some_and(|v| !is_nil(&v));
let buf = h.cur_buf_ref();
let is_word = |c: char| {
let code = h.syntax_class_of(c);
code == 'w' || (escapes && (code == '\\' || code == '/'))
};
let mut from = from;
while count > 0 {
loop {
if from == buf.zv {
return None;
}
from += 1;
if is_word(buf.text[from - 2]) {
break;
}
}
while from < buf.zv && is_word(buf.text[from - 1]) {
from += 1;
}
count -= 1;
}
while count < 0 {
loop {
if from == buf.begv {
return None;
}
from -= 1;
if is_word(buf.text[from - 1]) {
break;
}
}
while from > buf.begv && is_word(buf.text[from - 2]) {
from -= 1;
}
count += 1;
}
Some(from)
}
fn forward_word(h: &mut ElispHost, a: &[Value]) -> R {
let n = match a.first() {
Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
_ => 1,
};
let found = scan_words(h, h.cur_buf_ref().point, n);
let buf = h.cur_buf();
buf.point = found.unwrap_or(if n > 0 { buf.zv } else { buf.begv });
Ok(nil_or(found.is_some()))
}
fn backward_word(h: &mut ElispHost, a: &[Value]) -> R {
let arg = match a.first() {
Some(v) if !is_nil(v) => v.clone(),
_ => Value::Int(1),
};
let neg = match arg {
Value::Int(n) => Value::Int(-n),
Value::Float(f) => Value::Float(-f),
other => {
return Err(format!(
"wrong-type-argument: number-or-marker-p {}",
h.print(&other, true)
))
}
};
forward_word(h, &[neg])
}
pub fn install(h: &mut ElispHost) {
crate::window::install(h);
crate::window::install_frame_geometry(h);
crate::window::install_window_display(h);
let mut s = |n: &str, min: usize, max: Option<usize>, f: crate::host::SubrFn| {
h.defsubr(n, min, max, f);
};
s("+", 0, None, add);
s("-", 0, None, sub);
s("*", 0, None, mul);
s("/", 1, None, div);
s("%", 2, Some(2), modulo);
s("mod", 2, Some(2), mod_fn);
s("1+", 1, Some(1), one_plus);
s("1-", 1, Some(1), one_minus);
s("=", 1, None, num_eq);
s("<", 1, None, lt);
s(">", 1, None, gt);
s("<=", 1, None, le);
s(">=", 1, None, ge);
s("eq", 2, Some(2), eq_fn);
s("eql", 2, Some(2), eql_fn);
s("equal", 2, Some(2), equal_fn);
s("memq", 2, Some(2), memq_fn);
s("memql", 2, Some(2), memql_fn);
s("member", 2, Some(2), member_fn);
s("assq", 2, Some(2), assq_fn);
s("rassq", 2, Some(2), rassq_fn);
s("rassoc", 2, Some(2), rassoc_fn);
s("null", 1, Some(1), null_fn);
s("consp", 1, Some(1), consp);
s("listp", 1, Some(1), listp);
s("atom", 1, Some(1), atom);
s("symbolp", 1, Some(1), symbolp);
s("stringp", 1, Some(1), stringp);
s("natnump", 1, Some(1), natnump_fn);
s("nlistp", 1, Some(1), nlistp_fn);
s("numberp", 1, Some(1), numberp);
s("integerp", 1, Some(1), integerp);
s("max", 1, None, max_fn);
s("min", 1, None, min_fn);
s("fixnump", 1, Some(1), fixnump);
s("bignump", 1, Some(1), bignump);
s("floatp", 1, Some(1), floatp);
s("vectorp", 1, Some(1), vectorp);
s("cons", 2, Some(2), cons_fn);
s("car", 1, Some(1), car);
s("cdr", 1, Some(1), cdr);
s("setcar", 2, Some(2), setcar);
s("setcdr", 2, Some(2), setcdr);
s("car-less-than-car", 2, Some(2), car_less_than_car);
s("list", 0, None, list_fn);
s("append", 0, None, append_fn);
s("reverse", 1, Some(1), reverse_fn);
s("length", 1, Some(1), length_fn);
s("nth", 2, Some(2), nth_fn);
s("nthcdr", 2, Some(2), nthcdr_fn);
for (name, f) in CXR_SUBRS {
s(name, 1, Some(1), *f);
}
s("cl-caar", 1, Some(1), caar);
s("cl-cadr", 1, Some(1), cadr);
s("cl-cdar", 1, Some(1), cdar);
s("cl-cddr", 1, Some(1), cddr);
s("vector", 0, None, vector_fn);
s("make-vector", 2, Some(2), make_vector);
s("make-list", 2, Some(2), make_list);
s("record", 1, None, record_fn);
s("make-record", 3, Some(3), make_record);
s("make-bool-vector", 2, Some(2), make_bool_vector);
s("bool-vector", 0, None, bool_vector_fn);
s("bool-vector-p", 1, Some(1), bool_vector_p);
s(
"bool-vector-count-population",
1,
Some(1),
bool_vector_count_population,
);
s("bool-vector-subsetp", 2, Some(2), bool_vector_subsetp);
s("bool-vector-not", 1, Some(2), bool_vector_not);
s(
"bool-vector-exclusive-or",
2,
Some(3),
bool_vector_exclusive_or,
);
s("bool-vector-union", 2, Some(3), bool_vector_union);
s(
"bool-vector-intersection",
2,
Some(3),
bool_vector_intersection,
);
s(
"bool-vector-set-difference",
2,
Some(3),
bool_vector_set_difference,
);
s(
"bool-vector-count-consecutive",
3,
Some(3),
bool_vector_count_consecutive,
);
s("elt", 2, Some(2), elt_fn);
s("aref", 2, Some(2), aref);
s("aset", 3, Some(3), aset);
s("make-overlay", 2, Some(5), make_overlay);
s("overlayp", 1, Some(1), overlayp);
s("overlay-start", 1, Some(1), overlay_start);
s("overlay-end", 1, Some(1), overlay_end);
s("overlay-buffer", 1, Some(1), overlay_buffer);
s("overlay-get", 2, Some(2), overlay_get);
s("overlay-put", 3, Some(3), overlay_put);
s("overlay-properties", 1, Some(1), overlay_properties);
s("delete-overlay", 1, Some(1), delete_overlay);
s("move-overlay", 3, Some(4), move_overlay);
s("overlays-at", 1, Some(2), overlays_at);
s("overlays-in", 2, Some(2), overlays_in);
s("next-overlay-change", 1, Some(1), next_overlay_change);
s(
"previous-overlay-change",
1,
Some(1),
previous_overlay_change,
);
s("--note-compiler-macro", 1, Some(1), note_compiler_macro);
s("store-substring", 3, Some(3), store_substring);
s("clear-string", 1, Some(1), clear_string);
s("fillarray", 2, Some(2), fillarray);
s("make-char-table--new", 3, Some(3), make_char_table_new);
s("elisprs--copy-char-table", 1, Some(1), copy_char_table);
s("elisprs--copy-string", 1, Some(1), copy_string);
s("elisprs--char-table-runs", 1, Some(1), char_table_runs);
s("optimize-char-table", 1, Some(2), optimize_char_table);
s("char-table-p", 1, Some(1), char_table_p);
s("char-table-subtype", 1, Some(1), char_table_subtype);
s("char-table-parent", 1, Some(1), char_table_parent);
s("set-char-table-parent", 2, Some(2), set_char_table_parent);
s("char-table-extra-slot", 2, Some(2), char_table_extra_slot);
s(
"set-char-table-extra-slot",
3,
Some(3),
set_char_table_extra_slot,
);
s("char-table-range", 2, Some(2), char_table_range);
s("set-char-table-range", 3, Some(3), set_char_table_range);
s("--char-table-run-end--", 3, Some(3), char_table_run_end);
s("symbol-name", 1, Some(1), symbol_name);
s("intern", 1, Some(2), intern_fn);
s("obarray-make", 0, Some(1), obarray_make_fn);
s("obarrayp", 1, Some(1), obarrayp_fn);
s("unintern", 1, Some(2), unintern_fn);
s("make-symbol", 1, Some(1), make_symbol_fn);
s("set", 2, Some(2), set_fn);
s("symbol-value", 1, Some(1), symbol_value);
s("keywordp", 1, Some(1), keywordp);
s("boundp", 1, Some(1), boundp);
s("default-boundp", 1, Some(1), default_boundp);
s("default-toplevel-value", 1, Some(1), default_toplevel_value);
s("bare-symbol-p", 1, Some(1), bare_symbol_p);
s("makunbound", 1, Some(1), makunbound);
s("defvaralias", 2, Some(3), defvaralias);
s("indirect-variable", 1, Some(1), indirect_variable);
s("sha1", 1, Some(4), sha1_fn);
s("md5", 1, Some(5), md5_fn);
s("secure-hash", 2, Some(5), secure_hash);
s("secure-hash-algorithms", 0, Some(0), secure_hash_algorithms);
s("base64-encode-string", 1, Some(2), base64_encode_string);
s("base64-decode-string", 1, Some(3), base64_decode_string);
s(
"base64url-encode-string",
1,
Some(2),
base64url_encode_string,
);
s(
"base64url-decode-string",
1,
Some(2),
base64url_decode_string,
);
s("url-hexify-string", 1, Some(2), url_hexify_string);
s("url-unhex-string", 1, Some(2), url_unhex_string);
s("fset", 2, Some(2), fset);
s("fboundp", 1, Some(1), fboundp);
s("fmakunbound", 1, Some(1), fmakunbound);
s("json-parse-string", 1, None, crate::json::json_parse_string);
s("json-parse-buffer", 0, None, crate::json::json_parse_buffer);
s("json-serialize", 1, None, crate::json::json_serialize);
s("json-insert", 1, None, crate::json::json_insert);
s(
"json-available-p",
0,
Some(0),
crate::json::json_available_p,
);
s("indirect-function", 1, Some(2), indirect_function);
s("funcall", 1, None, intercepted_subr);
s("apply", 1, None, intercepted_subr);
s("mapcar", 2, Some(2), intercepted_subr);
s("mapc", 2, Some(2), intercepted_subr);
s("assoc", 2, Some(3), intercepted_subr);
s("mapconcat", 2, Some(3), intercepted_subr);
s("maphash", 2, Some(2), intercepted_subr);
s("mapatoms", 1, Some(2), intercepted_subr);
s("load", 1, Some(5), intercepted_subr);
s("eval", 1, Some(2), intercepted_subr);
s("macroexpand", 1, Some(2), intercepted_subr);
s("macroexpand-1", 1, Some(2), intercepted_subr);
s("macroexpand-all", 1, Some(2), intercepted_subr);
s("sort", 1, None, intercepted_subr);
s("identity", 1, Some(1), identity);
s("terpri", 0, Some(2), terpri);
s("write-char", 1, Some(2), write_char_fn);
s("backquote-process", 1, Some(2), backquote_process_fn);
s("print", 1, Some(2), print_fn);
s("prin1-to-string", 1, Some(3), prin1_to_string);
s("throw", 2, Some(2), throw_fn);
s("error", 1, None, error_fn);
s("user-error", 1, None, user_error_fn);
s("signal", 1, Some(2), signal_fn);
s("make-hash-table", 0, None, intercepted_subr);
s("gethash", 2, Some(3), intercepted_subr);
s("puthash", 3, Some(3), intercepted_subr);
s("remhash", 2, Some(2), intercepted_subr);
s("clrhash", 1, Some(1), clrhash);
s("hash-table-count", 1, Some(1), hash_table_count);
s("hash-table-test", 1, Some(1), hash_table_test);
s("hash-table-size", 1, Some(1), hash_table_size);
s("hash-table-weakness", 1, Some(1), hash_table_weakness);
s("hash-table-p", 1, Some(1), hash_table_p);
s("hash-table-keys", 1, Some(1), hash_table_keys);
s("hash-table-values", 1, Some(1), hash_table_values);
s("copy-hash-table", 1, Some(1), copy_hash_table);
s("getenv-internal", 1, Some(2), getenv_internal);
s("set-time-zone-rule", 1, Some(1), set_time_zone_rule);
s("undo-boundary", 0, Some(0), undo_boundary_fn);
s("subst-char-in-region", 4, Some(5), subst_char_in_region);
s("recent-auto-save-p", 0, Some(0), recent_auto_save_p);
s("special-variable-p", 1, Some(1), special_variable_p);
s("func-arity", 1, Some(1), func_arity);
s("subr-arity", 1, Some(1), func_arity);
s("subr-name", 1, Some(1), subr_name);
s("--current-directory--", 0, Some(0), current_directory);
s(
"file-name-directory",
1,
Some(1),
crate::fileio::file_name_directory,
);
s(
"file-name-nondirectory",
1,
Some(1),
crate::fileio::file_name_nondirectory,
);
s(
"file-name-as-directory",
1,
Some(1),
crate::fileio::file_name_as_directory,
);
s(
"directory-file-name",
1,
Some(1),
crate::fileio::directory_file_name,
);
s(
"directory-name-p",
1,
Some(1),
crate::fileio::directory_name_p,
);
s("file-name-concat", 1, None, crate::fileio::file_name_concat);
s(
"file-name-absolute-p",
1,
Some(1),
crate::fileio::file_name_absolute_p,
);
s(
"expand-file-name",
1,
Some(2),
crate::fileio::expand_file_name,
);
s(
"file-name-case-insensitive-p",
1,
Some(1),
crate::fileio::file_name_case_insensitive_p,
);
s("--system-type--", 0, Some(0), system_type);
s("--build-time--", 0, Some(0), build_time);
s("system-name", 0, Some(0), system_name);
s("user-login-name", 0, Some(1), user_login_name);
s("user-real-login-name", 0, Some(0), user_real_login_name);
s("user-uid", 0, Some(0), user_uid);
s("user-real-uid", 0, Some(0), user_real_uid);
s("--temp-directory--", 0, Some(0), temp_directory);
s("file-exists-p", 1, Some(1), file_exists_p);
s("file-directory-p", 1, Some(1), file_directory_p);
s("file-regular-p", 1, Some(1), file_regular_p);
s("file-readable-p", 1, Some(1), file_readable_p);
s("file-writable-p", 1, Some(1), file_writable_p);
s("file-symlink-p", 1, Some(1), file_symlink_p);
s("file-attributes", 1, Some(2), file_attributes);
s("file-modes", 1, Some(2), file_modes);
s("set-file-modes", 2, Some(3), set_file_modes);
s("file-newer-than-file-p", 2, Some(2), file_newer_than_file_p);
s(
"file-accessible-directory-p",
1,
Some(1),
file_accessible_directory_p,
);
s(
"delete-directory-internal",
1,
Some(1),
delete_directory_internal,
);
s("make-symbolic-link", 2, Some(3), make_symbolic_link);
s("add-name-to-file", 2, Some(3), add_name_to_file);
s("file-executable-p", 1, Some(1), file_executable_p);
s("--invocation-file--", 0, Some(0), invocation_file);
s("--directory-files--", 1, Some(3), directory_files_raw);
s("bufferp", 1, Some(1), bufferp);
s("current-buffer", 0, Some(0), current_buffer_fn);
s("set-buffer", 1, Some(1), set_buffer_fn);
s("get-buffer", 1, Some(1), get_buffer);
s("get-buffer-create", 1, Some(2), get_buffer_create);
s("generate-new-buffer", 1, Some(3), generate_new_buffer);
s(
"generate-new-buffer-name",
1,
Some(2),
generate_new_buffer_name,
);
s("buffer-name", 0, Some(1), buffer_name);
s("buffer-live-p", 1, Some(1), buffer_live_p);
s("kill-buffer", 0, Some(1), kill_buffer);
s("get-buffer-process", 1, Some(1), get_buffer_process);
s("rename-buffer", 1, Some(2), rename_buffer);
s("buffer-list", 0, Some(1), buffer_list);
s("mark-marker", 0, Some(0), mark_marker_fn);
s("region-beginning", 0, Some(0), region_beginning);
s("region-end", 0, Some(0), region_end);
s("narrow-to-region", 2, Some(2), narrow_to_region);
s("widen", 0, Some(0), widen_fn);
s("--se-push--", 0, Some(0), se_push);
s("--se-pop--", 0, Some(0), se_pop);
s("--save-restriction--", 0, Some(0), save_restriction_push);
s("--restore-restriction--", 0, Some(0), restore_restriction);
s("make-local-variable", 1, Some(1), make_local_variable);
s(
"make-variable-buffer-local",
1,
Some(1),
make_variable_buffer_local,
);
s("local-variable-p", 1, Some(2), local_variable_p);
s(
"local-variable-if-set-p",
1,
Some(2),
local_variable_if_set_p,
);
s("kill-local-variable", 1, Some(1), kill_local_variable);
s(
"--buffer-local-symbols--",
0,
Some(0),
buffer_local_symbols_fn,
);
s("--make-always-local--", 2, Some(2), make_always_local_fn);
s("--early-declarations--", 0, Some(0), early_declarations_fn);
s("--defvar-declare--", 1, Some(1), defvar_declare_fn);
s("--declare-special", 1, Some(1), declare_special_fn);
s("buffer-local-value", 2, Some(2), buffer_local_value_fn);
s("default-value", 1, Some(1), default_value_fn);
s("set-default", 2, Some(2), set_default_fn);
s("use-local-map", 1, Some(1), use_local_map_fn);
s("current-local-map", 0, Some(0), current_local_map_fn);
s("insert", 0, None, insert_fn);
s(
"insert-buffer-substring",
1,
Some(3),
insert_buffer_substring,
);
s("point-min-marker", 0, Some(0), point_min_marker);
s("point-max-marker", 0, Some(0), point_max_marker);
s(
"delete-and-extract-region",
2,
Some(2),
delete_and_extract_region,
);
s("buffer-string", 0, Some(0), buffer_string);
s("buffer-size", 0, Some(1), buffer_size);
s("point", 0, Some(0), point_fn);
s("point-min", 0, Some(0), point_min);
s("point-max", 0, Some(0), point_max);
s("goto-char", 1, Some(1), goto_char);
s("erase-buffer", 0, Some(0), erase_buffer);
s("buffer-modified-p", 0, Some(1), buffer_modified_p);
s("position-bytes", 1, Some(1), position_bytes);
s("byte-to-position", 1, Some(1), byte_to_position);
s(
"restore-buffer-modified-p",
1,
Some(1),
restore_buffer_modified_p,
);
s("set-buffer-modified-p", 1, Some(1), set_buffer_modified_p);
s("buffer-modified-tick", 0, Some(1), buffer_modified_tick);
s(
"buffer-chars-modified-tick",
0,
Some(1),
buffer_chars_modified_tick,
);
s("char-after", 0, Some(1), char_after);
s("buffer-substring", 2, Some(2), buffer_substring);
s(
"buffer-substring-no-properties",
2,
Some(2),
buffer_substring_no_properties,
);
s("delete-region", 2, Some(2), delete_region);
s("make-marker", 0, Some(0), make_marker);
s("point-marker", 0, Some(0), point_marker);
s("markerp", 1, Some(1), markerp_fn);
s("marker-position", 1, Some(1), marker_position_fn);
s("marker-buffer", 1, Some(1), marker_buffer_fn);
s(
"marker-insertion-type",
1,
Some(1),
marker_insertion_type_fn,
);
s(
"set-marker-insertion-type",
2,
Some(2),
set_marker_insertion_type_fn,
);
s("set-marker", 2, Some(3), set_marker_fn);
s("move-marker", 2, Some(3), set_marker_fn);
s("copy-marker", 0, Some(2), copy_marker_fn);
s("next-property-change", 1, Some(3), next_property_change_fn);
s(
"next-single-property-change",
2,
Some(4),
next_single_property_change_fn,
);
s(
"previous-property-change",
1,
Some(3),
previous_property_change_fn,
);
s(
"previous-single-property-change",
2,
Some(4),
previous_single_property_change_fn,
);
s("object-intervals", 1, Some(1), object_intervals_fn);
s(
"elisprs--inside-interval-p",
1,
Some(1),
inside_interval_p_fn,
);
s("elisprs--inherit-props", 5, Some(6), inherit_props_fn);
s(
"add-face-text-property",
3,
Some(5),
add_face_text_property_fn,
);
s("get-text-property", 2, Some(3), get_text_property_fn);
s("text-properties-at", 1, Some(2), text_properties_at_fn);
s("put-text-property", 4, Some(5), put_text_property_fn);
s("set-text-properties", 3, Some(4), set_text_properties_fn);
s("add-text-properties", 3, Some(4), add_text_properties_fn);
s(
"remove-text-properties",
3,
Some(4),
remove_text_properties_fn,
);
s("propertize", 1, None, propertize_fn);
s("transpose-regions", 4, Some(5), transpose_regions_fn);
s(
"elisprs--replace-chars-in-place",
3,
Some(3),
replace_chars_in_place_fn,
);
s(
"elisprs--carry-text-properties",
2,
Some(2),
carry_text_properties_fn,
);
s(
"--insert-before-markers--",
1,
Some(1),
insert_before_markers_fn,
);
s("insert-file-contents", 1, None, insert_file_contents);
s("forward-char", 0, Some(1), forward_char);
s("backward-char", 0, Some(1), backward_char);
s("beginning-of-line", 0, Some(1), beginning_of_line);
s("end-of-line", 0, Some(1), end_of_line);
s(
"line-beginning-position",
0,
Some(1),
line_beginning_position,
);
s("line-end-position", 0, Some(1), line_end_position);
s("pos-bol", 0, Some(1), line_beginning_position);
s("pos-eol", 0, Some(1), line_end_position);
s("bolp", 0, Some(0), bolp);
s("eolp", 0, Some(0), eolp);
s("bobp", 0, Some(0), bobp);
s("eobp", 0, Some(0), eobp);
s("forward-line", 0, Some(1), forward_line);
s("search-forward", 1, Some(4), search_forward);
s("re-search-forward", 1, Some(4), re_search_forward);
s("looking-at", 1, Some(2), looking_at);
s(
"current-bidi-paragraph-direction",
0,
Some(1),
crate::bidi::current_bidi_paragraph_direction,
);
s("looking-at-p", 1, Some(1), looking_at_p);
s("replace-match", 1, Some(5), replace_match);
s("write-region", 3, Some(7), write_region);
s("delete-file-internal", 1, Some(1), delete_file_internal);
s(
"make-directory-internal",
1,
Some(1),
make_directory_internal,
);
s("rename-file", 2, Some(3), rename_file);
s("copy-file", 2, Some(6), copy_file);
s(
"shell-command-to-string",
1,
Some(1),
shell_command_to_string,
);
s("call-process", 1, None, call_process);
s("char-before", 0, Some(1), char_before);
s("delete-char", 1, Some(2), delete_char);
s("insert-char", 1, Some(3), insert_char);
s("count-lines", 2, Some(3), count_lines);
s("line-number-at-pos", 0, Some(2), line_number_at_pos);
s("current-column", 0, Some(0), current_column);
s("current-indentation", 0, Some(0), current_indentation);
s("indent-to", 1, Some(2), indent_to);
s("move-to-column", 1, Some(2), move_to_column);
s("search-backward", 1, Some(4), search_backward);
s("re-search-backward", 1, Some(4), re_search_backward);
s("skip-chars-forward", 1, Some(2), skip_chars_forward);
s("skip-chars-backward", 1, Some(2), skip_chars_backward);
s("forward-word", 0, Some(1), forward_word);
s("backward-word", 0, Some(1), backward_word);
s("random", 0, Some(1), random_fn);
s("float-time", 0, Some(1), float_time);
s("sleep-for", 1, Some(2), sleep_for);
s("current-time", 0, Some(0), current_time);
s("format-time-string", 1, Some(3), format_time_string);
s("current-time-string", 0, Some(2), current_time_string);
s("decode-time", 0, Some(3), decode_time);
s("encode-time", 1, None, encode_time);
s("time--decode", 1, Some(1), crate::timefns::time_decode_fn);
s("substring", 1, Some(3), substring);
s(
"substring-no-properties",
1,
Some(3),
substring_no_properties_fn,
);
s("split-string", 1, Some(4), split_string);
s("string-prefix-p", 2, Some(3), string_prefix_p);
s("string-suffix-p", 2, Some(3), string_suffix_p);
s("string-empty-p", 1, Some(1), string_empty_p);
s("string-join", 1, Some(2), string_join);
s("char-to-string", 1, Some(1), char_to_string);
s("string-to-char", 1, Some(1), string_to_char);
s("make-string", 2, Some(3), make_string);
s("string", 0, None, string_fn);
s("string-to-list", 1, Some(1), string_to_list);
s("string-search", 2, Some(3), string_search);
s("string-match", 2, Some(3), string_match);
s("string-match-p", 2, Some(3), string_match_p);
s("match-beginning", 1, Some(1), match_beginning);
s("match-end", 1, Some(1), match_end);
s("match-string", 1, Some(2), match_string);
s("match-data", 0, Some(3), match_data_fn);
s("set-match-data", 1, Some(2), set_match_data);
s("match-data--translate", 1, Some(1), match_data_translate);
s("regexp-quote", 1, Some(1), regexp_quote);
s("concat", 0, None, concat_fn);
s("format", 1, None, format_fn);
s("message", 1, None, message_fn);
s("princ", 1, Some(2), princ_fn);
s("prin1", 1, Some(2), prin1_fn);
s("number-to-string", 1, Some(1), number_to_string);
s("floor", 1, Some(2), floor_fn);
s("ceiling", 1, Some(2), ceiling_fn);
s("round", 1, Some(2), round_fn);
s("truncate", 1, Some(2), truncate_fn);
s("float", 1, Some(1), float_fn);
s("logand", 0, None, logand_fn);
s("logior", 0, None, logior_fn);
s("logxor", 0, None, logxor_fn);
s("lognot", 1, Some(1), lognot_fn);
s("ash", 2, Some(2), ash_fn);
s("lsh", 2, Some(2), lsh_fn);
s("expt", 2, Some(2), expt_fn);
s("sqrt", 1, Some(1), sqrt_fn);
s("exp", 1, Some(1), exp_fn);
s("log", 1, Some(2), log_fn);
s("sin", 1, Some(1), sin_fn);
s("cos", 1, Some(1), cos_fn);
s("tan", 1, Some(1), tan_fn);
s("asin", 1, Some(1), asin_fn);
s("acos", 1, Some(1), acos_fn);
s("atan", 1, Some(2), atan_fn);
s("ldexp", 2, Some(2), ldexp_fn);
s("copysign", 2, Some(2), copysign_fn);
s("frexp", 1, Some(1), frexp_fn);
s("isnan", 1, Some(1), isnan_fn);
s("fround", 1, Some(1), fround_fn);
s("ffloor", 1, Some(1), ffloor_fn);
s("fceiling", 1, Some(1), fceiling_fn);
s("ftruncate", 1, Some(1), ftruncate_fn);
s("string-to-number", 1, Some(2), string_to_number);
s("downcase", 1, Some(1), downcase_fn);
s("upcase", 1, Some(1), upcase_fn);
s("--char-titlecase--", 1, Some(1), char_titlecase);
s("type-of", 1, Some(1), type_of);
s("recordp", 1, Some(1), recordp);
s("closurep", 1, Some(1), closurep_fn);
s(
"elisprs--prelude-closure-p",
1,
Some(1),
prelude_closure_p_fn,
);
s("oclosure--fix-type", 4, Some(4), oclosure_fix_type);
s("oclosure-type", 1, Some(1), oclosure_type_fn);
s("oclosure--get", 3, Some(3), oclosure_get_fn);
s("oclosure--set", 3, Some(3), oclosure_set_fn);
s("oclosure--copy", 2, None, oclosure_copy_fn);
s("sxhash-equal", 1, Some(1), sxhash_equal_fn);
s("sxhash", 1, Some(1), sxhash_equal_fn);
s("sxhash-eq", 1, Some(1), sxhash_eq_fn);
s("sxhash-eql", 1, Some(1), sxhash_eql_fn);
s("cl-struct-p", 1, Some(1), recordp);
s("functionp", 1, Some(1), functionp);
s("char-or-string-p", 1, Some(1), char_or_string_p);
s("char-equal", 2, Some(2), char_equal);
s("char-width", 1, Some(1), char_width_fn);
s("vconcat", 0, None, vconcat_fn);
s("string-to-vector", 1, Some(1), string_to_vector);
s("abs", 1, Some(1), abs_fn);
s("logcount", 1, Some(1), logcount_fn);
s("symbol-function", 1, Some(1), symbol_function);
s(
"--set-intrinsic-macro-cell",
2,
Some(2),
set_intrinsic_macro_cell,
);
s("intern-soft", 1, Some(2), intern_soft);
s("subrp", 1, Some(1), subrp);
s("--set-subr-intspec", 2, Some(2), set_subr_intspec);
s("--subr-intspec", 1, Some(1), subr_intspec);
s("macrop", 1, Some(1), macrop);
s("special-form-p", 1, Some(1), special_form_p);
s("char-uppercase-p", 1, Some(1), char_uppercase_p);
s("string-distance", 2, Some(3), string_distance);
s("logb", 1, Some(1), logb_fn);
s("max-char", 0, Some(1), max_char);
s("byteorder", 0, Some(0), byteorder);
s("char-resolve-modifiers", 1, Some(1), char_resolve_modifiers);
s("text-char-description", 1, Some(1), text_char_description);
s(
"unibyte-char-to-multibyte",
1,
Some(1),
unibyte_char_to_multibyte,
);
s(
"multibyte-char-to-unibyte",
1,
Some(1),
multibyte_char_to_unibyte,
);
s("decode-char", 2, Some(2), decode_char);
s("emacs-pid", 0, Some(0), emacs_pid);
s("load-average", 0, Some(1), load_average);
s("read", 0, Some(1), read_fn);
s("read-from-string", 1, Some(3), read_from_string);
s("read-from-minibuffer", 1, Some(7), read_from_minibuffer);
s("read-string", 1, Some(5), read_string);
s("kill-emacs", 0, Some(2), intercepted_subr);
s("compare-strings", 6, Some(7), compare_strings);
s("string-split", 1, Some(4), split_string);
s("member-ignore-case", 2, Some(2), member_ignore_case);
let null_sym = h.intern("null");
h.set_function("not", null_sym);
install_special_form_cells(h);
crate::intercepts::install(h);
}
pub(crate) fn is_special_form(name: &str) -> bool {
SPECIAL_FORMS.iter().any(|(sf, _)| *sf == name)
}
fn special_form_body(_h: &mut ElispHost, _a: &[Value]) -> R {
Err(
"internal: a special form's subr body was called; host::call_function \
should have signalled invalid-function"
.to_string(),
)
}
fn install_special_form_cells(h: &mut ElispHost) {
for (name, min) in SPECIAL_FORMS {
let subr = h.alloc(Obj::Subr {
name: (*name).to_string(),
min: *min as usize,
max: None,
f: special_form_body,
});
let sym = h.intern(name);
h.set_intrinsic_macro_cell(&sym, subr);
}
}
fn object_runs(h: &ElispHost, obj: &PropObj) -> Option<Vec<(i64, i64, Value)>> {
match obj {
PropObj::Str(s) => {
let runs = h.string_intervals(s);
if runs.is_empty() {
None
} else {
Some(
runs.into_iter()
.map(|(a, b, p)| (a as i64, b as i64, p))
.collect(),
)
}
}
PropObj::Buf(bi) => {
let b = &h.buffers[*bi];
if !b.has_intervals || b.props.is_empty() {
return None;
}
Some(
h.tp_runs(&b.props, &b.prop_bounds)
.into_iter()
.map(|(a, e)| (a as i64 + 1, e as i64 + 1, b.props[a].clone()))
.collect(),
)
}
}
}
fn single_position(h: &ElispHost, obj: &PropObj, pos: &Value) -> Result<i64, String> {
let p = match h.marker_position(pos) {
Some(p) => p as i64,
None => match pos {
Value::Int(n) => *n,
other => {
return Err(format!(
"wrong-type-argument: integer-or-marker-p {}",
h.print(other, true)
))
}
},
};
let (min, max) = match obj {
PropObj::Str(s) => (0, s.chars().count() as i64),
PropObj::Buf(bi) => {
let (begv, zv) = h.buffer_begv_zv(*bi);
(begv as i64, zv as i64)
}
};
if p < min || p > max {
return Err(format!("args-out-of-range: {p} {p}"));
}
Ok(p)
}
fn textget(h: &mut ElispHost, plist: &Value, prop: &Value) -> Value {
if let Some(v) = h.plist_lookup(plist, prop) {
return v;
}
let category = h.intern("category");
match h.plist_lookup(plist, &category) {
Some(cat) if h.sym_name(&cat).is_some() => {
let table_sym = h.intern("symbol-plist--table");
match h.get_dynamic_value(&table_sym) {
Ok(table) => {
let plist = gethash(h, &[cat, table]).unwrap_or(Value::Undef);
h.plist_get_eq(&plist, prop)
}
Err(_) => Value::Undef,
}
}
_ => Value::Undef,
}
}
fn object_end(h: &ElispHost, obj: &PropObj) -> i64 {
match obj {
PropObj::Str(s) => s.chars().count() as i64,
PropObj::Buf(bi) => h.buffer_begv_zv(*bi).1 as i64,
}
}
fn object_begin(h: &ElispHost, obj: &PropObj) -> i64 {
match obj {
PropObj::Str(_) => 0,
PropObj::Buf(bi) => h.buffer_begv_zv(*bi).0 as i64,
}
}
fn limit_arg(h: &ElispHost, v: Option<&Value>) -> Result<Value, String> {
match v {
None => Ok(Value::Undef),
Some(v) if is_nil(v) || matches!(v, Value::Bool(true)) => Ok(v.clone()),
Some(v) => match h.marker_position(v) {
Some(p) => Ok(Value::Int(p as i64)),
None => match v {
Value::Int(_) => Ok(v.clone()),
other => Err(format!(
"wrong-type-argument: integer-or-marker-p {}",
h.print(other, true)
)),
},
},
}
}
fn limit_int(limit: &Value) -> Option<i64> {
match limit {
Value::Int(n) => Some(*n),
_ => None,
}
}
fn next_property_change_fn(h: &mut ElispHost, a: &[Value]) -> R {
let obj = prop_object(h, a.get(1))?;
let limit = limit_arg(h, a.get(2))?;
let pos = single_position(h, &obj, &a[0])?;
let runs = object_runs(h, &obj);
let end = object_end(h, &obj);
let Some(runs) = runs else {
return Ok(limit);
};
let i = runs
.iter()
.position(|&(s, e, _)| s <= pos && pos < e)
.unwrap_or(runs.len() - 1);
if matches!(limit, Value::Bool(true)) {
return Ok(Value::Int(runs.get(i + 1).map_or(end, |r| r.0)));
}
let lim = limit_int(&limit);
let mut next = i + 1;
while next < runs.len()
&& h.plist_struct_eq(&runs[i].2, &runs[next].2)
&& lim.is_none_or(|l| runs[next].0 < l)
{
next += 1;
}
match runs.get(next) {
Some(r) if r.0 < lim.unwrap_or(end) => Ok(Value::Int(r.0)),
_ => Ok(limit),
}
}
fn next_single_property_change_fn(h: &mut ElispHost, a: &[Value]) -> R {
let obj = prop_object(h, a.get(2))?;
let limit = limit_arg(h, a.get(3))?;
if matches!(limit, Value::Bool(true)) {
return Err(format!(
"wrong-type-argument: integer-or-marker-p {}",
h.print(&limit, true)
));
}
let pos = single_position(h, &obj, &a[0])?;
let end = object_end(h, &obj);
let Some(runs) = object_runs(h, &obj) else {
return Ok(limit);
};
let i = runs
.iter()
.position(|&(s, e, _)| s <= pos && pos < e)
.unwrap_or(runs.len() - 1);
let here = textget(h, &runs[i].2, &a[1]);
let lim = limit_int(&limit);
let mut next = i + 1;
while next < runs.len()
&& {
let v = textget(h, &runs[next].2, &a[1]);
h.values_eq(&here, &v)
}
&& lim.is_none_or(|l| runs[next].0 < l)
{
next += 1;
}
match runs.get(next) {
Some(r) if r.0 < lim.unwrap_or(end) => Ok(Value::Int(r.0)),
_ => Ok(limit),
}
}
fn previous_property_change_fn(h: &mut ElispHost, a: &[Value]) -> R {
let obj = prop_object(h, a.get(1))?;
let limit = limit_arg(h, a.get(2))?;
let pos = single_position(h, &obj, &a[0])?;
let begin = object_begin(h, &obj);
let Some(runs) = object_runs(h, &obj) else {
return Ok(limit);
};
let mut i = runs
.iter()
.position(|&(s, e, _)| s <= pos && pos < e)
.unwrap_or(runs.len() - 1);
if runs[i].0 == pos {
if i == 0 {
return Ok(limit);
}
i -= 1;
}
let lim = limit_int(&limit);
let mut prev = i as i64 - 1;
while prev >= 0
&& h.plist_struct_eq(&runs[prev as usize].2, &runs[i].2)
&& lim.is_none_or(|l| runs[prev as usize].1 > l)
{
prev -= 1;
}
if prev < 0 || runs[prev as usize].1 <= lim.unwrap_or(begin) {
return Ok(limit);
}
Ok(Value::Int(runs[prev as usize].1))
}
fn previous_single_property_change_fn(h: &mut ElispHost, a: &[Value]) -> R {
let obj = prop_object(h, a.get(2))?;
let limit = limit_arg(h, a.get(3))?;
let pos = single_position(h, &obj, &a[0])?;
let begin = object_begin(h, &obj);
let Some(runs) = object_runs(h, &obj) else {
return Ok(limit);
};
let mut i = runs
.iter()
.position(|&(s, e, _)| s <= pos && pos < e)
.unwrap_or(runs.len() - 1);
if runs[i].0 == pos {
if i == 0 {
return Ok(limit);
}
i -= 1;
}
let here = textget(h, &runs[i].2, &a[1]);
let lim = limit_int(&limit);
let mut prev = i as i64 - 1;
while prev >= 0
&& {
let v = textget(h, &runs[prev as usize].2, &a[1]);
h.values_eq(&here, &v)
}
&& lim.is_none_or(|l| runs[prev as usize].1 > l)
{
prev -= 1;
}
if prev < 0 || runs[prev as usize].1 <= lim.unwrap_or(begin) {
return Ok(limit);
}
Ok(Value::Int(runs[prev as usize].1))
}
fn object_intervals_fn(h: &mut ElispHost, a: &[Value]) -> R {
let obj = match &a[0] {
v if h.is_string(v) => PropObj::Str(h.str_arc(v).expect("checked stringp")),
v => match h.resolve_buffer(v) {
Some(bi) if matches!(h.obj(v), Some(Obj::Buffer(_))) => PropObj::Buf(bi),
_ => {
return Err(format!(
"wrong-type-argument: buffer-or-string-p {}",
h.print(v, true)
))
}
},
};
let base = if matches!(obj, PropObj::Buf(_)) { 1 } else { 0 };
let runs = object_runs(h, &obj).unwrap_or_default();
let items = runs
.into_iter()
.map(|(s, e, p)| h.list_from(vec![Value::Int(s - base), Value::Int(e - base), p]))
.collect();
Ok(h.list_from(items))
}
fn add_face_text_property_fn(h: &mut ElispHost, a: &[Value]) -> R {
let start = as_int(h, &a[0])?;
let end = as_int(h, &a[1])?;
let append = a.get(3).is_some_and(|v| !is_nil(v));
let obj = prop_object(h, a.get(4))?;
let (lo, hi) = prop_range(&obj, start, end, h)?;
let face = h.intern("face");
let pairs = [(face, a[2].clone())];
let set_type = if append {
crate::textprop::SetType::Append
} else {
crate::textprop::SetType::Prepend
};
match &obj {
PropObj::Str(s) => {
h.string_add_props(s, lo, hi, &pairs, set_type);
}
PropObj::Buf(bi) => {
let bi = *bi;
record_prop_undo(h, bi, lo, hi, PropUndo::Add(&pairs));
let changed = with_buffer(h, bi, |h| h.buffer_add_props(lo, hi, &pairs, set_type));
if changed {
h.note_prop_change(bi);
}
}
}
Ok(Value::Undef)
}
fn inside_interval_p_fn(h: &mut ElispHost, a: &[Value]) -> R {
let pos = as_int(h, &a[0])?.max(0) as usize;
Ok(nil_or(h.buffer_inside_interval(pos)))
}
fn inherit_props_fn(h: &mut ElispHost, a: &[Value]) -> R {
let start = as_int(h, &a[0])?.max(1) as usize;
let end = as_int(h, &a[1])?.max(1) as usize;
let inside = a.get(5).is_some_and(|v| !is_nil(v));
h.buffer_inherit_props(start, end, &a[2], inside);
Ok(Value::Undef)
}
fn undo_boundary_fn(h: &mut ElispHost, _a: &[Value]) -> R {
h.undo_boundary();
Ok(Value::Undef)
}
enum PropUndo<'a> {
Add(&'a [(Value, Value)]),
Remove(&'a [Value]),
Set(&'a Value),
}
fn record_prop_undo(h: &mut ElispHost, bi: usize, lo: usize, hi: usize, change: PropUndo) {
if lo >= hi {
return;
}
let (props, bounds) = {
let b = &h.buffers[bi];
(b.props.clone(), b.prop_bounds.clone())
};
let runs = h.tp_runs(&props, &bounds);
let mut records: Vec<(usize, usize, Value, Value)> = Vec::new();
for (rs, re) in runs {
let (s, e) = (rs.max(lo), re.min(hi));
if s >= e {
continue;
}
let plist = props[rs].clone();
match &change {
PropUndo::Add(pairs) => {
for (prop, val) in pairs.iter() {
match plist_lookup(h, &plist, prop) {
Some(old) if h.values_eq(&old, val) => {}
Some(old) => records.push((s, e, prop.clone(), old)),
None => records.push((s, e, prop.clone(), Value::Undef)),
}
}
}
PropUndo::Remove(names) => {
for name in names.iter() {
if let Some(old) = plist_lookup(h, &plist, name) {
records.push((s, e, name.clone(), old));
}
}
}
PropUndo::Set(new) => {
for (prop, old) in each_prop_pair(h, &plist) {
let same = plist_lookup(h, new, &prop).is_some_and(|v| h.values_eq(&v, &old));
if !same {
records.push((s, e, prop, old));
}
}
for (prop, _) in each_prop_pair(h, new) {
if plist_lookup(h, &plist, &prop).is_none() {
records.push((s, e, prop, Value::Undef));
}
}
}
}
}
for (s, e, prop, old) in records {
h.record_property_change(bi, s + 1, e - s, prop, old);
}
}
fn recent_auto_save_p(h: &mut ElispHost, _a: &[Value]) -> R {
let m = &h.cur_buf_ref().mods;
Ok(nil_or(m.save_modiff < m.autosave_modiff))
}
pub(crate) fn text_prop_change_span(
h: &mut ElispHost,
name: &str,
args: &[Value],
object: usize,
) -> Option<(usize, usize, usize)> {
let (Value::Int(start), Value::Int(end)) = (args.first()?.clone(), args.get(1)?.clone()) else {
return None;
};
let obj = prop_object(h, args.get(object)).ok()?;
let PropObj::Buf(bi) = obj else {
return None;
};
let (lo, hi) = prop_range(&obj, start, end, h).ok()?;
if lo >= hi {
return None;
}
let changes = match name {
"put-text-property" => {
let pair = [(args.get(2)?.clone(), args.get(3)?.clone())];
props_would_change(h, &obj, lo, hi, &pair, true)
}
"add-text-properties" => {
let pairs = each_prop_pair(h, args.get(2)?);
props_would_change(h, &obj, lo, hi, &pairs, true)
}
"remove-text-properties" => {
let pairs = each_prop_pair(h, args.get(2)?);
props_would_change(h, &obj, lo, hi, &pairs, false)
}
"add-face-text-property" => {
let face = h.intern("face");
let pair = [(face, args.get(2)?.clone())];
props_would_change(h, &obj, lo, hi, &pair, true)
}
_ => !(args.get(2).is_none_or(is_nil) && !h.buffers[bi].has_intervals),
};
changes.then_some((bi, lo + 1, hi + 1))
}
pub(crate) fn subst_char_span(
h: &mut ElispHost,
a: &[Value],
) -> Option<(usize, usize, usize, usize)> {
let (lo, hi) = validate_region(h, &a[0], &a[1]).ok()?;
let from = char::from_u32(check_character(h, &a[2]).ok()? as u32)?;
check_character(h, &a[3]).ok()?;
let text = &h.cur_buf_ref().text[lo - 1..hi - 1];
let first = text.iter().position(|&c| c == from)?;
let last = text.iter().rposition(|&c| c == from)?;
Some((lo, hi, lo + first, lo + last + 1))
}
fn subst_char_in_region(h: &mut ElispHost, a: &[Value]) -> R {
let (lo, hi) = validate_region(h, &a[0], &a[1])?;
let from = check_character(h, &a[2])?;
let to = check_character(h, &a[3])?;
let noundo = a.get(4).is_some_and(|v| !is_nil(v));
let (from, to) = (
char::from_u32(from as u32).unwrap_or('\u{fffd}'),
char::from_u32(to as u32).unwrap_or('\u{fffd}'),
);
let positions: Vec<usize> = (lo..hi)
.filter(|&p| h.cur_buf_ref().text[p - 1] == from)
.collect();
let Some(&first) = positions.first() else {
return Ok(Value::Undef);
};
h.barf_if_read_only()?;
{
let m = &h.cur_buf_ref().mods;
if m.modiff <= m.save_modiff {
h.record_first_change_if_undo();
}
}
h.note_text_change(hi - first);
if noundo {
let m = &mut h.cur_buf().mods;
if m.save_modiff == m.modiff - 1 {
m.save_modiff = m.modiff;
}
if m.autosave_modiff == m.modiff - 1 {
m.autosave_modiff = m.modiff;
}
}
for p in positions {
if !noundo {
h.record_change(p, 1);
}
h.cur_buf().text[p - 1] = to;
}
Ok(Value::Undef)
}
#[cfg(test)]
mod tests {
use crate::{eval_str, print, reset_host};
fn eval(src: &str) -> String {
reset_host();
let v = eval_str(src).expect("eval failed");
print(&v, true)
}
fn eval_err(src: &str) -> String {
reset_host();
eval_str(src).unwrap_err()
}
#[test]
fn cadr_family_composition() {
assert_eq!(eval("(caadr '(1 (2 3) 4))"), "2");
assert_eq!(eval("(cadar '((1 2 3) 4))"), "2");
assert_eq!(eval("(cdaar '(((1 2) 3) 4))"), "(2)");
assert_eq!(eval("(cdadr '(1 (2 3) 4))"), "(3)");
assert_eq!(eval("(cddar '((1 2 3) 4))"), "(3)");
}
#[test]
fn cadr_family_nil_edges() {
assert_eq!(eval("(caadr '(1))"), "nil");
assert_eq!(eval("(cadar '(nil))"), "nil");
assert_eq!(eval("(cddar '((1)))"), "nil");
assert!(eval_err("(caadr '(1 2 3))").contains("listp"));
}
#[test]
fn cl_two_level_aliases() {
assert_eq!(eval("(cl-caar '((1 2) 3))"), "1");
assert_eq!(eval("(cl-cadr '(1 2 3))"), "2");
assert_eq!(eval("(cl-cdar '((1 2) 3))"), "(2)");
assert_eq!(eval("(cl-cddr '(1 2 3 4))"), "(3 4)");
assert_eq!(eval("(cl-cadr '(1))"), "nil");
assert_eq!(eval("(cl-cddr '(1))"), "nil");
}
#[test]
fn string_split_forwards_to_split_string() {
assert_eq!(eval("(string-split \" a b c \")"), "(\"a\" \"b\" \"c\")");
assert_eq!(eval("(string-split \"\")"), "nil");
assert_eq!(eval("(string-split \"a,,b\" \",\")"), "(\"a\" \"\" \"b\")");
assert_eq!(
eval("(string-split \"abc\" \"\")"),
"(\"\" \"a\" \"b\" \"c\" \"\")"
);
}
#[test]
fn member_ignore_case_semantics() {
assert_eq!(
eval("(member-ignore-case \"b\" '(\"A\" \"B\" \"C\"))"),
"(\"B\" \"C\")"
);
assert_eq!(eval("(member-ignore-case \"z\" '(\"a\" \"b\"))"), "nil");
assert_eq!(eval("(member-ignore-case \"b\" '(1 2 \"B\"))"), "(\"B\")");
assert_eq!(eval("(member-ignore-case \"a\" nil)"), "nil");
}
}