use crate::host;
use crate::host::{ops, ElispHost, FnKind, Obj};
use fusevm::{Chunk, ChunkBuilder, Op, Value};
use std::rc::Rc;
const OPEN_CODED: &[&str] = &[
"%",
"*",
"+",
"-",
"/",
"/=",
"1+",
"1-",
"<",
"<=",
"=",
">",
">=",
"aref",
"aset",
"assq",
"bobp",
"bolp",
"buffer-substring",
"car",
"car-safe",
"cdr",
"cdr-safe",
"char-after",
"concat",
"cons",
"consp",
"current-buffer",
"current-column",
"delete-region",
"downcase",
"elt",
"end-of-line",
"eobp",
"eolp",
"eq",
"equal",
"following-char",
"forward-char",
"forward-line",
"fset",
"funcall",
"get",
"goto-char",
"indent-to",
"insert",
"integerp",
"length",
"list",
"listp",
"match-beginning",
"match-end",
"max",
"member",
"memq",
"min",
"narrow-to-region",
"nconc",
"not",
"nreverse",
"nth",
"nthcdr",
"null",
"numberp",
"point",
"point-max",
"point-min",
"preceding-char",
"set-buffer",
"setcar",
"setcdr",
"skip-chars-forward",
"string-equal",
"string-lessp",
"string<",
"string=",
"stringp",
"substring",
"symbol-value",
"symbolp",
"upcase",
"widen",
];
fn is_open_coded(name: &str) -> bool {
OPEN_CODED.binary_search(&name).is_ok()
}
pub fn compile_top(h: &mut ElispHost, form: &Value) -> Result<Chunk, String> {
let mut b = ChunkBuilder::new();
compile_form(h, &mut b, form)?;
Ok(b.build())
}
pub fn compile_program(h: &mut ElispHost, forms: &[Value]) -> Result<Chunk, String> {
let mut b = ChunkBuilder::new();
if forms.is_empty() {
b.emit(Op::LoadUndef, 0);
}
for (i, form) in forms.iter().enumerate() {
emit_line_marker(h, &mut b, form);
compile_form(h, &mut b, form)?;
if i + 1 < forms.len() {
b.emit(Op::Pop, 0);
}
}
Ok(b.build())
}
fn emit_line_marker(h: &ElispHost, b: &mut ChunkBuilder, form: &Value) {
if crate::host::debug_mode() {
if let Some(line) = h.form_line(form) {
b.emit(Op::Extended(ops::DBG_LINE, 0), line);
}
}
}
fn compile_form(h: &mut ElispHost, b: &mut ChunkBuilder, form: &Value) -> Result<(), String> {
match form {
Value::Int(n) => {
b.emit(Op::LoadInt(*n), 0);
}
Value::Float(f) => {
b.emit(Op::LoadFloat(*f), 0);
}
Value::Str(_) => {
let cell = h.promote_string(form.clone());
load_const(b, cell);
}
Value::Undef | Value::Bool(false) => {
b.emit(Op::LoadUndef, 0);
}
Value::Bool(true) => {
b.emit(Op::LoadTrue, 0);
}
Value::Obj(_) => match h.obj(form) {
Some(Obj::Symbol(s)) => {
if s.name.starts_with(':') {
load_const(b, form.clone());
} else {
load_const(b, form.clone());
b.emit(Op::Extended(ops::GETVAR, 0), 0);
}
}
Some(Obj::Cons(..)) => compile_call(h, b, form)?,
_ => load_const(b, form.clone()),
},
other => load_const(b, other.clone()),
}
Ok(())
}
fn compile_call(h: &mut ElispHost, b: &mut ChunkBuilder, form: &Value) -> Result<(), String> {
let Some(elems) = h.list_vec(form) else {
return compile_dotted_call_signal(h, b, form);
};
let head = elems[0].clone();
let name = match h.obj(&head) {
Some(Obj::Symbol(s)) => Some(s.name.clone()),
_ => None,
};
if let Some(n) = name.as_deref() {
if let Some(argc) = special_form_arity_error(n, elems.len() - 1) {
compile_wrong_nargs_signal(h, b, &head, argc)?;
return Ok(());
}
if matches!(n, "when" | "unless") && elems.len() == 1 {
let template = h.cons(Value::Int(1), Value::Int(1));
compile_wrong_nargs_signal(h, b, &template, 0)?;
return Ok(());
}
}
match name.as_deref() {
Some("quote") => load_const(b, elems.get(1).cloned().unwrap_or(Value::Undef)),
Some("function") => {
let arg = elems.get(1).cloned().unwrap_or(Value::Undef);
let arg_elems = match h.obj(&arg) {
Some(Obj::Cons(..)) => h.list_vec(&arg),
_ => None,
};
let is_lambda = arg_elems
.as_ref()
.and_then(|e| e.first())
.map(|f| h.sym_name(f).as_deref() == Some("lambda"))
.unwrap_or(false);
if is_lambda {
let raw = eval_lambda_raw(h, &arg);
compile_lambda(h, b, &arg_elems.unwrap(), false, raw)?;
} else {
load_const(b, arg);
}
}
Some("lambda") => {
let raw = eval_lambda_raw(h, form);
compile_lambda(h, b, &elems, false, raw)?
}
Some("progn") => compile_progn(h, b, &elems[1..])?,
Some("interactive") => {
b.emit(Op::LoadUndef, 0);
}
Some("prog1") => compile_prog1(h, b, &elems[1..])?,
Some("if") => compile_if(h, b, &elems[1..])?,
Some("when") => compile_when(h, b, &elems[1..], true)?,
Some("unless") => compile_when(h, b, &elems[1..], false)?,
Some("and") => compile_andor(h, b, &elems[1..], true)?,
Some("or") => compile_andor(h, b, &elems[1..], false)?,
Some("while") => compile_while(h, b, &elems[1..])?,
Some("cond") => compile_cond(h, b, &elems[1..])?,
Some("let") => compile_let(h, b, &elems[1..], false)?,
Some("let*") => compile_let(h, b, &elems[1..], true)?,
Some("setq") => compile_setq(h, b, &elems[1..])?,
Some("defun") => {
let raw = eval_lambda_raw(h, form);
compile_defun(h, b, &elems, false, raw)?
}
Some("defmacro") => {
let raw = eval_lambda_raw(h, form);
compile_defun(h, b, &elems, true, raw)?
}
Some("defvar") => compile_defvar(h, b, &elems, false)?,
Some("defconst") => compile_defvar(h, b, &elems, true)?,
Some("catch") => compile_catch(h, b, &elems)?,
Some("unwind-protect") => compile_unwind(h, b, &elems)?,
Some("condition-case") => compile_condition_case(h, b, &elems)?,
Some(kw) if is_unsupported_special(kw) => {
return Err(format!(
"special form `{kw}` not yet lowered (buffer milestone)"
));
}
_ => {
if let Some(n) = &name {
if h.is_primitive_fn(n) && try_native_op(h, b, n, &elems[1..])? {
return Ok(());
}
}
let head_elems = match h.obj(&head) {
Some(Obj::Cons(..)) => h.list_vec(&head),
_ => None,
};
let head_is_lambda = head_elems
.as_ref()
.and_then(|e| e.first())
.map(|f| h.sym_name(f).as_deref() == Some("lambda"))
.unwrap_or(false);
let argc = elems.len() - 1;
if argc > u8::MAX as usize {
return Err("too many arguments".to_string());
}
if !head_is_lambda && needs_arity_guard(h, &head, argc) {
load_const(b, head.clone());
b.emit(Op::Extended(ops::CHECK_ARITY, argc as u8), 0);
}
if head_is_lambda {
compile_lambda(h, b, &head_elems.unwrap(), false, None)?;
} else {
let direct = name
.as_deref()
.filter(|n| host::prelude_compiling() && is_open_coded(n))
.and_then(|n| h.primitive_fn_value(n));
load_const(b, direct.unwrap_or(head));
}
for arg in &elems[1..] {
compile_form(h, b, arg)?;
}
b.emit(Op::Extended(ops::CALL, argc as u8), 0);
}
}
Ok(())
}
pub(crate) const SPECIAL_FORM_ARITY: &[(&str, usize, Option<usize>)] = &[
("quote", 1, Some(1)),
("function", 1, Some(1)),
("if", 2, None),
("let", 1, None),
("let*", 1, None),
("while", 1, None),
("prog1", 1, None),
("catch", 1, None),
("unwind-protect", 1, None),
("condition-case", 2, None),
("defvar", 1, None),
("defconst", 2, None),
];
fn compile_dotted_call_signal(
h: &mut ElispHost,
b: &mut ChunkBuilder,
form: &Value,
) -> Result<(), String> {
let (head, mut tail) = match h.obj(form) {
Some(Obj::Cons(car, cdr)) => (car.clone(), cdr.clone()),
_ => return Err("malformed call form".to_string()),
};
while let Some(Obj::Cons(_, cdr)) = h.obj(&tail) {
tail = cdr.clone();
}
let quote = h.intern("quote");
let quoted = |h: &mut ElispHost, v: Value| h.list_from(vec![quote.clone(), v]);
let signal = h.intern("signal");
let listp = h.intern("listp");
let wta = h.intern("wrong-type-argument");
let wta = quoted(h, wta);
let data = h.list_from(vec![listp, tail]);
let data = quoted(h, data);
let wrong_type = h.list_from(vec![signal.clone(), wta, data]);
let signal_form = if matches!(h.obj(&head), Some(Obj::Symbol(_))) {
let void = h.intern("void-function");
let void = quoted(h, void);
let data = h.list_from(vec![head.clone()]);
let data = quoted(h, data);
let void_signal = h.list_from(vec![signal, void, data]);
let fboundp = h.intern("fboundp");
let quoted_head = quoted(h, head);
let test = h.list_from(vec![fboundp, quoted_head]);
let if_sym = h.intern("if");
h.list_from(vec![if_sym, test, wrong_type, void_signal])
} else {
wrong_type
};
compile_form(h, b, &signal_form)
}
fn compile_wrong_nargs_signal(
h: &mut ElispHost,
b: &mut ChunkBuilder,
head: &Value,
argc: usize,
) -> Result<(), String> {
let quote = h.intern("quote");
let quoted = |h: &mut ElispHost, v: Value| h.list_from(vec![quote.clone(), v]);
let cond = h.intern("wrong-number-of-arguments");
let cond = quoted(h, cond);
let data = h.list_from(vec![head.clone(), Value::Int(argc as i64)]);
let data = quoted(h, data);
let signal = h.intern("signal");
let form = h.list_from(vec![signal, cond, data]);
compile_form(h, b, &form)
}
pub(crate) fn special_form_arity_error(name: &str, argc: usize) -> Option<usize> {
if name == "setq" {
return (argc % 2 == 1).then_some(argc);
}
let (_, min, max) = SPECIAL_FORM_ARITY.iter().find(|(n, ..)| *n == name)?;
(argc < *min || max.is_some_and(|m| argc > m)).then_some(argc)
}
fn needs_arity_guard(h: &ElispHost, head: &Value, argc: usize) -> bool {
if matches!(head, Value::Undef | Value::Bool(_)) {
return true;
}
if !matches!(h.obj(head), Some(Obj::Symbol(_))) {
return false;
}
let kind = h.fn_kind(head);
matches!(kind, FnKind::Vacant) || kind.rejects_before_args(argc) || h.is_subr_aliased(head)
}
fn try_native_op(
h: &mut ElispHost,
b: &mut ChunkBuilder,
name: &str,
args: &[Value],
) -> Result<bool, String> {
let binop = |h: &mut ElispHost, b: &mut ChunkBuilder, op: Op| -> Result<(), String> {
compile_form(h, b, &args[0])?;
compile_form(h, b, &args[1])?;
b.emit(op, 0);
Ok(())
};
match name {
"+" | "*" | "-" => {
let (ident, op) = match name {
"+" => (0, Op::Add),
"*" => (1, Op::Mul),
_ => (0, Op::Sub),
};
let native = matches!((name, args.len()), (_, 0) | (_, 2) | ("-", 1));
if !native {
return Ok(false);
}
if args.is_empty() {
b.emit(Op::LoadInt(ident), 0);
} else if name == "-" && args.len() == 1 {
compile_form(h, b, &args[0])?;
b.emit(Op::Negate, 0);
} else {
compile_form(h, b, &args[0])?;
for a in &args[1..] {
compile_form(h, b, a)?;
b.emit(op.clone(), 0);
}
}
}
"1+" if args.len() == 1 => {
compile_form(h, b, &args[0])?;
b.emit(Op::LoadInt(1), 0);
b.emit(Op::Add, 0);
}
"1-" if args.len() == 1 => {
compile_form(h, b, &args[0])?;
b.emit(Op::LoadInt(1), 0);
b.emit(Op::Sub, 0);
}
_ if native_cmp_op(name).is_some() && args.len() == NATIVE_CMP_ARITY => {
binop(h, b, native_cmp_op(name).expect("checked"))?
}
_ => return Ok(false),
}
Ok(true)
}
const NATIVE_CMP_ARITY: usize = 2;
fn native_cmp_op(name: &str) -> Option<Op> {
Some(match name {
"<" => Op::NumLt,
">" => Op::NumGt,
"<=" => Op::NumLe,
">=" => Op::NumGe,
"=" => Op::NumEq,
_ => return None,
})
}
fn lowers_to_native_bool(h: &mut ElispHost, form: &Value) -> bool {
let Some(elems) = h.list_vec(form) else {
return false;
};
if elems.len() != NATIVE_CMP_ARITY + 1 {
return false;
}
let Some(name) = h.sym_name(&elems[0]) else {
return false;
};
native_cmp_op(&name).is_some() && h.is_primitive_fn(&name)
}
fn compile_condition(h: &mut ElispHost, b: &mut ChunkBuilder, cond: &Value) -> Result<(), String> {
let already_bool = lowers_to_native_bool(h, cond);
compile_form(h, b, cond)?;
if !already_bool {
b.emit(Op::Extended(ops::TRUTHY, 0), 0);
}
Ok(())
}
fn is_unsupported_special(kw: &str) -> bool {
matches!(
kw,
"save-excursion" | "save-current-buffer" | "save-restriction"
)
}
fn lambda_of(h: &mut ElispHost, body: &[Value]) -> Value {
let mut items = vec![h.intern("lambda"), Value::Undef]; items.extend_from_slice(body);
h.list_from(items)
}
fn call_of(h: &mut ElispHost, name: &str, args: Vec<Value>) -> Value {
let mut items = vec![h.intern(name)];
items.extend(args);
h.list_from(items)
}
fn quote_of(h: &mut ElispHost, v: Value) -> Value {
let q = h.intern("quote");
h.list_from(vec![q, v])
}
fn compile_catch(h: &mut ElispHost, b: &mut ChunkBuilder, elems: &[Value]) -> Result<(), String> {
let tag = elems.get(1).cloned().unwrap_or(Value::Undef);
let thunk = lambda_of(h, elems.get(2..).unwrap_or(&[]));
let form = call_of(h, "--catch--", vec![tag, thunk]);
compile_form(h, b, &form)
}
fn compile_unwind(h: &mut ElispHost, b: &mut ChunkBuilder, elems: &[Value]) -> Result<(), String> {
let body_form = elems.get(1).cloned().unwrap_or(Value::Undef);
let body = lambda_of(h, &[body_form]);
let cleanup = lambda_of(h, elems.get(2..).unwrap_or(&[]));
let form = call_of(h, "--unwind--", vec![body, cleanup]);
compile_form(h, b, &form)
}
fn compile_condition_case(
h: &mut ElispHost,
b: &mut ChunkBuilder,
elems: &[Value],
) -> Result<(), String> {
let var = elems.get(1).cloned().unwrap_or(Value::Undef);
let body_form = elems.get(2).cloned().unwrap_or(Value::Undef);
let body = lambda_of(h, &[body_form]);
let mut pairs = Vec::new();
for hc in elems.get(3..).unwrap_or(&[]) {
let parts = h.list_vec(hc).ok_or("condition-case: malformed handler")?;
let cond = quote_of(h, parts.first().cloned().unwrap_or(Value::Undef));
let hthunk = lambda_of(h, parts.get(1..).unwrap_or(&[]));
pairs.push(call_of(h, "list", vec![cond, hthunk]));
}
let handlers_form = call_of(h, "list", pairs);
let qvar = quote_of(h, var);
let form = call_of(h, "--condition-case--", vec![qvar, body, handlers_form]);
compile_form(h, b, &form)
}
fn compile_body_chunk(h: &mut ElispHost, forms: &[Value]) -> Result<Chunk, String> {
let mut bb = ChunkBuilder::new();
compile_progn(h, &mut bb, forms)?;
Ok(bb.build())
}
fn printable_body(forms: &[Value]) -> Vec<Value> {
if forms.is_empty() {
vec![Value::Undef]
} else {
forms.to_vec()
}
}
fn eval_lambda_raw(h: &mut ElispHost, form: &Value) -> Option<Vec<Value>> {
match form {
Value::Obj(id) => h.eval_lambda_raw.remove(id),
_ => None,
}
}
fn compile_lambda(
h: &mut ElispHost,
b: &mut ChunkBuilder,
elems: &[Value],
is_macro: bool,
raw_body: Option<Vec<Value>>,
) -> Result<(), String> {
let arglist = elems.get(1).cloned().unwrap_or(Value::Undef);
let params = h.parse_params(&arglist)?;
let body = compile_body_chunk(h, elems.get(2..).unwrap_or(&[]))?;
let src = Rc::new(crate::host::ClosureSrc {
arglist: arglist.clone(),
body: printable_body(elems.get(2..).unwrap_or(&[])),
raw_body: raw_body.map(|r| printable_body(&r)),
});
let template = h.alloc(Obj::Closure {
params: Rc::new(params),
body: Rc::new(body),
is_macro,
env: None,
dynamic: false,
src,
});
load_const(b, template);
b.emit(Op::Extended(ops::MAKE_CLOSURE, 0), 0);
Ok(())
}
fn compile_defun(
h: &mut ElispHost,
b: &mut ChunkBuilder,
elems: &[Value],
is_macro: bool,
raw_body: Option<Vec<Value>>,
) -> Result<(), String> {
let name = elems.get(1).cloned().ok_or("defun: missing name")?;
if !matches!(h.obj(&name), Some(Obj::Symbol(_))) {
return Err("defun: name must be a symbol".to_string());
}
let arglist = elems.get(2).cloned().unwrap_or(Value::Undef);
let params = h.parse_params(&arglist)?;
let body = compile_body_chunk(h, elems.get(3..).unwrap_or(&[]))?;
let raw_body = raw_body.map(|r| printable_body(&r));
let (shown, raw_body) = match (is_macro, raw_body) {
(true, Some(raw)) => (raw, None),
(_, raw) => (printable_body(elems.get(3..).unwrap_or(&[])), raw),
};
let src = Rc::new(crate::host::ClosureSrc {
arglist: arglist.clone(),
body: shown,
raw_body,
});
let template = h.alloc(Obj::Closure {
params: Rc::new(params),
body: Rc::new(body),
is_macro,
env: None,
dynamic: false,
src,
});
load_const(b, name); load_const(b, template); if !is_macro {
b.emit(Op::Extended(ops::MAKE_CLOSURE, 0), 0);
}
b.emit(Op::Extended(ops::FSET, 0), 0); Ok(())
}
fn compile_defvar(
h: &mut ElispHost,
b: &mut ChunkBuilder,
elems: &[Value],
constant: bool,
) -> Result<(), String> {
let name = elems.get(1).cloned().ok_or("defvar: missing name")?;
if !constant && elems.len() == 2 && !crate::host::prelude_compiling() {
let declare = h.intern("--defvar-declare--");
let quote = h.intern("quote");
let qname = h.list_from(vec![quote, name]);
let form = h.list_from(vec![declare, qname]);
return compile_form(h, b, &form);
}
h.set_special(&name);
if let Some(doc) = elems
.get(3)
.filter(|d| !matches!(d, Value::Undef | Value::Bool(false)))
{
let put = h.intern("put");
let quote = h.intern("quote");
let prop = h.intern("variable-documentation");
let qname = h.list_from(vec![quote.clone(), name.clone()]);
let qprop = h.list_from(vec![quote.clone(), prop]);
let qdoc = h.list_from(vec![quote, doc.clone()]);
let form = h.list_from(vec![put, qname, qprop, qdoc]);
compile_form(h, b, &form)?;
b.emit(Op::Pop, 0);
}
if let Some(init) = elems.get(2) {
load_const(b, name.clone());
compile_form(h, b, init)?;
let op = if constant {
ops::SETVAR
} else {
ops::DEFVAR_INIT
};
b.emit(Op::Extended(op, 0), 0);
b.emit(Op::Pop, 0);
}
load_const(b, name);
Ok(())
}
fn parse_binding(h: &ElispHost, bd: &Value) -> Result<(Value, Value), String> {
if h.constant_symbol_name(bd).is_some() {
return Ok((bd.clone(), Value::Undef));
}
if matches!(h.obj(bd), Some(Obj::Symbol(_))) {
return Ok((bd.clone(), Value::Undef));
}
let parts = h.list_vec(bd).ok_or("let: malformed binding")?;
let sym = parts.first().cloned().ok_or("let: empty binding")?;
if !matches!(h.obj(&sym), Some(Obj::Symbol(_))) && h.constant_symbol_name(&sym).is_none() {
return Err("let: binding name must be a symbol".to_string());
}
Ok((sym, parts.get(1).cloned().unwrap_or(Value::Undef)))
}
fn compile_let(
h: &mut ElispHost,
b: &mut ChunkBuilder,
elems: &[Value],
sequential: bool,
) -> Result<(), String> {
let bindings = h
.list_vec(elems.first().unwrap_or(&Value::Undef))
.unwrap_or_default();
let parsed: Vec<(Value, Value)> = bindings
.iter()
.map(|bd| parse_binding(h, bd))
.collect::<Result<_, _>>()?;
let n = parsed.len();
if sequential {
b.emit(Op::Extended(ops::SCOPE_OPEN, 0), 0);
for (sym, init) in &parsed {
compile_form(h, b, init)?;
load_const(b, sym.clone());
b.emit(Op::Extended(ops::SPECBIND, 0), 0);
}
} else {
for (sym, init) in &parsed {
compile_form(h, b, init)?;
load_const(b, sym.clone());
}
b.emit(Op::ExtendedWide(ops::LETBIND, n), 0);
}
compile_progn(h, b, elems.get(1..).unwrap_or(&[]))?;
b.emit(Op::ExtendedWide(ops::UNBIND, n), 0);
Ok(())
}
fn compile_progn(h: &mut ElispHost, b: &mut ChunkBuilder, forms: &[Value]) -> Result<(), String> {
if forms.is_empty() {
b.emit(Op::LoadUndef, 0);
return Ok(());
}
for (i, f) in forms.iter().enumerate() {
emit_line_marker(h, b, f);
compile_form(h, b, f)?;
if i + 1 < forms.len() {
b.emit(Op::Pop, 0);
}
}
Ok(())
}
fn compile_prog1(h: &mut ElispHost, b: &mut ChunkBuilder, forms: &[Value]) -> Result<(), String> {
if forms.is_empty() {
b.emit(Op::LoadUndef, 0);
return Ok(());
}
compile_form(h, b, &forms[0])?; for f in &forms[1..] {
compile_form(h, b, f)?;
b.emit(Op::Pop, 0);
}
Ok(())
}
fn compile_if(h: &mut ElispHost, b: &mut ChunkBuilder, parts: &[Value]) -> Result<(), String> {
let cond = parts.first().cloned().unwrap_or(Value::Undef);
let then = parts.get(1).cloned().unwrap_or(Value::Undef);
compile_condition(h, b, &cond)?;
let jf = b.emit(Op::JumpIfFalse(0), 0);
compile_form(h, b, &then)?;
let jend = b.emit(Op::Jump(0), 0);
let else_pos = b.current_pos();
b.patch_jump(jf, else_pos);
compile_progn(h, b, parts.get(2..).unwrap_or(&[]))?;
let end_pos = b.current_pos();
b.patch_jump(jend, end_pos);
Ok(())
}
fn compile_when(
h: &mut ElispHost,
b: &mut ChunkBuilder,
parts: &[Value],
polarity: bool,
) -> Result<(), String> {
let cond = parts.first().cloned().unwrap_or(Value::Undef);
compile_condition(h, b, &cond)?;
let jmp = if polarity {
b.emit(Op::JumpIfFalse(0), 0)
} else {
b.emit(Op::JumpIfTrue(0), 0)
};
compile_progn(h, b, parts.get(1..).unwrap_or(&[]))?;
let jend = b.emit(Op::Jump(0), 0);
let skip_pos = b.current_pos();
b.patch_jump(jmp, skip_pos);
b.emit(Op::LoadUndef, 0);
let end_pos = b.current_pos();
b.patch_jump(jend, end_pos);
Ok(())
}
fn compile_andor(
h: &mut ElispHost,
b: &mut ChunkBuilder,
forms: &[Value],
is_and: bool,
) -> Result<(), String> {
if forms.is_empty() {
b.emit(if is_and { Op::LoadTrue } else { Op::LoadUndef }, 0);
return Ok(());
}
let mut end_jumps = Vec::new();
for (i, f) in forms.iter().enumerate() {
compile_form(h, b, f)?;
if i + 1 < forms.len() {
b.emit(Op::Dup, 0);
b.emit(Op::Extended(ops::TRUTHY, 0), 0);
let j = if is_and {
b.emit(Op::JumpIfFalse(0), 0)
} else {
b.emit(Op::JumpIfTrue(0), 0)
};
end_jumps.push(j);
b.emit(Op::Pop, 0);
}
}
let end_pos = b.current_pos();
for j in end_jumps {
b.patch_jump(j, end_pos);
}
Ok(())
}
fn compile_while(h: &mut ElispHost, b: &mut ChunkBuilder, parts: &[Value]) -> Result<(), String> {
let start = b.current_pos();
compile_condition(h, b, parts.first().unwrap_or(&Value::Undef))?;
let jexit = b.emit(Op::JumpIfFalse(0), 0);
compile_progn(h, b, parts.get(1..).unwrap_or(&[]))?;
b.emit(Op::Pop, 0); b.emit(Op::Jump(start), 0);
let exit = b.current_pos();
b.patch_jump(jexit, exit);
b.emit(Op::LoadUndef, 0); Ok(())
}
fn compile_cond(h: &mut ElispHost, b: &mut ChunkBuilder, clauses: &[Value]) -> Result<(), String> {
let mut end_jumps = Vec::new();
for clause in clauses {
let parts = h.list_vec(clause).ok_or("cond: malformed clause")?;
if parts.is_empty() {
continue;
}
compile_form(h, b, &parts[0])?; if parts.len() == 1 {
b.emit(Op::Dup, 0);
b.emit(Op::Extended(ops::TRUTHY, 0), 0);
let jnext = b.emit(Op::JumpIfFalse(0), 0);
let jend = b.emit(Op::Jump(0), 0); end_jumps.push(jend);
let next = b.current_pos();
b.patch_jump(jnext, next);
b.emit(Op::Pop, 0); } else {
if !lowers_to_native_bool(h, &parts[0]) {
b.emit(Op::Extended(ops::TRUTHY, 0), 0);
}
let jnext = b.emit(Op::JumpIfFalse(0), 0);
compile_progn(h, b, &parts[1..])?;
let jend = b.emit(Op::Jump(0), 0);
end_jumps.push(jend);
let next = b.current_pos();
b.patch_jump(jnext, next);
}
}
b.emit(Op::LoadUndef, 0); let end = b.current_pos();
for j in end_jumps {
b.patch_jump(j, end);
}
Ok(())
}
fn compile_setq(h: &mut ElispHost, b: &mut ChunkBuilder, parts: &[Value]) -> Result<(), String> {
if parts.is_empty() {
b.emit(Op::LoadUndef, 0);
return Ok(());
}
let mut i = 0;
while i + 1 < parts.len() {
let sym = parts[i].clone();
load_const(b, sym);
compile_form(h, b, &parts[i + 1])?;
b.emit(Op::Extended(ops::SETVAR, 0), 0);
i += 2;
if i + 1 < parts.len() {
b.emit(Op::Pop, 0);
}
}
Ok(())
}
fn load_const(b: &mut ChunkBuilder, v: Value) {
let c = b.add_constant(v);
b.emit(Op::LoadConst(c), 0);
}