Refactor Purity enum and NativeFunction struct

Move `Purity` enum definition from `optimizer.rs` to `types.rs` and
create a `NativeFunction` struct to hold the function and its purity.
Update `Value::Function` to store `Rc<NativeFunction>` and
`Value::make_function`
helper to simplify creation.

This change allows tracking the purity of native functions, which is
useful
for optimization and static analysis.
This commit is contained in:
Michael Schimmel
2026-02-22 10:50:37 +01:00
parent b54a449369
commit a726b79d8a
9 changed files with 111 additions and 83 deletions
+32 -2
View File
@@ -76,6 +76,29 @@ pub struct RecordData {
pub values: ValueList,
}
/// Purity level of an expression or function.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Purity {
/// Has side effects (e.g. Set, Print)
Impure,
/// No side effects, but not deterministic (e.g. now(), random())
SideEffectFree,
/// No side effects and deterministic (e.g. sin(x), 1 + 2)
Pure,
}
/// A native host function with metadata.
pub struct NativeFunction {
pub func: Rc<dyn Fn(Vec<Value>) -> Value>,
pub purity: Purity,
}
impl fmt::Debug for NativeFunction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "<native fn, {:?}>", self.purity)
}
}
/// Core data value in Myc Script (similar to TDataValue)
#[derive(Clone)]
pub enum Value {
@@ -88,7 +111,7 @@ pub enum Value {
Keyword(Keyword),
Tuple(ValueList),
Record(Rc<RecordData>),
Function(Rc<dyn Fn(Vec<Value>) -> Value>),
Function(Rc<NativeFunction>),
Object(Rc<dyn Object>), // For compiled Closures and other opaque types
Cell(Rc<RefCell<Value>>), // Boxed value for captures
TailCallRequest(Box<(Rc<dyn Object>, Vec<Value>)>), // Internal: For TCO (Boxed to keep Value small)
@@ -304,6 +327,13 @@ impl Value {
}))
}
pub fn make_function(purity: Purity, func: impl Fn(Vec<Value>) -> Value + 'static) -> Self {
Value::Function(Rc::new(NativeFunction {
func: Rc::new(func),
purity,
}))
}
pub fn static_type(&self) -> StaticType {
match self {
Value::Void => StaticType::Void,
@@ -391,7 +421,7 @@ impl fmt::Display for Value {
}
write!(f, "}}")
}
Value::Function(_) => write!(f, "<native fn>"),
Value::Function(f_meta) => write!(f, "<native fn, {:?}>", f_meta.purity),
Value::Object(o) => write!(f, "<{}>", o.type_name()),
Value::Cell(c) => write!(f, "{}", c.borrow()),
Value::TailCallRequest(_) => write!(f, "<tail call request>"),