use fusevm::{Chunk, NumOp, VMResult, Value, VM};
use indexmap::IndexMap;
use num_bigint::BigInt;
use serde::{Deserialize, Serialize};
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::{Arc, Weak};
pub const HEAP_IMAGE_TAG: &str = "\u{0}ELHEAP\u{0}";
pub const MAX_CHAR: u32 = 0x3F_FFFF;
#[derive(Serialize, Deserialize, Clone)]
pub enum SerObj {
Cons(Value, Value),
Symbol {
name: String,
value: Option<Value>,
function: Option<Value>,
special: bool,
#[serde(default)]
buffer_local_auto: bool,
#[serde(default)]
alias_of: Option<u32>,
#[serde(default)]
interned: bool,
},
Vector(Vec<Value>),
Record(Vec<Value>),
BoolVector(Vec<bool>),
HashTable {
test: u8,
slots: Vec<Option<(Value, Value)>>,
free: Vec<u32>,
size: usize,
weakness: Value,
user_test: Option<(Value, Value, Value)>,
},
CharTable {
subtype: Value,
default: Value,
parent: Value,
extra: Vec<Value>,
contents: Vec<CtSer>,
ascii: Option<Value>,
},
Closure {
required: Vec<u32>,
optional: Vec<u32>,
rest: Option<u32>,
body: Chunk,
is_macro: bool,
#[serde(default)]
env: Vec<(u32, Option<Value>)>,
#[serde(default)]
dynamic: bool,
#[serde(default)]
arglist: Value,
#[serde(default)]
src_body: Vec<Value>,
},
Bignum(BigInt),
Str(String),
}
pub mod ops {
pub const TRUTHY: u16 = 0; pub const CALL: u16 = 1; pub const GETVAR: u16 = 2; pub const SETVAR: u16 = 3; pub const FSET: u16 = 4; pub const SPECBIND: u16 = 5; pub const LETBIND: u16 = 6; pub const UNBIND: u16 = 7; pub const SCOPE_OPEN: u16 = 8; pub const MAKE_CLOSURE: u16 = 9; pub const DBG_LINE: u16 = 10; pub const CHECK_ARITY: u16 = 11; pub const DEFVAR_INIT: u16 = 12; }
pub type SubrFn = fn(&mut ElispHost, &[Value]) -> Result<Value, String>;
#[derive(Clone)]
enum SpecEntry {
Global(u32, usize, Option<Value>),
Local(u32, usize, Option<Option<Value>>),
}
pub struct Params {
pub required: Vec<u32>,
pub optional: Vec<u32>,
pub rest: Option<u32>,
}
pub struct Scope {
sym: u32,
val: Rc<RefCell<Value>>,
parent: Lex,
special: bool,
}
pub type Lex = Option<Rc<Scope>>;
impl Scope {
pub(crate) fn new(sym: u32, val: Value, parent: Lex) -> Self {
Scope {
sym,
val: Rc::new(RefCell::new(val)),
parent,
special: false,
}
}
pub(crate) fn declaration(sym: u32, parent: Lex) -> Self {
Scope {
special: true,
..Scope::new(sym, Value::Undef, parent)
}
}
pub(crate) fn is_declaration(&self) -> bool {
self.special
}
pub(crate) fn sharing(sym: u32, val: Rc<RefCell<Value>>, parent: Lex) -> Self {
Scope {
sym,
val,
parent,
special: false,
}
}
pub(crate) fn sym_handle(&self) -> u32 {
self.sym
}
pub(crate) fn value(&self) -> Value {
self.val.borrow().clone()
}
pub(crate) fn value_cell(&self) -> Rc<RefCell<Value>> {
Rc::clone(&self.val)
}
pub(crate) fn parent_lex(&self) -> Lex {
self.parent.clone()
}
fn lookup(self: &Rc<Scope>, sym: u32) -> Option<Value> {
let mut cur = Some(self.clone());
while let Some(s) = cur {
if s.sym == sym && !s.special {
return Some(s.val.borrow().clone());
}
cur = s.parent.clone();
}
None
}
fn set(self: &Rc<Scope>, sym: u32, val: &Value) -> bool {
let mut cur = Some(self.clone());
while let Some(s) = cur {
if s.sym == sym && !s.special {
*s.val.borrow_mut() = val.clone();
return true;
}
cur = s.parent.clone();
}
false
}
fn declares_special(self: &Rc<Scope>, sym: u32) -> bool {
let mut cur = Some(self.clone());
while let Some(s) = cur {
if s.sym == sym && s.special {
return true;
}
cur = s.parent.clone();
}
false
}
pub(crate) fn has_bindings(self: &Rc<Scope>) -> bool {
let mut cur = Some(self.clone());
while let Some(s) = cur {
if !s.special {
return true;
}
cur = s.parent.clone();
}
false
}
}
#[derive(Clone)]
pub struct SymbolData {
pub name: String,
pub value: Option<Value>,
pub function: Option<Value>, pub special: bool,
pub buffer_local_auto: bool,
pub alias_of: Option<u32>,
}
#[derive(Clone)]
pub enum Obj {
Cons(Value, Value),
Symbol(SymbolData),
Vector(Vec<Value>),
Record(Vec<Value>),
BoolVector(Vec<bool>),
Str(Arc<String>),
Subr {
name: String,
min: usize,
max: Option<usize>,
f: SubrFn,
},
Closure {
params: Rc<Params>,
body: Rc<Chunk>,
is_macro: bool,
env: Lex,
dynamic: bool,
src: Rc<ClosureSrc>,
},
HashTable(ElHashTable),
CharTable(CharTable),
Buffer(usize),
Marker(Rc<RefCell<MarkerData>>),
Overlay(Rc<RefCell<OverlayData>>),
Window(usize),
Frame(usize),
WindowConfig(usize),
Obarray(ObarrayData),
Bignum(BigInt),
}
#[derive(Clone)]
pub struct ObarrayData {
pub symbols: HashMap<String, u32>,
pub global: bool,
}
pub struct MarkerData {
pub buffer: Option<usize>,
pub pos: usize,
pub insertion_type: bool,
}
pub struct OverlayData {
pub buffer: Option<usize>,
pub start: usize,
pub end: usize,
pub front_advance: bool,
pub rear_advance: bool,
pub props: Vec<(Value, Value)>,
}
#[derive(Clone)]
pub struct ElHashTable {
pub test: u8,
pub user_test: Option<(Value, Value, Value)>,
pub slots: Vec<Option<(Value, Value)>>,
free: Vec<u32>,
index: HashMap<u64, Vec<u32>>,
live: usize,
indexed: bool,
pub size: usize,
pub weakness: Value,
}
impl ElHashTable {
pub fn new(test: u8, size: usize, weakness: Value) -> ElHashTable {
ElHashTable {
test,
user_test: None,
slots: Vec::new(),
free: Vec::new(),
index: HashMap::new(),
live: 0,
indexed: true,
size,
weakness,
}
}
pub fn from_slots(
test: u8,
slots: Vec<Option<(Value, Value)>>,
free: Vec<u32>,
size: usize,
weakness: Value,
) -> ElHashTable {
let live = slots.iter().flatten().count();
ElHashTable {
test,
user_test: None,
slots,
free,
index: HashMap::new(),
live,
indexed: false,
size,
weakness,
}
}
pub fn needs_index(&self) -> bool {
!self.indexed
}
pub fn reindex(&mut self, hashes: &[(u32, u64)]) {
self.index.clear();
for &(slot, hk) in hashes {
self.index.entry(hk).or_default().push(slot);
}
self.indexed = true;
}
fn grown(size: usize) -> usize {
match size {
0 => 6,
n if n <= 64 => (n * 4).max(24),
n => n * 2,
}
}
pub fn count(&self) -> usize {
self.live
}
pub fn pairs(&self) -> impl Iterator<Item = &(Value, Value)> {
self.slots.iter().flatten()
}
pub fn candidates(&self, hk: u64) -> &[u32] {
self.index.get(&hk).map_or(&[][..], |v| v.as_slice())
}
pub fn key_at(&self, slot: u32) -> Option<&Value> {
self.slots[slot as usize].as_ref().map(|(k, _)| k)
}
pub fn value_at(&self, slot: u32) -> Option<&Value> {
self.slots[slot as usize].as_ref().map(|(_, v)| v)
}
pub fn set_value_at(&mut self, slot: u32, val: Value) {
if let Some(e) = self.slots[slot as usize].as_mut() {
e.1 = val;
}
}
pub fn insert(&mut self, hk: u64, key: Value, val: Value) {
if self.live >= self.size {
self.size = Self::grown(self.size);
}
let slot = match self.free.pop() {
Some(i) => {
self.slots[i as usize] = Some((key, val));
i
}
None => {
self.slots.push(Some((key, val)));
(self.slots.len() - 1) as u32
}
};
self.index.entry(hk).or_default().push(slot);
self.live += 1;
}
pub fn remove(&mut self, hk: u64, slot: u32) {
if self.slots[slot as usize].take().is_none() {
return;
}
if let Some(bucket) = self.index.get_mut(&hk) {
bucket.retain(|&i| i != slot);
if bucket.is_empty() {
self.index.remove(&hk);
}
}
self.free.push(slot);
self.live -= 1;
}
pub fn clear(&mut self) {
self.slots.clear();
self.free.clear();
self.index.clear();
self.live = 0;
}
}
pub(crate) const CT_SIZE: [usize; 4] = [64, 16, 32, 128];
pub(crate) const CT_CHARS: [u32; 4] = [65_536, 4_096, 128, 1];
#[derive(Clone)]
pub enum CtSlot {
Val(Value),
Sub(Box<SubCharTable>),
}
#[derive(Clone)]
pub struct SubCharTable {
pub depth: u8,
pub min_char: u32,
pub contents: Vec<CtSlot>,
}
impl SubCharTable {
fn new(depth: u8, min_char: u32, init: &Value) -> SubCharTable {
SubCharTable {
depth,
min_char,
contents: vec![CtSlot::Val(init.clone()); CT_SIZE[depth as usize]],
}
}
fn index(&self, c: u32) -> usize {
((c - self.min_char) / CT_CHARS[self.depth as usize]) as usize
}
fn optimize(&mut self, same: &dyn Fn(&Value, &Value) -> bool) -> Option<Value> {
for slot in &mut self.contents {
if let CtSlot::Sub(s) = slot {
if let Some(v) = s.optimize(same) {
*slot = CtSlot::Val(v);
}
}
}
let CtSlot::Val(first) = &self.contents[0] else {
return None;
};
let all_same = self.contents[1..]
.iter()
.all(|slot| matches!(slot, CtSlot::Val(v) if same(v, first)));
all_same.then(|| first.clone())
}
fn set(&mut self, c: u32, val: Value) {
let i = self.index(c);
if self.depth == 3 {
self.contents[i] = CtSlot::Val(val);
return;
}
let depth = self.depth;
let min = self.min_char + i as u32 * CT_CHARS[depth as usize];
let slot = &mut self.contents[i];
if let CtSlot::Val(old) = slot {
let sub = SubCharTable::new(depth + 1, min, old);
*slot = CtSlot::Sub(Box::new(sub));
}
if let CtSlot::Sub(sub) = slot {
sub.set(c, val);
}
}
fn set_range(&mut self, from: u32, to: u32, val: &Value) {
let depth = self.depth as usize;
let block = CT_CHARS[depth];
let from = from.max(self.min_char);
let mut i = self.index(from);
let mut c = self.min_char + block * i as u32;
while i < CT_SIZE[depth] {
if c > to {
break;
}
if from <= c && c + block - 1 <= to {
self.contents[i] = CtSlot::Val(val.clone());
} else {
let slot = &mut self.contents[i];
if let CtSlot::Val(old) = slot {
let sub = SubCharTable::new(self.depth + 1, c, old);
*slot = CtSlot::Sub(Box::new(sub));
}
if let CtSlot::Sub(sub) = slot {
sub.set_range(from, to, val);
}
}
i += 1;
c += block;
}
}
}
#[derive(Clone)]
pub enum CtAscii {
Val(Value),
Tree,
}
#[derive(Clone)]
pub struct CharTable {
pub subtype: Value,
pub default: Value,
pub parent: Value,
pub extra: Vec<Value>,
pub contents: Vec<CtSlot>,
pub ascii: CtAscii,
}
fn ct_val_eq(a: &Value, b: &Value) -> bool {
if !el_truthy(a) && !el_truthy(b) {
return true;
}
match (a, b) {
(Value::Int(x), Value::Int(y)) => x == y,
(Value::Float(x), Value::Float(y)) => x.to_bits() == y.to_bits(),
(Value::Obj(x), Value::Obj(y)) => x == y,
(Value::Bool(true), Value::Bool(true)) => true,
_ => false,
}
}
const CT_ASCII_LABEL: u32 = 0x8000_0000;
impl SubCharTable {
fn leaf_values(&self, out: &mut Vec<Value>) {
for slot in &self.contents {
slot.leaf_values(out, false);
}
}
}
impl CtSlot {
fn leaf_values(&self, out: &mut Vec<Value>, skip_ascii: bool) {
match self {
CtSlot::Val(v) => out.push(v.clone()),
CtSlot::Sub(s) => {
if skip_ascii && s.depth == 3 && s.min_char == 0 {
return;
}
for slot in &s.contents {
slot.leaf_values(out, skip_ascii);
}
}
}
}
}
impl CharTable {
pub fn new(subtype: Value, init: Value, n_extra: usize) -> CharTable {
CharTable {
subtype,
default: init.clone(),
parent: Value::Undef,
extra: vec![init.clone(); n_extra],
contents: vec![CtSlot::Val(init.clone()); CT_SIZE[0]],
ascii: CtAscii::Val(init),
}
}
pub fn raw_get(&self, c: u32) -> Value {
let mut slot = &self.contents[(c / CT_CHARS[0]) as usize];
loop {
match slot {
CtSlot::Val(v) => return v.clone(),
CtSlot::Sub(s) => slot = &s.contents[s.index(c)],
}
}
}
pub fn ascii_table(&self) -> Option<&SubCharTable> {
let CtSlot::Sub(s1) = &self.contents[0] else {
return None;
};
let CtSlot::Sub(s2) = &s1.contents[0] else {
return None;
};
match &s2.contents[0] {
CtSlot::Sub(s3) => Some(s3),
CtSlot::Val(_) => None,
}
}
pub fn copied(&self) -> CharTable {
let mut copy = self.clone();
copy.ascii = copy.derived_ascii();
copy
}
pub fn copied_exact(&self) -> CharTable {
self.clone()
}
pub fn optimize(&mut self, same: &dyn Fn(&Value, &Value) -> bool) {
for slot in &mut self.contents {
if let CtSlot::Sub(s) = slot {
if let Some(v) = s.optimize(same) {
*slot = CtSlot::Val(v);
}
}
}
self.ascii = self.derived_ascii();
}
fn derived_ascii(&self) -> CtAscii {
let CtSlot::Sub(s1) = &self.contents[0] else {
return CtAscii::Val(match &self.contents[0] {
CtSlot::Val(v) => v.clone(),
CtSlot::Sub(_) => Value::Undef,
});
};
match &s1.contents[0] {
CtSlot::Val(v) => CtAscii::Val(v.clone()),
CtSlot::Sub(s2) => match &s2.contents[0] {
CtSlot::Val(v) => CtAscii::Val(v.clone()),
CtSlot::Sub(_) => CtAscii::Tree,
},
}
}
pub fn set(&mut self, c: u32, val: Value) {
let i = (c / CT_CHARS[0]) as usize;
let slot = &mut self.contents[i];
if let CtSlot::Val(old) = slot {
let sub = SubCharTable::new(1, i as u32 * CT_CHARS[0], old);
*slot = CtSlot::Sub(Box::new(sub));
}
if let CtSlot::Sub(sub) = slot {
sub.set(c, val);
}
if c < 128 {
self.ascii = self.derived_ascii();
}
}
pub fn set_range(&mut self, from: u32, to: u32, val: Value) {
if from == to {
self.set(from, val);
return;
}
let lim = (to / CT_CHARS[0]) as usize;
let mut i = (from / CT_CHARS[0]) as usize;
let mut c = i as u32 * CT_CHARS[0];
while i <= lim {
if c > to {
break;
}
if from <= c && c + CT_CHARS[0] - 1 <= to {
self.contents[i] = CtSlot::Val(val.clone());
} else {
let slot = &mut self.contents[i];
if let CtSlot::Val(old) = slot {
let sub = SubCharTable::new(1, c, old);
*slot = CtSlot::Sub(Box::new(sub));
}
if let CtSlot::Sub(sub) = slot {
sub.set_range(from, to, &val);
}
}
i += 1;
c += CT_CHARS[0];
}
if from < 128 {
self.ascii = self.derived_ascii();
}
}
pub fn set_all(&mut self, val: Value) {
for slot in &mut self.contents {
*slot = CtSlot::Val(val.clone());
}
self.ascii = CtAscii::Val(val);
}
pub fn runs(&self) -> Vec<(u32, Value)> {
fn walk(slots: &[CtSlot], min: u32, block: u32, out: &mut Vec<(u32, Value)>) {
for (i, slot) in slots.iter().enumerate() {
let start = min + i as u32 * block;
match slot {
CtSlot::Val(v) => match out.last() {
Some((_, last)) if ct_val_eq(last, v) => {}
_ => out.push((start, v.clone())),
},
CtSlot::Sub(s) => {
walk(&s.contents, s.min_char, CT_CHARS[s.depth as usize], out)
}
}
}
}
let mut out = Vec::new();
walk(&self.contents, 0, CT_CHARS[0], &mut out);
out
}
pub fn flatten(&self) -> Vec<CtSer> {
fn walk(slots: &[CtSlot], out: &mut Vec<CtSer>) {
for slot in slots {
match slot {
CtSlot::Val(v) => out.push(CtSer::Val(v.clone())),
CtSlot::Sub(s) => {
out.push(CtSer::Sub);
walk(&s.contents, out);
}
}
}
}
let mut out = Vec::new();
walk(&self.contents, &mut out);
out
}
pub fn unflatten(flat: &[CtSer]) -> Vec<CtSlot> {
fn read(flat: &[CtSer], pos: &mut usize, depth: usize, min: u32) -> Vec<CtSlot> {
let mut slots = Vec::with_capacity(CT_SIZE[depth]);
for i in 0..CT_SIZE[depth] {
let item = flat.get(*pos).cloned().unwrap_or(CtSer::Val(Value::Undef));
*pos += 1;
match item {
CtSer::Val(v) => slots.push(CtSlot::Val(v)),
CtSer::Sub => {
let child_min = min + i as u32 * CT_CHARS[depth];
let contents = read(flat, pos, depth + 1, child_min);
slots.push(CtSlot::Sub(Box::new(SubCharTable {
depth: (depth + 1) as u8,
min_char: child_min,
contents,
})));
}
}
}
slots
}
let mut pos = 0;
read(flat, &mut pos, 0, 0)
}
}
#[derive(Serialize, Deserialize, Clone)]
pub enum CtSer {
Val(Value),
Sub,
}
pub enum Resolved {
Subr {
f: SubrFn,
min: usize,
max: Option<usize>,
name: String,
},
Closure {
params: Rc<Params>,
body: Rc<Chunk>,
is_macro: bool,
env: Lex,
dynamic: bool,
object: Value,
},
}
pub enum FnKind {
Subr(usize, Option<usize>),
Other,
Vacant,
}
impl FnKind {
pub fn rejects_before_args(&self, argc: usize) -> bool {
match self {
FnKind::Subr(min, max) => argc < *min || max.is_some_and(|m| argc > m),
_ => false,
}
}
}
const PRELUDE_C_SUBR_NAMES: &[&str] = &[
"/=",
"all-completions",
"arrayp",
"assoc-string",
"autoload",
"backward-prefix-chars",
"bare-symbol",
"barf-if-buffer-read-only",
"bindings--define-key",
"buffer-enable-undo",
"buffer-file-name",
"buffer-hash",
"byte-code-function-p",
"capitalize",
"capitalize-region",
"capitalize-word",
"car-safe",
"cdr-safe",
"char-syntax",
"characterp",
"check-coding-system",
"cl-first",
"cl-rest",
"cl-type-of",
"cl-values",
"coding-system-base",
"coding-system-eol-type",
"coding-system-p",
"command-remapping",
"commandp",
"compare-buffer-substrings",
"copy-alist",
"copy-sequence",
"copy-syntax-table",
"current-message",
"current-time-zone",
"defalias",
"define-hash-table-test",
"define-key",
"delete",
"delq",
"directory-files",
"documentation",
"documentation-property",
"documentation-stringp",
"downcase-region",
"downcase-word",
"equal-including-properties",
"error-message-string",
"featurep",
"following-char",
"force-mode-line-update",
"format-message",
"forward-comment",
"get",
"get-char-property",
"get-load-suffixes",
"hash-table-rehash-size",
"hash-table-rehash-threshold",
"insert-and-inherit",
"insert-before-markers",
"integer-or-marker-p",
"interactive-form",
"internal--define-uninitialized-variable",
"key-description",
"keymap-parent",
"keymapp",
"kill-all-local-variables",
"length<",
"length=",
"length>",
"locate-file-internal",
"lookup-key",
"make-char-table",
"make-sparse-keymap",
"make-temp-name",
"mapcan",
"matching-paren",
"modify-syntax-entry",
"multibyte-string-p",
"nconc",
"next-property-change",
"next-single-property-change",
"ngettext",
"nreverse",
"ntake",
"number-or-marker-p",
"overlay-recenter",
"parse-partial-sexp",
"plist-get",
"plist-member",
"plist-put",
"preceding-char",
"prefix-numeric-value",
"previous-single-property-change",
"proper-list-p",
"provide",
"purecopy",
"put",
"remove-list-of-text-properties",
"require",
"run-hook-with-args",
"run-hook-with-args-until-failure",
"run-hook-with-args-until-success",
"run-hook-wrapped",
"run-hooks",
"safe-length",
"scan-lists",
"scan-sexps",
"sequencep",
"set-default-toplevel-value",
"set-keymap-parent",
"set-syntax-table",
"setplist",
"single-key-description",
"skip-syntax-backward",
"skip-syntax-forward",
"standard-syntax-table",
"string-as-multibyte",
"string-as-unibyte",
"string-bytes",
"string-collate-equalp",
"string-collate-lessp",
"string-equal",
"string-lessp",
"string-reverse",
"string-to-multibyte",
"string-to-syntax",
"string-to-unibyte",
"string-version-lessp",
"string-width",
"string<",
"string=",
"substitute-in-file-name",
"symbol-plist",
"symbol-with-pos-p",
"syntax-class-to-char",
"syntax-table",
"syntax-table-p",
"take",
"test-completion",
"text-property-any",
"text-property-not-all",
"text-quoting-style",
"time-add",
"time-convert",
"time-equal-p",
"time-less-p",
"time-subtract",
"try-completion",
"upcase-initials",
"upcase-initials-region",
"upcase-region",
"upcase-word",
"value<",
"wholenump",
];
const LISP_LEVEL_ARITY: &[(&str, u16, u16)] = &[
("backward-word", 0, 1),
("bignump", 1, 1),
("caaaar", 1, 1),
("caaadr", 1, 1),
("caaar", 1, 1),
("caadar", 1, 1),
("caaddr", 1, 1),
("caadr", 1, 1),
("caar", 1, 1),
("cadaar", 1, 1),
("cadadr", 1, 1),
("cadar", 1, 1),
("caddar", 1, 1),
("cadddr", 1, 1),
("caddr", 1, 1),
("cadr", 1, 1),
("cdaaar", 1, 1),
("cdaadr", 1, 1),
("cdaar", 1, 1),
("cdadar", 1, 1),
("cdaddr", 1, 1),
("cdadr", 1, 1),
("cdar", 1, 1),
("cddaar", 1, 1),
("cddadr", 1, 1),
("cddar", 1, 1),
("cdddar", 1, 1),
("cddddr", 1, 1),
("cdddr", 1, 1),
("cddr", 1, 1),
("char-uppercase-p", 1, 1),
("count-lines", 2, 3),
("error", 1, 1),
("fixnump", 1, 1),
("generate-new-buffer", 1, 2),
("hash-table-keys", 1, 1),
("hash-table-values", 1, 1),
("looking-at-p", 1, 1),
("lsh", 2, 2),
("macroexpand-1", 1, 2),
("macroexpand-all", 1, 2),
("macrop", 1, 1),
("match-string", 1, 2),
("member-ignore-case", 2, 2),
("oclosure--copy", 2, 2),
("oclosure--fix-type", 2, 2),
("oclosure--get", 3, 3),
("oclosure--set", 3, 3),
("oclosure-type", 1, 1),
("sha1", 1, 4),
("shell-command-to-string", 1, 1),
("special-form-p", 1, 1),
("split-string", 1, 4),
("store-substring", 3, 3),
("string-empty-p", 1, 1),
("string-join", 1, 2),
("string-match-p", 2, 3),
("string-prefix-p", 2, 3),
("string-suffix-p", 2, 3),
("string-to-list", 1, 1),
("string-to-vector", 1, 1),
("url-hexify-string", 1, 2),
("url-unhex-string", 1, 2),
("user-error", 1, 1),
];
fn lisp_level_arity(name: &str) -> Option<(u16, u16)> {
LISP_LEVEL_ARITY
.iter()
.find(|(n, _, _)| *n == name)
.map(|(_, m, r)| (*m, *r))
}
const PRINT_CIRCLE: usize = 200;
#[derive(Clone)]
pub enum StdinSource {
Process,
Fed(std::io::Cursor<Vec<u8>>),
}
impl std::io::Read for StdinSource {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self {
StdinSource::Process => std::io::stdin().read(buf),
StdinSource::Fed(c) => c.read(buf),
}
}
}
#[derive(Clone)]
pub struct ElispHost {
pub(crate) arena: Vec<Obj>,
pub(crate) windows: Vec<crate::window::WindowData>,
pub(crate) frames: Vec<crate::window::FrameData>,
pub(crate) window_configs: Vec<crate::window::WindowConfig>,
pub(crate) selected_window: usize,
pub(crate) selected_frame: usize,
pub(crate) window_count: i64,
pub(crate) window_select_count: i64,
pub(crate) buffer_order_seq: i64,
pub(crate) last_window_start: HashMap<usize, usize>,
point_before_last_command_or_undo: Option<usize>,
buffer_before_last_command_or_undo: Option<usize>,
obarray: HashMap<String, u32>,
builtin_count: usize,
prelude_end: usize,
specstack: Vec<SpecEntry>,
lex: Lex,
pub(crate) dynamic_binding: bool,
pub(crate) eval_depth: usize,
max_depth_sym: Option<u32>,
intrinsic_macro_cells: HashMap<u32, Value>,
compiling_form: bool,
compile_interned: HashSet<u32>,
frame_stack: Vec<(Lex, usize)>,
pub(crate) error: Option<String>,
pub(crate) pending_throw: Option<(Value, Value)>,
pub(crate) catch_tags: Vec<Value>,
pub(crate) pending_error: Option<(String, Value)>,
pub(crate) match_data: Option<MatchData>,
pub(crate) stdout_last: char,
pub capture: Option<String>,
pub stdin: StdinSource,
pub(crate) print_overflow: Cell<bool>,
pub(crate) print_backquote_depth: Cell<u32>,
pub(crate) print_labels: RefCell<HashMap<u32, i64>>,
pub(crate) print_next_label: Cell<usize>,
pub(crate) print_being: RefCell<Vec<Option<u32>>>,
pub(crate) print_circle_on: Cell<bool>,
pub(crate) print_gensym_on: Cell<bool>,
pub(crate) buffers: Vec<EditBuffer>,
pub(crate) always_local: Vec<(u32, SlotInit)>,
pub(crate) current: usize,
pub(crate) need_newline: bool,
pub(crate) load_buf: usize,
pub(crate) string_props: HashMap<usize, StrProps>,
pub(crate) closure_free: HashMap<u32, Rc<std::collections::HashSet<u32>>>,
pub(crate) eval_lambda_raw: HashMap<u32, Vec<Value>>,
pub(crate) early_declarations: Vec<Value>,
pub(crate) subr_intspecs: HashMap<u32, Value>,
pub(crate) compiler_macros: std::collections::HashSet<u32>,
pub(crate) empty_string: Value,
pub(crate) empty_vector: Value,
pub(crate) oclosure_meta: HashMap<u32, OClosureMeta>,
pub(crate) intercepts: Vec<crate::intercepts::Intercept>,
pub(crate) subr_aliased: std::collections::HashSet<u32>,
pub(crate) intercept_active: bool,
pub(crate) intercept_current: Option<(Value, Vec<Value>)>,
pub(crate) intercept_proceeded: bool,
pub(crate) form_lines: HashMap<u32, u32>,
}
pub type ClosureParts = (bool, bool, Value, Vec<Value>, Vec<(u32, Option<Value>)>);
#[derive(Default)]
pub struct ClosureSrc {
pub arglist: Value,
pub body: Vec<Value>,
pub raw_body: Option<Vec<Value>>,
}
pub struct ClosureSlots {
pub body: Vec<Value>,
pub doc: Option<Value>,
pub iform: Option<Value>,
}
impl ClosureSrc {
pub fn slots(&self, h: &ElispHost) -> ClosureSlots {
let mut body: &[Value] = &self.body;
let mut doc = None;
if body.len() > 1 && h.is_string(&body[0]) {
doc = Some(body[0].clone());
body = &body[1..];
}
let mut iform = None;
if let Some(first) = body.first() {
let is_interactive = match h.obj(first) {
Some(Obj::Cons(head, _)) => h.sym_name(head).as_deref() == Some("interactive"),
_ => false,
};
if is_interactive {
iform = Some(first.clone());
body = &body[1..];
}
}
let body = if body.is_empty() {
vec![Value::Undef]
} else {
body.to_vec()
};
ClosureSlots { body, doc, iform }
}
}
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct BufferState {
pub always_local: Vec<(u32, SlotInit)>,
pub locals: Vec<Vec<(u32, Option<Value>)>>,
}
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct SymbolBaseline {
pub value: Option<Value>,
pub function: Option<Value>,
pub buffer_local_auto: bool,
pub alias_of: Option<u32>,
}
#[derive(Clone)]
pub struct OClosureMeta {
pub ty: u32,
pub slots: Vec<u32>,
}
pub(crate) type StrProps = (Weak<String>, Vec<Value>, Vec<u32>);
#[derive(Default, Clone)]
pub struct EditBuffer {
pub name: Option<String>,
pub inhibit_hooks: bool,
pub self_obj: Value,
pub text: Vec<char>,
pub props: Vec<Value>,
pub prop_bounds: Vec<u32>,
pub markers: Vec<Rc<RefCell<MarkerData>>>,
pub overlays: Vec<Rc<RefCell<OverlayData>>>,
pub point: usize,
pub begv: usize,
pub zv: usize,
pub mark: Value,
pub se_markers: Vec<usize>,
pub restrict_stack: Vec<(usize, usize)>,
pub locals: IndexMap<u32, Option<Value>>,
pub local_map: Value,
pub mods: ModCounts,
pub has_intervals: bool,
pub list_order: i64,
}
#[derive(Clone, Serialize, Deserialize)]
pub enum SlotInit {
Value(Value),
Inherit,
UndoList,
}
#[derive(Clone, Copy)]
pub struct ModCounts {
pub modiff: i64,
pub chars_modiff: i64,
pub save_modiff: i64,
pub autosave_modiff: i64,
}
impl Default for ModCounts {
fn default() -> Self {
ModCounts {
modiff: 1,
chars_modiff: 1,
save_modiff: 1,
autosave_modiff: 0,
}
}
}
impl ModCounts {
pub fn incr(&mut self, len: usize) {
self.modiff += if len == 0 { 1 } else { len.ilog2() as i64 + 1 };
}
}
fn adj_ins(m: &mut usize, pos: usize, len: usize, advance_at_pos: bool) {
if *m > pos || (advance_at_pos && *m == pos) {
*m += len;
}
}
fn adj_del(m: &mut usize, from: usize, to: usize) {
if *m >= to {
*m -= to - from;
} else if *m > from {
*m = from;
}
}
#[derive(Clone, Debug)]
pub struct MatchData {
pub subject: String,
pub spans: Vec<Option<(usize, usize)>>,
pub from_buffer: bool,
pub buffer: Option<usize>,
}
impl Default for ElispHost {
fn default() -> Self {
Self::new()
}
}
impl ElispHost {
pub fn new() -> Self {
let mut h = ElispHost {
arena: Vec::new(),
windows: Vec::new(),
frames: Vec::new(),
window_configs: Vec::new(),
selected_window: 0,
selected_frame: 0,
window_count: 0,
window_select_count: 0,
buffer_order_seq: 0,
last_window_start: HashMap::new(),
point_before_last_command_or_undo: None,
buffer_before_last_command_or_undo: None,
obarray: HashMap::new(),
builtin_count: 0,
prelude_end: 0,
specstack: Vec::new(),
lex: None,
dynamic_binding: false,
eval_depth: 0,
max_depth_sym: None,
intrinsic_macro_cells: HashMap::new(),
compiling_form: false,
compile_interned: HashSet::new(),
frame_stack: Vec::new(),
error: None,
pending_throw: None,
catch_tags: Vec::new(),
pending_error: None,
match_data: None,
stdout_last: '\0',
capture: None,
stdin: StdinSource::Process,
print_overflow: Cell::new(false),
print_backquote_depth: Cell::new(0),
print_labels: RefCell::new(HashMap::new()),
print_next_label: Cell::new(1),
print_being: RefCell::new(Vec::new()),
print_circle_on: Cell::new(false),
print_gensym_on: Cell::new(false),
buffers: vec![EditBuffer {
overlays: Vec::new(),
name: Some("*scratch*".to_string()),
self_obj: Value::Undef,
text: Vec::new(),
props: Vec::new(),
prop_bounds: Vec::new(),
markers: Vec::new(),
point: 1,
begv: 1,
zv: 1,
mark: Value::Undef,
se_markers: Vec::new(),
restrict_stack: Vec::new(),
locals: IndexMap::new(),
local_map: Value::Undef,
mods: ModCounts::default(),
has_intervals: false,
list_order: 0,
inhibit_hooks: false,
}],
always_local: Vec::new(),
current: 0,
need_newline: false,
load_buf: 0, string_props: HashMap::new(),
closure_free: HashMap::new(),
eval_lambda_raw: HashMap::new(),
early_declarations: Vec::new(),
subr_intspecs: HashMap::new(),
compiler_macros: std::collections::HashSet::new(),
empty_string: Value::Undef, empty_vector: Value::Undef,
oclosure_meta: HashMap::new(),
intercepts: Vec::new(),
subr_aliased: std::collections::HashSet::new(),
intercept_active: false,
intercept_current: None,
intercept_proceeded: false,
form_lines: HashMap::new(),
};
crate::builtins::install(&mut h);
h.empty_string = h.alloc(Obj::Str(Arc::new(String::new())));
h.empty_vector = h.alloc(Obj::Vector(Vec::new()));
let scratch = h.alloc(Obj::Buffer(0));
h.buffers[0].self_obj = scratch;
let minibuf = h.new_buffer(" *Minibuf-0*".to_string());
let minibuf = h.buffer_slot(&minibuf).expect("minibuffer slot");
crate::window::init(&mut h, 0, minibuf);
h.new_buffer("*Messages*".to_string());
let load_slot = h.new_buffer(" *load*".to_string());
h.load_buf = h.buffer_slot(&load_slot).expect("reserved load slot");
h.buffers[h.load_buf].name = None;
let global_ob = h.alloc(Obj::Obarray(ObarrayData {
symbols: HashMap::new(),
global: true,
}));
if let Value::Obj(sid) = h.intern("obarray") {
if let Some(Obj::Symbol(s)) = h.arena.get_mut(sid as usize) {
s.value = Some(global_ob);
s.special = true;
}
}
if let Value::Obj(sid) = h.intern("enable-multibyte-characters") {
if let Some(Obj::Symbol(s)) = h.arena.get_mut(sid as usize) {
s.value = Some(Value::Bool(true));
s.special = true;
}
}
h.builtin_count = h.arena.len();
h
}
pub fn alloc(&mut self, obj: Obj) -> Value {
if let Obj::Vector(items) = &obj {
if items.is_empty() && !matches!(self.empty_vector, Value::Undef) {
return self.empty_vector.clone();
}
}
let id = self.arena.len() as u32;
self.arena.push(obj);
Value::Obj(id)
}
pub fn str_text<'a>(&'a self, v: &'a Value) -> Option<&'a str> {
match v {
Value::Str(s) => Some(s.as_str()),
Value::Obj(id) => match self.arena.get(*id as usize) {
Some(Obj::Str(s)) => Some(s.as_str()),
_ => None,
},
_ => None,
}
}
pub fn str_arc(&self, v: &Value) -> Option<Arc<String>> {
match v {
Value::Str(s) => Some(Arc::clone(s)),
Value::Obj(id) => match self.arena.get(*id as usize) {
Some(Obj::Str(s)) => Some(Arc::clone(s)),
_ => None,
},
_ => None,
}
}
pub fn str_view(&self, v: &Value) -> Value {
match v {
Value::Obj(id) => match self.arena.get(*id as usize) {
Some(Obj::Str(s)) => Value::Str(Arc::clone(s)),
_ => v.clone(),
},
_ => v.clone(),
}
}
pub fn is_string(&self, v: &Value) -> bool {
self.str_text(v).is_some()
}
pub fn new_string(&mut self, s: impl Into<String>) -> Value {
self.new_string_arc(Arc::new(s.into()))
}
pub fn new_string_arc(&mut self, s: Arc<String>) -> Value {
if s.is_empty() {
return self.empty_string.clone();
}
self.alloc(Obj::Str(s))
}
pub fn new_string_keyed(&mut self, s: String) -> (Value, Arc<String>) {
let v = self.new_string(s);
let arc = self.str_arc(&v).expect("new_string yields a string cell");
(v, arc)
}
pub fn promote_string(&mut self, v: Value) -> Value {
match v {
Value::Str(s) => self.new_string_arc(s),
other => other,
}
}
pub fn set_string_text(&mut self, v: &Value, text: String) -> bool {
let Value::Obj(id) = v else { return false };
let Some(Obj::Str(old)) = self.arena.get(*id as usize) else {
return false;
};
let old_key = Arc::as_ptr(old) as usize;
let fresh = Arc::new(text);
let new_key = Arc::as_ptr(&fresh) as usize;
if let Some((_, props, bounds)) = self.string_props.remove(&old_key) {
self.string_props
.insert(new_key, (Arc::downgrade(&fresh), props, bounds));
}
self.arena[*id as usize] = Obj::Str(fresh);
true
}
pub fn make_integer(&mut self, n: BigInt) -> Value {
use num_traits::ToPrimitive;
match n.to_i64() {
Some(i) if (MOST_NEGATIVE_FIXNUM..=MOST_POSITIVE_FIXNUM).contains(&i) => Value::Int(i),
_ => self.alloc(Obj::Bignum(n)),
}
}
pub fn as_bigint(&self, v: &Value) -> Option<BigInt> {
match v {
Value::Int(n) => Some(BigInt::from(*n)),
Value::Obj(_) => match self.obj(v) {
Some(Obj::Bignum(b)) => Some(b.clone()),
_ => None,
},
_ => None,
}
}
pub fn is_integer(&self, v: &Value) -> bool {
matches!(v, Value::Int(_)) || matches!(self.obj(v), Some(Obj::Bignum(_)))
}
pub fn is_number(&self, v: &Value) -> bool {
matches!(v, Value::Int(_) | Value::Float(_)) || self.is_bignum(v)
}
pub fn is_bignum(&self, v: &Value) -> bool {
matches!(self.obj(v), Some(Obj::Bignum(_)))
}
pub fn apply_num_op(&mut self, op: NumOp, a: Num, b: Num) -> Result<Value, String> {
use NumOp::*;
if matches!(op, Lt | Gt | Le | Ge | Eq | Ne) {
let ord = match num_cmp(&a, &b) {
Some(o) => o,
None => return Ok(Value::Bool(matches!(op, Ne))),
};
let yes = match op {
Lt => ord.is_lt(),
Gt => ord.is_gt(),
Le => ord.is_le(),
Ge => ord.is_ge(),
Eq => ord.is_eq(),
_ => ord.is_ne(),
};
return Ok(Value::Bool(yes));
}
match (a, b) {
(Num::Int(x), Num::Int(y)) => {
let r = match op {
Add => x + y,
Sub => x - y,
Mul => x * y,
Neg => -x,
Mod => {
if y == BigInt::from(0) {
return Err("arith-error".to_string());
}
x % y
}
Div | Pow => return Ok(Value::Float(bigint_to_f64(&x) / bigint_to_f64(&y))),
Lt | Gt | Le | Ge | Eq | Ne => unreachable!("handled above"),
};
Ok(self.make_integer(r))
}
(a, b) => {
let (x, y) = (a.to_f64(), b.to_f64());
Ok(Value::Float(match op {
Add => x + y,
Sub => x - y,
Mul => x * y,
Neg => -x,
Div => x / y,
Mod => x % y,
Pow => x.powf(y),
Lt | Gt | Le | Ge | Eq | Ne => unreachable!("handled above"),
}))
}
}
}
pub fn intern(&mut self, name: &str) -> Value {
if let Some(&id) = self.obarray.get(name) {
if self.compiling_form {
self.compile_interned.insert(id);
}
return Value::Obj(id);
}
let id = self.arena.len() as u32;
let keyword = name.starts_with(':');
self.arena.push(Obj::Symbol(SymbolData {
name: name.to_string(),
value: keyword.then_some(Value::Obj(id)),
function: None,
special: keyword,
buffer_local_auto: false,
alias_of: None,
}));
self.obarray.insert(name.to_string(), id);
if self.compiling_form {
self.compile_interned.insert(id);
}
Value::Obj(id)
}
pub fn make_symbol(&mut self, name: &str) -> Value {
self.alloc(Obj::Symbol(SymbolData {
name: name.to_string(),
value: None,
function: None,
special: false,
buffer_local_auto: false,
alias_of: None,
}))
}
pub fn obj(&self, v: &Value) -> Option<&Obj> {
match v {
Value::Obj(id) => self.arena.get(*id as usize),
_ => None,
}
}
pub fn obarray_intern(&mut self, ob_id: u32, name: &str) -> Value {
if let Some(Obj::Obarray(d)) = self.arena.get(ob_id as usize) {
if let Some(&sid) = d.symbols.get(name) {
return Value::Obj(sid);
}
}
let sym = self.make_symbol(name);
if let Value::Obj(sid) = sym {
if let Some(Obj::Obarray(d)) = self.arena.get_mut(ob_id as usize) {
d.symbols.insert(name.to_string(), sid);
}
}
sym
}
pub fn obarray_intern_soft(&self, ob_id: u32, name: &str) -> Value {
match self.arena.get(ob_id as usize) {
Some(Obj::Obarray(d)) => d
.symbols
.get(name)
.map(|&sid| Value::Obj(sid))
.unwrap_or(Value::Undef),
_ => Value::Undef,
}
}
pub fn obarray_unintern(&mut self, ob_id: u32, name: &str) -> bool {
match self.arena.get_mut(ob_id as usize) {
Some(Obj::Obarray(d)) => d.symbols.remove(name).is_some(),
_ => false,
}
}
pub fn obarray_unintern_global(&mut self, name: &str) -> bool {
self.obarray.remove(name).is_some()
}
pub fn obarray_symbols(&self, ob: &Value) -> Vec<Value> {
match self.obj(ob) {
Some(Obj::Obarray(d)) if d.global => {
self.obarray.values().map(|&id| Value::Obj(id)).collect()
}
Some(Obj::Obarray(d)) => d.symbols.values().map(|&id| Value::Obj(id)).collect(),
_ => Vec::new(),
}
}
pub fn as_sym_handle(&self, v: &Value) -> Option<u32> {
self.sym_handle(v)
}
fn sym_handle(&self, v: &Value) -> Option<u32> {
match v {
Value::Obj(id) if matches!(self.arena.get(*id as usize), Some(Obj::Symbol(_))) => {
Some(*id)
}
_ => None,
}
}
pub fn sym_name(&self, v: &Value) -> Option<String> {
match self.obj(v) {
Some(Obj::Symbol(s)) => Some(s.name.clone()),
_ => match v {
Value::Bool(true) => Some("t".to_string()),
_ if el_nil(v) => Some("nil".to_string()),
_ => None,
},
}
}
fn interned_in_standard_obarray(&self, id: u32) -> bool {
match &self.arena[id as usize] {
Obj::Symbol(s) => self.obarray.get(&s.name) == Some(&id),
_ => false,
}
}
pub fn is_keyword(&self, v: &Value) -> bool {
match self.sym_handle(v) {
Some(id) => match &self.arena[id as usize] {
Obj::Symbol(s) => s.name.starts_with(':') && self.interned_in_standard_obarray(id),
_ => false,
},
None => false,
}
}
pub fn constant_symbol_name(&self, v: &Value) -> Option<String> {
if matches!(v, Value::Bool(true)) {
return Some("t".to_string());
}
if el_nil(v) {
return Some("nil".to_string());
}
let id = self.sym_handle(v)?;
let Obj::Symbol(s) = &self.arena[id as usize] else {
return None;
};
let constant_name = s.name == "nil"
|| s.name == "t"
|| s.name.starts_with(':')
|| s.name == "enable-multibyte-characters";
(constant_name && self.interned_in_standard_obarray(id)).then(|| s.name.clone())
}
pub fn check_settable(&self, v: &Value) -> Result<(), String> {
match self.constant_symbol_name(v) {
Some(name) => Err(format!("setting-constant: {name}")),
None => Ok(()),
}
}
pub fn cons(&mut self, a: Value, b: Value) -> Value {
self.alloc(Obj::Cons(a, b))
}
pub fn list_from(&mut self, items: Vec<Value>) -> Value {
let mut acc = Value::Undef;
for x in items.into_iter().rev() {
acc = self.cons(x, acc);
}
acc
}
pub fn list_vec(&self, v: &Value) -> Option<Vec<Value>> {
let mut out = Vec::new();
let mut cur = v.clone();
loop {
if el_nil(&cur) {
return Some(out);
}
match &cur {
Value::Obj(id) => match self.arena.get(*id as usize) {
Some(Obj::Cons(a, d)) => {
out.push(a.clone());
let next = d.clone();
cur = next;
}
_ => return None,
},
_ => return None,
}
}
}
pub fn seq_vec(&self, v: &Value) -> Option<Vec<Value>> {
match v {
Value::Str(s) => Some(s.chars().map(|c| Value::Int(c as i64)).collect()),
Value::Obj(id) => match self.arena.get(*id as usize) {
Some(Obj::Str(s)) => Some(s.chars().map(|c| Value::Int(c as i64)).collect()),
Some(Obj::Vector(items)) => Some(items.clone()),
Some(Obj::BoolVector(bits)) => Some(
bits.iter()
.map(|&b| if b { Value::Bool(true) } else { Value::Undef })
.collect(),
),
_ => self.list_vec(v),
},
_ => self.list_vec(v),
}
}
pub fn indirect_var(&self, id: u32) -> u32 {
let mut cur = id;
for _ in 0..64 {
match self.arena.get(cur as usize) {
Some(Obj::Symbol(s)) => match s.alias_of {
Some(base) if base != cur => cur = base,
_ => return cur,
},
_ => return cur,
}
}
cur
}
pub fn defvaralias(&mut self, alias: &Value, base: &Value) -> Result<Value, String> {
if let Some(name) = self.constant_symbol_name(alias) {
return Err(format!("error: Cannot make a constant an alias: {name}"));
}
let aid = self
.sym_handle(alias)
.ok_or_else(|| self.wrong_type_symbolp(alias))?;
let bid = self
.sym_handle(base)
.ok_or_else(|| self.wrong_type_symbolp(base))?;
let mut probe = bid;
for _ in 0..64 {
if probe == aid {
return Err(format!(
"cyclic-variable-indirection: {}",
self.sym_name(alias).unwrap_or_default()
));
}
match self.arena.get(probe as usize) {
Some(Obj::Symbol(s)) => match s.alias_of {
Some(next) if next != probe => probe = next,
_ => break,
},
_ => break,
}
}
let base_id = self.indirect_var(bid);
let base_void =
matches!(self.arena.get(base_id as usize), Some(Obj::Symbol(s)) if s.value.is_none());
if base_void {
let alias_val = match self.arena.get(aid as usize) {
Some(Obj::Symbol(s)) => s.value.clone(),
_ => None,
};
if let Some(val) = alias_val {
if let Obj::Symbol(s) = &mut self.arena[base_id as usize] {
s.value = Some(val);
}
}
}
if let Obj::Symbol(s) = &mut self.arena[base_id as usize] {
s.special = true;
}
if let Obj::Symbol(s) = &mut self.arena[aid as usize] {
s.alias_of = Some(base_id);
s.special = true;
}
Ok(base.clone())
}
pub fn set_value(&mut self, v: &Value, val: Value) -> Result<(), String> {
self.set_value_in(v, val, true)
}
pub fn set_dynamic_value(&mut self, v: &Value, val: Value) -> Result<(), String> {
self.set_value_in(v, val, false)
}
fn set_value_in(&mut self, v: &Value, val: Value, lexical: bool) -> Result<(), String> {
self.check_settable(v)?;
let Some(id0) = self.sym_handle(v) else {
return Err(self.signal_wrong_type("symbolp", v));
};
let id = self.indirect_var(id0);
if lexical && self.lex.as_ref().is_some_and(|s| s.set(id, &val)) {
return Ok(());
}
let bi = self.cur_buf_idx();
if self.buffers[bi].locals.contains_key(&id)
|| (self.is_auto_local(id) && !self.let_shadows_buffer_binding(id, bi))
{
self.buffers[bi].locals.insert(id, Some(val));
return Ok(());
}
if let Obj::Symbol(s) = &mut self.arena[id as usize] {
s.value = Some(val);
}
Ok(())
}
fn let_shadows_buffer_binding(&self, id: u32, bi: usize) -> bool {
self.specstack
.iter()
.any(|e| matches!(e, SpecEntry::Global(i, b, _) if *i == id && *b == bi))
}
fn is_auto_local(&self, id: u32) -> bool {
matches!(self.arena.get(id as usize), Some(Obj::Symbol(s)) if s.buffer_local_auto)
}
pub fn make_local_variable(&mut self, v: &Value) -> Result<Value, String> {
self.check_settable(v)?;
let id0 = self
.sym_handle(v)
.ok_or_else(|| self.wrong_type_symbolp(v))?;
let id = self.indirect_var(id0);
let bi = self.cur_buf_idx();
if !self.buffers[bi].locals.contains_key(&id) {
let snapshot = match &self.arena[id as usize] {
Obj::Symbol(s) => s.value.clone(),
_ => None,
};
self.buffers[bi].locals.insert(id, snapshot);
}
Ok(v.clone())
}
pub fn make_variable_buffer_local(&mut self, v: &Value) -> Result<Value, String> {
self.check_settable(v)?;
let id0 = self
.sym_handle(v)
.ok_or_else(|| self.wrong_type_symbolp(v))?;
let id = self.indirect_var(id0);
if let Obj::Symbol(s) = &mut self.arena[id as usize] {
s.buffer_local_auto = true;
s.special = true;
}
Ok(v.clone())
}
pub fn local_variable_p(&self, v: &Value, bi: usize) -> bool {
match self.sym_handle(v) {
Some(id) => self.buffers[bi].locals.contains_key(&self.indirect_var(id)),
None => false,
}
}
pub fn make_always_local(&mut self, v: &Value, init: SlotInit) -> Result<Value, String> {
let id0 = self
.sym_handle(v)
.ok_or("--make-always-local--: not a symbol")?;
let id = self.indirect_var(id0);
if let Obj::Symbol(s) = &mut self.arena[id as usize] {
s.special = true;
}
let default = match &self.arena[id as usize] {
Obj::Symbol(s) => s.value.clone(),
_ => None,
};
for b in &mut self.buffers {
b.locals.entry(id).or_insert_with(|| default.clone());
}
self.always_local.retain(|(s, _)| *s != id);
self.always_local.push((id, init));
Ok(v.clone())
}
fn initial_slots(&self, name: &str) -> IndexMap<u32, Option<Value>> {
let creator = &self.buffers[self.cur_buf_idx()];
self.always_local
.iter()
.map(|(id, init)| {
let val = match init {
SlotInit::Value(v) => Some(v.clone()),
SlotInit::Inherit => creator.locals.get(id).cloned().flatten(),
SlotInit::UndoList => Some(if name.starts_with(' ') {
Value::Bool(true)
} else {
Value::Undef
}),
};
(*id, val)
})
.collect()
}
pub fn has_any_local(&self, v: &Value) -> bool {
self.sym_handle(v).is_some_and(|id0| {
let id = self.indirect_var(id0);
self.buffers.iter().any(|b| b.locals.contains_key(&id))
})
}
pub fn is_auto_local_var(&self, v: &Value) -> bool {
self.sym_handle(v)
.is_some_and(|id0| self.is_auto_local(self.indirect_var(id0)))
}
pub fn wrong_type_symbolp(&self, v: &Value) -> String {
format!("wrong-type-argument: symbolp {}", self.print(v, true))
}
pub fn kill_local_variable(&mut self, v: &Value) -> Result<Value, String> {
if self.sym_handle(v).is_none() && !el_nil(v) && !matches!(v, Value::Bool(true)) {
return Err(self.wrong_type_symbolp(v));
}
if let Some(id0) = self.sym_handle(v) {
let id = self.indirect_var(id0);
if self.always_local.iter().any(|(s, _)| *s == id) {
return Ok(v.clone());
}
let bi = self.cur_buf_idx();
self.buffers[bi].locals.shift_remove(&id);
}
Ok(v.clone())
}
pub fn buffer_local_symbols(&mut self) -> Value {
let ids: Vec<u32> = self.buffers[self.cur_buf_idx()]
.locals
.keys()
.copied()
.collect();
let items: Vec<Value> = ids.into_iter().map(Value::Obj).collect();
self.list_from(items)
}
pub fn use_local_map(&mut self, map: Value) {
let bi = self.cur_buf_idx();
self.buffers[bi].local_map = map;
}
pub fn current_local_map(&self) -> Value {
self.buffers[self.cur_buf_idx()].local_map.clone()
}
pub fn buffer_local_or_default(&self, v: &Value, buf_idx: usize) -> Result<Value, String> {
if let Some(id0) = self.sym_handle(v) {
let id = self.indirect_var(id0);
if let Some(slot) = self.buffers[buf_idx].locals.get(&id) {
return slot.clone().ok_or_else(|| {
format!("void-variable: {}", self.sym_name(v).unwrap_or_default())
});
}
}
self.raw_global_value(v)
}
pub fn unset_value(&mut self, v: &Value) -> Result<(), String> {
self.check_settable(v)?;
let id0 = self
.sym_handle(v)
.ok_or_else(|| self.wrong_type_symbolp(v))?;
let id = self.indirect_var(id0);
if let Obj::Symbol(s) = &mut self.arena[id as usize] {
s.value = None;
}
Ok(())
}
pub fn get_value(&self, v: &Value) -> Result<Value, String> {
self.get_value_in(v, true)
}
pub fn get_dynamic_value(&self, v: &Value) -> Result<Value, String> {
self.get_value_in(v, false)
}
fn get_value_in(&self, v: &Value, lexical: bool) -> Result<Value, String> {
if let Some(id0) = self.sym_handle(v) {
let id = self.indirect_var(id0);
if lexical {
if let Some(val) = self.lex.as_ref().and_then(|s| s.lookup(id)) {
return Ok(val);
}
}
if let Some(slot) = self.buffers[self.cur_buf_idx()].locals.get(&id) {
return slot.clone().ok_or_else(|| {
format!("void-variable: {}", self.sym_name(v).unwrap_or_default())
});
}
return match &self.arena[id as usize] {
Obj::Symbol(s) => s
.value
.clone()
.ok_or_else(|| format!("void-variable: {}", s.name)),
_ => Err(self.wrong_type_symbolp(v)),
};
}
match v {
Value::Bool(true) => Ok(Value::Bool(true)),
_ if el_nil(v) => Ok(Value::Undef),
_ => Err(self.wrong_type_symbolp(v)),
}
}
fn cur_buf_idx(&self) -> usize {
self.current
}
pub fn raw_global_value(&self, v: &Value) -> Result<Value, String> {
if let Some(id0) = self.sym_handle(v) {
let id = self.indirect_var(id0);
return match &self.arena[id as usize] {
Obj::Symbol(s) => s
.value
.clone()
.ok_or_else(|| format!("void-variable: {}", s.name)),
_ => Err(self.wrong_type_symbolp(v)),
};
}
match v {
Value::Bool(true) => Ok(Value::Bool(true)),
_ if el_nil(v) => Ok(Value::Undef),
_ => Err(self.wrong_type_symbolp(v)),
}
}
pub fn default_boundp_raw(&self, v: &Value) -> bool {
if self.constant_symbol_name(v).is_some() {
return true;
}
match self.sym_handle(v) {
Some(id0) => {
let id = self.indirect_var(id0);
matches!(self.arena.get(id as usize), Some(Obj::Symbol(s)) if s.value.is_some())
}
None => false,
}
}
pub fn set_raw_global(&mut self, v: &Value, val: Value) -> Result<(), String> {
self.check_settable(v)?;
let id0 = self
.sym_handle(v)
.ok_or_else(|| self.wrong_type_symbolp(v))?;
let id = self.indirect_var(id0);
if let Obj::Symbol(s) = &mut self.arena[id as usize] {
s.value = Some(val);
}
Ok(())
}
pub fn declare_special_locally(&mut self, v: &Value) {
let Some(id0) = self.sym_handle(v) else {
return;
};
let id = self.indirect_var(id0);
if !self.dynamic_binding && !self.is_special(id) {
self.lex = Some(Rc::new(Scope::declaration(id, self.lex.take())));
}
}
pub fn set_special(&mut self, v: &Value) {
if let Some(id) = self.sym_handle(v) {
if let Obj::Symbol(s) = &mut self.arena[id as usize] {
s.special = true;
}
}
}
fn is_special(&self, id: u32) -> bool {
matches!(self.arena.get(id as usize), Some(Obj::Symbol(s)) if s.special)
}
pub fn symbol_special(&self, v: &Value) -> bool {
if self.constant_symbol_name(v).is_some() {
return true;
}
self.sym_handle(v)
.map(|id| self.is_special(self.indirect_var(id)))
.unwrap_or(false)
}
pub fn set_function_value(&mut self, sym: &Value, def: Value) -> Result<(), String> {
if matches!(self.constant_symbol_name(sym).as_deref(), Some("nil")) {
return Err("setting-constant: nil".to_string());
}
let id = match self.sym_handle(sym) {
Some(id) => id,
None => {
return Err(format!(
"wrong-type-argument: symbolp {}",
self.print(sym, true)
))
}
};
if let Obj::Symbol(s) = &mut self.arena[id as usize] {
s.function = if el_truthy(&def) { Some(def) } else { None };
}
Ok(())
}
pub fn set_function(&mut self, name: &str, def: Value) {
let v = self.intern(name);
let _ = self.set_function_value(&v, def);
}
pub fn function_cell(&self, sym: &Value) -> Option<Value> {
match self.obj(sym) {
Some(Obj::Symbol(s)) => s.function.clone(),
_ => None,
}
}
pub fn introspect_function_cell(&self, sym: &Value) -> Option<Value> {
if let Some(cell) = self.function_cell(sym) {
return Some(cell);
}
self.sym_handle(sym)
.and_then(|id| self.intrinsic_macro_cells.get(&id))
.cloned()
}
pub fn set_intrinsic_macro_cell(&mut self, sym: &Value, cell: Value) {
if let Some(id) = self.sym_handle(sym) {
self.intrinsic_macro_cells.insert(id, cell);
}
}
pub fn special_form_object(&self, v: &Value) -> Option<Value> {
if let Some(Obj::Subr { name, .. }) = self.obj(v) {
return crate::builtins::is_special_form(name).then(|| v.clone());
}
let cell = self
.sym_handle(v)
.and_then(|id| self.intrinsic_macro_cells.get(&id))?;
match self.obj(cell) {
Some(Obj::Subr { name, .. }) if crate::builtins::is_special_form(name) => {
Some(cell.clone())
}
_ => None,
}
}
pub fn signal_invalid_function(&mut self, fun: &Value) -> String {
let msg = format!("invalid-function: {}", self.print(fun, true));
let sym = self.intern("invalid-function");
let data = self.list_from(vec![fun.clone()]);
let obj = self.cons(sym, data);
self.set_pending_error(&msg, obj);
msg
}
pub fn export_intrinsic_macro_cells(&self) -> Vec<(u32, Value)> {
let mut out: Vec<(u32, Value)> = self
.intrinsic_macro_cells
.iter()
.map(|(&id, v)| (id, v.clone()))
.collect();
out.sort_by_key(|(id, _)| *id);
out
}
pub fn import_intrinsic_macro_cells(&mut self, cells: Vec<(u32, Value)>) {
for (id, v) in cells {
self.intrinsic_macro_cells.entry(id).or_insert(v);
}
}
pub fn find_symbol(&self, name: &str) -> Option<Value> {
self.obarray.get(name).map(|&id| Value::Obj(id))
}
pub fn defsubr(&mut self, name: &str, min: usize, max: Option<usize>, f: SubrFn) {
let subr = self.alloc(Obj::Subr {
name: name.to_string(),
min,
max,
f,
});
self.set_function(name, subr);
}
pub fn is_bound(&self, v: &Value) -> bool {
match self.sym_handle(v) {
Some(id0) => {
let id = self.indirect_var(id0);
matches!(self.arena.get(id as usize), Some(Obj::Symbol(s)) if s.value.is_some())
}
None => false,
}
}
pub fn is_fbound(&self, v: &Value) -> bool {
matches!(self.obj(v), Some(Obj::Symbol(s)) if s.function.is_some())
}
pub fn specdepth(&self) -> usize {
self.specstack.len()
}
pub fn specbind(&mut self, sym: &Value, val: Value) -> Result<(), String> {
let id0 = self.sym_handle(sym).ok_or("cannot bind a non-symbol")?;
let id = self.indirect_var(id0);
let bi = self.cur_buf_idx();
if self.buffers[bi].locals.contains_key(&id) {
let old = self.buffers[bi].locals.get(&id).cloned();
self.specstack.push(SpecEntry::Local(id, bi, old));
self.buffers[bi].locals.insert(id, Some(val));
return Ok(());
}
let old = if let Obj::Symbol(s) = &self.arena[id as usize] {
s.value.clone()
} else {
None
};
self.specstack.push(SpecEntry::Global(id, bi, old));
if let Obj::Symbol(s) = &mut self.arena[id as usize] {
s.value = Some(val);
}
Ok(())
}
pub fn unbind_to(&mut self, depth: usize) {
while self.specstack.len() > depth {
match self.specstack.pop().unwrap() {
SpecEntry::Global(id, _, old) => {
if let Obj::Symbol(s) = &mut self.arena[id as usize] {
s.value = old;
}
}
SpecEntry::Local(id, buf, old) => {
if let Some(b) = self.buffers.get_mut(buf) {
match old {
None => {
b.locals.shift_remove(&id);
}
Some(prev) => {
b.locals.insert(id, prev);
}
}
}
}
}
}
}
pub fn open_scope(&mut self) {
self.frame_stack
.push((self.lex.clone(), self.specstack.len()));
}
pub fn open_scope_in(&mut self, env: Lex) {
self.frame_stack
.push((self.lex.clone(), self.specstack.len()));
self.lex = env;
}
pub fn close_scope(&mut self) {
if let Some((saved, depth)) = self.frame_stack.pop() {
self.unbind_to(depth);
self.lex = saved;
}
}
pub fn record_form_line(&mut self, form: &Value, line: u32) {
if let Value::Obj(id) = form {
self.form_lines.insert(*id, line);
}
}
pub fn form_line(&self, form: &Value) -> Option<u32> {
match form {
Value::Obj(id) => self.form_lines.get(id).copied(),
_ => None,
}
}
pub fn unwind_scopes_to(&mut self, target_len: usize) {
while self.frame_stack.len() > target_len {
self.close_scope();
}
}
pub fn scope_depth(&self) -> usize {
self.frame_stack.len()
}
pub fn bind_here(&mut self, id: u32, val: Value) {
if self.dynamic_binding
|| self.is_special(id)
|| self.lex.as_ref().is_some_and(|s| s.declares_special(id))
{
let _ = self.specbind(&Value::Obj(id), val);
} else {
self.lex = Some(Rc::new(Scope::new(id, val, self.lex.take())));
}
}
pub fn bind_value(&mut self, symv: &Value, val: Value) {
if let Some(id) = self.sym_handle(symv) {
self.bind_here(id, val);
}
}
pub fn enter_eval_frame(&mut self) -> Result<(), String> {
let sym = match self.max_depth_sym {
Some(s) => s,
None => {
let s = self.intern("max-lisp-eval-depth");
let h = self.sym_handle(&s);
self.max_depth_sym = h;
match h {
Some(h) => h,
None => {
self.eval_depth += 1;
return Ok(());
}
}
}
};
let limit = match &self.arena[sym as usize] {
Obj::Symbol(s) => match s.value {
Some(Value::Int(n)) => (n.max(100)) as usize,
_ => usize::MAX,
},
_ => usize::MAX,
};
if self.eval_depth >= limit {
return Err(format!("excessive-lisp-nesting: {}", self.eval_depth + 1));
}
self.eval_depth += 1;
Ok(())
}
pub fn leave_eval_frame(&mut self) {
self.eval_depth = self.eval_depth.saturating_sub(1);
}
pub fn instantiate_closure(&mut self, template: &Value) -> Value {
if let Some(Obj::Closure {
params,
body,
is_macro,
src,
..
}) = self.obj(template)
{
let (params, body, is_macro, src) =
(params.clone(), body.clone(), *is_macro, src.clone());
let dynamic = self.dynamic_binding;
let template_id = match template {
Value::Obj(id) => *id,
_ => u32::MAX,
};
let env = if dynamic {
None
} else {
self.trim_lex(template_id, &src)
};
return self.alloc(Obj::Closure {
params,
body,
is_macro,
env,
dynamic,
src,
});
}
template.clone()
}
fn trim_lex(&mut self, template_id: u32, src: &Rc<ClosureSrc>) -> Lex {
if !self.lex.as_ref()?.has_bindings() {
return self.lex.clone();
}
let free = match self.closure_free.get(&template_id) {
Some(f) => Rc::clone(f),
None => {
let f = Rc::new(crate::freevars::free_vars(self, &src.arglist, &src.body));
if template_id != u32::MAX {
self.closure_free.insert(template_id, Rc::clone(&f));
}
f
}
};
let mut kept: Vec<(u32, Rc<RefCell<Value>>)> = Vec::new();
let mut declared: Vec<u32> = Vec::new();
let mut seen: std::collections::HashSet<u32> = std::collections::HashSet::new();
let mut cur = self.lex.clone();
while let Some(scope) = cur {
let sym = scope.sym_handle();
if scope.is_declaration() {
declared.push(sym);
} else if free.contains(&sym) && seen.insert(sym) {
kept.push((sym, scope.value_cell()));
}
cur = scope.parent_lex();
}
let dyns: Vec<u32> = if declared.is_empty() {
Vec::new()
} else {
crate::freevars::let_bound_vars(self, &src.arglist, &src.body)
.into_iter()
.filter(|s| declared.contains(s))
.collect()
};
let mut env: Lex = None;
for &sym in dyns.iter().rev() {
env = Some(Rc::new(Scope::declaration(sym, env)));
}
for (sym, cell) in kept.into_iter().rev() {
env = Some(Rc::new(Scope::sharing(sym, cell, env)));
}
env
}
pub fn is_closure(&self, v: &Value) -> bool {
matches!(self.obj(v), Some(Obj::Closure { .. }))
}
pub fn oclosure_set_meta(&mut self, v: &Value, ty: u32, slots: Vec<u32>) {
if let Value::Obj(id) = v {
if matches!(self.arena.get(*id as usize), Some(Obj::Closure { .. })) {
self.oclosure_meta.insert(*id, OClosureMeta { ty, slots });
}
}
}
pub fn oclosure_type_of(&self, v: &Value) -> Option<u32> {
match v {
Value::Obj(id) if self.is_closure(v) => self.oclosure_meta.get(id).map(|m| m.ty),
_ => None,
}
}
pub fn closure_parts(&self, v: &Value) -> Option<ClosureParts> {
match self.obj(v) {
Some(Obj::Closure {
is_macro,
dynamic,
src,
env,
..
}) => {
let mut captures = Vec::new();
let mut cur = env.clone();
while let Some(scope) = cur {
let val = (!scope.is_declaration()).then(|| scope.value());
captures.push((scope.sym_handle(), val));
cur = scope.parent_lex();
}
Some((
*is_macro,
*dynamic,
src.arglist.clone(),
src.body.clone(),
captures,
))
}
_ => None,
}
}
pub fn closure_slots(&mut self, v: &Value) -> Option<Vec<Value>> {
let (dynamic, src, env) = match self.obj(v) {
Some(Obj::Closure {
dynamic, src, env, ..
}) => (*dynamic, src.clone(), env.clone()),
_ => return None,
};
let slots = src.slots(self);
let body = self.list_from(slots.body);
let env = if dynamic {
Value::Undef
} else {
let mut cells = Vec::new();
let only_declarations = env.as_ref().is_some_and(|s| !s.has_bindings());
let mut cur = env;
while let Some(scope) = cur {
let name = Value::Obj(scope.sym_handle());
if scope.is_declaration() {
cells.push(name);
} else {
cells.push(self.cons(name, scope.value()));
}
cur = scope.parent_lex();
}
if cells.is_empty() || only_declarations {
cells.push(Value::Bool(true));
}
self.list_from(cells)
};
let mut out = vec![src.arglist.clone(), body, env];
if slots.doc.is_some() || slots.iform.is_some() {
out.push(Value::Undef);
out.push(slots.doc.unwrap_or(Value::Undef));
}
if let Some(iform) = slots.iform {
let spec = self.list_vec(&iform).unwrap_or_default();
let value = if spec.len() <= 2 {
spec.get(1).cloned().unwrap_or(Value::Undef)
} else {
let modes = self.list_from(spec[2..].to_vec());
self.alloc(Obj::Vector(vec![spec[1].clone(), modes]))
};
out.push(value);
}
Some(out)
}
fn closure_env(&self, v: &Value) -> Option<Lex> {
match self.obj(v) {
Some(Obj::Closure { env, .. }) => Some(env.clone()),
_ => None,
}
}
pub fn oclosure_get(&self, v: &Value, index: usize) -> Option<Value> {
let id = match v {
Value::Obj(id) => *id,
_ => return None,
};
let sym = *self.oclosure_meta.get(&id)?.slots.get(index)?;
let env = self.closure_env(v)?;
env.as_ref().and_then(|h| h.lookup(sym))
}
pub fn oclosure_set(&self, v: &Value, index: usize, val: &Value) -> bool {
let id = match v {
Value::Obj(id) => *id,
_ => return false,
};
let sym = match self.oclosure_meta.get(&id).and_then(|m| m.slots.get(index)) {
Some(s) => *s,
None => return false,
};
match self.closure_env(v).flatten() {
Some(head) => head.set(sym, val),
None => false,
}
}
pub fn oclosure_copy(&mut self, src: &Value, args: &[Value]) -> Option<Value> {
let id = match src {
Value::Obj(id) => *id,
_ => return None,
};
let slots = self.oclosure_meta.get(&id)?.slots.clone();
let ty = self.oclosure_meta.get(&id)?.ty;
let (params, body, is_macro, base_env, csrc, dynamic) = match self.obj(src) {
Some(Obj::Closure {
params,
body,
is_macro,
env,
src: csrc,
dynamic,
}) => (
params.clone(),
body.clone(),
*is_macro,
env.clone(),
csrc.clone(),
*dynamic,
),
_ => return None,
};
let mut vals: Vec<Value> = Vec::with_capacity(slots.len());
for (k, &sym) in slots.iter().enumerate() {
let v = if k < args.len() {
args[k].clone()
} else {
base_env
.as_ref()
.and_then(|h| h.lookup(sym))
.unwrap_or(Value::Undef)
};
vals.push(v);
}
let mut env = base_env;
for (k, &sym) in slots.iter().enumerate().rev() {
env = Some(Rc::new(Scope::new(sym, vals[k].clone(), env.take())));
}
let newv = self.alloc(Obj::Closure {
params,
body,
is_macro,
env,
dynamic,
src: csrc,
});
if let Value::Obj(nid) = newv {
self.oclosure_meta.insert(nid, OClosureMeta { ty, slots });
}
Some(newv)
}
pub fn export_heap_image(&self) -> Vec<SerObj> {
self.arena[self.builtin_count..]
.iter()
.enumerate()
.map(|(off, o)| match o {
Obj::Cons(a, b) => SerObj::Cons(a.clone(), b.clone()),
Obj::Symbol(s) => SerObj::Symbol {
name: s.name.clone(),
value: s.value.clone(),
function: s.function.clone(),
special: s.special,
buffer_local_auto: s.buffer_local_auto,
alias_of: s.alias_of,
interned: self.symbol_is_interned(s, (self.builtin_count + off) as u32),
},
Obj::Vector(v) => SerObj::Vector(v.clone()),
Obj::Record(v) => SerObj::Record(v.clone()),
Obj::BoolVector(v) => SerObj::BoolVector(v.clone()),
Obj::Str(s) => SerObj::Str(s.to_string()),
Obj::Bignum(b) => SerObj::Bignum(b.clone()),
Obj::HashTable(t) => SerObj::HashTable {
test: t.test,
slots: t.slots.clone(),
free: t.free.clone(),
size: t.size,
weakness: t.weakness.clone(),
user_test: t.user_test.clone(),
},
Obj::CharTable(t) => SerObj::CharTable {
subtype: t.subtype.clone(),
default: t.default.clone(),
parent: t.parent.clone(),
extra: t.extra.clone(),
contents: t.flatten(),
ascii: match &t.ascii {
CtAscii::Val(v) => Some(v.clone()),
CtAscii::Tree => None,
},
},
Obj::Buffer(_)
| Obj::Marker(_)
| Obj::Overlay(_)
| Obj::Window(_)
| Obj::Frame(_)
| Obj::WindowConfig(_)
| Obj::Obarray(_) => SerObj::Symbol {
name: "--unexpected-runtime-obj--".to_string(),
value: None,
function: None,
special: false,
buffer_local_auto: false,
alias_of: None,
interned: false,
},
Obj::Closure {
params,
body,
is_macro,
env,
dynamic,
src,
} => SerObj::Closure {
required: params.required.clone(),
optional: params.optional.clone(),
rest: params.rest,
body: (**body).clone(),
is_macro: *is_macro,
env: self.flatten_lex(env),
dynamic: *dynamic,
arglist: src.arglist.clone(),
src_body: src.body.clone(),
},
Obj::Subr { .. } => SerObj::Symbol {
name: "--unexpected-subr--".to_string(),
value: None,
function: None,
special: false,
buffer_local_auto: false,
alias_of: None,
interned: false,
},
})
.collect()
}
pub fn builtin_count(&self) -> usize {
self.builtin_count
}
pub fn set_prelude_end(&mut self, end: usize) {
self.prelude_end = end;
}
pub fn is_prelude_object(&self, v: &Value) -> bool {
matches!(v, Value::Obj(id) if (*id as usize) >= self.builtin_count && (*id as usize) < self.prelude_end)
}
fn captured_alist(&self, env: &Lex, readable: bool, depth: usize) -> String {
let mut cells = Vec::new();
let only_declarations = env.as_ref().is_some_and(|s| !s.has_bindings());
let mut cur = env.clone();
while let Some(scope) = cur {
let name = match self.arena.get(scope.sym_handle() as usize) {
Some(Obj::Symbol(s)) => s.name.clone(),
_ => break,
};
if scope.is_declaration() {
cells.push(name);
} else {
let val = self.print_inner(&scope.value(), readable, depth + 1);
cells.push(format!("({name} . {val})"));
}
cur = scope.parent_lex();
}
if only_declarations {
cells.push("t".to_string());
}
if cells.is_empty() {
"(t)".to_string()
} else {
format!("({})", cells.join(" "))
}
}
fn symbol_is_interned(&self, s: &SymbolData, id: u32) -> bool {
self.obarray.get(&s.name) == Some(&id)
}
pub fn set_compiling_form(&mut self, on: bool) -> bool {
std::mem::replace(&mut self.compiling_form, on)
}
fn interned_at_compile_time(&self, id: u32) -> bool {
self.compile_interned.contains(&id)
}
pub fn builtin_fingerprint(&self) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
self.builtin_count.hash(&mut hasher);
for obj in &self.arena[..self.builtin_count] {
if let Obj::Symbol(s) = obj {
s.name.hash(&mut hasher);
}
}
hasher.finish()
}
pub fn primitive_fn_value(&self, name: &str) -> Option<Value> {
let f = self
.obarray
.get(name)
.and_then(|&id| self.arena.get(id as usize))
.and_then(|o| match o {
Obj::Symbol(s) => s.function.clone(),
_ => None,
})?;
matches!(self.obj(&f), Some(Obj::Subr { .. })).then_some(f)
}
pub fn is_primitive_fn(&self, name: &str) -> bool {
self.obarray
.get(name)
.and_then(|&id| self.arena.get(id as usize))
.and_then(|o| match o {
Obj::Symbol(s) => s.function.clone(),
_ => None,
})
.map(|f| matches!(self.obj(&f), Some(Obj::Subr { .. })))
.unwrap_or(false)
}
pub fn arena_len(&self) -> usize {
self.arena.len()
}
pub fn flatten_lex(&self, env: &Lex) -> Vec<(u32, Option<Value>)> {
let mut out = Vec::new();
let mut cur = env.clone();
while let Some(scope) = cur {
let val = (!scope.is_declaration()).then(|| scope.value());
out.push((scope.sym_handle(), val));
cur = scope.parent_lex();
}
out
}
pub fn rebuild_lex(&self, pairs: Vec<(u32, Option<Value>)>) -> Lex {
let mut env: Lex = None;
for (sym, val) in pairs.into_iter().rev() {
env = Some(Rc::new(match val {
Some(val) => Scope::new(sym, val, env),
None => Scope::declaration(sym, env),
}));
}
env
}
fn ser_obj(&self, o: &Obj, id: u32) -> SerObj {
match o {
Obj::Bignum(b) => SerObj::Bignum(b.clone()),
Obj::Symbol(s) => SerObj::Symbol {
name: s.name.clone(),
value: s.value.clone(),
function: s.function.clone(),
special: s.special,
buffer_local_auto: s.buffer_local_auto,
alias_of: s.alias_of,
interned: self.symbol_is_interned(s, id),
},
Obj::Cons(a, b) => SerObj::Cons(a.clone(), b.clone()),
Obj::Vector(v) => SerObj::Vector(v.clone()),
Obj::Record(v) => SerObj::Record(v.clone()),
Obj::BoolVector(v) => SerObj::BoolVector(v.clone()),
Obj::Str(s) => SerObj::Str(s.to_string()),
Obj::HashTable(t) => SerObj::HashTable {
test: t.test,
slots: t.slots.clone(),
free: t.free.clone(),
size: t.size,
weakness: t.weakness.clone(),
user_test: t.user_test.clone(),
},
Obj::CharTable(t) => SerObj::CharTable {
subtype: t.subtype.clone(),
default: t.default.clone(),
parent: t.parent.clone(),
extra: t.extra.clone(),
contents: t.flatten(),
ascii: match &t.ascii {
CtAscii::Val(v) => Some(v.clone()),
CtAscii::Tree => None,
},
},
Obj::Closure {
params,
body,
is_macro,
env,
dynamic,
src,
} => SerObj::Closure {
required: params.required.clone(),
optional: params.optional.clone(),
rest: params.rest,
body: (**body).clone(),
is_macro: *is_macro,
env: self.flatten_lex(env),
dynamic: *dynamic,
arglist: src.arglist.clone(),
src_body: src.body.clone(),
},
Obj::Subr { .. }
| Obj::Buffer(_)
| Obj::Marker(_)
| Obj::Overlay(_)
| Obj::Window(_)
| Obj::Frame(_)
| Obj::WindowConfig(_)
| Obj::Obarray(_) => SerObj::Symbol {
name: "--unexpected-runtime-obj--".to_string(),
value: None,
function: None,
special: false,
buffer_local_auto: false,
alias_of: None,
interned: false,
},
}
}
pub fn export_heap_range(&self, start: usize, end: usize) -> Vec<SerObj> {
self.arena[start..end]
.iter()
.enumerate()
.map(|(off, o)| self.ser_obj(o, (start + off) as u32))
.collect()
}
pub fn export_builtin_cells(&self) -> Vec<Option<SymbolBaseline>> {
self.snapshot_values(0, self.builtin_count)
}
pub fn import_builtin_cells(&mut self, cells: Vec<Option<SymbolBaseline>>) {
for (i, cell) in cells.into_iter().enumerate() {
let (Some(cell), Some(Obj::Symbol(sym))) = (cell, self.arena.get_mut(i)) else {
continue;
};
sym.value = cell.value;
sym.function = cell.function;
sym.buffer_local_auto = cell.buffer_local_auto;
sym.alias_of = cell.alias_of;
}
}
pub fn export_buffer_state(&self) -> BufferState {
BufferState {
always_local: self.always_local.clone(),
locals: self
.buffers
.iter()
.map(|b| {
b.locals
.iter()
.map(|(k, v)| (*k, v.clone()))
.collect::<Vec<_>>()
})
.collect(),
}
}
pub fn import_buffer_state(&mut self, state: BufferState) {
self.always_local = state.always_local;
for (b, locals) in self.buffers.iter_mut().zip(state.locals) {
b.locals = locals.into_iter().collect();
}
}
pub fn snapshot_values(&self, start: usize, end: usize) -> Vec<Option<SymbolBaseline>> {
(start..end)
.map(|i| match self.arena.get(i) {
Some(Obj::Symbol(s)) => Some(SymbolBaseline {
value: s.value.clone(),
function: s.function.clone(),
buffer_local_auto: s.buffer_local_auto,
alias_of: s.alias_of,
}),
_ => None,
})
.collect()
}
pub fn export_heap_tail_clean(&self, prelude_end: usize) -> Vec<SerObj> {
let mut out: Vec<SerObj> = Vec::with_capacity(self.arena.len() - prelude_end);
for (off, o) in self.arena[prelude_end..].iter().enumerate() {
let id = (prelude_end + off) as u32;
let ser = match o {
Obj::Symbol(s) => SerObj::Symbol {
name: s.name.clone(),
value: None,
function: None,
special: s.special,
buffer_local_auto: false,
alias_of: None,
interned: self.symbol_is_interned(s, id) && self.interned_at_compile_time(id),
},
other => self.ser_obj(other, id),
};
out.push(ser);
}
out
}
pub fn import_heap_image(&mut self, image: Vec<SerObj>) {
for ser in image {
let id = self.arena.len() as u32;
let obj = match ser {
SerObj::Cons(a, b) => Obj::Cons(a, b),
SerObj::Bignum(b) => Obj::Bignum(b),
SerObj::Symbol {
name,
value,
function,
special,
buffer_local_auto,
alias_of,
interned,
} => {
if interned {
self.obarray.insert(name.clone(), id);
}
Obj::Symbol(SymbolData {
name,
value,
function,
special,
buffer_local_auto,
alias_of,
})
}
SerObj::Vector(v) => Obj::Vector(v),
SerObj::Record(v) => Obj::Record(v),
SerObj::BoolVector(v) => Obj::BoolVector(v),
SerObj::Str(s) => Obj::Str(Arc::new(s)),
SerObj::HashTable {
test,
slots,
free,
size,
weakness,
user_test,
} => {
let mut t = ElHashTable::from_slots(test, slots, free, size, weakness);
t.user_test = user_test;
Obj::HashTable(t)
}
SerObj::CharTable {
subtype,
default,
parent,
extra,
contents,
ascii,
} => Obj::CharTable(CharTable {
subtype,
default,
parent,
extra,
contents: CharTable::unflatten(&contents),
ascii: match ascii {
Some(v) => CtAscii::Val(v),
None => CtAscii::Tree,
},
}),
SerObj::Closure {
required,
optional,
rest,
body,
is_macro,
env,
dynamic,
arglist,
src_body,
} => Obj::Closure {
params: Rc::new(Params {
required,
optional,
rest,
}),
src: Rc::new(ClosureSrc {
arglist,
body: src_body,
raw_body: None,
}),
body: Rc::new(body),
is_macro,
env: self.rebuild_lex(env),
dynamic,
},
};
self.arena.push(obj);
}
}
pub fn bind_params_into_scope(
&mut self,
params: &Params,
args: &[Value],
) -> Result<(), String> {
if args.len() < params.required.len() {
return Err("wrong-number-of-arguments".to_string());
}
let max = params.required.len() + params.optional.len();
if params.rest.is_none() && args.len() > max {
return Err("wrong-number-of-arguments".to_string());
}
let mut i = 0;
for &id in ¶ms.required {
self.bind_here(id, args[i].clone());
i += 1;
}
for &id in ¶ms.optional {
let v = args.get(i).cloned().unwrap_or(Value::Undef);
self.bind_here(id, v);
i += 1;
}
if let Some(id) = params.rest {
let rest = args.get(i..).map(|s| s.to_vec()).unwrap_or_default();
let lst = self.list_from(rest);
self.bind_here(id, lst);
}
Ok(())
}
pub fn parse_params(&mut self, arglist: &Value) -> Result<Params, String> {
let items = self.list_vec(arglist).ok_or("malformed lambda list")?;
let mut p = Params {
required: vec![],
optional: vec![],
rest: None,
};
let mut mode = 0u8;
for it in items {
let id = self.sym_handle(&it).ok_or("lambda list: expected symbol")?;
let name = self.sym_name(&it).unwrap_or_default();
match name.as_str() {
"&optional" => mode = 1,
"&rest" => mode = 2,
_ => match mode {
0 => p.required.push(id),
1 => p.optional.push(id),
_ => p.rest = Some(id),
},
}
}
Ok(p)
}
pub fn fn_kind(&self, f: &Value) -> FnKind {
let mut cur = f.clone();
for _ in 0..64 {
let next = match self.obj(&cur) {
Some(Obj::Subr { min, max, .. }) => return FnKind::Subr(*min, *max),
Some(Obj::Symbol(s)) => s.function.clone(),
Some(_) => return FnKind::Other,
None => return FnKind::Vacant,
};
match next {
Some(v) => cur = v,
None => return FnKind::Vacant,
}
}
FnKind::Other
}
pub fn note_subr_alias(&mut self, sym: &Value, def: &Value) {
if matches!(self.fn_kind(def), FnKind::Subr(..)) {
if let Some(id) = self.sym_handle(sym) {
self.subr_aliased.insert(id);
}
}
}
pub fn is_subr_aliased(&self, sym: &Value) -> bool {
self.sym_handle(sym)
.is_some_and(|id| self.subr_aliased.contains(&id))
}
pub fn indirect_lambda_list(&self, f: &Value) -> Option<Value> {
let mut cur = f.clone();
for _ in 0..64 {
match self.obj(&cur) {
Some(Obj::Symbol(s)) => cur = s.function.clone()?,
Some(Obj::Cons(car, _)) => {
return (self.sym_name(car).as_deref() == Some("lambda")).then_some(cur);
}
_ => return None,
}
}
None
}
pub fn indirect_autoload(&self, f: &Value) -> Option<Value> {
let mut cur = f.clone();
for _ in 0..64 {
match self.obj(&cur) {
Some(Obj::Symbol(s)) => cur = s.function.clone()?,
Some(Obj::Cons(car, _)) => {
return (self.sym_name(car).as_deref() == Some("autoload")).then_some(cur);
}
_ => return None,
}
}
None
}
pub fn resolve_function(&self, f: &Value) -> Result<Resolved, String> {
let mut cur = f.clone();
for _ in 0..64 {
match self.obj(&cur) {
Some(Obj::Subr { f, min, max, name }) => {
return Ok(Resolved::Subr {
f: *f,
min: *min,
max: *max,
name: name.clone(),
})
}
Some(Obj::Closure {
params,
body,
is_macro,
env,
dynamic,
..
}) => {
return Ok(Resolved::Closure {
params: params.clone(),
body: body.clone(),
is_macro: *is_macro,
env: env.clone(),
dynamic: *dynamic,
object: cur.clone(),
})
}
Some(Obj::Symbol(s)) => match &s.function {
Some(def) => cur = def.clone(),
None => return Err(format!("void-function: {}", s.name)),
},
None if matches!(cur, Value::Bool(true)) => {
return Err("void-function: t".to_string())
}
None if matches!(cur, Value::Undef | Value::Bool(false)) => {
return Err("void-function: nil".to_string())
}
_ => return Err(format!("invalid-function: {}", self.print(&cur, true))),
}
}
Err("function indirection too deep".to_string())
}
pub fn print(&self, v: &Value, readable: bool) -> String {
self.print_overflow.set(false);
self.print_backquote_depth.set(0);
self.print_labels.borrow_mut().clear();
self.print_being.borrow_mut().clear();
self.print_next_label.set(1);
self.print_circle_on.set(self.print_flag("print-circle"));
self.print_gensym_on.set(self.print_flag("print-gensym"));
if self.print_circle_on.get() {
self.print_next_label.set(1);
self.print_preprocess(v);
}
self.print_inner(v, readable, 0)
}
fn print_preprocess(&self, v: &Value) {
let mut stack: Vec<Value> = Vec::new();
let mut obj = v.clone();
loop {
if let Value::Obj(id) = obj {
if id & CT_ASCII_LABEL != 0 {
let mut labels = self.print_labels.borrow_mut();
if let std::collections::hash_map::Entry::Vacant(e) = labels.entry(id) {
let n = self.print_next_label.get();
self.print_next_label.set(n + 1);
e.insert(-(n as i64));
}
drop(labels);
match stack.pop() {
Some(next) => {
obj = next;
continue;
}
None => break,
}
}
let children: Option<Vec<Value>> = match self.arena.get(id as usize) {
Some(Obj::Cons(car, cdr)) => {
let mut kids = vec![car.clone()];
if el_truthy(cdr) {
kids.push(cdr.clone());
}
Some(kids)
}
Some(Obj::Vector(items)) if items.is_empty() => None,
Some(Obj::Str(a)) if a.is_empty() => None,
Some(Obj::Vector(items)) | Some(Obj::Record(items)) => Some(items.clone()),
Some(Obj::Str(a)) => {
let kids: Vec<Value> = self
.string_intervals(a)
.into_iter()
.filter(|(_, _, p)| el_truthy(p))
.map(|(_, _, p)| p)
.collect();
Some(kids)
}
Some(Obj::CharTable(t)) => {
let mut kids = vec![t.default.clone(), t.parent.clone(), t.subtype.clone()];
let shared = matches!(t.ascii, CtAscii::Tree);
match &t.ascii {
CtAscii::Val(v) => kids.push(v.clone()),
CtAscii::Tree => {
if let Some(sub) = t.ascii_table() {
sub.leaf_values(&mut kids);
}
kids.push(Value::Obj(id | CT_ASCII_LABEL));
}
}
for slot in &t.contents {
slot.leaf_values(&mut kids, shared);
}
kids.extend(t.extra.iter().cloned());
Some(kids)
}
Some(Obj::Closure { src, .. }) => {
let mut kids = vec![src.arglist.clone()];
kids.extend(src.body.iter().cloned());
Some(kids)
}
Some(Obj::HashTable(t)) => {
let mut kids = Vec::with_capacity(t.count() * 2);
for (k, val) in t.pairs() {
kids.push(k.clone());
kids.push(val.clone());
}
Some(kids)
}
Some(Obj::Symbol(_))
if self.print_gensym_on.get() && !self.interned_in_standard_obarray(id) =>
{
Some(Vec::new())
}
_ => None,
};
if let Some(kids) = children {
let mut labels = self.print_labels.borrow_mut();
match labels.get(&id).copied() {
Some(0) => {
let n = self.print_next_label.get();
self.print_next_label.set(n + 1);
labels.insert(id, -(n as i64));
}
Some(_) => {}
None => {
labels.insert(id, 0);
drop(labels);
stack.extend(kids.into_iter().rev());
}
}
}
}
match stack.pop() {
Some(next) => obj = next,
None => break,
}
}
}
#[allow(clippy::result_large_err)]
fn circle_label(&self, v: &Value) -> Option<Result<String, String>> {
let Value::Obj(id) = v else { return None };
let mut labels = self.print_labels.borrow_mut();
let slot = labels.get_mut(id)?;
match (*slot).cmp(&0) {
std::cmp::Ordering::Equal => None,
std::cmp::Ordering::Less => {
let n = -*slot;
*slot = n;
Some(Ok(format!("#{n}=")))
}
std::cmp::Ordering::Greater => Some(Err(format!("#{slot}#"))),
}
}
pub fn print_checked(&self, v: &Value, readable: bool) -> Result<String, String> {
let s = self.print(v, readable);
if self.print_overflow.get() {
return Err("Apparently circular structure being printed".to_string());
}
Ok(s)
}
fn print_limit(&self, name: &str) -> Option<usize> {
let id = *self.obarray.get(name)?;
match self.arena.get(id as usize)? {
Obj::Symbol(s) => match s.value.as_ref()? {
Value::Int(n) if *n >= 0 => Some(*n as usize),
_ => None,
},
_ => None,
}
}
fn float_to_string(&self, f: f64) -> String {
let spec = self
.obarray
.get("float-output-format")
.and_then(|id| match self.arena.get(*id as usize) {
Some(Obj::Symbol(s)) => s.value.clone(),
_ => None,
})
.and_then(|v| self.str_text(&v).map(str::to_string));
let Some((prec, conv)) = spec.as_deref().and_then(parse_float_output_format) else {
return format_float(f);
};
let s = match conv {
'f' => format!("{f:.prec$}", prec = prec.unwrap_or(0)),
'e' => {
let e_form = format!("{:.*e}", prec.unwrap_or(0), f);
let (mantissa, exp) = e_form.rsplit_once('e').unwrap_or((&e_form, "0"));
let exp: i32 = exp.parse().unwrap_or(0);
let sign = if exp < 0 { '-' } else { '+' };
format!("{mantissa}e{sign}{:02}", exp.abs())
}
_ => format_g(f, prec.unwrap_or(0)),
};
if prec == Some(0) {
return s;
}
match s.find(|c: char| !c.is_ascii_digit() && c != '-') {
None => format!("{s}.0"),
Some(i) if i + 1 == s.len() && s.ends_with('.') => format!("{s}0"),
_ => s,
}
}
fn escape_string_body(&self, s: &str) -> String {
let esc_newlines = self.print_flag("print-escape-newlines");
let esc_control = self.print_flag("print-escape-control-characters");
let esc_multibyte = self.print_flag("print-escape-multibyte");
let chars: Vec<char> = s.chars().collect();
let mut out = String::with_capacity(s.len() + 2);
let mut need_nonhex = false;
for (i, &c) in chars.iter().enumerate() {
if esc_multibyte && !c.is_ascii() {
out.push_str(&format!("\\x{:04x}", c as u32));
need_nonhex = true;
continue;
}
if need_nonhex && c.is_ascii_hexdigit() {
out.push_str("\\ ");
}
need_nonhex = false;
match c {
'\n' if esc_newlines => out.push_str("\\n"),
'\u{c}' if esc_newlines => out.push_str("\\f"),
'"' | '\\' => {
out.push('\\');
out.push(c);
}
c if esc_control && c.is_ascii_control() => {
let next_octal = chars.get(i + 1).is_some_and(|n| ('0'..='7').contains(n));
let c = c as u32;
let digits = if c > 0o77 || next_octal {
3
} else if c > 0o7 {
2
} else {
1
};
out.push_str(&format!("\\{c:0digits$o}"));
}
_ => out.push(c),
}
}
out
}
fn int_as_character(&self, n: i64) -> Option<String> {
use std::sync::OnceLock;
static GRAPHIC: OnceLock<fancy_regex::Regex> = OnceLock::new();
if !self.print_flag("print-integers-as-characters") {
return None;
}
let c = char::from_u32(u32::try_from(n).ok()?)?;
let body = match c {
'\u{8}' => "\\b".to_string(),
'\t' => "\\t".to_string(),
'\n' => "\\n".to_string(),
'\u{c}' => "\\f".to_string(),
'\r' => "\\r".to_string(),
' ' => "\\s".to_string(),
'"' | '\'' | '(' | ')' | ';' | '[' | '\\' | ']' | '{' | '}' => format!("\\{c}"),
' '..='~' => c.to_string(),
c if c.is_ascii() => return None,
c => {
let graphic = GRAPHIC.get_or_init(|| {
fancy_regex::Regex::new(r"^[\p{L}\p{N}\p{P}\p{S}\p{Co}]$")
.expect("static regex")
});
if !graphic.is_match(&c.to_string()).unwrap_or(false) {
return None;
}
c.to_string()
}
};
Some(format!("?{body}"))
}
fn print_flag(&self, name: &str) -> bool {
self.print_flag_or(name, false)
}
fn print_flag_or(&self, name: &str, default: bool) -> bool {
match self
.obarray
.get(name)
.and_then(|id| self.arena.get(*id as usize))
{
Some(Obj::Symbol(s)) => s.value.as_ref().map(el_truthy).unwrap_or(default),
_ => default,
}
}
fn print_seq(&self, items: &[Value], readable: bool, depth: usize) -> Vec<String> {
let limit = self.print_limit("print-length");
let mut parts = Vec::new();
for (i, e) in items.iter().enumerate() {
if limit.is_some_and(|lim| i >= lim) {
parts.push("...".to_string());
break;
}
parts.push(self.print_inner(e, readable, depth));
}
parts
}
fn print_inner(&self, v: &Value, readable: bool, depth: usize) -> String {
stacker::maybe_grow(128 * 1024, 8 * 1024 * 1024, || {
self.print_inner_frame(v, readable, depth)
})
}
fn print_ct_slot(&self, slot: &CtSlot, key: u32, readable: bool, depth: usize) -> String {
match slot {
CtSlot::Val(v) => self.print_inner(v, readable, depth),
CtSlot::Sub(s) => self.print_sub_char_table(s, key, readable, depth),
}
}
fn print_sub_char_table(
&self,
sub: &SubCharTable,
key: u32,
readable: bool,
depth: usize,
) -> String {
if sub.depth == 3 && sub.min_char == 0 && self.print_circle_on.get() {
let mut labels = self.print_labels.borrow_mut();
if let Some(slot) = labels.get_mut(&key) {
if *slot > 0 {
return format!("#{slot}#");
}
let n = -*slot;
*slot = n;
drop(labels);
return format!("#{n}={}", self.print_sub_body(sub, key, readable, depth));
}
}
self.print_sub_body(sub, key, readable, depth)
}
fn print_sub_body(&self, sub: &SubCharTable, key: u32, readable: bool, depth: usize) -> String {
let mut parts = vec![sub.depth.to_string(), sub.min_char.to_string()];
for slot in &sub.contents {
parts.push(self.print_ct_slot(slot, key, readable, depth));
}
format!("#^^[{}]", parts.join(" "))
}
fn print_inner_frame(&self, v: &Value, readable: bool, depth: usize) -> String {
if self.print_circle_on.get() {
match self.circle_label(v) {
Some(Err(backref)) => return backref,
Some(Ok(prefix)) => {
return format!("{prefix}{}", self.print_body(v, readable, depth))
}
None => {}
}
} else {
if depth >= PRINT_CIRCLE {
self.print_overflow.set(true);
return String::new();
}
let id = match v {
Value::Obj(id) => Some(*id),
_ => None,
};
if id.is_some() {
let being = self.print_being.borrow();
for (i, slot) in being.iter().take(depth).enumerate() {
if *slot == id {
return format!("#{i}");
}
}
}
let mut being = self.print_being.borrow_mut();
if being.len() <= depth {
being.resize(depth + 1, None);
}
being[depth] = id;
}
self.print_body(v, readable, depth)
}
fn print_body(&self, v: &Value, readable: bool, depth: usize) -> String {
let view;
let v = match self.obj(v) {
Some(Obj::Str(s)) => {
view = Value::Str(Arc::clone(s));
&view
}
_ => v,
};
match v {
Value::Undef => "nil".to_string(),
Value::Bool(true) => "t".to_string(),
Value::Bool(false) => "nil".to_string(),
Value::Int(n) => self.int_as_character(*n).unwrap_or_else(|| n.to_string()),
Value::Float(f) => {
if f.is_nan() {
let payload = f.to_bits() & crate::reader::NAN_PAYLOAD_MASK;
let sign = if f.is_sign_negative() { "-" } else { "" };
format!("{sign}{payload}.0e+NaN")
} else if f.is_infinite() {
if *f < 0.0 { "-1.0e+INF" } else { "1.0e+INF" }.to_string()
} else {
self.float_to_string(*f)
}
}
Value::Str(s) => {
if readable {
let t = self.escape_string_body(s);
let intervals = self.string_prop_intervals(s, depth);
if intervals.is_empty() {
format!("\"{t}\"")
} else {
format!("#(\"{t}\"{intervals})")
}
} else {
s.to_string()
}
}
Value::Obj(id) => match self.arena.get(*id as usize) {
Some(Obj::Str(s)) => self.print_body(&Value::Str(Arc::clone(s)), readable, depth),
Some(Obj::Symbol(s)) => {
if readable {
if self.print_gensym_on.get() && !self.interned_in_standard_obarray(*id) {
let name = if s.name.is_empty() {
String::new()
} else {
print_symbol_readable(&s.name)
};
return format!("#:{name}");
}
print_symbol_readable(&s.name)
} else {
s.name.clone()
}
}
Some(Obj::Cons(..)) => self.print_list(v, readable, depth),
Some(Obj::Vector(items)) => {
let parts = self.print_seq(items, readable, depth + 1);
format!("[{}]", parts.join(" "))
}
Some(Obj::Record(items)) => {
let parts = self.print_seq(items, readable, depth + 1);
format!("#s({})", parts.join(" "))
}
Some(Obj::BoolVector(bits)) => {
let nbytes = bits.len().div_ceil(8);
let mut packed = vec![0u8; nbytes];
for (i, &b) in bits.iter().enumerate() {
if b {
packed[i / 8] |= 1 << (i % 8);
}
}
let esc_ctl = self.print_flag("print-escape-control-characters");
let mut inner = String::new();
for &byte in &packed {
match byte {
b'"' => inner.push_str("\\\""),
b'\\' => inner.push_str("\\\\"),
0..=0x1f | 0x7f if esc_ctl => inner.push_str(&format!("\\{byte:o}")),
0..=127 => inner.push(byte as char),
_ => inner.push_str(&format!("\\{byte:o}")),
}
}
format!("#&{}\"{}\"", bits.len(), inner)
}
Some(Obj::CharTable(t)) => {
let key = match v {
Value::Obj(id) => *id | CT_ASCII_LABEL,
_ => 0,
};
let mut parts = vec![
self.print_inner(&t.default, readable, depth + 1),
self.print_inner(&t.parent, readable, depth + 1),
self.print_inner(&t.subtype, readable, depth + 1),
];
parts.push(match &t.ascii {
CtAscii::Val(a) => self.print_inner(a, readable, depth + 1),
CtAscii::Tree => match t.ascii_table() {
Some(sub) => self.print_sub_char_table(sub, key, readable, depth + 1),
None => "nil".to_string(),
},
});
for slot in &t.contents {
parts.push(self.print_ct_slot(slot, key, readable, depth + 1));
}
for e in &t.extra {
parts.push(self.print_inner(e, readable, depth + 1));
}
format!("#^[{}]", parts.join(" "))
}
Some(Obj::Bignum(b)) => b.to_string(),
Some(Obj::Buffer(idx)) => {
match self.buffers.get(*idx).and_then(|b| b.name.as_ref()) {
Some(name) => format!("#<buffer {name}>"),
None => "#<killed buffer>".to_string(),
}
}
Some(Obj::Marker(m)) => {
let md = m.borrow();
let moves = if md.insertion_type {
"(moves after insertion) "
} else {
""
};
match md
.buffer
.and_then(|bi| self.buffers.get(bi).and_then(|b| b.name.as_ref()))
{
Some(name) => format!("#<marker {moves}at {} in {}>", md.pos, name),
None => format!("#<marker {moves}in no buffer>"),
}
}
Some(Obj::Window(w)) => crate::window::print_window(self, *w),
Some(Obj::Frame(f)) => crate::window::print_frame(self, *f),
Some(Obj::WindowConfig(_)) => "#<window-configuration>".to_string(),
Some(Obj::Overlay(o)) => {
let od = o.borrow();
match od
.buffer
.and_then(|bi| self.buffers.get(bi).and_then(|b| b.name.as_ref()))
{
Some(name) => {
format!("#<overlay from {} to {} in {}>", od.start, od.end, name)
}
None => "#<overlay in no buffer>".to_string(),
}
}
Some(Obj::Obarray(d)) => {
let n = if d.global {
self.obarray.len()
} else {
d.symbols.len()
};
format!("#<obarray n={n}>")
}
Some(Obj::Subr { name, .. }) => format!("#<subr {name}>"),
Some(Obj::Closure {
is_macro,
env,
src,
dynamic,
..
}) => {
let arglist = self.print_inner(&src.arglist, readable, depth + 1);
let slots = src.slots(self);
let body: Vec<String> = slots
.body
.iter()
.map(|f| self.print_inner(f, readable, depth + 1))
.collect();
let captures = if *dynamic {
"nil".to_string()
} else {
self.captured_alist(env, readable, depth + 1)
};
let mut extra = String::new();
if slots.doc.is_some() || slots.iform.is_some() {
let doc = slots.doc.clone().unwrap_or(Value::Undef);
extra = format!(" nil {}", self.print_inner(&doc, readable, depth + 1));
}
if let Some(iform) = &slots.iform {
let spec = self.list_vec(iform).unwrap_or_default();
let shown = match spec.len() {
0..=2 => {
let v = spec.get(1).cloned().unwrap_or(Value::Undef);
self.print_inner(&v, readable, depth + 1)
}
_ => {
let modes: Vec<String> = spec[2..]
.iter()
.map(|m| self.print_inner(m, readable, depth + 1))
.collect();
format!(
"[{} ({})]",
self.print_inner(&spec[1], readable, depth + 1),
modes.join(" ")
)
}
};
extra.push(' ');
extra.push_str(&shown);
}
let closure = format!("#[{arglist} ({}) {captures}{extra}]", body.join(" "));
if *is_macro {
format!("(macro . {closure})")
} else {
closure
}
}
Some(Obj::HashTable(tbl)) => {
let (test, entries) = (&tbl.test, tbl.pairs().collect::<Vec<_>>());
let mut s = String::from("#s(hash-table");
match (&tbl.user_test, test) {
(Some((name, _, _)), _) => {
s.push_str(" test ");
s.push_str(&self.print_inner(name, readable, depth + 1));
}
(None, 0) => s.push_str(" test eq"),
(None, 2) => s.push_str(" test equal"),
_ => {}
}
if !el_nil(&tbl.weakness) {
s.push_str(" weakness ");
s.push_str(&self.print_inner(&tbl.weakness, readable, depth + 1));
}
if !entries.is_empty() {
s.push_str(" data (");
for (i, (k, v)) in entries.iter().enumerate() {
if i > 0 {
s.push(' ');
}
s.push_str(&self.print_inner(k, readable, depth + 1));
s.push(' ');
s.push_str(&self.print_inner(v, readable, depth + 1));
}
s.push(')');
}
s.push(')');
s
}
None => "#<dangling>".to_string(),
},
other => other.as_str_cow().into_owned(),
}
}
fn print_list(&self, v: &Value, readable: bool, depth: usize) -> String {
if self
.print_limit("print-level")
.is_some_and(|lvl| depth + 1 > lvl)
{
return "...".to_string();
}
let nd = depth + 1;
if let Some(Obj::Cons(head, tail)) = self.obj(v) {
let depth_now = self.print_backquote_depth.get();
let prefix = if self.print_flag_or("print-quoted", true) {
match self.obj(head) {
Some(Obj::Symbol(s)) => match s.name.as_str() {
"quote" => Some(("'", depth_now)),
"function" => Some(("#'", depth_now)),
"`" => Some(("`", depth_now + 1)),
"," if depth_now > 0 => Some((",", depth_now - 1)),
",@" if depth_now > 0 => Some((",@", depth_now - 1)),
_ => None,
},
_ => None,
}
} else {
None
};
if let Some((prefix, inner_depth)) = prefix {
if let Some(Obj::Cons(arg, rest)) = self.obj(tail) {
if !el_truthy(rest) {
self.print_backquote_depth.set(inner_depth);
let body = self.print_inner(arg, readable, nd);
self.print_backquote_depth.set(depth_now);
return format!("{prefix}{body}");
}
}
}
}
let print_length = self.print_limit("print-length");
if print_length == Some(0) {
return "(...)".to_string();
}
let mut maxlen: i64 = print_length.map_or(i64::MAX, |n| n as i64);
let mut out = String::from("(");
let Some(Obj::Cons(car0, _)) = self.obj(v) else {
return "()".to_string();
};
out.push_str(&self.print_inner(car0, readable, nd));
let mut last = v.clone();
let mut tortoise = match v {
Value::Obj(id) => *id,
_ => return "()".to_string(),
};
let (mut n, mut m, mut tortoise_idx): (i64, i64, i64) = (2, 2, 0);
while let Some(Obj::Cons(_, cdr)) = self.obj(&last) {
let next = cdr.clone();
match &next {
Value::Undef | Value::Bool(false) => break,
Value::Obj(id) if matches!(self.arena.get(*id as usize), Some(Obj::Cons(..))) => {
if self.print_circle_on.get()
&& self
.print_labels
.borrow()
.get(id)
.is_some_and(|slot| *slot != 0)
{
out.push_str(" . ");
out.push_str(&self.print_inner(&next, readable, nd));
break;
}
out.push(' ');
maxlen -= 1;
if maxlen <= 0 {
out.push_str("...");
break;
}
last = next.clone();
n -= 1;
if n == 0 {
tortoise_idx += m;
m <<= 1;
n = m;
tortoise = *id;
} else if tortoise == *id {
out.push_str(". #");
out.push_str(&tortoise_idx.to_string());
break;
}
let Some(Obj::Cons(a, _)) = self.obj(&last) else {
break;
};
out.push_str(&self.print_inner(a, readable, nd));
}
_ => {
out.push_str(" . ");
out.push_str(&self.print_inner(&next, readable, nd));
break;
}
}
}
out.push(')');
out
}
pub fn take_error(&mut self) -> Option<String> {
self.error.take()
}
pub fn write_stdout(&mut self, s: &str) {
use std::io::Write;
match &mut self.capture {
Some(buf) => buf.push_str(s),
None => {
print!("{s}");
let _ = std::io::stdout().flush();
}
}
}
pub fn emit(&mut self, s: &str) {
self.write_stdout(s);
if let Some(c) = s.chars().last() {
self.stdout_last = c;
}
self.need_newline = true;
}
pub fn cur_buf(&mut self) -> &mut EditBuffer {
&mut self.buffers[self.current]
}
pub fn cur_buf_ref(&self) -> &EditBuffer {
&self.buffers[self.current]
}
pub fn current_buffer(&self) -> Value {
self.buffers[self.current].self_obj.clone()
}
pub fn resolve_buffer(&self, v: &Value) -> Option<usize> {
match self.obj(v) {
Some(Obj::Buffer(idx)) => {
let idx = *idx;
self.buffers.get(idx).filter(|b| b.name.is_some())?;
Some(idx)
}
_ => self
.str_text(v)
.and_then(|name| self.find_buffer_by_name(name)),
}
}
pub(crate) fn buffer_slot(&self, v: &Value) -> Option<usize> {
match self.obj(v) {
Some(Obj::Buffer(idx)) if *idx < self.buffers.len() => Some(*idx),
_ => None,
}
}
pub fn get_buffer(&self, v: &Value) -> Result<Option<usize>, String> {
if let Some(idx) = self.buffer_slot(v) {
return Ok(Some(idx));
}
match self.str_text(v) {
Some(name) => Ok(self.find_buffer_by_name(name)),
None => Err(format!(
"wrong-type-argument: stringp {}",
self.print(v, true)
)),
}
}
pub fn nsberror(&self, v: &Value) -> String {
match self.str_text(v) {
Some(name) => format!("error: No buffer named {name}"),
None => "error: Invalid buffer argument".to_string(),
}
}
pub fn find_buffer_by_name(&self, name: &str) -> Option<usize> {
self.buffers
.iter()
.position(|b| b.name.as_deref() == Some(name))
}
fn new_buffer(&mut self, name: String) -> Value {
let idx = self.buffers.len();
let locals = self.initial_slots(&name);
self.buffers.push(EditBuffer {
overlays: Vec::new(),
name: Some(name),
self_obj: Value::Undef,
text: Vec::new(),
props: Vec::new(),
prop_bounds: Vec::new(),
markers: Vec::new(),
point: 1,
begv: 1,
zv: 1,
mark: Value::Undef,
se_markers: Vec::new(),
restrict_stack: Vec::new(),
locals,
local_map: Value::Undef,
mods: ModCounts::default(),
has_intervals: false,
list_order: 0,
inhibit_hooks: false,
});
self.buffer_order_seq += 1;
self.buffers[idx].list_order = self.buffer_order_seq;
let handle = self.alloc(Obj::Buffer(idx));
self.buffers[idx].self_obj = handle.clone();
handle
}
pub fn get_buffer_create(&mut self, name: &str) -> Value {
match self.find_buffer_by_name(name) {
Some(idx) => self.buffers[idx].self_obj.clone(),
None => self.new_buffer(name.to_string()),
}
}
pub fn generate_new_buffer_name(&self, name: &str, ignore: Option<&str>) -> String {
if ignore == Some(name) || self.find_buffer_by_name(name).is_none() {
return name.to_string();
}
let genbase = if !name.starts_with(' ') {
name.to_string()
} else {
let cand = format!("{name}-{}", crate::builtins::rng_next() % 1_000_000);
if self.find_buffer_by_name(&cand).is_none() {
return cand;
}
cand
};
let mut count = 2;
loop {
let cand = format!("{genbase}<{count}>");
if ignore == Some(cand.as_str()) || self.find_buffer_by_name(&cand).is_none() {
return cand;
}
count += 1;
}
}
pub fn set_buffer(&mut self, v: &Value) -> Result<Value, String> {
let idx = self.get_buffer(v)?.ok_or_else(|| self.nsberror(v))?;
if self.buffers[idx].name.is_none() {
return Err("error: Selecting deleted buffer".to_string());
}
self.current = idx;
Ok(self.buffers[idx].self_obj.clone())
}
pub fn kill_buffer(&mut self, v: Option<&Value>) -> Value {
let idx = match v {
Some(v) if el_truthy(v) => match self.resolve_buffer(v) {
Some(i) => i,
None => return Value::Undef,
},
_ => self.current,
};
if self.buffers[idx].name.is_none() {
return Value::Undef;
}
let b = &mut self.buffers[idx];
b.name = None;
b.text.clear();
b.props.clear();
b.prop_bounds.clear();
b.has_intervals = false;
b.locals.clear();
b.se_markers.clear();
b.restrict_stack.clear();
b.point = 1;
b.begv = 1;
b.zv = 1;
for mk in b.markers.drain(..) {
let mut md = mk.borrow_mut();
md.buffer = None;
md.pos = 0;
}
let fallback = |h: &mut Self| match crate::window::other_buffer(h, Some(idx), false) {
Some(b) => b,
None => {
let handle = h.new_buffer("*scratch*".to_string());
h.buffer_slot(&handle).expect("fresh buffer slot")
}
};
if self.windows.iter().any(|w| w.buffer == Some(idx)) {
let replacement = fallback(self);
crate::window::replace_buffer_in_windows(self, idx, replacement);
}
if self.current == idx {
self.current = fallback(self);
}
let f = self.selected_frame;
self.frames[f].buffer_list.retain(|&x| x != idx);
Value::Bool(true)
}
pub fn rename_buffer(&mut self, newname: &str, unique: bool) -> Result<Value, String> {
if newname.is_empty() {
return Err("error: Empty string is invalid as a buffer name".to_string());
}
let mut newname = newname.to_string();
if let Some(other) = self.find_buffer_by_name(&newname) {
if unique {
let ignore = self.buffers[self.current].name.clone();
newname = self.generate_new_buffer_name(&newname, ignore.as_deref());
} else if other == self.current {
return Ok(self.new_string(newname));
} else {
return Err(format!(
"error: Buffer name \u{2018}{newname}\u{2019} is in use"
));
}
}
self.buffers[self.current].name = Some(newname.clone());
Ok(self.new_string(newname))
}
pub fn open_load_buffer(&mut self, src: &str, top_level: bool) -> usize {
let idx = if top_level {
let idx = self.load_buf;
self.buffers[idx].name = Some(" *load*".to_string());
self.buffer_order_seq += 1;
self.buffers[idx].list_order = self.buffer_order_seq;
idx
} else {
let name = self.generate_new_buffer_name(" *load*", None);
let handle = self.get_buffer_create(&name);
self.buffer_slot(&handle).expect("fresh load buffer slot")
};
let text: Vec<char> = src.chars().collect();
let len = text.len();
let b = &mut self.buffers[idx];
b.props = vec![Value::Undef; len];
b.prop_bounds.clear();
b.text = text;
b.point = 1;
b.begv = 1;
b.zv = len + 1;
idx
}
pub fn load_buffer_object(&self) -> Value {
self.buffers[self.load_buf].self_obj.clone()
}
pub fn buffer_object(&self, idx: usize) -> Value {
self.buffers[idx].self_obj.clone()
}
pub fn buffer_order(&self) -> Vec<usize> {
let mut live: Vec<usize> = (0..self.buffers.len())
.filter(|&i| self.buffers[i].name.is_some())
.collect();
live.sort_by_key(|&i| self.buffers[i].list_order);
live
}
pub fn buffer_list(&mut self) -> Value {
let items: Vec<Value> = self
.buffer_order()
.into_iter()
.map(|i| self.buffers[i].self_obj.clone())
.collect();
self.list_from(items)
}
fn adjust_for_insert(&mut self, pos: usize, len: usize) {
let cur = self.current;
for w in self.windows.iter_mut().filter(|w| w.buffer == Some(cur)) {
adj_ins(&mut w.pointm, pos, len, false);
adj_ins(&mut w.old_pointm, pos, len, false);
adj_ins(&mut w.start, pos, len, false);
}
let b = &mut self.buffers[self.current];
adj_ins(&mut b.begv, pos, len, false);
adj_ins(&mut b.zv, pos, len, true);
for m in b.se_markers.iter_mut() {
adj_ins(m, pos, len, false);
}
for (lo, hi) in b.restrict_stack.iter_mut() {
adj_ins(lo, pos, len, false);
adj_ins(hi, pos, len, true);
}
for mk in b.markers.iter() {
let mut md = mk.borrow_mut();
let ins_type = md.insertion_type;
adj_ins(&mut md.pos, pos, len, ins_type);
}
for ov in b.overlays.iter() {
let mut od = ov.borrow_mut();
let (fa, ra) = (od.front_advance, od.rear_advance);
adj_ins(&mut od.start, pos, len, fa);
adj_ins(&mut od.end, pos, len, ra);
}
}
fn adjust_for_delete(&mut self, from: usize, to: usize) {
let cur = self.current;
for w in self.windows.iter_mut().filter(|w| w.buffer == Some(cur)) {
adj_del(&mut w.pointm, from, to);
adj_del(&mut w.old_pointm, from, to);
adj_del(&mut w.start, from, to);
}
let b = &mut self.buffers[self.current];
adj_del(&mut b.point, from, to);
adj_del(&mut b.begv, from, to);
adj_del(&mut b.zv, from, to);
for m in b.se_markers.iter_mut() {
adj_del(m, from, to);
}
for (lo, hi) in b.restrict_stack.iter_mut() {
adj_del(lo, from, to);
adj_del(hi, from, to);
}
for mk in b.markers.iter() {
adj_del(&mut mk.borrow_mut().pos, from, to);
}
for ov in b.overlays.iter() {
let mut od = ov.borrow_mut();
adj_del(&mut od.start, from, to);
adj_del(&mut od.end, from, to);
}
}
pub fn barf_if_read_only(&mut self) -> Result<(), String> {
let set = |h: &Self, name: &str| {
h.find_symbol(name)
.and_then(|s| h.get_value(&s).ok())
.is_some_and(|v| el_truthy(&v))
};
if !set(self, "buffer-read-only") || set(self, "inhibit-read-only") {
return Ok(());
}
let buf = self.current_buffer();
let msg = format!("buffer-read-only: {}", self.print(&buf, true));
let sym = self.intern("buffer-read-only");
let data = self.list_from(vec![buf]);
let obj = self.cons(sym, data);
self.set_pending_error(&msg, obj);
Err(msg)
}
pub fn note_text_change(&mut self, len: usize) {
let m = &mut self.buffers[self.current].mods;
m.incr(len);
m.chars_modiff = m.modiff;
}
pub fn note_prop_change(&mut self, bi: usize) {
self.buffers[bi].mods.incr(1);
}
fn undo_list(&mut self) -> Value {
let sym = self.intern("buffer-undo-list");
self.get_value(&sym).unwrap_or(Value::Undef)
}
fn set_undo_list(&mut self, v: Value) {
let sym = self.intern("buffer-undo-list");
let _ = self.set_value(&sym, v);
}
fn undo_enabled(&mut self) -> bool {
!matches!(self.undo_list(), Value::Bool(true))
}
fn push_undo(&mut self, entry: Value) {
let list = self.undo_list();
let list = self.cons(entry, list);
self.set_undo_list(list);
}
pub(crate) fn record_first_change_if_undo(&mut self) {
if self.undo_enabled() {
self.record_first_change();
}
}
pub(crate) fn record_first_change(&mut self) {
let t = Value::Bool(true);
let entry = self.cons(t, Value::Int(0));
self.push_undo(entry);
}
fn record_point(&mut self, beg: usize) {
let inhibit = self.intern("undo-inhibit-record-point");
if el_truthy(&self.get_value(&inhibit).unwrap_or(Value::Undef)) {
return;
}
let list = self.undo_list();
let at_boundary = match self.obj(&list) {
Some(Obj::Cons(car, _)) => el_nil(car),
_ => true,
};
let m = &self.buffers[self.current].mods;
if m.modiff <= m.save_modiff {
self.record_first_change();
}
if at_boundary
&& self.buffer_before_last_command_or_undo == Some(self.current)
&& self.point_before_last_command_or_undo != Some(beg)
{
if let Some(p) = self.point_before_last_command_or_undo {
self.push_undo(Value::Int(p as i64));
}
}
}
pub fn record_insert(&mut self, beg: usize, len: usize) {
if !self.undo_enabled() {
return;
}
self.record_point(beg);
let list = self.undo_list();
if let Some(Obj::Cons(elt, _)) = self.obj(&list) {
let elt = elt.clone();
if let Some(Obj::Cons(Value::Int(_), Value::Int(end))) = self.obj(&elt) {
if *end == beg as i64 {
if let Value::Obj(id) = elt {
if let Some(Obj::Cons(_, cdr)) = self.arena.get_mut(id as usize) {
*cdr = Value::Int((beg + len) as i64);
}
}
return;
}
}
}
let entry = self.cons(Value::Int(beg as i64), Value::Int((beg + len) as i64));
self.push_undo(entry);
}
fn buffer_string_with_props(&mut self, from: usize, to: usize) -> Value {
let text: String = self.buffers[self.current].text[from - 1..to - 1]
.iter()
.collect();
let plists: Vec<Value> = self.buffers[self.current].props[from - 1..to - 1].to_vec();
let (out, arc) = self.new_string_keyed(text);
if plists.iter().any(el_truthy) {
let plists = self.copy_plist_runs(plists);
self.string_set_props_vec(&arc, plists);
}
out
}
pub fn record_delete(&mut self, from: usize, to: usize, record_markers: bool) {
if !self.undo_enabled() {
return;
}
let string = self.buffer_string_with_props(from, to);
self.record_point(from);
let pt = self.buffers[self.current].point;
let sbeg = if pt == to {
-(from as i64)
} else {
from as i64
};
if record_markers {
let markers: Vec<(Value, usize, bool)> = self.buffers[self.current]
.markers
.iter()
.rev()
.filter_map(|m| {
let md = m.borrow();
(from <= md.pos && md.pos <= to).then(|| (m.clone(), md.pos, md.insertion_type))
})
.filter_map(|(m, pos, itype)| self.marker_object_of(&m).map(|o| (o, pos, itype)))
.collect();
for (marker, pos, itype) in markers {
let adjustment = (if itype { to } else { from }) as i64 - pos as i64;
if adjustment != 0 {
let entry = self.cons(marker, Value::Int(adjustment));
self.push_undo(entry);
}
}
}
let entry = self.cons(string, Value::Int(sbeg));
self.push_undo(entry);
}
pub fn record_change(&mut self, beg: usize, len: usize) {
self.record_delete(beg, beg + len, false);
self.record_insert(beg, len);
}
pub fn record_property_change(
&mut self,
bi: usize,
beg: usize,
len: usize,
prop: Value,
value: Value,
) {
let saved = self.current;
self.current = bi;
if self.undo_enabled() {
let m = &self.buffers[bi].mods;
if m.modiff <= m.save_modiff {
self.record_first_change();
}
let tail = self.cons(Value::Int(beg as i64), Value::Int((beg + len) as i64));
let tail = self.cons(value, tail);
let tail = self.cons(prop, tail);
let entry = self.cons(Value::Undef, tail);
self.push_undo(entry);
}
self.current = saved;
}
pub fn undo_boundary(&mut self) {
if !self.undo_enabled() {
return;
}
let list = self.undo_list();
let head_nil = match self.obj(&list) {
Some(Obj::Cons(car, _)) => el_nil(car),
_ => true,
};
if !head_nil {
let list = self.cons(Value::Undef, list);
self.set_undo_list(list);
}
let cause = self.intern("undo-auto--last-boundary-cause");
let explicit = self.intern("explicit");
let _ = self.set_value(&cause, explicit);
self.point_before_last_command_or_undo = Some(self.buffers[self.current].point);
self.buffer_before_last_command_or_undo = Some(self.current);
}
pub fn cur_insert(&mut self, chars: Vec<char>, leave_after: bool) {
let pos = self.buffers[self.current].point;
let len = chars.len();
if len == 0 {
return;
}
self.record_insert(pos, len);
self.note_text_change(len);
let b = &mut self.buffers[self.current];
b.text.splice((pos - 1)..(pos - 1), chars);
b.props
.splice((pos - 1)..(pos - 1), std::iter::repeat_n(Value::Undef, len));
self.shift_prop_bounds_for_insert(pos - 1, len);
self.adjust_for_insert(pos, len);
self.buffers[self.current].point = if leave_after { pos + len } else { pos };
}
pub fn cur_insert_before_markers(&mut self, chars: Vec<char>) {
let pos = self.buffers[self.current].point;
let len = chars.len();
if len == 0 {
return;
}
self.record_insert(pos, len);
self.note_text_change(len);
let b = &mut self.buffers[self.current];
b.text.splice((pos - 1)..(pos - 1), chars);
b.props
.splice((pos - 1)..(pos - 1), std::iter::repeat_n(Value::Undef, len));
self.shift_prop_bounds_for_insert(pos - 1, len);
self.adjust_for_insert(pos, len);
for mk in self.buffers[self.current].markers.iter() {
let mut md = mk.borrow_mut();
if md.pos == pos {
md.pos = pos + len;
}
}
self.buffers[self.current].point = pos + len;
}
pub fn cur_delete(&mut self, from: usize, to: usize) {
if from >= to {
return;
}
self.record_delete(from, to, true);
self.note_text_change(to - from);
if to - from == self.buffers[self.current].text.len() {
self.buffers[self.current].has_intervals = false;
}
let b = &mut self.buffers[self.current];
b.text.drain((from - 1)..(to - 1));
b.props.drain((from - 1)..(to - 1));
let (lo, hi) = ((from - 1) as u32, (to - 1) as u32);
b.prop_bounds.retain(|&p| p <= lo || p >= hi);
for p in &mut b.prop_bounds {
if *p >= hi {
*p -= hi - lo;
}
}
self.adjust_for_delete(from, to);
}
pub fn narrow(&mut self, beg: usize, end: usize) {
let (lo, hi) = if beg <= end { (beg, end) } else { (end, beg) };
let b = &mut self.buffers[self.current];
let maxzv = b.text.len() + 1;
b.begv = lo.clamp(1, maxzv);
b.zv = hi.clamp(1, maxzv);
b.point = b.point.clamp(b.begv, b.zv);
}
pub fn widen(&mut self) {
let b = &mut self.buffers[self.current];
b.begv = 1;
b.zv = b.text.len() + 1;
}
pub fn mark_marker(&mut self) -> Value {
let cur = self.current;
if !self.is_marker(&self.buffers[cur].mark) {
let m = self.alloc_marker(None, 0, false);
self.buffers[cur].mark = m;
}
self.buffers[cur].mark.clone()
}
pub fn mark_pos(&self) -> Option<usize> {
self.marker_position(&self.buffers[self.current].mark)
}
pub fn alloc_marker(&mut self, buffer: Option<usize>, pos: usize, itype: bool) -> Value {
let md = Rc::new(RefCell::new(MarkerData {
buffer,
pos,
insertion_type: itype,
}));
if let Some(bi) = buffer {
self.buffers[bi].markers.push(md.clone());
}
self.alloc(Obj::Marker(md))
}
fn marker_object_of(&self, m: &Rc<RefCell<MarkerData>>) -> Option<Value> {
self.arena
.iter()
.position(|o| matches!(o, Obj::Marker(x) if Rc::ptr_eq(x, m)))
.map(|i| Value::Obj(i as u32))
}
fn marker_rc(&self, v: &Value) -> Option<Rc<RefCell<MarkerData>>> {
match self.obj(v) {
Some(Obj::Marker(m)) => Some(m.clone()),
_ => None,
}
}
pub fn is_marker(&self, v: &Value) -> bool {
matches!(self.obj(v), Some(Obj::Marker(_)))
}
pub fn marker_position(&self, v: &Value) -> Option<usize> {
let m = self.marker_rc(v)?;
let md = m.borrow();
md.buffer.map(|_| md.pos)
}
pub fn marker_buffer(&self, v: &Value) -> Option<Value> {
let m = self.marker_rc(v)?;
let bi = m.borrow().buffer?;
Some(self.buffers[bi].self_obj.clone())
}
pub fn marker_insertion_type(&self, v: &Value) -> Option<bool> {
Some(self.marker_rc(v)?.borrow().insertion_type)
}
pub fn set_marker_insertion_type(&mut self, v: &Value, itype: bool) {
if let Some(m) = self.marker_rc(v) {
m.borrow_mut().insertion_type = itype;
}
}
pub fn as_position(&self, v: &Value) -> Option<i64> {
match v {
Value::Int(n) => Some(*n),
Value::Float(f) => Some(*f as i64),
_ => self.marker_position(v).map(|p| p as i64),
}
}
pub fn set_marker_to(
&mut self,
marker: &Value,
buffer: Option<usize>,
pos: usize,
) -> Result<(), String> {
let m = self.marker_rc(marker).ok_or("set-marker: not a marker")?;
let old_buf = m.borrow().buffer;
if let Some(ob) = old_buf {
if let Some(b) = self.buffers.get_mut(ob) {
b.markers.retain(|x| !Rc::ptr_eq(x, &m));
}
}
match buffer {
None => {
let mut md = m.borrow_mut();
md.buffer = None;
md.pos = 0;
}
Some(bi) => {
let size = self.buffers[bi].text.len();
let p = pos.clamp(1, size + 1);
{
let mut md = m.borrow_mut();
md.buffer = Some(bi);
md.pos = p;
}
self.buffers[bi].markers.push(m.clone());
}
}
Ok(())
}
pub fn markers_equal(&self, a: &Value, b: &Value) -> bool {
match (self.marker_rc(a), self.marker_rc(b)) {
(Some(x), Some(y)) => {
let (xa, xb) = (x.borrow(), y.borrow());
xa.buffer == xb.buffer && xa.pos == xb.pos
}
_ => false,
}
}
pub fn plist_get_eq(&self, plist: &Value, prop: &Value) -> Value {
let mut cur = plist.clone();
while let Some(Obj::Cons(k, d)) = self.obj(&cur) {
let k = k.clone();
let rest = d.clone();
let (val, rest2) = match self.obj(&rest) {
Some(Obj::Cons(v, d2)) => (v.clone(), d2.clone()),
_ => return Value::Undef,
};
if self.values_eq(&k, prop) {
return val;
}
cur = rest2;
}
Value::Undef
}
pub fn buffer_plist_at(&self, idx0: usize) -> Value {
self.cur_buf_ref()
.props
.get(idx0)
.cloned()
.unwrap_or(Value::Undef)
}
pub fn buffer_set_plist_at(&mut self, idx0: usize, plist: Value) {
if el_truthy(&plist) {
self.buffers[self.current].has_intervals = true;
}
if let Some(slot) = self.buffers[self.current].props.get_mut(idx0) {
*slot = plist;
}
}
pub fn buffer_plist_at_idx(&self, bi: usize, idx0: usize) -> Value {
self.buffers[bi]
.props
.get(idx0)
.cloned()
.unwrap_or(Value::Undef)
}
pub fn buffer_begv_zv(&self, bi: usize) -> (usize, usize) {
let b = &self.buffers[bi];
(b.begv, b.zv)
}
fn shift_prop_bounds_for_insert(&mut self, at: usize, len: usize) {
let has = self.buffers[self.current].has_intervals;
let b = &mut self.buffers[self.current];
for p in &mut b.prop_bounds {
if *p as usize > at {
*p += len as u32;
}
}
if has {
let total = b.props.len();
for edge in [at, at + len] {
if edge > 0 && edge < total {
let e = edge as u32;
if let Err(i) = b.prop_bounds.binary_search(&e) {
b.prop_bounds.insert(i, e);
}
}
}
}
}
pub(crate) fn buffer_tp<T>(
&mut self,
bi: usize,
f: impl FnOnce(&mut Self, &mut Vec<Value>, &mut Vec<u32>) -> T,
) -> T {
let mut props = std::mem::take(&mut self.buffers[bi].props);
let mut bounds = std::mem::take(&mut self.buffers[bi].prop_bounds);
let r = f(self, &mut props, &mut bounds);
self.buffers[bi].props = props;
self.buffers[bi].prop_bounds = bounds;
r
}
pub fn buffer_add_props(
&mut self,
s0: usize,
e0: usize,
pairs: &[(Value, Value)],
set_type: crate::textprop::SetType,
) -> bool {
let bi = self.current;
self.buffers[bi].has_intervals |= s0 < e0;
self.buffer_tp(bi, |h, props, bounds| {
let end = e0.min(props.len());
h.tp_add(props, bounds, s0, end, pairs, set_type)
})
}
pub fn buffer_put_prop(&mut self, s0: usize, e0: usize, prop: &Value, val: &Value) {
self.buffer_add_props(
s0,
e0,
&[(prop.clone(), val.clone())],
crate::textprop::SetType::Replace,
);
}
pub fn buffer_set_props(&mut self, s0: usize, e0: usize, plist: &Value) {
let bi = self.current;
self.buffers[bi].has_intervals |= s0 < e0;
self.buffer_tp(bi, |h, props, bounds| {
let end = e0.min(props.len());
h.tp_set(props, bounds, s0, end, plist);
});
}
pub fn buffer_remove_props(&mut self, s0: usize, e0: usize, names: &[Value]) -> bool {
let bi = self.current;
self.buffer_tp(bi, |h, props, bounds| {
let end = e0.min(props.len());
h.tp_remove(props, bounds, s0, end, names)
})
}
pub fn buffer_remove_prop(&mut self, s0: usize, e0: usize, prop: &Value) {
self.buffer_remove_props(s0, e0, std::slice::from_ref(prop));
}
pub fn string_props_vec(&self, s: &Arc<String>) -> Option<Vec<Value>> {
let key = Arc::as_ptr(s) as usize;
let (weak, props, _) = self.string_props.get(&key)?;
weak.upgrade().filter(|a| Arc::as_ptr(a) as usize == key)?;
Some(props.clone())
}
pub fn string_bounds_vec(&self, s: &Arc<String>) -> Vec<u32> {
let key = Arc::as_ptr(s) as usize;
match self.string_props.get(&key) {
Some((weak, _, bounds))
if weak
.upgrade()
.is_some_and(|a| Arc::as_ptr(&a) as usize == key) =>
{
bounds.clone()
}
_ => Vec::new(),
}
}
pub fn string_intervals(&self, s: &Arc<String>) -> Vec<(usize, usize, Value)> {
let Some(props) = self.string_props_vec(s) else {
return Vec::new();
};
let bounds = self.string_bounds_vec(s);
self.tp_runs(&props, &bounds)
.into_iter()
.map(|(a, b)| (a, b, props[a].clone()))
.collect()
}
pub fn string_plist_at(&self, s: &Arc<String>, idx0: usize) -> Value {
self.string_props_vec(s)
.and_then(|v| v.get(idx0).cloned())
.unwrap_or(Value::Undef)
}
pub fn string_clear_props(&mut self, s: &Arc<String>) {
self.string_props.remove(&(Arc::as_ptr(s) as usize));
}
pub fn string_set_props_vec(&mut self, s: &Arc<String>, vec: Vec<Value>) {
let key = Arc::as_ptr(s) as usize;
self.string_props
.insert(key, (Arc::downgrade(s), vec, Vec::new()));
}
pub fn string_set_props_bounded(&mut self, s: &Arc<String>, vec: Vec<Value>, bounds: Vec<u32>) {
let key = Arc::as_ptr(s) as usize;
self.string_props
.insert(key, (Arc::downgrade(s), vec, bounds));
}
fn string_props_or_new(&self, s: &Arc<String>) -> Vec<Value> {
self.string_props_vec(s)
.unwrap_or_else(|| vec![Value::Undef; s.chars().count()])
}
pub fn copy_plist_runs(&mut self, plists: Vec<Value>) -> Vec<Value> {
let mut out: Vec<Value> = Vec::with_capacity(plists.len());
for (i, p) in plists.iter().enumerate() {
if !el_truthy(p) {
out.push(Value::Undef);
} else if i > 0 && self.values_eq(&plists[i - 1], p) {
out.push(out[i - 1].clone());
} else {
let items = self.list_vec(p).unwrap_or_default();
out.push(self.list_from(items));
}
}
out
}
pub fn string_carry_props(
&mut self,
out: &Arc<String>,
pieces: &[(Option<Arc<String>>, usize, usize)],
) {
self.string_carry_props_ordered(out, pieces, false);
}
pub fn string_copy_props(
&mut self,
out: &Arc<String>,
pieces: &[(Option<Arc<String>>, usize, usize)],
) {
self.string_carry_props_ordered(out, pieces, true);
}
fn string_carry_props_ordered(
&mut self,
out: &Arc<String>,
pieces: &[(Option<Arc<String>>, usize, usize)],
reverse_pairs: bool,
) {
let total: usize = pieces.iter().map(|p| p.2).sum();
let mut vec: Vec<Value> = vec![Value::Undef; total];
let mut bounds: Vec<u32> = Vec::new();
let mut any = false;
let mut at = 0;
for (src, start, len) in pieces {
if let Some(s) = src {
if let Some(props) = self.string_props_vec(s) {
let sb = self.string_bounds_vec(s);
for (rs, re) in self.tp_runs(&props, &sb) {
if re <= *start || rs >= start + len || !el_truthy(&props[rs]) {
continue;
}
any = true;
let mut items = self.list_vec(&props[rs]).unwrap_or_default();
if reverse_pairs {
items = items.chunks(2).rev().flatten().cloned().collect();
}
let copy = self.list_from(items);
let a = rs.max(*start) - start + at;
let b = re.min(start + len) - start + at;
for slot in &mut vec[a..b] {
*slot = copy.clone();
}
}
self.tp_clip(&props, &sb, (*start, *len, at, total), &mut bounds);
}
}
at += len;
}
if any {
self.string_set_props_bounded(out, vec, bounds);
}
}
pub fn string_carry_all(&mut self, out: &Arc<String>, src: &Arc<String>) {
let len = src.chars().count();
self.string_carry_props(out, &[(Some(Arc::clone(src)), 0, len)]);
}
pub fn string_put_prop(
&mut self,
s: &Arc<String>,
s0: usize,
e0: usize,
prop: &Value,
val: &Value,
) {
self.string_add_props(
s,
s0,
e0,
&[(prop.clone(), val.clone())],
crate::textprop::SetType::Replace,
);
}
pub fn string_add_props(
&mut self,
s: &Arc<String>,
s0: usize,
e0: usize,
pairs: &[(Value, Value)],
set_type: crate::textprop::SetType,
) -> bool {
let mut vec = self.string_props_or_new(s);
let mut bounds = self.string_bounds_vec(s);
let end = e0.min(vec.len());
let changed = self.tp_add(&mut vec, &mut bounds, s0, end, pairs, set_type);
self.string_set_props_bounded(s, vec, bounds);
changed
}
pub fn string_set_props(&mut self, s: &Arc<String>, s0: usize, e0: usize, plist: &Value) {
let len = s.chars().count();
if !el_truthy(plist) && s0 == 0 && e0 >= len {
self.string_clear_props(s);
return;
}
let mut vec = self.string_props_or_new(s);
let mut bounds = self.string_bounds_vec(s);
let end = e0.min(vec.len());
self.tp_set(&mut vec, &mut bounds, s0, end, plist);
self.string_set_props_bounded(s, vec, bounds);
}
pub fn string_remove_props(
&mut self,
s: &Arc<String>,
s0: usize,
e0: usize,
names: &[Value],
) -> bool {
let Some(mut vec) = self.string_props_vec(s) else {
return false;
};
let mut bounds = self.string_bounds_vec(s);
let end = e0.min(vec.len());
let changed = self.tp_remove(&mut vec, &mut bounds, s0, end, names);
self.string_set_props_bounded(s, vec, bounds);
changed
}
pub fn string_remove_prop(&mut self, s: &Arc<String>, s0: usize, e0: usize, prop: &Value) {
self.string_remove_props(s, s0, e0, std::slice::from_ref(prop));
}
fn merge_val_eq(&self, a: &Value, b: &Value) -> bool {
match (self.str_text(a), self.str_text(b)) {
(Some(x), Some(y)) => x == y,
_ => self.values_eq(a, b),
}
}
fn plist_subset(&self, a: &Value, b: &Value) -> bool {
let mut cur = a.clone();
while let Some(Obj::Cons(k, d)) = self.obj(&cur) {
let k = k.clone();
let (v, rest2) = match self.obj(d) {
Some(Obj::Cons(v, d2)) => (v.clone(), d2.clone()),
_ => break,
};
let bv = self.plist_get_eq(b, &k);
if !self.merge_val_eq(&bv, &v) {
return false;
}
cur = rest2;
}
true
}
pub(crate) fn plist_struct_eq(&self, a: &Value, b: &Value) -> bool {
if el_truthy(a) != el_truthy(b) {
return false;
}
self.plist_subset(a, b) && self.plist_subset(b, a)
}
fn string_prop_intervals(&self, s: &Arc<String>, depth: usize) -> String {
let mut out = String::new();
for (i, j, plist) in self.string_intervals(s) {
if el_truthy(&plist) {
out.push_str(&format!(
" {} {} {}",
i,
j,
self.print_inner(&plist, true, depth + 1)
));
}
}
out
}
pub fn char_table_ref(&self, ct: &Value, c: u32) -> Value {
let mut cur = ct.clone();
loop {
let Some(Obj::CharTable(t)) = self.obj(&cur) else {
return Value::Undef;
};
let v = t.raw_get(c);
if el_truthy(&v) {
return v;
}
if el_truthy(&t.default) {
return t.default.clone();
}
if matches!(self.obj(&t.parent), Some(Obj::CharTable(_))) {
cur = t.parent.clone();
} else {
return Value::Undef;
}
}
}
const SYNTAX_CODE_SPEC: &'static [u8] = b" .w_()'\"$\\/<>@!|";
fn current_syntax_table(&self) -> Value {
let local = self
.find_symbol("--current-syntax-table--")
.and_then(|s| self.get_value(&s).ok());
match local {
Some(v) if el_truthy(&v) => v,
_ => self
.find_symbol("--standard-syntax-table--")
.and_then(|s| self.get_value(&s).ok())
.unwrap_or(Value::Undef),
}
}
pub fn syntax_class_of(&self, c: char) -> char {
self.syntax_class_in(&self.current_syntax_table(), c as u32)
}
fn syntax_class_in(&self, table: &Value, c: u32) -> char {
let v = self.char_table_ref(table, c);
let code = match self.obj(&v) {
Some(Obj::Cons(Value::Int(n), _)) => (*n as u64 & 0xFFFF) as usize,
_ => 0,
};
*Self::SYNTAX_CODE_SPEC.get(code).unwrap_or(&b' ') as char
}
pub fn syntax_fingerprint(&self) -> u64 {
use std::hash::{Hash, Hasher};
let code_of = |v: &Value| match self.obj(v) {
Some(Obj::Cons(Value::Int(n), m)) => (*n, if let Value::Int(m) = m { *m } else { -1 }),
_ => (-1, -1),
};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
let mut cur = self.current_syntax_table();
for _ in 0..64 {
let Some(Obj::CharTable(t)) = self.obj(&cur) else {
break;
};
if let Value::Obj(id) = cur {
id.hash(&mut hasher);
}
code_of(&t.default).hash(&mut hasher);
for (start, v) in t.runs() {
start.hash(&mut hasher);
code_of(&v).hash(&mut hasher);
}
cur = t.parent.clone();
}
hasher.finish()
}
pub fn syntax_class_ranges(&self, class: char) -> Vec<(u32, u32)> {
let table = self.current_syntax_table();
let mut breaks: Vec<u32> = vec![0];
let mut cur = table.clone();
for _ in 0..64 {
let Some(Obj::CharTable(t)) = self.obj(&cur) else {
break;
};
breaks.extend(t.runs().iter().map(|(s, _)| *s));
cur = t.parent.clone();
}
breaks.sort_unstable();
breaks.dedup();
let class_at = |c: u32| self.syntax_class_in(&table, c);
let mut out: Vec<(u32, u32)> = Vec::new();
for (i, &lo) in breaks.iter().enumerate() {
let hi = breaks.get(i + 1).map_or(MAX_CHAR, |n| n - 1);
if class_at(lo) != class {
continue;
}
match out.last_mut() {
Some(last) if last.1 + 1 == lo => last.1 = hi,
_ => out.push((lo, hi)),
}
}
out
}
fn current_category_table(&self) -> Value {
let local = self
.find_symbol("--current-category-table--")
.and_then(|s| self.get_value(&s).ok());
match local {
Some(v) if el_truthy(&v) => v,
_ => self
.find_symbol("--standard-category-table--")
.and_then(|s| self.get_value(&s).ok())
.unwrap_or(Value::Undef),
}
}
fn category_member(&self, set: &Value, category: u8) -> bool {
matches!(self.obj(set), Some(Obj::BoolVector(bits))
if bits.get(category as usize).copied().unwrap_or(false))
}
pub fn category_ranges(&self, category: u8) -> Vec<(u32, u32)> {
let table = self.current_category_table();
let Some(Obj::CharTable(t)) = self.obj(&table) else {
return Vec::new();
};
let runs = t.runs();
let mut out: Vec<(u32, u32)> = Vec::new();
for (i, (lo, val)) in runs.iter().enumerate() {
let hi = runs.get(i + 1).map_or(MAX_CHAR, |(n, _)| n - 1);
let set = if el_truthy(val) { val } else { &t.default };
if !self.category_member(set, category) {
continue;
}
match out.last_mut() {
Some(last) if last.1 + 1 == *lo => last.1 = hi,
_ => out.push((*lo, hi)),
}
}
out
}
pub fn category_fingerprint(&self) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
let table = self.current_category_table();
if let Value::Obj(id) = table {
id.hash(&mut hasher);
}
let bits_of = |v: &Value| match self.obj(v) {
Some(Obj::BoolVector(bits)) => bits.clone(),
_ => Vec::new(),
};
if let Some(Obj::CharTable(t)) = self.obj(&table) {
bits_of(&t.default).hash(&mut hasher);
for (start, v) in t.runs() {
start.hash(&mut hasher);
bits_of(&v).hash(&mut hasher);
}
}
hasher.finish()
}
pub fn values_eq(&self, a: &Value, b: &Value) -> bool {
if !el_truthy(a) && !el_truthy(b) {
return true;
}
match (a, b) {
(Value::Int(x), Value::Int(y)) => x == y,
(Value::Float(x), Value::Float(y)) => x.to_bits() == y.to_bits(),
(Value::Obj(x), Value::Obj(y)) => x == y,
(Value::Bool(true), Value::Bool(true)) => true,
_ => false,
}
}
pub fn take_lex(&mut self) -> Lex {
self.lex.take()
}
pub fn restore_lex(&mut self, lex: Lex) {
self.lex = lex;
}
pub fn export_oclosure_meta(&self) -> Vec<(u32, u32, Vec<u32>)> {
self.oclosure_meta
.iter()
.map(|(id, m)| (*id, m.ty, m.slots.clone()))
.collect()
}
pub fn import_oclosure_meta(&mut self, meta: Vec<(u32, u32, Vec<u32>)>) {
for (id, ty, slots) in meta {
self.oclosure_meta.insert(id, OClosureMeta { ty, slots });
}
}
pub fn seq_vec_checked(&mut self, v: &Value) -> Result<Vec<Value>, String> {
if matches!(self.obj(v), Some(Obj::Cons(..))) {
let mut out = Vec::new();
let mut w = crate::builtins::TailWalk::new(v);
while let Some((car, cdr)) = w.cons(self) {
out.push(car);
if w.step(cdr) {
let tail = w.tail.clone();
return Err(self.signal_circular_list(&tail));
}
}
if !el_nil(&w.tail) {
return Err(format!(
"wrong-type-argument: listp {}",
self.print(&w.tail, true)
));
}
return Ok(out);
}
if let Some(items) = self.seq_vec(v) {
return Ok(items);
}
Err(format!(
"wrong-type-argument: sequencep {}",
self.print(v, true)
))
}
fn is_macro_cell(&self, cell: &Value) -> bool {
match self.obj(cell) {
Some(Obj::Closure { is_macro, .. }) => *is_macro,
Some(Obj::Cons(car, _)) => self.sym_name(car).as_deref() == Some("macro"),
_ => false,
}
}
pub fn function_designator(&mut self, f: &Value) -> Value {
let mut cur = f.clone();
for _ in 0..16 {
match self.obj(&cur) {
Some(Obj::Symbol(s)) => match s.function.clone() {
Some(_) if self.indirect_autoload(&cur).is_some() => return cur,
Some(next) if self.is_macro_cell(&next) => return f.clone(),
Some(next) => cur = next,
None => return cur,
},
_ => return cur,
}
}
cur
}
pub fn signal_macro_wrong_nargs(
&mut self,
macro_obj: &Value,
params: &Params,
argc: usize,
) -> String {
let prelude = self.is_prelude_object(macro_obj);
let fun = match self.obj(macro_obj) {
Some(Obj::Closure {
params,
body,
env,
dynamic,
src,
..
}) => {
let c = Obj::Closure {
params: params.clone(),
body: body.clone(),
is_macro: false,
env: env.clone(),
dynamic: *dynamic,
src: src.clone(),
};
if prelude {
macro_obj.clone()
} else {
self.alloc(c)
}
}
_ => macro_obj.clone(),
};
let subject = if prelude {
let mandatory = params.required.len() as i64;
let nonrest = mandatory + params.optional.len() as i64;
self.cons(Value::Int(mandatory), Value::Int(nonrest))
} else {
fun
};
let sym = self.intern("wrong-number-of-arguments");
let data = self.list_from(vec![subject.clone(), Value::Int(argc as i64)]);
let msg = format!(
"wrong-number-of-arguments: {} {argc}",
self.print(&subject, true)
);
let obj = self.cons(sym, data);
self.set_pending_error(&msg, obj);
msg
}
pub fn signal_intrinsic_macro_wrong_nargs(&mut self) -> String {
let sym = self.intern("wrong-number-of-arguments");
let template = self.cons(Value::Int(1), Value::Int(1));
let data = self.list_from(vec![template, Value::Int(0)]);
let obj = self.cons(sym, data);
let msg = "wrong-number-of-arguments: (1 . 1) 0".to_string();
self.set_pending_error(&msg, obj);
msg
}
pub fn signal_closure_wrong_nargs(
&mut self,
callee: &Value,
object: &Value,
argc: usize,
) -> String {
if self.is_prelude_object(object) {
let named_subr = self
.sym_name(callee)
.is_some_and(|n| PRELUDE_C_SUBR_NAMES.binary_search(&n.as_str()).is_ok());
if named_subr {
return self.signal_wrong_nargs_subject(callee.clone(), argc);
}
if let Some(Obj::Closure { params, .. }) = self.obj(object) {
let mandatory = params.required.len() as i64;
let nonrest = mandatory + params.optional.len() as i64;
let template = self.cons(Value::Int(mandatory), Value::Int(nonrest));
return self.signal_wrong_nargs_subject(template, argc);
}
}
self.signal_wrong_nargs(object, argc)
}
pub fn signal_wrong_nargs_subject(&mut self, subject: Value, argc: usize) -> String {
let sym = self.intern("wrong-number-of-arguments");
let data = self.list_from(vec![subject.clone(), Value::Int(argc as i64)]);
let display = format!("{} {}", self.print(&subject, true), argc);
let obj = self.cons(sym, data);
let msg = format!("wrong-number-of-arguments: {display}");
self.set_pending_error(&msg, obj);
msg
}
pub fn signal_wrong_nargs(&mut self, callee: &Value, argc: usize) -> String {
let sym = self.intern("wrong-number-of-arguments");
let count = Value::Int(argc as i64);
let subject = match self.byte_compiled_arity_template(callee) {
Some((mandatory, nonrest)) => {
self.cons(Value::Int(mandatory as i64), Value::Int(nonrest as i64))
}
None => callee.clone(),
};
let data = self.list_from(vec![subject.clone(), count]);
let display = format!("{} {}", self.print(&subject, true), argc);
let obj = self.cons(sym, data);
let msg = format!("wrong-number-of-arguments: {display}");
self.set_pending_error(&msg, obj);
msg
}
fn byte_compiled_arity_template(&self, callee: &Value) -> Option<(u16, u16)> {
let mut cur = callee.clone();
for _ in 0..64 {
match self.obj(&cur) {
Some(Obj::Subr { name, .. }) => return lisp_level_arity(name),
Some(Obj::Symbol(s)) => cur = s.function.clone()?,
_ => return None,
}
}
None
}
pub fn signal_circular_list(&mut self, list: &Value) -> String {
let sym = self.intern("circular-list");
let data = self.list_from(vec![list.clone()]);
let obj = self.cons(sym, data);
let msg = "circular-list: circular list".to_string();
self.set_pending_error(&msg, obj);
msg
}
pub fn signal_wrong_type(&mut self, pred: &str, value: &Value) -> String {
let msg = format!("wrong-type-argument: {pred} {}", self.print(value, true));
let sym = self.intern("wrong-type-argument");
let p = self.intern(pred);
let data = self.list_from(vec![p, value.clone()]);
let obj = self.cons(sym, data);
self.set_pending_error(&msg, obj);
msg
}
pub fn signal_error_with(&mut self, message: &str, datum: &Value) -> String {
let msg = format!("error: {message} {}", self.print(datum, true));
let sym = self.intern("error");
let m = self.new_string(message);
let data = self.list_from(vec![m, datum.clone()]);
let obj = self.cons(sym, data);
self.set_pending_error(&msg, obj);
msg
}
pub fn signal_error_arg(&mut self, message: &str, arg: &Value) -> String {
let msg = format!("error: {message} {}", self.print(arg, true));
let sym = self.intern("error");
let m = self.new_string(message);
let mut items = vec![m];
match self.list_vec(arg) {
Some(tail) => items.extend(tail),
None => items.push(arg.clone()),
}
let data = self.list_from(items);
let obj = self.cons(sym, data);
self.set_pending_error(&msg, obj);
msg
}
pub fn set_pending_error(&mut self, msg: &str, obj: Value) {
self.pending_error = Some((msg.to_string(), obj));
}
pub fn take_pending_error(&mut self, msg: &str) -> Option<Value> {
match &self.pending_error {
Some((m, _)) if m == msg => self.pending_error.take().map(|(_, v)| v),
_ => None,
}
}
pub fn make_error_object(&mut self, e: &str) -> Value {
const NIL_DATA_ERRORS: &[&str] = &[
"arith-error",
"overflow-error",
"end-of-file",
"beginning-of-buffer",
"end-of-buffer",
];
let trimmed = e.trim();
let sym_candidate = trimmed.split_once(':').map_or(trimmed, |(s, _)| s.trim());
if NIL_DATA_ERRORS.contains(&sym_candidate) {
let s = self.intern(sym_candidate);
return self.list_from(vec![s]);
}
let (sym, msg) = match e.split_once(':') {
Some((s, m)) => (s.trim().to_string(), m.trim().to_string()),
None => ("error".to_string(), e.to_string()),
};
if matches!(
sym.as_str(),
"wrong-type-argument"
| "args-out-of-range"
| "void-variable"
| "void-function"
| "wrong-number-of-arguments"
| "wrong-length-argument"
| "invalid-function"
| "excessive-lisp-nesting"
| "setting-constant"
| "cl-assertion-failed"
| "cyclic-variable-indirection"
) {
if let Some(data) = self.read_all_forms(&msg) {
let s = self.intern(&sym);
return self.cons(s, data);
}
}
let s = self.intern(&sym);
let m = self.new_string(msg);
self.list_from(vec![s, m])
}
fn read_all_forms(&mut self, src: &str) -> Option<Value> {
let len = src.chars().count();
let mut forms = Vec::new();
let mut pos = 0;
while pos < len {
match crate::reader::read_one(self, src, pos) {
Ok((v, next)) if next > pos => {
forms.push(v);
pos = next;
}
_ => break,
}
}
if forms.is_empty() {
None
} else {
Some(self.list_from(forms))
}
}
}
fn parse_float_output_format(spec: &str) -> Option<(Option<usize>, char)> {
let rest = spec.strip_prefix("%.")?;
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
let conv_rest = &rest[digits.len()..];
let mut it = conv_rest.chars();
let conv = it.next()?;
if !matches!(conv, 'e' | 'f' | 'g') || it.next().is_some() {
return None;
}
if digits.is_empty() {
return Some((None, conv));
}
let prec: usize = digits.parse().ok().filter(|&p| p <= 15)?;
if prec == 0 && conv != 'f' {
return None;
}
Some((Some(prec), conv))
}
pub fn format_float(f: f64) -> String {
let start = if f != 0.0 && f.abs() < f64::MIN_POSITIVE {
1
} else {
15
};
for prec in start..=17 {
let s = format_g(f, prec);
if s.parse::<f64>() == Ok(f) {
return ensure_float_syntax(s);
}
}
ensure_float_syntax(format_g(f, 17))
}
fn format_g(x: f64, prec: usize) -> String {
let prec = prec.max(1);
let e_form = format!("{:.*e}", prec - 1, x);
let (mantissa, exp_str) = e_form.rsplit_once('e').unwrap_or((e_form.as_str(), "0"));
let exp: i32 = exp_str.parse().unwrap_or(0);
if exp < -4 || exp >= prec as i32 {
let sign = if exp < 0 { '-' } else { '+' };
format!("{}e{}{:02}", trim_zeros(mantissa), sign, exp.abs())
} else {
let decimals = (prec as i32 - 1 - exp).max(0) as usize;
trim_zeros(&format!("{x:.decimals$}"))
}
}
fn trim_zeros(s: &str) -> String {
if !s.contains('.') {
return s.to_string();
}
let t = s.trim_end_matches('0');
t.strip_suffix('.').unwrap_or(t).to_string()
}
fn ensure_float_syntax(s: String) -> String {
if s.contains('.') || s.contains('e') || s.contains("INF") || s.contains("NaN") {
s
} else {
format!("{s}.0")
}
}
pub fn el_nil(v: &Value) -> bool {
matches!(v, Value::Undef | Value::Bool(false))
}
pub fn el_truthy(v: &Value) -> bool {
!el_nil(v)
}
fn print_symbol_readable(name: &str) -> String {
if name.is_empty() {
return "##".to_string();
}
let numeric = crate::reader::token_is_number(name);
let all_dots = name.chars().all(|c| c == '.');
let mut out = String::new();
for (i, c) in name.chars().enumerate() {
let needs_escape = matches!(
c,
'"' | '\\' | '\'' | ';' | '#' | '(' | ')' | ',' | '`' | '[' | ']'
) || (c as u32) <= 0x20
|| (i == 0 && (numeric || c == '?' || (c == '.' && all_dots)));
if needs_escape {
out.push('\\');
}
out.push(c);
}
out
}
thread_local! {
static HOST: RefCell<ElispHost> = RefCell::new(ElispHost::new());
static PRELUDE_LOADED: Cell<bool> = const { Cell::new(false) };
static PRELUDE_COMPILING: Cell<bool> = const { Cell::new(false) };
static DEBUG_MODE: Cell<bool> = const { Cell::new(false) };
static PRELUDE_SNAPSHOT: RefCell<Option<ElispHost>> = const { RefCell::new(None) };
static PRELUDE_SNAPSHOT_ON: Cell<bool> = const { Cell::new(true) };
}
pub fn set_prelude_snapshot_enabled(on: bool) {
PRELUDE_SNAPSHOT_ON.with(|c| c.set(on));
if !on {
PRELUDE_SNAPSHOT.with(|s| *s.borrow_mut() = None);
}
}
pub fn restore_prelude_snapshot() -> bool {
if !PRELUDE_SNAPSHOT_ON.with(|c| c.get()) {
return false;
}
let Some(snap) = PRELUDE_SNAPSHOT.with(|s| s.borrow().clone()) else {
return false;
};
HOST.with(|h| *h.borrow_mut() = snap);
PRELUDE_LOADED.with(|c| c.set(true));
true
}
pub fn save_prelude_snapshot() {
if !PRELUDE_SNAPSHOT_ON.with(|c| c.get()) {
return;
}
let copy = HOST.with(|h| h.borrow().clone());
PRELUDE_SNAPSHOT.with(|s| *s.borrow_mut() = Some(copy));
}
pub fn set_debug_mode(on: bool) {
DEBUG_MODE.with(|d| d.set(on));
}
pub fn debug_mode() -> bool {
DEBUG_MODE.with(|d| d.get())
}
pub fn with_host<R>(f: impl FnOnce(&mut ElispHost) -> R) -> R {
HOST.with(|h| f(&mut h.borrow_mut()))
}
pub fn reset_host() {
HOST.with(|h| *h.borrow_mut() = ElispHost::new());
PRELUDE_LOADED.with(|c| c.set(false));
PRELUDE_COMPILING.with(|c| c.set(false));
clear_vm_pool();
crate::builtins::clear_regexp_cache();
}
pub fn prelude_loaded() -> bool {
PRELUDE_LOADED.with(|c| c.get())
}
pub fn set_prelude_loaded(b: bool) {
PRELUDE_LOADED.with(|c| c.set(b));
}
pub fn prelude_compiling() -> bool {
PRELUDE_COMPILING.with(|c| c.get())
}
pub fn set_prelude_compiling(b: bool) {
PRELUDE_COMPILING.with(|c| c.set(b));
}
fn kill_emacs(args: &[Value]) -> Result<Value, String> {
for f in hook_functions("kill-emacs-hook")? {
if let Err(e) = call_function(&f, &[]) {
let report = with_host(|h| {
let obj = h
.take_pending_error(&e)
.unwrap_or_else(|| h.make_error_object(&e));
let (f, obj) = (h.print(&f, true), h.print(&obj, true));
format!("Error in kill-emacs-hook ({f}): {obj}")
});
eprintln!("{report}");
}
}
let code = match args.first() {
Some(Value::Int(n)) => (*n & 0xff) as i32,
_ => 0,
};
if with_host(|h| h.capture.is_some()) {
std::panic::resume_unwind(Box::new(crate::embed::ExitNow(code)));
}
use std::io::Write;
let _ = std::io::stdout().flush();
std::process::exit(code);
}
fn hook_functions(hook: &str) -> Result<Vec<Value>, String> {
let (boundp, symbol_value, functionp, sym) = with_host(|h| {
(
h.intern("boundp"),
h.intern("symbol-value"),
h.intern("functionp"),
h.intern(hook),
)
});
if el_nil(&call_function(&boundp, std::slice::from_ref(&sym))?) {
return Ok(Vec::new());
}
let value = call_function(&symbol_value, &[sym])?;
if el_nil(&value) {
return Ok(Vec::new());
}
if el_truthy(&call_function(&functionp, std::slice::from_ref(&value))?) {
return Ok(vec![value]);
}
let fns = with_host(|h| h.list_vec(&value)).unwrap_or_default();
Ok(fns
.into_iter()
.filter(|f| !matches!(f, Value::Bool(true)))
.collect())
}
fn is_void_function_head(h: &ElispHost, head: &Value) -> bool {
if h.special_form_object(head).is_some() {
return false;
}
match h.sym_name(head).as_deref() {
Some(
"--catch--" | "--unwind--" | "--condition-case--" | "intercept-proceed"
| "__rust-compile",
) => false,
Some(name) => !fusevm::ffi::is_registered(name),
None => true,
}
}
fn intrinsic_wrong_nargs(f: &Value, argc: usize) -> String {
with_host(|h| h.signal_wrong_nargs(f, argc))
}
const FILE_NAME_ARGS: &[(&str, &[usize])] = &[
("insert-file-contents", &[0]),
("write-region", &[2]),
("delete-file-internal", &[0]),
("delete-directory-internal", &[0]),
("make-directory-internal", &[0]),
("rename-file", &[0, 1]),
("copy-file", &[0, 1]),
("--directory-files--", &[0]),
("file-exists-p", &[0]),
("file-directory-p", &[0]),
("file-regular-p", &[0]),
("file-readable-p", &[0]),
("file-writable-p", &[0]),
("file-executable-p", &[0]),
("file-symlink-p", &[0]),
("file-attributes", &[0]),
("file-modes", &[0]),
("set-file-modes", &[0]),
("file-newer-than-file-p", &[0, 1]),
("file-accessible-directory-p", &[0]),
("make-symbolic-link", &[1]),
("add-name-to-file", &[0, 1]),
];
fn expand_file_name_args(f: &Value, args: &[Value]) -> Result<Option<Vec<Value>>, String> {
let positions = with_host(|h| {
let name = match h.obj(f) {
Some(Obj::Symbol(s)) => s.name.as_str(),
Some(Obj::Subr { name, .. }) => name.as_str(),
_ => return None,
};
let (listed, positions) = FILE_NAME_ARGS.iter().find(|(n, _)| *n == name)?;
match h.resolve_function(f) {
Ok(Resolved::Subr { name, .. }) if name == *listed => Some(*positions),
_ => None,
}
});
let Some(positions) = positions else {
return Ok(None);
};
let expand = with_host(|h| h.intern("expand-file-name"));
let mut out = args.to_vec();
for &i in positions {
if out.get(i).is_some_and(|v| with_host(|h| h.is_string(v))) {
out[i] = call_function(&expand, &out[i..=i])?;
}
}
Ok(Some(out))
}
pub fn call_function(f: &Value, args: &[Value]) -> Result<Value, String> {
let expanded_args;
let args = match expand_file_name_args(f, args)? {
Some(v) => {
expanded_args = v;
&expanded_args[..]
}
None => args,
};
if let Some(subr) = with_host(|h| h.special_form_object(f)) {
return Err(with_host(|h| h.signal_invalid_function(&subr)));
}
if let Some(name) = with_host(|h| {
h.sym_name(f).or_else(|| match h.obj(f) {
Some(Obj::Subr { name, .. }) => Some(name.clone()),
_ => None,
})
}) {
match name.as_str() {
"kill-emacs" => return kill_emacs(args),
"funcall" => {
if args.is_empty() {
return Err(intrinsic_wrong_nargs(f, 0));
}
let f = with_host(|h| h.function_designator(&args[0]));
return call_function(&f, &args[1..]);
}
"apply" => {
if args.is_empty() {
return Err(intrinsic_wrong_nargs(f, 0));
}
let spread = args.last().unwrap();
let tail = with_host(|h| h.list_vec(spread)).ok_or_else(|| {
with_host(|h| {
let mut t = spread.clone();
while let Some(Obj::Cons(_, cdr)) = h.obj(&t) {
t = cdr.clone();
}
format!("wrong-type-argument: listp {}", h.print(&t, true))
})
})?;
let mut a: Vec<Value> = if args.len() >= 2 {
args[1..args.len() - 1].to_vec()
} else {
Vec::new()
};
a.extend(tail);
let f = with_host(|h| h.function_designator(&args[0]));
return call_function(&f, &a);
}
"mapcar" => {
if args.len() < 2 {
return Err(intrinsic_wrong_nargs(f, args.len()));
}
let seq = with_host(|h| h.seq_vec_checked(&args[1]))?;
let f = with_host(|h| h.function_designator(&args[0]));
let mut out = Vec::with_capacity(seq.len());
for e in seq {
out.push(call_function(&f, &[e])?);
}
return Ok(with_host(|h| h.list_from(out)));
}
"assoc" => {
if args.len() < 2 || args.len() > 3 {
return Err(intrinsic_wrong_nargs(f, args.len()));
}
let key = args[0].clone();
let alist = args[1].clone();
let testfn = args.get(2).cloned().unwrap_or(Value::Undef);
if !el_truthy(&testfn) && with_host(|h| crate::builtins::eq_comparable(h, &key)) {
return with_host(|h| crate::builtins::assq(h, &[key, alist]));
}
let mut w = crate::builtins::TailWalk::new(&alist);
while let Some((car, cdr)) = with_host(|h| w.cons(h)) {
if let Some((elt_key, _)) = with_host(|h| match h.obj(&car) {
Some(Obj::Cons(k, v)) => Some((k.clone(), v.clone())),
_ => None,
}) {
let hit = if el_truthy(&testfn) {
let tf = with_host(|h| h.function_designator(&testfn));
el_truthy(&call_function(&tf, &[elt_key, key.clone()])?)
} else {
with_host(|h| crate::builtins::equal_or_eq(h, &elt_key, &key))
};
if hit {
return Ok(car);
}
}
if w.step(cdr) {
return Err(with_host(|h| h.signal_circular_list(&w.tail)));
}
}
let tail = w.tail.clone();
with_host(|h| crate::builtins::check_end(h, &tail, &alist))?;
return Ok(Value::Undef);
}
"mapconcat" => {
if args.len() < 2 || args.len() > 3 {
return Err(intrinsic_wrong_nargs(f, args.len()));
}
let seq = with_host(|h| h.seq_vec_checked(&args[1]))?;
let fun = with_host(|h| h.function_designator(&args[0]));
let mut parts: Vec<Value> = Vec::with_capacity(2 * seq.len());
let sep = args.get(2).cloned().unwrap_or(Value::Undef);
let sep_empty = !el_truthy(&sep)
|| with_host(|h| h.str_text(&sep).map(|s| s.is_empty()).unwrap_or(false));
for (i, e) in seq.into_iter().enumerate() {
if i > 0 && !sep_empty {
parts.push(sep.clone());
}
parts.push(call_function(&fun, &[e])?);
}
return with_host(|h| crate::builtins::concat(h, &parts));
}
"mapc" => {
if args.len() < 2 {
return Err(intrinsic_wrong_nargs(f, args.len()));
}
let seq = with_host(|h| h.seq_vec_checked(&args[1]))?;
let f = with_host(|h| h.function_designator(&args[0]));
for e in seq {
call_function(&f, &[e])?;
}
return Ok(args[1].clone());
}
"sort" => {
if args.is_empty() {
return Err(intrinsic_wrong_nargs(f, 0));
}
let mut pred: Option<Value> = None;
let mut key: Option<Value> = None;
let mut reverse = false;
let mut in_place = false;
if args.len() == 2 {
if el_truthy(&args[1]) {
pred = Some(with_host(|h| h.function_designator(&args[1])));
}
in_place = true;
} else if args.len() % 2 == 0 {
return Err("error: Invalid argument list".to_string());
} else {
for pair in args[1..].chunks(2) {
let kw = with_host(|h| h.sym_name(&pair[0])).unwrap_or_default();
let val = &pair[1];
let truthy = el_truthy(val);
match kw.as_str() {
":key" => key = truthy.then(|| val.clone()),
":lessp" => {
pred = truthy.then(|| with_host(|h| h.function_designator(val)))
}
":in-place" => in_place = truthy,
":reverse" => reverse = truthy,
_ => {
let bad = pair[0].clone();
return Err(with_host(|h| {
h.signal_error_arg("Invalid keyword argument", &bad)
}));
}
}
}
}
let (items, was_vec) = match with_host(|h| match h.obj(&args[0]) {
Some(Obj::Vector(v)) => Some((v.clone(), true)),
_ => h.list_vec(&args[0]).map(|l| (l, false)),
}) {
Some(pair) => pair,
None if with_host(|h| matches!(h.obj(&args[0]), Some(Obj::Cons(..)))) => {
return Err(with_host(|h| h.seq_vec_checked(&args[0]))
.expect_err("a cons that is not a proper list must fail"))
}
None => {
return Err(format!(
"wrong-type-argument: list-or-vector-p {}",
with_host(|h| h.print(&args[0], true))
))
}
};
let mut pairs: Vec<(Value, Value)> = Vec::with_capacity(items.len());
for it in &items {
let k = match &key {
Some(kf) => call_function(kf, std::slice::from_ref(it))?,
None => it.clone(),
};
pairs.push((k, it.clone()));
}
if reverse {
pairs.reverse();
}
merge_sort_by(&mut pairs, pred.as_ref())?;
let mut sorted: Vec<Value> = pairs.into_iter().map(|(_, it)| it).collect();
if reverse {
sorted.reverse();
}
return Ok(with_host(|h| {
if !in_place {
return if was_vec {
h.alloc(Obj::Vector(sorted))
} else {
h.list_from(sorted)
};
}
if was_vec {
if let Value::Obj(id) = &args[0] {
if let Some(Obj::Vector(v)) = h.arena.get_mut(*id as usize) {
*v = sorted;
return args[0].clone();
}
}
h.alloc(Obj::Vector(sorted))
} else {
let mut cur = args[0].clone();
for val in sorted {
let next = match h.obj(&cur) {
Some(Obj::Cons(_, cdr)) => cdr.clone(),
_ => break,
};
if let Value::Obj(id) = cur {
if let Some(Obj::Cons(car, _)) = h.arena.get_mut(id as usize) {
*car = val;
}
}
cur = next;
}
args[0].clone()
}
}));
}
"maphash" => {
if args.len() < 2 {
return Err(intrinsic_wrong_nargs(f, args.len()));
}
let entries = with_host(|h| match h.obj(&args[1]) {
Some(Obj::HashTable(t)) => Some(t.pairs().cloned().collect::<Vec<_>>()),
_ => None,
})
.ok_or("maphash: not a hash table")?;
for (k, v) in entries {
call_function(&args[0], &[k, v])?;
}
return Ok(Value::Undef);
}
"gethash" | "puthash" | "remhash" => {
let table_at = if name == "puthash" { 2 } else { 1 };
let Some(table) = args.get(table_at) else {
return Err(intrinsic_wrong_nargs(f, args.len()));
};
if let Some(t) = crate::builtins::ht_user_test(table) {
return match name.as_str() {
"gethash" => crate::builtins::gethash_user(args, &t),
"puthash" => crate::builtins::puthash_user(args, &t),
_ => crate::builtins::remhash_user(args, &t),
};
}
return with_host(|h| match name.as_str() {
"gethash" => crate::builtins::gethash(h, args),
"puthash" => crate::builtins::puthash(h, args),
_ => crate::builtins::remhash(h, args),
})
.map(|v| with_host(|h| h.promote_string(v)));
}
"make-hash-table" => {
let named = with_host(|h| -> Result<Option<(Value, String)>, String> {
let kw = crate::builtins::hash_table_keywords(h, args)?;
let Some(t) = kw.test else { return Ok(None) };
match h.sym_name(&t) {
Some(n) if !matches!(n.as_str(), "eq" | "eql" | "equal" | "nil") => {
Ok(Some((t, n)))
}
Some(_) => Ok(None),
None => Err(format!(
"wrong-type-argument: symbolp {}",
h.print(&t, true)
)),
}
})?;
let user = match named {
None => None,
Some((sym, _)) => {
let getf = with_host(|h| h.intern("get"));
let prop = with_host(|h| h.intern("hash-table-test"));
let spec = call_function(&getf, &[sym.clone(), prop])?;
match with_host(|h| h.list_vec(&spec)) {
Some(fns) if fns.len() >= 2 => {
Some((sym, fns[0].clone(), fns[1].clone()))
}
_ => {
return Err(with_host(|h| {
h.signal_error_with("Invalid hash table test", &sym)
}))
}
}
}
};
return with_host(|h| crate::builtins::make_hash_table_with(h, args, user));
}
"princ" | "prin1" | "print" | "terpri" | "write-char" => {
let (min, pcf) = if name == "terpri" { (0, 0) } else { (1, 1) };
let ensure = name == "terpri" && args.get(1).is_some_and(el_truthy);
if (min..=2).contains(&args.len()) && !ensure {
let dest = with_host(|h| crate::builtins::print_dest(h, args.get(pcf)))?;
if let crate::builtins::PrintDest::Function(pf) = dest {
if let Some(text) =
with_host(|h| crate::builtins::print_text(h, &name, args))?
{
let pf = with_host(|h| h.function_designator(&pf));
for c in text.chars() {
call_function(&pf, &[Value::Int(c as i64)])?;
}
return Ok(if name == "terpri" {
Value::Bool(true)
} else {
args[0].clone()
});
}
}
}
}
"mapatoms" => {
if args.is_empty() {
return Err(intrinsic_wrong_nargs(f, args.len()));
}
let ob = match args.get(1) {
Some(v) if !matches!(v, Value::Undef | Value::Bool(false)) => v.clone(),
_ => with_host(|h| {
let sym = h.find_symbol("obarray").unwrap_or(Value::Undef);
h.get_value(&sym).unwrap_or(Value::Undef)
}),
};
let syms = with_host(|h| h.obarray_symbols(&ob));
for s in syms {
call_function(&args[0], &[s])?;
}
return Ok(Value::Undef);
}
"load" => return intrinsic_load(f, args),
"eval" => {
let form = args
.first()
.ok_or_else(|| intrinsic_wrong_nargs(f, args.len()))?;
if matches!(form, Value::Bool(true)) {
return Ok(form.clone());
}
let lexical = args.get(1).is_some_and(el_truthy);
let saved = with_host(|h| h.take_lex());
let prev_mode = with_host(|h| std::mem::replace(&mut h.dynamic_binding, !lexical));
let out = eval_in_place(form);
with_host(|h| {
h.restore_lex(saved);
h.dynamic_binding = prev_mode;
});
return out;
}
"macroexpand-1" => {
let form = args
.first()
.ok_or_else(|| intrinsic_wrong_nargs(f, args.len()))?;
let env = args.get(1).cloned().unwrap_or(Value::Undef);
match env_expand(form, &env)? {
EnvHit::Expanded(e) => return Ok(e),
EnvHit::Shadowed => return Ok(form.clone()),
EnvHit::Miss => {}
}
if let Some(e) = macroexpand_1(form)? {
return Ok(e);
}
return Ok(expand_intrinsic_macro(form)?.unwrap_or_else(|| form.clone()));
}
"macroexpand" => {
let mut f = args
.first()
.ok_or_else(|| intrinsic_wrong_nargs(f, args.len()))?
.clone();
let env = args.get(1).cloned().unwrap_or(Value::Undef);
loop {
match env_expand(&f, &env)? {
EnvHit::Expanded(e) => {
let same = with_host(|h| h.values_eq(&e, &f));
f = e;
if same {
break;
}
continue;
}
EnvHit::Shadowed => break,
EnvHit::Miss => {}
}
if let Some(e) = macroexpand_1(&f)? {
f = e;
continue;
}
if let Some(e) = expand_intrinsic_macro(&f)? {
f = e;
continue;
}
break;
}
return Ok(f);
}
"macroexpand-all" => {
return macroexpand_all_builtin(
args.first()
.ok_or_else(|| intrinsic_wrong_nargs(f, args.len()))?,
args.get(1).unwrap_or(&Value::Undef),
)
}
"--catch--" => return intrinsic_catch(args),
"--unwind--" => return intrinsic_unwind(args),
"--condition-case--" => return intrinsic_condition_case(args),
"intercept-proceed" => return crate::intercepts::intrinsic_intercept_proceed(),
"__rust-compile" => {
let b64 = with_host(|h| {
args.first()
.and_then(|v| h.str_text(v).map(str::to_string))
.unwrap_or_default()
});
return fusevm::ffi::compile_and_register(&b64).map(|_| Value::Undef);
}
_ => {}
}
}
if with_host(|h| !h.intercepts.is_empty() && !h.intercept_active) {
if let Some(name) = with_host(|h| h.sym_name(f)) {
if let Some(result) = crate::intercepts::run_intercepts(f, &name, args)? {
return Ok(result);
}
}
}
let callee = f.clone();
let resolved = match with_host(|h| h.resolve_function(f)) {
Ok(r) => r,
Err(e) => {
if let Some(fun) = with_host(|h| h.indirect_lambda_list(f)) {
return call_lambda_list(&fun, args);
}
if matches!(f, Value::Obj(_)) {
if let Some(fundef) = with_host(|h| h.indirect_autoload(f)) {
let loader = with_host(|h| h.intern("autoload-do-load"));
call_function(&loader, &[fundef, f.clone()])?;
return call_function(f, args);
}
}
if let Some(r) = try_rust_ffi(f, args) {
return r;
}
let intrinsic_macro = with_host(|h| {
h.function_cell(f).is_none() && h.introspect_function_cell(f).is_some()
});
if intrinsic_macro || e.starts_with("invalid-function: ") {
return Err(with_host(|h| h.signal_invalid_function(&callee)));
}
return Err(e);
}
};
match resolved {
Resolved::Subr { f, min, max, name } => {
if args.len() < min || max.is_some_and(|m| args.len() > m) {
let _ = &name;
return Err(with_host(|h| h.signal_wrong_nargs(&callee, args.len())));
}
if std::ptr::fn_addr_eq(f, crate::builtins::intercepted_subr as SubrFn) {
let target = with_host(|h| h.intern(&name));
return call_function(&target, args);
}
if let Some(r) = crate::modhooks::around(&name, f, args) {
return r.map(|v| with_host(|h| h.promote_string(v)));
}
with_host(|h| f(h, args).map(|v| h.promote_string(v)))
}
Resolved::Closure {
params,
body,
is_macro,
env,
dynamic,
object,
} => {
if is_macro {
return Err(with_host(|h| h.signal_invalid_function(&callee)));
}
let max = params.required.len() + params.optional.len();
if args.len() < params.required.len() || (params.rest.is_none() && args.len() > max) {
return Err(with_host(|h| {
h.signal_closure_wrong_nargs(&callee, &object, args.len())
}));
}
crate::dap::enter_function(&callee);
run_closure(¶ms, &body, env, dynamic, args)
}
}
}
fn call_lambda_list(fun: &Value, args: &[Value]) -> Result<Value, String> {
let (eval_sym, form, well_formed) = with_host(|h| {
let well_formed = matches!(h.obj(fun), Some(Obj::Cons(_, rest)) if matches!(h.obj(rest), Some(Obj::Cons(..))));
let fsym = h.intern("function");
(
h.intern("eval"),
h.list_from(vec![fsym, fun.clone()]),
well_formed,
)
});
if !well_formed {
return Err(with_host(|h| h.signal_invalid_function(fun)));
}
let closure = call_function(&eval_sym, &[form, Value::Undef])?;
if let Ok(Resolved::Closure { params, .. }) = with_host(|h| h.resolve_function(&closure)) {
let max = params.required.len() + params.optional.len();
if args.len() < params.required.len() || (params.rest.is_none() && args.len() > max) {
return Err(with_host(|h| h.signal_wrong_nargs(fun, args.len())));
}
}
call_function(&closure, args)
}
#[inline(never)]
fn try_rust_ffi(f: &Value, args: &[Value]) -> Option<Result<Value, String>> {
let name = with_host(|h| h.sym_name(f))?;
if !fusevm::ffi::is_registered(&name) {
return None;
}
let flat: Vec<Value> = with_host(|h| args.iter().map(|v| h.str_view(v)).collect());
let r = fusevm::ffi::try_call(&name, &flat)?;
Some(r.map(|v| with_host(|h| h.promote_string(v))))
}
fn num_f(v: &Value) -> Option<f64> {
match v {
Value::Int(n) => Some(*n as f64),
Value::Float(f) => Some(*f),
_ => None,
}
}
fn value_lt(a: &Value, b: &Value) -> Result<bool, String> {
if let (Some(x), Some(y)) = (num_f(a), num_f(b)) {
return Ok(x < y);
}
if let (Some(x), Some(y)) = with_host(|h| {
(
h.str_text(a).map(str::to_string),
h.str_text(b).map(str::to_string),
)
}) {
return Ok(x < y);
}
match (with_host(|h| h.sym_name(a)), with_host(|h| h.sym_name(b))) {
(Some(x), Some(y)) => Ok(x < y),
_ => {
let f = with_host(|h| h.intern("value<"));
Ok(el_truthy(&call_function(&f, &[a.clone(), b.clone()])?))
}
}
}
fn merge_sort_by(items: &mut Vec<(Value, Value)>, pred: Option<&Value>) -> Result<(), String> {
let n = items.len();
if n < 2 {
return Ok(());
}
let lt = |x: &Value, y: &Value| -> Result<bool, String> {
match pred {
Some(p) => {
let r = call_function(p, &[x.clone(), y.clone()])?;
Ok(!matches!(r, Value::Undef | Value::Bool(false)))
}
None => value_lt(x, y),
}
};
if n < 64 {
let mut run = 2;
if lt(&items[1].0, &items[0].0)? {
while run < n && lt(&items[run].0, &items[run - 1].0)? {
run += 1;
}
items[..run].reverse();
} else {
while run < n && !lt(&items[run].0, &items[run - 1].0)? {
run += 1;
}
}
for start in run..n {
let (mut l, mut r) = (0usize, start);
while l < r {
let p = l + ((r - l) >> 1);
if lt(&items[start].0, &items[p].0)? {
r = p;
} else {
l = p + 1;
}
}
items[l..=start].rotate_right(1);
}
return Ok(());
}
let mid = n / 2;
let mut right = items.split_off(mid);
merge_sort_by(items, pred)?;
merge_sort_by(&mut right, pred)?;
let left = std::mem::take(items);
let (mut i, mut j) = (0, 0);
items.reserve(left.len() + right.len());
while i < left.len() && j < right.len() {
let rhs_first = match pred {
Some(p) => {
let r = call_function(p, &[right[j].0.clone(), left[i].0.clone()])?;
!matches!(r, Value::Undef | Value::Bool(false))
}
None => value_lt(&right[j].0, &left[i].0)?,
};
if rhs_first {
items.push(right[j].clone());
j += 1;
} else {
items.push(left[i].clone());
i += 1;
}
}
items.extend_from_slice(&left[i..]);
items.extend_from_slice(&right[j..]);
Ok(())
}
fn run_closure(
params: &Rc<Params>,
body: &Rc<Chunk>,
env: Lex,
dynamic: bool,
args: &[Value],
) -> Result<Value, String> {
stacker::maybe_grow(256 * 1024, 8 * 1024 * 1024, || {
run_closure_inner(params, body, env, dynamic, args)
})
}
fn run_closure_inner(
params: &Rc<Params>,
body: &Rc<Chunk>,
env: Lex,
dynamic: bool,
args: &[Value],
) -> Result<Value, String> {
with_host(|h| h.enter_eval_frame())?;
let entry = with_host(|h| h.scope_depth());
let prev_mode = with_host(|h| std::mem::replace(&mut h.dynamic_binding, dynamic));
let setup = with_host(|h| {
h.open_scope_in(env.clone());
h.bind_params_into_scope(params, args)
});
if let Err(e) = setup {
with_host(|h| {
h.unwind_scopes_to(entry);
h.dynamic_binding = prev_mode;
h.leave_eval_frame();
});
return Err(e);
}
let result = run_body(body);
with_host(|h| {
h.unwind_scopes_to(entry);
h.dynamic_binding = prev_mode;
h.leave_eval_frame();
});
result
}
pub(crate) enum EnvHit {
Miss,
Shadowed,
Expanded(Value),
}
pub(crate) fn env_expand(form: &Value, env: &Value) -> Result<EnvHit, String> {
let entry = with_host(|h| {
let Some(Obj::Cons(head, rest)) = h.obj(form) else {
return None;
};
let (head, rest) = (head.clone(), rest.clone());
let mut e = env.clone();
while let Some(Obj::Cons(item, next)) = h.obj(&e) {
if let Some(Obj::Cons(k, v)) = h.obj(item) {
if h.values_eq(k, &head) {
return Some((v.clone(), rest));
}
}
e = next.clone();
}
None
});
match entry {
None => Ok(EnvHit::Miss),
Some((expander, _)) if !el_truthy(&expander) => Ok(EnvHit::Shadowed),
Some((expander, rest)) => {
let args = with_host(|h| h.list_vec(&rest)).unwrap_or_default();
let f = with_host(|h| h.function_designator(&expander));
Ok(EnvHit::Expanded(call_function(&f, &args)?))
}
}
}
pub fn macroexpand_1(form: &Value) -> Result<Option<Value>, String> {
let pending = with_host(|h| {
let head = h.list_vec(form)?.into_iter().next()?;
let fundef = h.indirect_autoload(&head)?;
let ty = h.list_vec(&fundef)?.get(4).cloned()?;
el_truthy(&ty).then_some((head, fundef))
});
if let Some((head, fundef)) = pending {
let loader = with_host(|h| h.intern("autoload-do-load"));
let macro_only = with_host(|h| h.intern("macro"));
call_function(&loader, &[fundef, head, macro_only])?;
}
let info = with_host(|h| {
let elems = h.list_vec(form)?;
if elems.is_empty() {
return None;
}
match h.resolve_function(&elems[0]) {
Ok(Resolved::Closure {
params,
body,
is_macro: true,
env,
dynamic,
object,
}) => Some((params, body, env, dynamic, object, elems[1..].to_vec())),
_ => None,
}
});
match info {
Some((params, body, env, dynamic, object, args)) => {
let max = params.required.len() + params.optional.len();
if args.len() < params.required.len() || (params.rest.is_none() && args.len() > max) {
return Err(with_host(|h| {
h.signal_macro_wrong_nargs(&object, ¶ms, args.len())
}));
}
Ok(Some(run_closure(¶ms, &body, env, dynamic, &args)?))
}
None => Ok(None),
}
}
pub fn expand_intrinsic_macro(form: &Value) -> Result<Option<Value>, String> {
with_host(|h| {
let Some(elems) = h.list_vec(form) else {
return Ok(None);
};
if elems.is_empty() {
return Ok(None);
}
let Some(name) = h.sym_name(&elems[0]) else {
return Ok(None);
};
if elems.len() == 1 && matches!(name.as_str(), "when" | "unless") {
return Err(h.signal_intrinsic_macro_wrong_nargs());
}
let body = &elems[2.min(elems.len())..];
let cond = elems.get(1).cloned().unwrap_or(Value::Undef);
let empty_body = body.is_empty();
Ok(match name.as_str() {
"lambda" => {
let function_sym = h.intern("function");
Some(h.list_from(vec![function_sym, form.clone()]))
}
"when" => {
if empty_body {
let progn_sym = h.intern("progn");
return Ok(Some(h.list_from(vec![progn_sym, cond, Value::Undef])));
}
let if_sym = h.intern("if");
let mut progn = vec![h.intern("progn")];
progn.extend_from_slice(body);
let progn = h.list_from(progn);
Some(h.list_from(vec![if_sym, cond, progn]))
}
"unless" => {
if empty_body {
let progn_sym = h.intern("progn");
return Ok(Some(h.list_from(vec![progn_sym, cond, Value::Undef])));
}
let mut out = vec![h.intern("if"), cond, Value::Undef];
out.extend_from_slice(body);
Some(h.list_from(out))
}
_ => None,
})
})
}
pub fn macroexpand_all(form: &Value) -> Result<Value, String> {
macroexpand_all_impl(form, Walk::Load, &Value::Undef)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Walk {
Load,
Eval,
Builtin,
}
pub fn macroexpand_all_for_eval(form: &Value) -> Result<Value, String> {
macroexpand_all_impl(form, Walk::Eval, &Value::Undef)
}
pub fn macroexpand_all_builtin(form: &Value, env: &Value) -> Result<Value, String> {
let depth = with_host(|h| {
let d = h.specdepth();
let sym = h.intern("macroexpand-all-environment");
let _ = h.specbind(&sym, env.clone());
d
});
let out = macroexpand_all_impl(form, Walk::Builtin, env);
with_host(|h| h.unbind_to(depth));
out
}
pub fn macroexpand_for_load(form: &Value) -> Result<Value, String> {
macroexpand_all_builtin(form, &Value::Undef).map_err(|err| {
if err == "--throw--" {
return err;
}
with_host(|h| {
let obj = h
.take_pending_error(&err)
.unwrap_or_else(|| h.make_error_object(&err));
let text = format!("Eager macro-expansion failure: {}", h.print(&obj, true));
let msg = format!("error: {text}");
let sym = h.intern("error");
let s = h.new_string(&text);
let data = h.list_from(vec![s]);
let obj = h.cons(sym, data);
h.set_pending_error(&msg, obj);
msg
})
})
}
fn lambda_parts(v: Option<&Value>) -> Option<Vec<Value>> {
let v = v?;
with_host(|h| {
let parts = h.list_vec(v)?;
(parts.len() >= 2 && h.sym_name(parts.first()?).as_deref() == Some("lambda"))
.then_some(parts)
})
}
fn expand_lambda_bare(elems: &[Value], walk: Walk, env: &Value) -> Result<Value, String> {
let mut out = Vec::with_capacity(elems.len());
out.push(elems[0].clone());
out.push(elems[1].clone()); for e in &elems[2..] {
out.push(macroexpand_all_impl(e, walk, env)?);
}
let lam = with_host(|h| h.list_from(out));
if let (Walk::Eval, Value::Obj(id)) = (walk, &lam) {
with_host(|h| h.eval_lambda_raw.insert(*id, elems[2..].to_vec()));
}
Ok(lam)
}
fn apply_compiler_macro(form: &Value) -> Result<Option<Value>, String> {
let handler = with_host(|h| {
let elems = h.list_vec(form)?;
let head = elems.first()?;
let id = match head {
Value::Obj(id) if h.compiler_macros.contains(id) => *id,
_ => return None,
};
let _ = id;
let getter = h.find_symbol("function-get")?;
h.resolve_function(&getter).ok()?;
Some((getter, head.clone(), elems[1..].to_vec()))
});
let Some((getter, head, args)) = handler else {
return Ok(None);
};
let prop = with_host(|h| h.intern("compiler-macro"));
let Ok(cm) = call_function(&getter, &[head, prop]) else {
return Ok(None);
};
if !el_truthy(&cm) {
return Ok(None);
}
let mut call = vec![form.clone()];
call.extend(args);
let Ok(out) = call_function(&cm, &call) else {
return Ok(None);
};
if with_host(|h| h.values_eq(&out, form)) {
return Ok(None);
}
Ok(Some(out))
}
fn deferred_expansion_failure(err: String) -> Value {
with_host(|h| {
let quote = h.intern("quote");
let thrown = if err == "--throw--" {
h.pending_throw.take()
} else {
None
};
let (head, a, b) = match thrown {
Some((tag, val)) => (h.intern("throw"), tag, val),
None => {
let obj = h
.take_pending_error(&err)
.unwrap_or_else(|| h.make_error_object(&err));
let (sym, data) = match h.obj(&obj) {
Some(Obj::Cons(a, d)) => (a.clone(), d.clone()),
_ => (h.intern("error"), Value::Undef),
};
let no_catch = h.sym_name(&sym).as_deref() == Some("no-catch");
match h.list_vec(&data) {
Some(d) if no_catch && d.len() == 2 => {
(h.intern("throw"), d[0].clone(), d[1].clone())
}
_ => (h.intern("signal"), sym, data),
}
}
};
let qa = h.list_from(vec![quote.clone(), a]);
let qb = h.list_from(vec![quote, b]);
h.list_from(vec![head, qa, qb])
})
}
fn is_condless_when(form: &Value) -> bool {
with_host(|h| {
h.list_vec(form).is_some_and(|v| {
v.len() == 1 && matches!(h.sym_name(&v[0]).as_deref(), Some("when" | "unless"))
})
})
}
fn macroexpand_all_impl(form: &Value, walk: Walk, env: &Value) -> Result<Value, String> {
let mut f = form.clone();
loop {
match env_expand(&f, env)? {
EnvHit::Expanded(e) => {
let same = with_host(|h| h.values_eq(&e, &f));
f = e;
if same {
break;
}
continue;
}
EnvHit::Shadowed => break,
EnvHit::Miss => {}
}
match macroexpand_1(&f) {
Ok(Some(e)) => {
f = e;
continue;
}
Ok(None) => {}
Err(e) if walk == Walk::Eval => return Ok(deferred_expansion_failure(e)),
Err(e) => return Err(e),
}
let unfold_intrinsics = match walk {
Walk::Eval => false,
Walk::Load => !is_condless_when(&f),
Walk::Builtin => true,
};
if unfold_intrinsics {
if let Some(e) = expand_intrinsic_macro(&f)? {
f = e;
continue;
}
}
if walk != Walk::Eval {
if let Some(e) = apply_compiler_macro(&f)? {
f = e;
continue;
}
}
break;
}
let elems = with_host(|h| {
if matches!(h.obj(&f), Some(Obj::Cons(..))) {
h.list_vec(&f)
} else {
None
}
});
let Some(elems) = elems else { return Ok(f) };
if elems.is_empty() {
return Ok(f);
}
let head = with_host(|h| h.sym_name(&elems[0]));
if let Some(n) = head.as_deref() {
if crate::compiler::special_form_arity_error(n, elems.len() - 1).is_some() {
return Ok(f);
}
}
match head.as_deref() {
Some("quote") => Ok(f),
Some("function") => {
let Some(inner) = lambda_parts(elems.get(1)) else {
return Ok(f);
};
let lam = expand_lambda_bare(&inner, walk, env)?;
Ok(with_host(|h| h.list_from(vec![elems[0].clone(), lam])))
}
Some(kw @ ("let" | "let*")) => {
let bindings = with_host(|h| h.list_vec(elems.get(1).unwrap_or(&Value::Undef)));
let new_bindings = match bindings {
Some(bs) => {
let mut out = Vec::with_capacity(bs.len());
for bd in &bs {
let parts = with_host(|h| {
if matches!(h.obj(bd), Some(Obj::Cons(..))) {
h.list_vec(bd)
} else {
None
}
});
match parts {
Some(parts) if !parts.is_empty() => {
let mut np = Vec::with_capacity(parts.len());
np.push(parts[0].clone()); for p in &parts[1..] {
np.push(macroexpand_all_impl(p, walk, env)?);
}
out.push(with_host(|h| h.list_from(np)));
}
_ => out.push(bd.clone()),
}
}
with_host(|h| h.list_from(out))
}
None => elems.get(1).cloned().unwrap_or(Value::Undef),
};
let mut out = Vec::with_capacity(elems.len());
out.push(elems[0].clone());
out.push(new_bindings);
for e in &elems[2..] {
out.push(macroexpand_all_impl(e, walk, env)?);
}
let _ = kw;
Ok(with_host(|h| h.list_from(out)))
}
Some("lambda") if elems.len() >= 2 => {
let lam = expand_lambda_bare(&elems, walk, env)?;
Ok(with_host(|h| {
let fsym = h.intern("function");
h.list_from(vec![fsym, lam])
}))
}
Some(construct @ ("defun" | "defmacro")) if elems.len() >= 3 => {
let bridge_ready = with_host(|h| {
let s = h.intern("elisprs--expand-defun-declarations");
h.is_fbound(&s)
});
if bridge_ready {
let (bridge, cons_sym, name, arglist, body_list) = with_host(|h| {
let bridge = h.intern("elisprs--expand-defun-declarations");
let cons_sym = h.intern(construct);
let body_list = h.list_from(elems[3..].to_vec());
(
bridge,
cons_sym,
elems[1].clone(),
elems[2].clone(),
body_list,
)
});
let replaced = call_function(&bridge, &[cons_sym, name, arglist, body_list])?;
if el_truthy(&replaced) {
return macroexpand_all_impl(&replaced, walk, env);
}
}
let early_declare = if bridge_ready {
None
} else {
with_host(|h| {
let declare = h.intern("declare");
let at = (3..elems.len().min(5)).find(|&i| {
h.list_vec(&elems[i])
.and_then(|l| l.first().cloned())
.is_some_and(|head| head == declare)
});
if at.is_some() {
h.early_declarations.push(f.clone());
}
at
})
};
let mut out = Vec::with_capacity(elems.len());
out.push(elems[0].clone());
out.push(elems[1].clone()); out.push(elems[2].clone()); for (i, e) in elems.iter().enumerate().skip(3) {
if Some(i) != early_declare {
out.push(macroexpand_all_impl(e, walk, env)?);
}
}
if early_declare.is_some() {
let doc = out.len() > 3 && with_host(|h| h.is_string(&out[3]));
if out.len() == 3 + doc as usize {
out.push(Value::Undef);
}
}
let def = with_host(|h| h.list_from(out));
if let (Walk::Eval, Value::Obj(id)) = (walk, &def) {
with_host(|h| h.eval_lambda_raw.insert(*id, elems[3..].to_vec()));
}
Ok(def)
}
Some("cond") => {
let mut out = Vec::with_capacity(elems.len());
out.push(elems[0].clone());
for clause in &elems[1..] {
match with_host(|h| h.list_vec(clause)) {
Some(forms) if !forms.is_empty() => {
let mut nc = Vec::with_capacity(forms.len());
for f in &forms {
nc.push(macroexpand_all_impl(f, walk, env)?);
}
out.push(with_host(|h| h.list_from(nc)));
}
_ => out.push(clause.clone()),
}
}
Ok(with_host(|h| h.list_from(out)))
}
_ => {
let mut out = Vec::with_capacity(elems.len());
for (i, e) in elems.iter().enumerate() {
let expanded = match (i == 0).then(|| lambda_parts(Some(e))).flatten() {
Some(parts) => expand_lambda_bare(&parts, walk, env)?,
None => macroexpand_all_impl(e, walk, env)?,
};
if is_defmacro_form(e) {
if let Ok(chunk) = with_host(|h| crate::compiler::compile_top(h, &expanded)) {
let _ = run_chunk(chunk);
}
}
out.push(expanded);
}
Ok(with_host(|h| h.list_from(out)))
}
}
}
fn is_defmacro_form(form: &Value) -> bool {
with_host(|h| {
let Some(Obj::Cons(head, _)) = h.obj(form) else {
return false;
};
let head = head.clone();
h.sym_name(&head).as_deref() == Some("defmacro")
})
}
pub(crate) fn file_lexical_cookie(src: &str) -> bool {
let mut lines = src.lines();
let mut first = lines.next().unwrap_or("");
if first.starts_with("#!") {
first = lines.next().unwrap_or("");
}
if !first.starts_with(';') {
return false;
}
let Some(start) = first.find("-*-") else {
return false;
};
let rest = &first[start + 3..];
let vars = rest.find("-*-").map_or(rest, |end| &rest[..end]);
vars.split(';')
.filter_map(|pair| pair.split_once(':'))
.find(|(var, _)| var.trim() == "lexical-binding")
.is_some_and(|(_, val)| val.trim() != "nil")
}
pub(crate) fn load_abspath(candidate: &str) -> std::path::PathBuf {
if let Some(rest) = candidate.strip_prefix("~/") {
if let Ok(home) = std::env::var("HOME") {
return std::path::PathBuf::from(home).join(rest);
}
}
let p = std::path::PathBuf::from(candidate);
if p.is_absolute() {
p
} else {
std::env::current_dir().map(|d| d.join(&p)).unwrap_or(p)
}
}
fn intrinsic_load(f: &Value, args: &[Value]) -> Result<Value, String> {
let file = match args
.first()
.map(|v| (v, with_host(|h| h.str_text(v).map(str::to_string))))
{
Some((_, Some(s))) => s,
Some((other, None)) => {
return Err(format!(
"wrong-type-argument: stringp {}",
other.as_str_cow()
))
}
None => return Err(intrinsic_wrong_nargs(f, args.len())),
};
let noerror = args.get(1).is_some_and(el_truthy);
let nosuffix = args.get(3).is_some_and(el_truthy);
let must_suffix = args.get(4).is_some_and(el_truthy);
let suffixes: &[&str] = if nosuffix {
&["", ".gz"]
} else if must_suffix {
&[".el", ".el.gz"]
} else {
&[".el", ".el.gz", "", ".gz"]
};
let has_dir = file.contains('/') || file.starts_with('~');
let bases: Vec<String> = if has_dir {
vec![file.clone()]
} else {
let lp = with_host(|h| {
let sym = h.intern("load-path");
h.get_value(&sym).ok().and_then(|v| h.list_vec(&v))
});
let dirs: Vec<String> = lp
.unwrap_or_default()
.iter()
.filter_map(|v| with_host(|h| h.str_text(v).map(str::to_string)))
.collect();
if dirs.is_empty() {
vec![format!("./{file}")]
} else {
dirs.iter()
.map(|d| {
if d.ends_with('/') {
format!("{d}{file}")
} else {
format!("{d}/{file}")
}
})
.collect()
}
};
let mut resolved: Option<std::path::PathBuf> = None;
'search: for base in &bases {
for suf in suffixes {
let cand = load_abspath(&format!("{base}{suf}"));
if cand.is_file() {
resolved = Some(cand);
break 'search;
}
}
}
let bundled = if resolved.is_none() {
crate::bundled::find(&file)
} else {
None
};
let (src, path_text) = match (resolved, bundled) {
(Some(path), _) => {
let src = if path.extension().and_then(|e| e.to_str()) == Some("gz") {
let bytes = std::fs::read(&path).map_err(|e| {
format!("file-error: Cannot open load file: {}: {e}", path.display())
})?;
let mut dec = flate2::read::GzDecoder::new(&bytes[..]);
let mut s = String::new();
std::io::Read::read_to_string(&mut dec, &mut s)
.map_err(|e| format!("file-error: uncompressing {}: {e}", path.display()))?;
s
} else {
std::fs::read_to_string(&path).map_err(|e| {
format!("file-error: Cannot open load file: {}: {e}", path.display())
})?
};
(src, path.to_string_lossy().into_owned())
}
(None, Some(lib)) => (lib.source.to_string(), crate::bundled::virtual_path(lib)),
(None, None) => {
if noerror {
return Ok(Value::Undef);
}
let enoent = std::io::Error::from_raw_os_error(libc::ENOENT);
return Err(with_host(|h| {
crate::builtins::report_file_errno(h, "Cannot open load file", &[&file], &enoent)
}));
}
};
let abs = with_host(|h| h.new_string(path_text));
let depth = with_host(|h| {
let d = h.specdepth();
let lfn = h.intern("load-file-name");
let ltn = h.intern("load-true-file-name");
let lip = h.intern("load-in-progress");
let _ = h.specbind(&lfn, abs.clone());
let _ = h.specbind(<n, abs.clone());
let _ = h.specbind(&lip, Value::Bool(true));
let lb = h.intern("lexical-binding");
let _ = h.specbind(&lb, Value::Bool(file_lexical_cookie(&src)));
d
});
let load_buf = with_host(|h| h.open_load_buffer(&src, false));
let load_obj = with_host(|h| h.buffer_object(load_buf));
let result = crate::run_top_forms(&src, Some(load_obj));
with_host(|h| {
let obj = h.buffer_object(load_buf);
h.kill_buffer(Some(&obj));
h.unbind_to(depth);
});
result.map(|_| Value::Bool(true))
}
fn intrinsic_catch(args: &[Value]) -> Result<Value, String> {
let tag = args.first().cloned().unwrap_or(Value::Undef);
let thunk = args.get(1).cloned().unwrap_or(Value::Undef);
with_host(|h| h.catch_tags.push(tag.clone()));
let result = call_function(&thunk, &[]);
with_host(|h| {
h.catch_tags.pop();
});
match result {
Ok(v) => Ok(v),
Err(e) => {
let pend = with_host(|h| h.pending_throw.clone());
match pend {
Some((ttag, tval)) if with_host(|h| h.values_eq(&ttag, &tag)) => {
with_host(|h| h.pending_throw = None);
Ok(tval)
}
_ => Err(e), }
}
}
}
fn intrinsic_unwind(args: &[Value]) -> Result<Value, String> {
let body = args.first().cloned().unwrap_or(Value::Undef);
let cleanup = args.get(1).cloned().unwrap_or(Value::Undef);
let r = call_function(&body, &[]);
let saved = with_host(|h| h.pending_throw.take());
let cleanup_r = call_function(&cleanup, &[]);
with_host(|h| {
if h.pending_throw.is_none() {
h.pending_throw = saved;
}
});
cleanup_r?;
r
}
fn intrinsic_condition_case(args: &[Value]) -> Result<Value, String> {
let var = args.first().cloned().unwrap_or(Value::Undef);
let body = args.get(1).cloned().unwrap_or(Value::Undef);
let handlers = args.get(2).cloned().unwrap_or(Value::Undef);
with_host(|h| h.pending_error = None);
match call_function(&body, &[]) {
Ok(v) => {
let hlist = with_host(|h| h.list_vec(&handlers)).unwrap_or_default();
for hp in hlist {
let parts = with_host(|h| h.list_vec(&hp)).unwrap_or_default();
if parts.len() < 2 {
continue;
}
let cname = with_host(|h| h.sym_name(&parts[0])).unwrap_or_default();
if cname == ":success" {
let depth = with_host(|h| {
let d = h.specdepth();
if matches!(h.obj(&var), Some(Obj::Symbol(_))) {
let _ = h.specbind(&var, v.clone());
}
d
});
let hr = call_function(&parts[1], &[]);
with_host(|h| h.unbind_to(depth));
return hr;
}
}
Ok(v)
}
Err(e) => {
if with_host(|h| h.pending_throw.is_some()) {
return Err(e);
}
let esym: String = with_host(|h| {
let obj = h
.pending_error
.as_ref()
.filter(|(m, _)| *m == e)
.map(|(_, eo)| eo.clone())?;
match h.obj(&obj) {
Some(Obj::Cons(car, _)) => {
let car = car.clone();
h.sym_name(&car)
}
_ => None,
}
})
.unwrap_or_else(|| e.split(':').next().unwrap_or("error").trim().to_string());
let hlist = with_host(|h| h.list_vec(&handlers)).unwrap_or_default();
let getfn = with_host(|h| h.intern("get"));
let symv = with_host(|h| h.intern(&esym));
let propv = with_host(|h| h.intern("error-conditions"));
let mut signal_conditions: Vec<String> = call_function(&getfn, &[symv, propv])
.ok()
.and_then(|v| with_host(|h| h.list_vec(&v)))
.map(|items| with_host(|h| items.iter().filter_map(|x| h.sym_name(x)).collect()))
.unwrap_or_default();
if signal_conditions.is_empty() {
let chain: &[&str] = match esym.as_str() {
"overflow-error" => &["overflow-error", "range-error", "arith-error", "error"],
"range-error" => &["range-error", "arith-error", "error"],
_ => &[],
};
signal_conditions = chain.iter().map(|s| s.to_string()).collect();
}
for hp in hlist {
let parts = with_host(|h| h.list_vec(&hp)).unwrap_or_default();
if parts.len() < 2 {
continue;
}
let conds: Vec<String> = with_host(|h| match h.sym_name(&parts[0]) {
Some(name) => vec![name],
None => h
.list_vec(&parts[0])
.map(|items| items.iter().filter_map(|x| h.sym_name(x)).collect())
.unwrap_or_default(),
});
let derives_from_error =
signal_conditions.is_empty() || signal_conditions.iter().any(|c| c == "error");
if conds.iter().any(|c| {
(c == "error" && derives_from_error)
|| c == "t"
|| *c == esym
|| signal_conditions.contains(c)
}) {
let depth = with_host(|h| {
let d = h.specdepth();
if matches!(h.obj(&var), Some(Obj::Symbol(_))) {
let eobj = h
.take_pending_error(&e)
.unwrap_or_else(|| h.make_error_object(&e));
let _ = h.specbind(&var, eobj);
}
d
});
let hr = call_function(&parts[1], &[]);
with_host(|h| h.unbind_to(depth));
return hr;
}
}
Err(e)
}
}
}
pub fn ext_dispatch(vm: &mut VM, id: u16, arg: u8) {
match id {
ops::TRUTHY => {
let v = vm.pop();
vm.push(Value::Bool(el_truthy(&v)));
}
ops::CALL => {
let argc = arg as usize;
let mut args = Vec::with_capacity(argc);
for _ in 0..argc {
args.push(vm.pop());
}
args.reverse();
let symv = vm.pop();
match call_function(&symv, &args) {
Ok(v) => vm.push(v),
Err(e) => abort(vm, e),
}
}
ops::CHECK_ARITY => {
let argc = arg as usize;
let symv = vm.pop();
let failure = with_host(|h| {
if !h.intercepts.is_empty() {
return None;
}
let kind = h.fn_kind(&symv);
if matches!(kind, FnKind::Vacant) && is_void_function_head(h, &symv) {
let sym = h.intern("void-function");
let msg = format!("void-function: {}", h.print(&symv, true));
let obj = h.list_from(vec![sym, symv.clone()]);
h.set_pending_error(&msg, obj);
return Some(msg);
}
kind.rejects_before_args(argc)
.then(|| h.signal_wrong_nargs(&symv, argc))
});
if let Some(e) = failure {
abort(vm, e);
}
}
ops::GETVAR => {
let symv = vm.pop();
match with_host(|h| h.get_value(&symv)) {
Ok(v) => vm.push(v),
Err(e) => abort(vm, e),
}
}
ops::SETVAR => {
let val = vm.pop();
let symv = vm.pop();
match with_host(|h| h.set_value(&symv, val.clone())) {
Ok(()) => vm.push(val),
Err(e) => abort(vm, e),
}
}
ops::DEFVAR_INIT => {
let val = vm.pop();
let symv = vm.pop();
let bound = with_host(|h| h.default_boundp_raw(&symv));
if bound {
vm.push(val);
} else {
match with_host(|h| h.set_value(&symv, val.clone())) {
Ok(()) => vm.push(val),
Err(e) => abort(vm, e),
}
}
}
ops::FSET => {
let def = vm.pop();
let symv = vm.pop();
match with_host(|h| h.set_function_value(&symv, def)) {
Ok(()) => vm.push(symv),
Err(e) => abort(vm, e),
}
}
ops::SPECBIND => {
let symv = vm.pop();
let val = vm.pop();
match with_host(|h| h.check_settable(&symv)) {
Ok(()) => with_host(|h| h.bind_value(&symv, val)),
Err(e) => abort(vm, e),
}
}
ops::SCOPE_OPEN => {
with_host(|h| h.open_scope());
}
ops::MAKE_CLOSURE => {
let template = vm.pop();
let clo = with_host(|h| h.instantiate_closure(&template));
match eval_closure_source(&clo) {
Ok(()) => vm.push(clo),
Err(e) => abort(vm, e),
}
}
ops::DBG_LINE => {
let line = *vm.chunk.lines.get(vm.ip.saturating_sub(1)).unwrap_or(&0);
if line != 0 {
crate::dap::check_line(line);
}
}
_ => {}
}
}
fn eval_in_place(form: &Value) -> Result<Value, String> {
let progn_body = with_host(|h| {
h.list_vec(form)
.filter(|v| !v.is_empty() && h.sym_name(&v[0]).as_deref() == Some("progn"))
});
if let Some(body) = progn_body {
let mut last = Value::Undef;
for sub in &body[1..] {
last = eval_in_place(sub)?;
}
return Ok(last);
}
if matches!(form, Value::Bool(true)) {
return Ok(form.clone());
}
let expanded = macroexpand_all_for_eval(form)?;
let chunk = with_host(|h| crate::compiler::compile_top(h, &expanded))?;
run_chunk(chunk)
}
fn eval_closure_source(clo: &Value) -> Result<(), String> {
let Some((arglist, raw, has_lexvars)) = with_host(|h| match h.obj(clo) {
Some(Obj::Closure { src, dynamic, .. }) => {
let raw = src.raw_body.clone()?;
Some((
src.arglist.clone(),
raw,
!*dynamic && h.lex.as_ref().is_some_and(|s| s.has_bindings()),
))
}
_ => None,
}) else {
return Ok(());
};
let body = if has_lexvars {
let (form, env) = with_host(|h| {
let mut lam = vec![h.intern("lambda"), arglist.clone()];
lam.extend(raw.iter().cloned());
let lam = h.list_from(lam);
let function = h.intern("function");
let env_sym = h.intern("macroexpand-all-environment");
let env = h.get_value(&env_sym).unwrap_or(Value::Undef);
(h.list_from(vec![function, lam]), env)
});
let expanded = macroexpand_all_builtin(&form, &env)?;
with_host(|h| {
let lam = h.list_vec(&expanded).and_then(|v| v.get(1).cloned());
match lam.and_then(|l| h.list_vec(&l)) {
Some(parts) if parts.len() >= 2 => parts[2..].to_vec(),
_ => raw.clone(),
}
})
} else {
raw
};
with_host(|h| {
let new_src = Rc::new(ClosureSrc {
arglist,
body: if body.is_empty() {
vec![Value::Undef]
} else {
body
},
raw_body: None,
});
let new_env = has_lexvars.then(|| h.trim_lex(u32::MAX, &new_src));
if let Value::Obj(id) = clo {
if let Some(Obj::Closure { src, env, .. }) = h.arena.get_mut(*id as usize) {
*src = new_src;
if let Some(e) = new_env {
*env = e;
}
}
}
});
Ok(())
}
pub fn ext_dispatch_wide(vm: &mut VM, id: u16, n: usize) {
match id {
ops::LETBIND => {
let mut pairs = Vec::with_capacity(n);
for _ in 0..n {
let sym = vm.pop();
let val = vm.pop();
pairs.push((sym, val));
}
pairs.reverse();
let rejected = with_host(|h| {
pairs
.iter()
.find_map(|(sym, _)| h.check_settable(sym).err())
});
match rejected {
Some(e) => abort(vm, e),
None => with_host(|h| {
h.open_scope();
for (sym, val) in pairs {
h.bind_value(&sym, val);
}
}),
}
}
ops::UNBIND => {
let _ = n;
with_host(|h| h.close_scope());
}
_ => {}
}
}
fn abort(vm: &mut VM, e: String) {
with_host(|h| h.error = Some(e));
vm.ip = vm.chunk.ops.len();
}
pub const MOST_POSITIVE_FIXNUM: i64 = 2305843009213693951;
pub const MOST_NEGATIVE_FIXNUM: i64 = -2305843009213693952;
pub enum Num {
Int(BigInt),
Float(f64),
}
impl Num {
pub fn to_f64(&self) -> f64 {
match self {
Num::Int(i) => bigint_to_f64(i),
Num::Float(f) => *f,
}
}
}
pub fn num_cmp(a: &Num, b: &Num) -> Option<std::cmp::Ordering> {
match (a, b) {
(Num::Int(x), Num::Int(y)) => Some(x.cmp(y)),
(Num::Int(x), Num::Float(y)) => cmp_int_f64(x, *y),
(Num::Float(x), Num::Int(y)) => cmp_int_f64(y, *x).map(std::cmp::Ordering::reverse),
(Num::Float(x), Num::Float(y)) => x.partial_cmp(y),
}
}
fn cmp_int_f64(x: &BigInt, y: f64) -> Option<std::cmp::Ordering> {
use num_traits::FromPrimitive;
use std::cmp::Ordering;
if y.is_nan() {
return None;
}
if y == f64::INFINITY {
return Some(Ordering::Less);
}
if y == f64::NEG_INFINITY {
return Some(Ordering::Greater);
}
let t = y.trunc();
let ti = BigInt::from_f64(t)?;
Some(match x.cmp(&ti) {
Ordering::Equal => t.partial_cmp(&y)?,
o => o,
})
}
pub fn bigint_to_f64(i: &BigInt) -> f64 {
use num_traits::ToPrimitive;
i.to_f64()
.unwrap_or(if i.sign() == num_bigint::Sign::Minus {
f64::NEG_INFINITY
} else {
f64::INFINITY
})
}
pub(crate) fn numeric_hook(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
with_host(|h| {
let coerce = |h: &ElispHost, v: &Value| -> Option<Num> {
match v {
Value::Int(n) => Some(Num::Int(BigInt::from(*n))),
Value::Float(f) => Some(Num::Float(*f)),
Value::Obj(_) => match h.obj(v) {
Some(Obj::Bignum(b)) => Some(Num::Int(b.clone())),
_ => h.marker_position(v).map(|p| Num::Int(BigInt::from(p))),
},
_ => None,
}
};
let unary = matches!(op, NumOp::Neg);
let an = coerce(h, a).ok_or_else(|| {
format!(
"wrong-type-argument: number-or-marker-p {}",
h.print(a, true)
)
})?;
let bn = if unary {
Num::Int(BigInt::from(0))
} else {
coerce(h, b).ok_or_else(|| {
format!(
"wrong-type-argument: number-or-marker-p {}",
h.print(b, true)
)
})?
};
h.apply_num_op(op, an, bn)
})
}
fn configure_vm(vm: &mut VM) {
vm.set_extension_handler(Box::new(ext_dispatch));
vm.set_extension_wide_handler(Box::new(ext_dispatch_wide));
vm.set_numeric_hook(std::sync::Arc::new(numeric_hook));
vm.set_fixnum_range(MOST_NEGATIVE_FIXNUM, MOST_POSITIVE_FIXNUM);
if !debug_mode() {
vm.enable_tracing_jit();
}
}
fn vm_outcome(vm: &VM, outcome: VMResult) -> Result<Value, String> {
if let Some(e) = with_host(|h| h.take_error()) {
return Err(e);
}
match outcome {
VMResult::Ok(v) => Ok(v),
VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
VMResult::Error(e) => Err(e),
}
}
pub fn run_chunk(chunk: Chunk) -> Result<Value, String> {
with_host(|h| h.error = None);
let mut vm = VM::new(chunk);
configure_vm(&mut vm);
let outcome = vm.run();
vm_outcome(&vm, outcome)
}
struct VmPoolEntry {
_chunk: Rc<Chunk>,
#[allow(clippy::vec_box)]
vms: Vec<Box<VM>>,
}
thread_local! {
#[allow(clippy::type_complexity)]
static VM_POOL: RefCell<HashMap<usize, VmPoolEntry, BuildPtrHasher>> =
RefCell::new(HashMap::default());
}
#[derive(Default, Clone, Copy)]
pub struct PtrHasher(u64);
impl std::hash::Hasher for PtrHasher {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for b in bytes {
self.write_u64(u64::from(*b));
}
}
fn write_usize(&mut self, n: usize) {
self.write_u64(n as u64);
}
fn write_u64(&mut self, n: u64) {
self.0 = (self.0 ^ n).wrapping_mul(0x9E37_79B9_7F4A_7C15);
}
}
type BuildPtrHasher = std::hash::BuildHasherDefault<PtrHasher>;
const VM_POOL_PER_CHUNK: usize = 16;
pub fn run_body(body: &Rc<Chunk>) -> Result<Value, String> {
with_host(|h| h.error = None);
let key = Rc::as_ptr(body) as usize;
let pooled = VM_POOL.with(|p| p.borrow_mut().get_mut(&key).and_then(|e| e.vms.pop()));
let mut vm: Box<VM> = match pooled {
Some(mut vm) => {
let chunk = std::mem::take(&mut vm.chunk);
vm.reset(chunk);
vm
}
None => {
let mut vm = Box::new(VM::new((**body).clone()));
configure_vm(&mut vm);
vm
}
};
let outcome = vm.run();
let result = vm_outcome(&vm, outcome);
VM_POOL.with(|p| {
let mut pool = p.borrow_mut();
let entry = pool.entry(key).or_insert_with(|| VmPoolEntry {
_chunk: Rc::clone(body),
vms: Vec::new(),
});
if entry.vms.len() < VM_POOL_PER_CHUNK {
entry.vms.push(vm);
}
});
result
}
pub fn clear_vm_pool() {
VM_POOL.with(|p| p.borrow_mut().clear());
}
#[cfg(test)]
mod numeric_hook_tests {
use super::*;
const L: i64 = 16_677_181_699_666_569;
const F: f64 = 16_677_181_699_666_568.0;
fn hook(op: NumOp, a: Value, b: Value) -> Value {
reset_host();
numeric_hook(op, &a, &b).expect("numeric hook")
}
fn truthy(v: &Value) -> bool {
matches!(v, Value::Bool(true))
}
#[test]
fn the_f64_image_of_l_is_not_l() {
assert_eq!(L as f64, F);
assert_ne!(L, F as i64);
assert_eq!(F as i64, L - 1);
}
#[test]
fn hook_compares_int_against_float_exactly() {
for (op, want) in [
(NumOp::Eq, false),
(NumOp::Ne, true),
(NumOp::Lt, false),
(NumOp::Gt, true),
(NumOp::Le, false),
(NumOp::Ge, true),
] {
let got = hook(op, Value::Int(L), Value::Float(F));
assert_eq!(truthy(&got), want, "({op:?} L F) => {got:?}");
}
for (op, want) in [
(NumOp::Eq, false),
(NumOp::Ne, true),
(NumOp::Lt, true),
(NumOp::Gt, false),
(NumOp::Le, true),
(NumOp::Ge, false),
] {
let got = hook(op, Value::Float(F), Value::Int(L));
assert_eq!(truthy(&got), want, "({op:?} F L) => {got:?}");
}
}
#[test]
fn hook_keeps_the_representable_answers() {
assert!(truthy(&hook(NumOp::Eq, Value::Int(1), Value::Float(1.0))));
assert!(truthy(&hook(NumOp::Lt, Value::Int(1), Value::Float(1.5))));
assert!(truthy(&hook(NumOp::Gt, Value::Int(2), Value::Float(1.5))));
assert!(truthy(&hook(NumOp::Eq, Value::Int(0), Value::Float(-0.0))));
let two53 = 1i64 << 53;
let two53f = two53 as f64;
assert!(truthy(&hook(
NumOp::Eq,
Value::Int(two53),
Value::Float(two53f)
)));
assert!(truthy(&hook(
NumOp::Gt,
Value::Int(two53 + 1),
Value::Float(two53f)
)));
}
#[test]
fn hook_handles_infinities_and_nan() {
assert!(truthy(&hook(
NumOp::Lt,
Value::Int(L),
Value::Float(f64::INFINITY)
)));
assert!(truthy(&hook(
NumOp::Gt,
Value::Int(L),
Value::Float(f64::NEG_INFINITY)
)));
for op in [NumOp::Eq, NumOp::Lt, NumOp::Gt, NumOp::Le, NumOp::Ge] {
assert!(!truthy(&hook(op, Value::Int(L), Value::Float(f64::NAN))));
assert!(!truthy(&hook(op, Value::Float(f64::NAN), Value::Int(L))));
}
assert!(truthy(&hook(
NumOp::Ne,
Value::Int(L),
Value::Float(f64::NAN)
)));
}
#[test]
fn hook_arithmetic_stays_float_contagious() {
assert_eq!(
hook(NumOp::Add, Value::Int(L), Value::Float(0.0)),
Value::Float(16_677_181_699_666_568.0)
);
assert_eq!(
hook(NumOp::Mul, Value::Int(L), Value::Float(2.0)),
Value::Float(33_354_363_399_333_136.0)
);
assert_eq!(
hook(NumOp::Sub, Value::Float(0.0), Value::Int(L)),
Value::Float(-16_677_181_699_666_568.0)
);
}
#[test]
fn hook_compares_bignum_against_float_exactly() {
use num_traits::One;
reset_host();
let (big, bigf) = with_host(|h| {
let mut n = BigInt::one();
for _ in 0..100 {
n *= 3;
}
let f = bigint_to_f64(&n);
(h.make_integer(n), f)
});
assert!(matches!(big, Value::Obj(_)), "expected a heap bignum");
assert!(!truthy(
&numeric_hook(NumOp::Eq, &big, &Value::Float(bigf)).unwrap()
));
assert!(truthy(
&numeric_hook(NumOp::Gt, &big, &Value::Float(bigf)).unwrap()
));
assert!(truthy(
&numeric_hook(NumOp::Lt, &Value::Float(bigf), &big).unwrap()
));
}
}
#[cfg(test)]
mod arity_table_tests {
use super::*;
#[test]
fn prelude_c_subr_names_are_sorted_and_unique() {
assert!(PRELUDE_C_SUBR_NAMES.windows(2).all(|w| w[0] < w[1]));
}
}