Refactor Binder to support recursion and add stdlib operators

This commit introduces two main changes:

1.  **Binder Refactoring**: The `Binder` has been refactored to support
    recursive definitions by pre-declaring names in the scope before
    binding their values. This ensures that a name is visible to itself
    when its definition is being processed.

2.  **Stdlib Operator Implementation**: Several standard library
    operators, including `+`, `-`, `*`, `/`, `>`, and `<`, have been
    implemented. These operators now correctly handle both `Int` and
    `Float` types for numerical operations and comparisons.
    Additionally, the display formatting for `Value::List` and
    `Value::Record` has been improved for better readability. The
    default source code in `main.rs` has also been updated to include a
    Fibonacci example, demonstrating the new recursive capabilities.
This commit is contained in:
Michael Schimmel
2026-02-17 13:22:04 +01:00
parent 9afde5a301
commit 3cca0e06c2
4 changed files with 120 additions and 19 deletions
+30 -12
View File
@@ -119,28 +119,46 @@ impl Binder {
},
UntypedKind::Def { name, value } => {
let val_node = self.bind(value)?;
let ty = val_node.ty.clone();
if self.functions.len() == 1 {
// 1. Pre-declare name to support recursion
let slot_or_idx = if self.functions.len() == 1 {
let mut globals = self.globals.borrow_mut();
let idx = if let Some((idx, _)) = globals.get(name.as_ref()) {
if let Some((idx, _)) = globals.get(name.as_ref()) {
*idx
} else {
let idx = globals.len() as u32;
globals.insert(name.to_string(), (idx, ty.clone()));
globals.insert(name.to_string(), (idx, StaticType::Any));
idx
};
}
} else {
let current_fn = self.functions.last_mut().unwrap();
current_fn.scope.define(name, StaticType::Any)
};
// 2. Bind Value (now 'name' is visible)
let val_node = self.bind(value)?;
let ty = val_node.ty.clone();
// 3. Update Type and Return Node
if self.functions.len() == 1 {
{
let mut globals = self.globals.borrow_mut();
if let Some(entry) = globals.get_mut(name.as_ref()) {
entry.1 = ty.clone();
}
}
Ok(self.make_node(node.identity.clone(), BoundKind::DefGlobal {
global_index: idx,
global_index: slot_or_idx,
value: Box::new(val_node)
}, ty))
} else {
let current_fn = self.functions.last_mut().unwrap();
let slot = current_fn.scope.define(name, ty.clone());
{
let current_fn = self.functions.last_mut().unwrap();
if let Some(info) = current_fn.scope.locals.get_mut(name.as_ref()) {
info.ty = ty.clone();
}
}
Ok(self.make_node(node.identity.clone(), BoundKind::Set {
addr: Address::Local(slot),
addr: Address::Local(slot_or_idx),
value: Box::new(val_node)
}, ty))
}
+48 -1
View File
@@ -37,7 +37,6 @@ impl Environment {
}
fn register_stdlib(&self) {
// Simple math for testing
self.register_native("+", StaticType::Any, |args| {
let mut acc = 0.0;
for arg in args {
@@ -46,11 +45,59 @@ impl Environment {
}
if acc.fract() == 0.0 { Value::Int(acc as i64) } else { Value::Float(acc) }
});
self.register_native("-", StaticType::Any, |args| {
if args.is_empty() { return Value::Void; }
let mut acc = match args[0] {
Value::Int(i) => i as f64,
Value::Float(f) => f,
_ => return Value::Void,
};
if args.len() == 1 {
acc = -acc;
} else {
for arg in &args[1..] {
if let Value::Int(i) = arg { acc -= *i as f64; }
else if let Value::Float(f) = arg { acc -= f; }
}
}
if acc.fract() == 0.0 { Value::Int(acc as i64) } else { Value::Float(acc) }
});
self.register_native("*", StaticType::Any, |args| {
let mut acc = 1.0;
for arg in args {
if let Value::Int(i) = arg { acc *= i as f64; }
else if let Value::Float(f) = arg { acc *= f; }
}
if acc.fract() == 0.0 { Value::Int(acc as i64) } else { Value::Float(acc) }
});
self.register_native("/", StaticType::Any, |args| {
if args.len() != 2 { return Value::Void; }
let a = match args[0] { Value::Int(i) => i as f64, Value::Float(f) => f, _ => return Value::Void };
let b = match args[1] { Value::Int(i) => i as f64, Value::Float(f) => f, _ => return Value::Void };
Value::Float(a / b)
});
self.register_native(">", StaticType::Any, |args| {
if args.len() != 2 { return Value::Void; }
match (&args[0], &args[1]) {
(Value::Int(a), Value::Int(b)) => Value::Bool(a > b),
(Value::Int(a), Value::Float(b)) => Value::Bool((*a as f64) > *b),
(Value::Float(a), Value::Int(b)) => Value::Bool(*a > (*b as f64)),
(Value::Float(a), Value::Float(b)) => Value::Bool(a > b),
_ => Value::Bool(false),
}
});
self.register_native("<", StaticType::Any, |args| {
if args.len() != 2 { return Value::Void; }
match (&args[0], &args[1]) {
(Value::Int(a), Value::Int(b)) => Value::Bool(a < b),
(Value::Int(a), Value::Float(b)) => Value::Bool((*a as f64) < *b),
(Value::Float(a), Value::Int(b)) => Value::Bool(*a < (*b as f64)),
(Value::Float(a), Value::Float(b)) => Value::Bool(a < b),
_ => Value::Bool(false),
}
});
+16 -2
View File
@@ -126,8 +126,22 @@ impl fmt::Display for Value {
Value::Float(fl) => write!(f, "{}", fl),
Value::Text(t) => write!(f, "\"{}\"", t),
Value::Keyword(k) => write!(f, ":{}", k.name()),
Value::List(l) => write!(f, "<list[{}]>", l.len()),
Value::Record(r) => write!(f, "<record[{}]>", r.len()),
Value::List(l) => {
write!(f, "[")?;
for (i, val) in l.iter().enumerate() {
if i > 0 { write!(f, " ")?; }
write!(f, "{}", val)?;
}
write!(f, "]")
},
Value::Record(r) => {
write!(f, "{{")?;
for (i, (k, v)) in r.iter().enumerate() {
if i > 0 { write!(f, ", ")?; }
write!(f, ":{} {}", k.name(), v)?;
}
write!(f, "}}")
},
Value::Function(_) => write!(f, "<native fn>"),
Value::Object(o) => write!(f, "<{}>", o.type_name()),
Value::Cell(c) => write!(f, "{}", c.borrow()),
+26 -4
View File
@@ -27,7 +27,25 @@ struct CompilerApp {
impl Default for CompilerApp {
fn default() -> Self {
Self {
source_code: String::new(),
source_code: String::from(r#"
(do
(def fib (fn [n]
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2))))))
(def result (fib 10))
(def data {
:name "Fibonacci"
:input 10
:output result
:sequence [0 1 1 2 3 5 8 13 21 34 55]
})
data
)
"#),
output_log: String::from("Ready to compile..."),
env: Environment::new(),
is_first_frame: true,
@@ -68,8 +86,12 @@ impl eframe::App for CompilerApp {
}
ui.add_space(5.0);
ui.separator();
ui.label("Output / Logs:");
ui.horizontal(|ui| {
ui.label("Output / Logs:");
if ui.button("Copy to Clipboard").clicked() {
ui.ctx().copy_text(self.output_log.clone());
}
});
// Log Output Area
egui::ScrollArea::vertical()
@@ -80,7 +102,7 @@ impl eframe::App for CompilerApp {
egui::TextEdit::multiline(&mut self.output_log)
.font(egui::TextStyle::Monospace)
.desired_width(f32::INFINITY)
.interactive(false), // Read-only
.interactive(true)
);
});
});