From 51bb8767e33d6e8e13712d1ad63d8d37e23f5793 Mon Sep 17 00:00:00 2001 From: cflmy Date: Mon, 7 Sep 2026 15:13:47 +0800 Subject: [PATCH] feat(linalg): matrix infix ops and # matrix methods MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .cursor/skills/marqdo/SKILL.md | 2 +- .cursor/skills/marqdo/examples.md | 29 +++++--- CHANGELOG.md | 2 +- doc/design/ext-linalg.md | 14 ++-- examples/linalg-svd/index.mq.md | 4 +- ext/linalg/linalg.mq.md | 87 +++++++++++++++++++--- ext/linalg/线性代数.mq.md | 87 ++++++++++++++++++++-- plugins/linalg/src/complex.rs | 3 +- plugins/linalg/src/dense.rs | 5 +- plugins/linalg/src/matexpr.rs | 10 ++- src/bytecode/vm.rs | 81 +++++++++++++++++---- src/interp.rs | 19 ++++- src/lib.rs | 1 + src/linalg_ops.rs | 112 +++++++++++++++++++++++++++++ tests/ext/linalg-infix-smoke.mq.md | 46 ++++++++++++ tests/gold.rs | 14 ++++ 16 files changed, 459 insertions(+), 57 deletions(-) create mode 100644 src/linalg_ops.rs create mode 100644 tests/ext/linalg-infix-smoke.mq.md diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index 6ab2779..e00f67d 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -235,7 +235,7 @@ Install: `marqdo ext add linalg` (ZH id: `线性代数`). Build: `cargo build -- **Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; prefer top-level `la.symbol` (not `matrix.symbol` without a receiver); quote `kind=` strings; dense `explicit` / factorize obey size guards. -APIs (EN): `symbol` / `mul` / `simplify` / `ascii` / `show` · `from_formula` / `explicit` / `det` / `solve` · `block` / `kron` / `collapse` · `factorize` / `draw` (`theme=light|dark|bw`) · `lstsq` / `norm` / `cond` / `rank`. +APIs (EN): `symbol` → `# matrix`;中缀 `+`/`-`/`*`;方法 `` `A`.T `` / ``.simplify`` / ``.ascii`` · `from_formula` / `explicit` / `factorize` / `draw` · `lstsq` / `norm` / `cond` / `rank`. Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../../examples/linalg-least-squares/). Design: [ext-linalg.md](../../doc/design/ext-linalg.md). diff --git a/.cursor/skills/marqdo/examples.md b/.cursor/skills/marqdo/examples.md index 815c151..21b7362 100644 --- a/.cursor/skills/marqdo/examples.md +++ b/.cursor/skills/marqdo/examples.md @@ -336,16 +336,25 @@ import la:ext/linalg/linalg.mq.md # main -`M` = -$$ -\begin{bmatrix}2&0\\0&3\end{bmatrix} -$$ - -*`M` = > la.from_formula formula=`M`* -*`f` = > la.factorize matrix=`M` kind="eig"* -*_ = > la.draw factor=`f` kind="eig" path="eig.svg"* -> print text=ok +*`A` = > la.symbol name="A" rows=2 cols=2* +*`B` = > la.symbol name="B" rows=2 cols=2* +*`C` = `A` + `B`* +*`P` = `A` * `B`* +*`s` = > `P`.T.simplify* ``` +Prefer: + +```markdown +*`A` = > la.symbol name="A" rows=2 cols=2* +*`B` = > la.symbol name="B" rows=2 cols=2* +*`P` = `A` * `B`* +*`Pt` = > `P`.T* +*`s` = > `Pt`.simplify* +*`t` = > `s`.ascii* +> print text=`t` +``` + +- Infix `+` / `-` / `*` dispatch when both sides are matrices (needs linalg plugin loaded). +- `# matrix` methods: `T`, `add`, `mul`, `simplify`, `ascii`, … - Examples: `examples/linalg-svd/`, `examples/linalg-least-squares/`. -- After rebuilding: `marqdo ext add linalg` (or `MARQDO_LINALG_PLUGIN`). diff --git a/CHANGELOG.md b/CHANGELOG.md index 9950b44..5313f72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## Unreleased ### Added -- **`ext/linalg` L0–L6**:公式 MatExpr(含分块/`kron`)+ 稠密 `explicit`/`det`/`trace`/`solve`;`collapse`;`factorize` + 结构/`heatmap` SVG;`lstsq`/`norm`/`cond`/`rank`;`dtype=complex` 基线;`draw theme=light|dark|bw`;示例 `linalg-svd` · `linalg-least-squares`;金样至 `linalg-metrics-smoke`。设计:[ext-linalg.md](doc/design/ext-linalg.md)。 +- **`ext/linalg` L0–L6 + 作者面中缀**:公式 MatExpr;`lstsq`/`norm`/`cond`/`rank`;复数基线;`draw theme`;**`A + B` / `A * B` / `A - B` 运行时分派** + `# matrix` 方法(``.T`` / ``.simplify`` …)。金样含 `linalg-infix-smoke`。设计:[ext-linalg.md](doc/design/ext-linalg.md)。 ### Fixed diff --git a/doc/design/ext-linalg.md b/doc/design/ext-linalg.md index c67bb75..d4f9722 100644 --- a/doc/design/ext-linalg.md +++ b/doc/design/ext-linalg.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Draft · L0–L6 已落地** | +| 状态 | **Draft · L0–L6 + 中缀/方法面 v1** | | 日期 | 2026-09-07 | | 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) | | 路线图 | [roadmap/ext-linalg.md](../roadmap/ext-linalg.md) | @@ -55,7 +55,7 @@ plugins/linalg(ABI v2) │ ▼(可选) 核心 Value::Formula 仅保留「数值矩阵字面量」现状; -符号 MatExpr 以 **map `_type=linalg_expr`**(或插件句柄)承载,避免撑爆高中 formula AST。 +符号 MatExpr 以 **map `_type=matrix`(中文构造为 `矩阵`)** 承载,避免撑爆高中 formula AST;遗留标签 `linalg_expr` / `linalg_dense` 仍可解析。 ``` ### 2.1 为何 MatExpr 不直接塞进 `formula::Expr` @@ -152,14 +152,16 @@ $$ | `latex` / `ascii` | `乳胶` / `文本` | 展示字符串 | | `shape` | `形状` | | -链式风格(L1 对象方法,可选): +链式 / 中缀(v1 已落地): ```markdown -*`AtA` = > `A`.T * -*`AtA` = > la.mul a=`AtA` b=`A` * -*`s` = > la.simplify expr=`AtA` * +*`C` = `A` + `B`* +*`P` = `A` * `B`* +*`Pt` = > `P`.T* +*`s` = > `Pt`.simplify* ``` +运行时对双方为 `matrix` / `矩阵` / 数值 `$$` 矩阵 / 遗留 `linalg_expr` 的 `+` `-` `*` 分派到插件;结果保留左操作数 `_type` 以便中英方法链。 ### 4.3 求值与分解(热路径 → 稠密) | 英文 | 说明 | diff --git a/examples/linalg-svd/index.mq.md b/examples/linalg-svd/index.mq.md index c6b43e0..1002e25 100644 --- a/examples/linalg-svd/index.mq.md +++ b/examples/linalg-svd/index.mq.md @@ -6,7 +6,7 @@ import la:ext/linalg/linalg.mq.md # SVD from a runnable document -A diagonal matrix has singular values on the diagonal. `factorize kind=svd` returns `U`, `S`, `Vt`; `draw kind=svd` writes a teaching structure SVG for `view`. +A diagonal matrix has singular values on the diagonal. Prefer matrix values and methods; `factorize` / `draw` stay explicit for teaching SVGs. # main @@ -18,7 +18,7 @@ $$ *`M` = > la.from_formula formula=`M`* *`f` = > la.factorize matrix=`M` kind="svd"* *`S` = f[^S]* -*`_` = > la.draw factor=`f` kind="svd" path="svd-structure.svg"* +*`_` = > la.draw factor=`f` kind="svd" theme="light" path="svd-structure.svg"* *`hm` = > la.draw factor=`M` kind="hinton" path="svd-hinton.svg"* > print text=`S` diff --git a/ext/linalg/linalg.mq.md b/ext/linalg/linalg.mq.md index bad03a9..8dcf237 100644 --- a/ext/linalg/linalg.mq.md +++ b/ext/linalg/linalg.mq.md @@ -246,21 +246,87 @@ Numerical rank (SVD). + `rows` + `cols` -Abstract `MatrixSymbol` (`linalg_expr`). Prefer this over `matrix.symbol` (needs a receiver). +Abstract matrix symbol. Returns a `# matrix` instance (supports `+` / `*` and methods). > ensure_plugin -**> linalg_symbol name=`name` rows=`rows` cols=`cols`** +**> matrix name=`name` rows=`rows` cols=`cols`** # matrix + + `name`=None + + `rows`=None + + `cols`=None + + `data`=None + + `formula`=None + + `n`=None -Constructor-style helpers (call after `> la.matrix` if you hold an instance; prefer top-level `symbol` / `eye` / `zeros` / `from_list`). +Matrix value (`_type=matrix`). Prefer infix `A + B` / `A * B`, or methods `` `A`.T ``. -## symbol - + `name` - + `rows` - + `cols` +> ensure_plugin +1. `formula` + **> linalg_from_formula formula=`formula`** +2. `data` + **> linalg_from_list data=`data`** +3. `name` + **> linalg_symbol name=`name` rows=`rows` cols=`cols`** +4. `n` + **> linalg_eye n=`n`** +5. `rows` + **> linalg_zeros rows=`rows` cols=`cols`** +6. * + > print text=ext/linalg: matrix needs name= / data= / formula= / n= / rows= + **None** -**> linalg_symbol name=`name` rows=`rows` cols=`cols`** +## T + +**> linalg_transpose expr=`self`** + +## add + + `b` + +**> linalg_add a=`self` b=`b`** + +## sub + + `b` + +**> linalg_sub a=`self` b=`b`** + +## mul + + `b` + +**> linalg_mul a=`self` b=`b`** + +## inv + +**> linalg_inv expr=`self`** + +## simplify + +**> linalg_simplify expr=`self`** + +## ascii + +**> linalg_ascii expr=`self`** + +## latex + +**> linalg_latex expr=`self`** + +## explicit + +**> linalg_explicit expr=`self`** + +## det + +**> linalg_det expr=`self`** + +## trace + +**> linalg_trace expr=`self`** + +## show + + `path`=None + +**> linalg_show expr=`self` path=`path`** ## eye + `n` @@ -277,3 +343,8 @@ Constructor-style helpers (call after `> la.matrix` if you hold an instance; pre + `data` **> linalg_from_list data=`data`** + +## from_formula + + `formula` + +**> linalg_from_formula formula=`formula`** diff --git a/ext/linalg/线性代数.mq.md b/ext/linalg/线性代数.mq.md index 220d512..143b4be 100644 --- a/ext/linalg/线性代数.mq.md +++ b/ext/linalg/线性代数.mq.md @@ -238,19 +238,87 @@ import sys:lib/sys.mq.md + `行` + `列` -抽象矩阵符号(`linalg_expr`)。 +抽象矩阵符号。返回 `# 矩阵` 实例(可用 `+` / `*` 与方法)。 > 确保插件 -**> linalg_symbol name=`名` rows=`行` cols=`列`** +**> 矩阵 名=`名` 行=`行` 列=`列`** # 矩阵 + + `名`=None + + `行`=None + + `列`=None + + `数据`=None + + `公式`=None + + `阶`=None -## 符号 - + `名` - + `行` - + `列` +矩阵值(`_type=矩阵`)。优先中缀 `A + B` / `A * B`,或 `` `A`.转置 ``。 -**> linalg_symbol name=`名` rows=`行` cols=`列`** +> 确保插件 +1. `公式` + **> linalg_from_formula formula=`公式`** +2. `数据` + **> linalg_from_list data=`数据`** +3. `名` + **> linalg_symbol name=`名` rows=`行` cols=`列`** +4. `阶` + **> linalg_eye n=`阶`** +5. `行` + **> linalg_zeros rows=`行` cols=`列`** +6. * + > print text=ext/linalg: 矩阵需要 名= / 数据= / 公式= / 阶= / 行= + **None** + +## 转置 + +**> linalg_transpose expr=`self`** + +## 加 + + `右` + +**> linalg_add a=`self` b=`右`** + +## 减 + + `右` + +**> linalg_sub a=`self` b=`右`** + +## 乘 + + `右` + +**> linalg_mul a=`self` b=`右`** + +## 逆 + +**> linalg_inv expr=`self`** + +## 化简 + +**> linalg_simplify expr=`self`** + +## 文本 + +**> linalg_ascii expr=`self`** + +## 乳胶 + +**> linalg_latex expr=`self`** + +## 求值 + +**> linalg_explicit expr=`self`** + +## 行列式 + +**> linalg_det expr=`self`** + +## 迹 + +**> linalg_trace expr=`self`** + +## 展示 + + `路径`=None + +**> linalg_show expr=`self` path=`路径`** ## 单位 + `阶` @@ -267,3 +335,8 @@ import sys:lib/sys.mq.md + `数据` **> linalg_from_list data=`数据`** + +## 自公式 + + `公式` + +**> linalg_from_formula formula=`公式`** diff --git a/plugins/linalg/src/complex.rs b/plugins/linalg/src/complex.rs index c630f1b..6218ce0 100644 --- a/plugins/linalg/src/complex.rs +++ b/plugins/linalg/src/complex.rs @@ -171,7 +171,8 @@ pub fn to_dense_value(m: &CMat) -> Result { }) .collect(); Ok(json!({ - "_type": "linalg_dense", + "_type": "matrix", + "kind": "dense", "rows": rows, "cols": cols, "data": data, diff --git a/plugins/linalg/src/dense.rs b/plugins/linalg/src/dense.rs index 92934dc..6b65d5c 100644 --- a/plugins/linalg/src/dense.rs +++ b/plugins/linalg/src/dense.rs @@ -47,7 +47,8 @@ pub fn to_dense_value(m: &Mat) -> Result { let (rows, cols) = shape(m)?; check_elems(rows, cols)?; Ok(json!({ - "_type": "linalg_dense", + "_type": "matrix", + "kind": "dense", "rows": rows, "cols": cols, "data": m, @@ -108,7 +109,7 @@ pub fn from_value(v: &Value) -> Result { if v.is_array() { return parse_data(v); } - Err("expected linalg_dense, dense expr, or nested list".into()) + Err("expected matrix dense, dense expr, or nested list".into()) } fn parse_data(v: &Value) -> Result { diff --git a/plugins/linalg/src/matexpr.rs b/plugins/linalg/src/matexpr.rs index 4af4b5f..a0c079f 100644 --- a/plugins/linalg/src/matexpr.rs +++ b/plugins/linalg/src/matexpr.rs @@ -349,7 +349,7 @@ impl Expr { pub fn to_value(&self) -> Result { let (rows, cols) = self.shape()?; let mut obj = serde_json::Map::new(); - obj.insert("_type".into(), json!("linalg_expr")); + obj.insert("_type".into(), json!("matrix")); obj.insert("shape".into(), json!([rows.to_json(), cols.to_json()])); obj.insert("ascii".into(), json!(self.ascii())); obj.insert("latex".into(), json!(self.latex())); @@ -421,7 +421,13 @@ impl Expr { pub fn from_value(v: &Value) -> Result { let obj = v .as_object() - .ok_or_else(|| "linalg_expr must be a map".to_string())?; + .ok_or_else(|| "matrix expr must be a map".to_string())?; + // Accept legacy `linalg_expr` and author types `matrix` / `矩阵`. + if let Some(t) = obj.get("_type").and_then(|x| x.as_str()) { + if !matches!(t, "matrix" | "矩阵" | "linalg_expr" | "linalg_dense") { + // still allow untyped maps that have `kind` + } + } let kind = obj .get("kind") .and_then(|x| x.as_str()) diff --git a/src/bytecode/vm.rs b/src/bytecode/vm.rs index be89577..fce6a67 100644 --- a/src/bytecode/vm.rs +++ b/src/bytecode/vm.rs @@ -30,6 +30,8 @@ struct Frame { fn_idx: usize, ip: usize, slots: Vec, + /// When set, retag matrix-like return to this `_type` (method chaining). + retag_matrix: Option, } 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 { } } -fn bin_int(stack: &mut Vec, 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, pred: impl Fn(std::cmp::Ordering) -> bool) -> Result<(), String> { let b = pop(stack)?; diff --git a/src/interp.rs b/src/interp.rs index eba0771..999ec81 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -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) + } } } diff --git a/src/lib.rs b/src/lib.rs index b5d0589..d6df028 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/linalg_ops.rs b/src/linalg_ops.rs new file mode 100644 index 0000000..91a8af7 --- /dev/null +++ b/src/linalg_ops.rs @@ -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, 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))) +} diff --git a/tests/ext/linalg-infix-smoke.mq.md b/tests/ext/linalg-infix-smoke.mq.md new file mode 100644 index 0000000..b6e8328 --- /dev/null +++ b/tests/ext/linalg-infix-smoke.mq.md @@ -0,0 +1,46 @@ +--- +title: linalg infix and matrix methods +description: A+B / A*B dispatch; `A`.T method chain. +import la:ext/linalg/linalg.mq.md +--- + +# main + +*`A` = > la.symbol name="A" rows=2 cols=2* +*`B` = > la.symbol name="B" rows=2 cols=2* +*`C` = `A` + `B`* +*`ct` = > la.ascii expr=`C`* +> print text=`ct` + +*`P` = `A` * `B`* +*`Pt` = > `P`.T* +*`s` = > `Pt`.simplify* +*`st` = > `s`.ascii* +> print text=`st` + +*`ty` = C[^_type]* +1. `ty` == matrix + > print text=type-ok +2. * + > print text=type-fail + +`M` = +$$ +\begin{bmatrix}1&0\\0&1\end{bmatrix} +$$ + +`N` = +$$ +\begin{bmatrix}2&0\\0&3\end{bmatrix} +$$ + +*`S` = `M` + `N`* +*`Se` = > la.explicit expr=`S`* +*`d` = Se[^data]* +*`r0` = > at value=`d` index=0* +*`x00` = > at value=`r0` index=0* +*`xs` = > str value=`x00`* +1. `xs` == "3" + > print text=formula-add-ok +2. * + > print text=formula-add-fail diff --git a/tests/gold.rs b/tests/gold.rs index 37b3a0d..38399a5 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -2464,6 +2464,20 @@ txn-rollback-ok", ); } +#[test] +fn ext_linalg_infix_smoke() { + let status = Command::new("cargo") + .args(["build", "-p", "marqdo_plugin_linalg"]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .status() + .expect("build linalg plugin"); + assert!(status.success(), "failed to build marqdo_plugin_linalg"); + assert_out( + "tests/ext/linalg-infix-smoke.mq.md", + "A + B\nB^T*A^T\ntype-ok\nformula-add-ok", + ); +} + #[test] fn ext_linalg_metrics_smoke() { let status = Command::new("cargo")