feat(linalg): matrix infix ops and # matrix methods

Dispatch +/−/* to the linalg plugin for matrix values, retag for EN/ZH
method chains, and expand # matrix with T/simplify/ascii-style methods.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-07 15:13:47 +08:00
1 parent c0fbe9b182
commit 51bb8767e3
16 files changed
+459 -57

No files matched your search

+66 -15
View File
@@ -30,6 +30,8 @@ struct Frame {
fn_idx: usize,
ip: usize,
slots: Vec<Value>,
/// When set, retag matrix-like return to this `_type` (method chaining).
retag_matrix: Option<String>,
}
impl Vm {
@@ -115,6 +117,7 @@ impl Vm {
fn_idx: entry,
ip: 0,
slots: vec![Value::None; program.functions[entry].locals.len().max(1)],
retag_matrix: None,
}];
self.host
.push_call_frame(&program.functions[entry].name.clone());
@@ -182,10 +185,57 @@ impl Vm {
Op::Add => {
let b = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
let a = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
stack.push(add(a, b).map_err(|m| self.err_at(span, m))?);
if let Some(v) = crate::linalg_ops::try_matrix_binary(
&mut self.host,
crate::ast::BinaryOp::Add,
&a,
&b,
)
.map_err(|m| self.err_at(span, m))?
{
stack.push(v);
} else {
stack.push(add(a, b).map_err(|m| self.err_at(span, m))?);
}
}
Op::Sub => {
let b = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
let a = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
if let Some(v) = crate::linalg_ops::try_matrix_binary(
&mut self.host,
crate::ast::BinaryOp::Sub,
&a,
&b,
)
.map_err(|m| self.err_at(span, m))?
{
stack.push(v);
} else {
match (a, b) {
(Value::Int(x), Value::Int(y)) => stack.push(Value::Int(x - y)),
_ => return Err(self.err_at(span, "`-` needs ints")),
}
}
}
Op::Mul => {
let b = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
let a = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
if let Some(v) = crate::linalg_ops::try_matrix_binary(
&mut self.host,
crate::ast::BinaryOp::Mul,
&a,
&b,
)
.map_err(|m| self.err_at(span, m))?
{
stack.push(v);
} else {
match (a, b) {
(Value::Int(x), Value::Int(y)) => stack.push(Value::Int(x * y)),
_ => return Err(self.err_at(span, "`*` needs ints")),
}
}
}
Op::Sub => bin_int(&mut stack, |a, b| a - b).map_err(|m| self.err_at(span, m))?,
Op::Mul => bin_int(&mut stack, |a, b| a * b).map_err(|m| self.err_at(span, m))?,
Op::Div => {
let b = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
let a = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
@@ -383,6 +433,7 @@ impl Vm {
fn_idx: fid,
ip: 0,
slots,
retag_matrix: None,
});
self.host.push_call_frame(&fname);
self.host.push_call_site_line(span.line);
@@ -457,11 +508,17 @@ impl Vm {
slots[i] = recv.clone();
}
}
let retag_matrix = if crate::linalg_ops::is_matrix_value(&recv) {
Some(type_name.clone())
} else {
None
};
let fname = callee.name.clone();
frames.push(Frame {
fn_idx: method_fid,
ip: 0,
slots,
retag_matrix,
});
self.host.push_call_frame(&fname);
self.host.push_call_site_line(span.line);
@@ -551,15 +608,20 @@ impl Vm {
fn_idx: fid,
ip: 0,
slots,
retag_matrix: None,
});
self.host.push_call_frame(&fname);
self.host.push_call_site_line(span.line);
}
Op::Return => {
let ret = pop(&mut stack).unwrap_or(Value::None);
frames.pop();
let frame = frames.pop();
self.host.pop_call_frame();
self.host.pop_call_site_line();
let ret = match frame.and_then(|f| f.retag_matrix) {
Some(ty) => crate::linalg_ops::retag_matrix_like(&ty, ret),
None => ret,
};
if frames.is_empty() {
return Ok(ret);
}
@@ -610,17 +672,6 @@ fn add(a: Value, b: Value) -> Result<Value, String> {
}
}
fn bin_int(stack: &mut Vec<Value>, f: impl Fn(i64, i64) -> i64) -> Result<(), String> {
let b = pop(stack)?;
let a = pop(stack)?;
match (a, b) {
(Value::Int(x), Value::Int(y)) => {
stack.push(Value::Int(f(x, y)));
Ok(())
}
_ => Err("binary op needs ints".into()),
}
}
fn cmp(stack: &mut Vec<Value>, pred: impl Fn(std::cmp::Ordering) -> bool) -> Result<(), String> {
let b = pop(stack)?;
+17 -2
View File
@@ -513,6 +513,16 @@ impl Interpreter {
_ => {}
}
let r = self.eval_expr(module, fun, env, right)?;
if let Some(v) = crate::linalg_ops::try_matrix_binary(
&mut self.host,
*op,
&l,
&r,
)
.map_err(|e| self.err(e))?
{
return Ok(v);
}
eval_binary(*op, &l, &r).map_err(|e| self.err(e.to_string()))
}
Expr::Call(call) => self.eval_call(module, fun, env, call),
@@ -869,11 +879,16 @@ impl Interpreter {
call_env.set(k, v);
}
call_env.set("自".into(), recv.clone());
call_env.set("self".into(), recv);
call_env.set("self".into(), recv.clone());
self.host.push_call_site_line(self.host.current_line);
let result = self.run_function(owner, target, call_env, &[], false);
self.host.pop_call_site_line();
result
let result = result?;
if crate::linalg_ops::is_matrix_value(&recv) {
Ok(crate::linalg_ops::retag_matrix_like(&type_name, result))
} else {
Ok(result)
}
}
}
+1
View File
@@ -25,6 +25,7 @@ pub mod inherit;
pub mod input_feed;
pub mod interp;
pub mod lex;
pub mod linalg_ops;
pub mod load;
pub mod parse;
pub mod value;
+112
View File
@@ -0,0 +1,112 @@
//! Infix / runtime helpers for `ext/linalg` matrix values.
//!
//! Keeps MatExpr in the plugin; core only dispatches `+` / `-` / `*` when both
//! sides look like matrices (map `_type` or numeric `Formula::Matrix`).
use std::collections::HashMap;
use crate::ast::BinaryOp;
use crate::formula::Expr as FormulaExpr;
use crate::host::plugin;
use crate::host::HostContext;
use crate::value::Value;
fn map_type(v: &Value) -> Option<&str> {
match v {
Value::Map(entries) => entries
.iter()
.find(|(k, _)| k == "_type")
.and_then(|(_, t)| match t {
Value::Text(s) => Some(s.as_str()),
_ => None,
}),
_ => None,
}
}
/// Author-facing matrix object types (EN / ZH) plus legacy plugin tags.
pub fn is_matrix_value(v: &Value) -> bool {
if matches!(v, Value::Formula(FormulaExpr::Matrix { .. })) {
return true;
}
matches!(
map_type(v),
Some("matrix" | "矩阵" | "linalg_expr" | "linalg_dense")
)
}
fn prefer_result_type(left: &Value, right: &Value) -> &'static str {
match map_type(left) {
Some("矩阵") => "矩阵",
Some("matrix") | Some("linalg_expr") | Some("linalg_dense") => "matrix",
_ => match map_type(right) {
Some("矩阵") => "矩阵",
_ => "matrix",
},
}
}
/// Stamp `_type` for method chaining (EN `matrix` / ZH `矩阵`).
pub fn retag_matrix_like(type_name: &str, value: Value) -> Value {
if !is_matrix_value(&value) {
return value;
}
tag_type(type_name, value)
}
fn tag_type(type_name: &str, value: Value) -> Value {
match value {
Value::Map(mut entries) => {
entries.retain(|(k, _)| k != "_type");
entries.insert(0, ("_type".into(), Value::Text(type_name.into())));
Value::Map(entries)
}
other => Value::Map(vec![
("_type".into(), Value::Text(type_name.into())),
("value".into(), other),
]),
}
}
fn plugin_name(op: BinaryOp) -> Option<&'static str> {
match op {
BinaryOp::Add => Some("linalg_add"),
BinaryOp::Sub => Some("linalg_sub"),
BinaryOp::Mul => Some("linalg_mul"),
_ => None,
}
}
/// If both sides are matrices, call the linalg plugin; otherwise `Ok(None)`.
pub fn try_matrix_binary(
host: &mut HostContext,
op: BinaryOp,
left: &Value,
right: &Value,
) -> Result<Option<Value>, String> {
let Some(fname) = plugin_name(op) else {
return Ok(None);
};
if !is_matrix_value(left) || !is_matrix_value(right) {
return Ok(None);
}
if host.plugins.get(fname).is_none() {
let op_s = match op {
BinaryOp::Add => "+",
BinaryOp::Sub => "-",
BinaryOp::Mul => "*",
_ => "?",
};
return Err(format!(
"matrix `{op_s}` needs the linalg plugin loaded (import ext/linalg / `marqdo ext add linalg`)"
));
}
let mut bound = HashMap::new();
bound.insert("a".into(), left.clone());
bound.insert("b".into(), right.clone());
// ZH param aliases used by some L1 wrappers — plugin accepts both.
bound.insert("左".into(), left.clone());
bound.insert("右".into(), right.clone());
let out = plugin::call_registered(host, fname, &bound)?;
Ok(Some(tag_type(prefer_result_type(left, right), out)))
}