Add math stdlib with formulas/plots and polish the docs view.
Ship Num/Formula runtime, bilingual math libs, SVG plots with axes/grid, and view UX for collapsible folders plus centered plots. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a53ebb65ee
commit
dcd0cdb8f7
40 files changed
+3553
-276
No files matched your search
+243
-3
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{fs, json, net, sys, time, HostContext};
|
||||
use crate::host::{fs, json, math, net, sys, time, HostContext};
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -33,6 +33,43 @@ pub enum HostFn {
|
||||
HttpGet = 23,
|
||||
HttpPost = 24,
|
||||
UrlEncode = 25,
|
||||
// math
|
||||
Pi = 26,
|
||||
EConst = 27,
|
||||
Num = 28,
|
||||
MathAdd = 29,
|
||||
MathSub = 30,
|
||||
MathMul = 31,
|
||||
MathDiv = 32,
|
||||
MathPow = 33,
|
||||
MathNeg = 34,
|
||||
MathSin = 35,
|
||||
MathCos = 36,
|
||||
MathTan = 37,
|
||||
MathAsin = 38,
|
||||
MathAcos = 39,
|
||||
MathAtan = 40,
|
||||
MathSqrt = 41,
|
||||
MathAbs = 42,
|
||||
MathLn = 43,
|
||||
MathExp = 44,
|
||||
MathFloor = 45,
|
||||
MathCeil = 46,
|
||||
MathMin = 47,
|
||||
MathMax = 48,
|
||||
Random = 49,
|
||||
RandomInt = 50,
|
||||
Seed = 51,
|
||||
Formula = 52,
|
||||
Simplify = 53,
|
||||
Expand = 54,
|
||||
Diff = 55,
|
||||
Subs = 56,
|
||||
Eval = 57,
|
||||
Solve = 58,
|
||||
Plot = 59,
|
||||
PlotPoints = 60,
|
||||
PlotConic = 61,
|
||||
}
|
||||
|
||||
impl HostFn {
|
||||
@@ -63,6 +100,42 @@ impl HostFn {
|
||||
23 => Self::HttpGet,
|
||||
24 => Self::HttpPost,
|
||||
25 => Self::UrlEncode,
|
||||
26 => Self::Pi,
|
||||
27 => Self::EConst,
|
||||
28 => Self::Num,
|
||||
29 => Self::MathAdd,
|
||||
30 => Self::MathSub,
|
||||
31 => Self::MathMul,
|
||||
32 => Self::MathDiv,
|
||||
33 => Self::MathPow,
|
||||
34 => Self::MathNeg,
|
||||
35 => Self::MathSin,
|
||||
36 => Self::MathCos,
|
||||
37 => Self::MathTan,
|
||||
38 => Self::MathAsin,
|
||||
39 => Self::MathAcos,
|
||||
40 => Self::MathAtan,
|
||||
41 => Self::MathSqrt,
|
||||
42 => Self::MathAbs,
|
||||
43 => Self::MathLn,
|
||||
44 => Self::MathExp,
|
||||
45 => Self::MathFloor,
|
||||
46 => Self::MathCeil,
|
||||
47 => Self::MathMin,
|
||||
48 => Self::MathMax,
|
||||
49 => Self::Random,
|
||||
50 => Self::RandomInt,
|
||||
51 => Self::Seed,
|
||||
52 => Self::Formula,
|
||||
53 => Self::Simplify,
|
||||
54 => Self::Expand,
|
||||
55 => Self::Diff,
|
||||
56 => Self::Subs,
|
||||
57 => Self::Eval,
|
||||
58 => Self::Solve,
|
||||
59 => Self::Plot,
|
||||
60 => Self::PlotPoints,
|
||||
61 => Self::PlotConic,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -94,6 +167,44 @@ impl HostFn {
|
||||
"host_http_get" => Self::HttpGet,
|
||||
"host_http_post" => Self::HttpPost,
|
||||
"host_url_encode" => Self::UrlEncode,
|
||||
"host_pi" => Self::Pi,
|
||||
"host_e" => Self::EConst,
|
||||
"host_num" => Self::Num,
|
||||
"host_math_add" => Self::MathAdd,
|
||||
"host_math_sub" => Self::MathSub,
|
||||
"host_math_mul" => Self::MathMul,
|
||||
"host_math_div" => Self::MathDiv,
|
||||
"host_math_pow" => Self::MathPow,
|
||||
"host_math_neg" => Self::MathNeg,
|
||||
"host_math_sin" => Self::MathSin,
|
||||
"host_math_cos" => Self::MathCos,
|
||||
"host_math_tan" => Self::MathTan,
|
||||
"host_math_asin" => Self::MathAsin,
|
||||
"host_math_acos" => Self::MathAcos,
|
||||
"host_math_atan" => Self::MathAtan,
|
||||
"host_math_sqrt" => Self::MathSqrt,
|
||||
"host_math_abs" => Self::MathAbs,
|
||||
"host_math_ln" => Self::MathLn,
|
||||
"host_math_exp" => Self::MathExp,
|
||||
"host_math_floor" => Self::MathFloor,
|
||||
"host_math_ceil" => Self::MathCeil,
|
||||
"host_math_min" => Self::MathMin,
|
||||
"host_math_max" => Self::MathMax,
|
||||
"host_random" => Self::Random,
|
||||
"host_random_int" => Self::RandomInt,
|
||||
"host_seed" => Self::Seed,
|
||||
"host_formula" => Self::Formula,
|
||||
"host_simplify" => Self::Simplify,
|
||||
"host_expand" => Self::Expand,
|
||||
"host_diff" => Self::Diff,
|
||||
"host_subs" => Self::Subs,
|
||||
"host_eval" => Self::Eval,
|
||||
"host_solve" => Self::Solve,
|
||||
// Friendly aliases so L1 `plot` / `绘图` get host optionals (`grid`, `path`, …)
|
||||
// instead of thin wrappers that only forward required params.
|
||||
"host_plot" | "plot" | "绘图" => Self::Plot,
|
||||
"host_plot_points" | "plot_points" | "绘点列" => Self::PlotPoints,
|
||||
"host_plot_conic" | "plot_conic" | "绘圆锥" => Self::PlotConic,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -129,10 +240,45 @@ impl HostFn {
|
||||
Self::HttpGet => "host_http_get",
|
||||
Self::HttpPost => "host_http_post",
|
||||
Self::UrlEncode => "host_url_encode",
|
||||
Self::Pi => "host_pi",
|
||||
Self::EConst => "host_e",
|
||||
Self::Num => "host_num",
|
||||
Self::MathAdd => "host_math_add",
|
||||
Self::MathSub => "host_math_sub",
|
||||
Self::MathMul => "host_math_mul",
|
||||
Self::MathDiv => "host_math_div",
|
||||
Self::MathPow => "host_math_pow",
|
||||
Self::MathNeg => "host_math_neg",
|
||||
Self::MathSin => "host_math_sin",
|
||||
Self::MathCos => "host_math_cos",
|
||||
Self::MathTan => "host_math_tan",
|
||||
Self::MathAsin => "host_math_asin",
|
||||
Self::MathAcos => "host_math_acos",
|
||||
Self::MathAtan => "host_math_atan",
|
||||
Self::MathSqrt => "host_math_sqrt",
|
||||
Self::MathAbs => "host_math_abs",
|
||||
Self::MathLn => "host_math_ln",
|
||||
Self::MathExp => "host_math_exp",
|
||||
Self::MathFloor => "host_math_floor",
|
||||
Self::MathCeil => "host_math_ceil",
|
||||
Self::MathMin => "host_math_min",
|
||||
Self::MathMax => "host_math_max",
|
||||
Self::Random => "host_random",
|
||||
Self::RandomInt => "host_random_int",
|
||||
Self::Seed => "host_seed",
|
||||
Self::Formula => "host_formula",
|
||||
Self::Simplify => "host_simplify",
|
||||
Self::Expand => "host_expand",
|
||||
Self::Diff => "host_diff",
|
||||
Self::Subs => "host_subs",
|
||||
Self::Eval => "host_eval",
|
||||
Self::Solve => "host_solve",
|
||||
Self::Plot => "host_plot",
|
||||
Self::PlotPoints => "host_plot_points",
|
||||
Self::PlotConic => "host_plot_conic",
|
||||
}
|
||||
}
|
||||
|
||||
/// Required params first; see `optional_params` for trailing optionals.
|
||||
pub fn required_params(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::ReadText | Self::Exists | Self::ListDir | Self::MakeDir | Self::Remove => {
|
||||
@@ -152,6 +298,20 @@ impl HostFn {
|
||||
Self::JsonGet => &["value", "key"],
|
||||
Self::HttpGet => &["url"],
|
||||
Self::HttpPost => &["url", "body"],
|
||||
Self::Pi | Self::EConst | Self::Random => &[],
|
||||
Self::Num | Self::MathNeg | Self::MathSin | Self::MathCos | Self::MathTan
|
||||
| Self::MathAsin | Self::MathAcos | Self::MathAtan | Self::MathSqrt
|
||||
| Self::MathAbs | Self::MathLn | Self::MathExp | Self::MathFloor | Self::MathCeil
|
||||
| Self::Seed | Self::Formula | Self::Simplify | Self::Expand => &["value"],
|
||||
Self::MathAdd | Self::MathSub | Self::MathMul | Self::MathDiv | Self::MathPow
|
||||
| Self::MathMin | Self::MathMax => &["a", "b"],
|
||||
Self::RandomInt => &["min", "max"],
|
||||
Self::Diff => &["formula", "var"],
|
||||
Self::Subs | Self::Eval => &["formula", "var", "value"],
|
||||
Self::Solve => &["formula", "var"],
|
||||
Self::Plot => &["formula", "var", "min", "max"],
|
||||
Self::PlotPoints => &["xs", "ys"],
|
||||
Self::PlotConic => &["kind", "a"],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +320,10 @@ impl HostFn {
|
||||
Self::JsonStringify => &["indent"],
|
||||
Self::HttpPost => &["content_type"],
|
||||
Self::Exec => &["args"],
|
||||
Self::Solve => &["min", "max"],
|
||||
Self::Plot => &["steps", "path", "derivative", "grid"],
|
||||
Self::PlotPoints => &["path", "grid"],
|
||||
Self::PlotConic => &["b", "h", "k", "path", "grid"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -172,7 +336,7 @@ impl HostFn {
|
||||
}
|
||||
|
||||
pub fn call_host(
|
||||
ctx: &HostContext,
|
||||
ctx: &mut HostContext,
|
||||
fn_id: HostFn,
|
||||
bound: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
@@ -217,6 +381,82 @@ pub fn call_host(
|
||||
bound.get("content_type"),
|
||||
),
|
||||
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
|
||||
HostFn::Pi => math::pi(),
|
||||
HostFn::EConst => math::e_const(),
|
||||
HostFn::Num => math::to_num(require(bound, "value")?),
|
||||
HostFn::MathAdd => math::binary_num("add", require(bound, "a")?, require(bound, "b")?),
|
||||
HostFn::MathSub => math::binary_num("sub", require(bound, "a")?, require(bound, "b")?),
|
||||
HostFn::MathMul => math::binary_num("mul", require(bound, "a")?, require(bound, "b")?),
|
||||
HostFn::MathDiv => math::binary_num("div", require(bound, "a")?, require(bound, "b")?),
|
||||
HostFn::MathPow => math::binary_num("pow", require(bound, "a")?, require(bound, "b")?),
|
||||
HostFn::MathMin => math::binary_num("min", require(bound, "a")?, require(bound, "b")?),
|
||||
HostFn::MathMax => math::binary_num("max", require(bound, "a")?, require(bound, "b")?),
|
||||
HostFn::MathNeg => math::unary_num("neg", require(bound, "value")?),
|
||||
HostFn::MathSin => math::unary_num("sin", require(bound, "value")?),
|
||||
HostFn::MathCos => math::unary_num("cos", require(bound, "value")?),
|
||||
HostFn::MathTan => math::unary_num("tan", require(bound, "value")?),
|
||||
HostFn::MathAsin => math::unary_num("asin", require(bound, "value")?),
|
||||
HostFn::MathAcos => math::unary_num("acos", require(bound, "value")?),
|
||||
HostFn::MathAtan => math::unary_num("atan", require(bound, "value")?),
|
||||
HostFn::MathSqrt => math::unary_num("sqrt", require(bound, "value")?),
|
||||
HostFn::MathAbs => math::unary_num("abs", require(bound, "value")?),
|
||||
HostFn::MathLn => math::unary_num("ln", require(bound, "value")?),
|
||||
HostFn::MathExp => math::unary_num("exp", require(bound, "value")?),
|
||||
HostFn::MathFloor => math::unary_num("floor", require(bound, "value")?),
|
||||
HostFn::MathCeil => math::unary_num("ceil", require(bound, "value")?),
|
||||
HostFn::Random => math::random(ctx),
|
||||
HostFn::RandomInt => {
|
||||
math::random_int(ctx, require(bound, "min")?, require(bound, "max")?)
|
||||
}
|
||||
HostFn::Seed => math::seed(ctx, require(bound, "value")?),
|
||||
HostFn::Formula => math::formula_parse(require(bound, "value")?),
|
||||
HostFn::Simplify => math::simplify(require(bound, "value")?),
|
||||
HostFn::Expand => math::expand(require(bound, "value")?),
|
||||
HostFn::Diff => math::diff(require(bound, "formula")?, require(bound, "var")?),
|
||||
HostFn::Subs => math::subs(
|
||||
require(bound, "formula")?,
|
||||
require(bound, "var")?,
|
||||
require(bound, "value")?,
|
||||
),
|
||||
HostFn::Eval => math::eval_at(
|
||||
require(bound, "formula")?,
|
||||
require(bound, "var")?,
|
||||
require(bound, "value")?,
|
||||
),
|
||||
HostFn::Solve => math::solve(
|
||||
require(bound, "formula")?,
|
||||
require(bound, "var")?,
|
||||
bound.get("min"),
|
||||
bound.get("max"),
|
||||
),
|
||||
HostFn::Plot => math::plot(
|
||||
ctx,
|
||||
require(bound, "formula")?,
|
||||
require(bound, "var")?,
|
||||
require(bound, "min")?,
|
||||
require(bound, "max")?,
|
||||
bound.get("steps"),
|
||||
bound.get("path"),
|
||||
bound.get("derivative"),
|
||||
bound.get("grid"),
|
||||
),
|
||||
HostFn::PlotPoints => math::plot_points(
|
||||
ctx,
|
||||
require(bound, "xs")?,
|
||||
require(bound, "ys")?,
|
||||
bound.get("path"),
|
||||
bound.get("grid"),
|
||||
),
|
||||
HostFn::PlotConic => math::plot_conic(
|
||||
ctx,
|
||||
require(bound, "kind")?,
|
||||
require(bound, "a")?,
|
||||
bound.get("b"),
|
||||
bound.get("h"),
|
||||
bound.get("k"),
|
||||
bound.get("path"),
|
||||
bound.get("grid"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,8 @@ fn json_to_value(v: &serde_json::Value) -> Result<Value, String> {
|
||||
serde_json::Value::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
Value::Int(i)
|
||||
} else if let Some(f) = n.as_f64() {
|
||||
Value::Num(f)
|
||||
} else {
|
||||
Value::Text(n.to_string())
|
||||
}
|
||||
@@ -87,6 +89,9 @@ fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
|
||||
Value::None => serde_json::Value::Null,
|
||||
Value::Bool(b) => serde_json::Value::Bool(*b),
|
||||
Value::Int(n) => serde_json::Value::Number((*n).into()),
|
||||
Value::Num(n) => serde_json::Number::from_f64(*n)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
Value::Text(s) => serde_json::Value::String(s.clone()),
|
||||
Value::List(xs) => {
|
||||
let mut arr = Vec::with_capacity(xs.len());
|
||||
@@ -102,5 +107,6 @@ fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
|
||||
}
|
||||
serde_json::Value::Object(map)
|
||||
}
|
||||
Value::Formula(e) => serde_json::Value::String(e.as_display()),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! Host entry points for math / formula / random / plot.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::formula::{self, Expr};
|
||||
use crate::host::fs;
|
||||
use crate::host::{HostContext, PlotArtifact};
|
||||
use crate::value::Value;
|
||||
|
||||
pub fn as_f64(v: &Value) -> Result<f64, String> {
|
||||
match v {
|
||||
Value::Num(n) => Ok(*n),
|
||||
Value::Int(n) => Ok(*n as f64),
|
||||
Value::Text(s) => s
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.map_err(|_| format!("cannot convert to num: {s:?}")),
|
||||
_ => Err("expected num (or int/text)".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt<'a>(v: Option<&'a Value>) -> Option<&'a Value> {
|
||||
match v {
|
||||
None | Some(Value::None) => None,
|
||||
Some(v) => Some(v),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_text(v: &Value) -> Result<&str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err("expected text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_bool(v: &Value) -> bool {
|
||||
v.truthy()
|
||||
}
|
||||
|
||||
pub fn formula_from_value(v: &Value) -> Result<Expr, String> {
|
||||
match v {
|
||||
Value::Formula(e) => Ok(e.clone()),
|
||||
Value::Text(s) => formula::parse(s),
|
||||
Value::Num(n) => Ok(Expr::Num(*n)),
|
||||
Value::Int(n) => Ok(Expr::Num(*n as f64)),
|
||||
_ => Err("expected formula or expression text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn num_val(n: f64) -> Value {
|
||||
Value::Num(n)
|
||||
}
|
||||
|
||||
pub fn pi() -> Result<Value, String> {
|
||||
Ok(num_val(std::f64::consts::PI))
|
||||
}
|
||||
|
||||
pub fn e_const() -> Result<Value, String> {
|
||||
Ok(num_val(std::f64::consts::E))
|
||||
}
|
||||
|
||||
pub fn to_num(v: &Value) -> Result<Value, String> {
|
||||
Ok(num_val(as_f64(v)?))
|
||||
}
|
||||
|
||||
pub fn unary_num(op: &str, x: &Value) -> Result<Value, String> {
|
||||
let x = as_f64(x)?;
|
||||
let y = match op {
|
||||
"neg" => -x,
|
||||
"sin" => x.sin(),
|
||||
"cos" => x.cos(),
|
||||
"tan" => x.tan(),
|
||||
"asin" => x.asin(),
|
||||
"acos" => x.acos(),
|
||||
"atan" => x.atan(),
|
||||
"sqrt" => x.sqrt(),
|
||||
"abs" => x.abs(),
|
||||
"ln" | "log" => x.ln(),
|
||||
"exp" => x.exp(),
|
||||
"floor" => x.floor(),
|
||||
"ceil" => x.ceil(),
|
||||
_ => return Err(format!("unknown unary math op `{op}`")),
|
||||
};
|
||||
Ok(num_val(y))
|
||||
}
|
||||
|
||||
pub fn binary_num(op: &str, a: &Value, b: &Value) -> Result<Value, String> {
|
||||
let a = as_f64(a)?;
|
||||
let b = as_f64(b)?;
|
||||
let y = match op {
|
||||
"add" => a + b,
|
||||
"sub" => a - b,
|
||||
"mul" => a * b,
|
||||
"div" => {
|
||||
if b == 0.0 {
|
||||
return Err("division by zero".into());
|
||||
}
|
||||
a / b
|
||||
}
|
||||
"pow" => a.powf(b),
|
||||
"min" => a.min(b),
|
||||
"max" => a.max(b),
|
||||
_ => return Err(format!("unknown binary math op `{op}`")),
|
||||
};
|
||||
Ok(num_val(y))
|
||||
}
|
||||
|
||||
pub fn seed(ctx: &mut HostContext, v: &Value) -> Result<Value, String> {
|
||||
let n = as_f64(v)? as u64;
|
||||
ctx.rng = n ^ 0xA5A5_A5A5_A5A5_A5A5;
|
||||
if ctx.rng == 0 {
|
||||
ctx.rng = 0xC0FFEE;
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn random(ctx: &mut HostContext) -> Result<Value, String> {
|
||||
Ok(num_val(ctx.next_f64()))
|
||||
}
|
||||
|
||||
pub fn random_int(ctx: &mut HostContext, lo: &Value, hi: &Value) -> Result<Value, String> {
|
||||
let lo = as_f64(lo)? as i64;
|
||||
let hi = as_f64(hi)? as i64;
|
||||
if hi < lo {
|
||||
return Err("random_int: max < min".into());
|
||||
}
|
||||
let span = (hi - lo + 1) as u64;
|
||||
let r = ctx.next_u64() % span;
|
||||
Ok(Value::Int(lo + r as i64))
|
||||
}
|
||||
|
||||
pub fn formula_parse(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text)?;
|
||||
Ok(Value::Formula(formula::parse(s)?))
|
||||
}
|
||||
|
||||
pub fn simplify(v: &Value) -> Result<Value, String> {
|
||||
Ok(Value::Formula(formula::simplify(&formula_from_value(v)?)))
|
||||
}
|
||||
|
||||
pub fn expand(v: &Value) -> Result<Value, String> {
|
||||
Ok(Value::Formula(formula::expand(&formula_from_value(v)?)))
|
||||
}
|
||||
|
||||
pub fn diff(formula: &Value, var: &Value) -> Result<Value, String> {
|
||||
let e = formula_from_value(formula)?;
|
||||
let var = as_text(var)?;
|
||||
Ok(Value::Formula(formula::diff(&e, var)))
|
||||
}
|
||||
|
||||
pub fn subs(formula: &Value, var: &Value, value: &Value) -> Result<Value, String> {
|
||||
let e = formula_from_value(formula)?;
|
||||
let var = as_text(var)?;
|
||||
let val = formula_from_value(value)?;
|
||||
let out = formula::subs(&e, var, &val);
|
||||
if let Expr::Num(n) = out {
|
||||
Ok(num_val(n))
|
||||
} else {
|
||||
Ok(Value::Formula(out))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval_at(formula: &Value, var: &Value, value: &Value) -> Result<Value, String> {
|
||||
let e = formula_from_value(formula)?;
|
||||
let var = as_text(var)?;
|
||||
let x = as_f64(value)?;
|
||||
let mut env = HashMap::new();
|
||||
env.insert(var.to_string(), x);
|
||||
Ok(num_val(formula::eval_f64(&e, &env)?))
|
||||
}
|
||||
|
||||
pub fn solve(
|
||||
formula: &Value,
|
||||
var: &Value,
|
||||
min: Option<&Value>,
|
||||
max: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let e = formula_from_value(formula)?;
|
||||
let var = as_text(var)?;
|
||||
let xmin = opt(min).map(as_f64).transpose()?.unwrap_or(-100.0);
|
||||
let xmax = opt(max).map(as_f64).transpose()?.unwrap_or(100.0);
|
||||
let roots = formula::solve(&e, var, xmin, xmax)?;
|
||||
Ok(Value::List(roots.into_iter().map(num_val).collect()))
|
||||
}
|
||||
|
||||
fn maybe_write_plot(
|
||||
ctx: &mut HostContext,
|
||||
path: Option<&Value>,
|
||||
svg: String,
|
||||
) -> Result<Value, String> {
|
||||
let path_s = match opt(path) {
|
||||
Some(v) => Some(as_text(v)?.to_string()),
|
||||
None => None,
|
||||
};
|
||||
if let Some(ref p) = path_s {
|
||||
fs::write_text(ctx, &Value::Text(p.clone()), &Value::Text(svg.clone()))?;
|
||||
}
|
||||
ctx.plots.push(PlotArtifact {
|
||||
path: path_s,
|
||||
svg: svg.clone(),
|
||||
});
|
||||
Ok(Value::Text(svg))
|
||||
}
|
||||
|
||||
fn plot_style(grid: Option<&Value>) -> Result<formula::PlotStyle, String> {
|
||||
let grid = match opt(grid) {
|
||||
None => true,
|
||||
Some(v) => as_bool(v),
|
||||
};
|
||||
Ok(formula::PlotStyle { grid })
|
||||
}
|
||||
|
||||
pub fn plot(
|
||||
ctx: &mut HostContext,
|
||||
formula: &Value,
|
||||
var: &Value,
|
||||
min: &Value,
|
||||
max: &Value,
|
||||
steps: Option<&Value>,
|
||||
path: Option<&Value>,
|
||||
derivative: Option<&Value>,
|
||||
grid: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let mut e = formula_from_value(formula)?;
|
||||
let var_s = as_text(var)?;
|
||||
if opt(derivative).map(as_bool).unwrap_or(false) {
|
||||
e = formula::diff(&e, var_s);
|
||||
}
|
||||
let xmin = as_f64(min)?;
|
||||
let xmax = as_f64(max)?;
|
||||
let steps = match opt(steps) {
|
||||
Some(v) => as_f64(v)? as usize,
|
||||
None => 200,
|
||||
};
|
||||
let style = plot_style(grid)?;
|
||||
let svg = formula::plot_function_svg(&e, var_s, xmin, xmax, steps, style)?;
|
||||
maybe_write_plot(ctx, path, svg)
|
||||
}
|
||||
|
||||
pub fn plot_points(
|
||||
ctx: &mut HostContext,
|
||||
xs: &Value,
|
||||
ys: &Value,
|
||||
path: Option<&Value>,
|
||||
grid: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let xs = match xs {
|
||||
Value::List(xs) => xs
|
||||
.iter()
|
||||
.map(as_f64)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
_ => return Err("plot_points needs list xs".into()),
|
||||
};
|
||||
let ys = match ys {
|
||||
Value::List(ys) => ys
|
||||
.iter()
|
||||
.map(as_f64)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
_ => return Err("plot_points needs list ys".into()),
|
||||
};
|
||||
let style = plot_style(grid)?;
|
||||
let svg = formula::plot_points_svg(&xs, &ys, style)?;
|
||||
maybe_write_plot(ctx, path, svg)
|
||||
}
|
||||
|
||||
pub fn plot_conic(
|
||||
ctx: &mut HostContext,
|
||||
kind: &Value,
|
||||
a: &Value,
|
||||
b: Option<&Value>,
|
||||
h: Option<&Value>,
|
||||
k: Option<&Value>,
|
||||
path: Option<&Value>,
|
||||
grid: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let kind = as_text(kind)?;
|
||||
let a = as_f64(a)?;
|
||||
let b = opt(b).map(as_f64).transpose()?.unwrap_or(a);
|
||||
let h = opt(h).map(as_f64).transpose()?.unwrap_or(0.0);
|
||||
let k = opt(k).map(as_f64).transpose()?.unwrap_or(0.0);
|
||||
let style = plot_style(grid)?;
|
||||
let svg = formula::plot_conic_svg(kind, a, b, h, k, style)?;
|
||||
maybe_write_plot(ctx, path, svg)
|
||||
}
|
||||
+57
-1
@@ -1,4 +1,4 @@
|
||||
//! L0.5 host primitives for official stdlib (`lib/fs`, `time`, …).
|
||||
//! L0.5 host primitives for official stdlib (`lib/fs`, `time`, `math`, …).
|
||||
//!
|
||||
//! User docs should import L1 wrappers; these `host_*` names are the Rust surface.
|
||||
//! Capabilities default **on** (importing a lib means you intend to use it).
|
||||
@@ -7,6 +7,7 @@
|
||||
mod dispatch;
|
||||
mod fs;
|
||||
mod json;
|
||||
pub mod math;
|
||||
mod net;
|
||||
mod sys;
|
||||
mod time;
|
||||
@@ -34,6 +35,14 @@ impl Default for HostCaps {
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG plot produced during a run (for CLI auto-write / view embed).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PlotArtifact {
|
||||
/// User-requested path, if any.
|
||||
pub path: Option<String>,
|
||||
pub svg: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HostContext {
|
||||
pub caps: HostCaps,
|
||||
@@ -43,6 +52,9 @@ pub struct HostContext {
|
||||
/// Soft mode: do not `process::exit`; honor sleep_limit (view / capture / export).
|
||||
pub soft_side_effects: bool,
|
||||
pub sleep_limit_ms: Option<u64>,
|
||||
/// LCG state for `random` / `random_int`.
|
||||
pub rng: u64,
|
||||
pub plots: Vec<PlotArtifact>,
|
||||
}
|
||||
|
||||
impl Default for HostContext {
|
||||
@@ -54,6 +66,8 @@ impl Default for HostContext {
|
||||
argv: Vec::new(),
|
||||
soft_side_effects: false,
|
||||
sleep_limit_ms: Some(30_000),
|
||||
rng: 0xC0FF_EE42_CAFE_BABE,
|
||||
plots: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,6 +111,23 @@ impl HostContext {
|
||||
self.caps.net
|
||||
}
|
||||
|
||||
pub fn next_u64(&mut self) -> u64 {
|
||||
// SplitMix64-ish LCG step
|
||||
self.rng = self
|
||||
.rng
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1);
|
||||
let mut z = self.rng;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
pub fn next_f64(&mut self) -> f64 {
|
||||
let x = self.next_u64() >> 11;
|
||||
(x as f64) / ((1u64 << 53) as f64)
|
||||
}
|
||||
|
||||
pub fn resolve_path(&self, rel: &str) -> Result<PathBuf, String> {
|
||||
let p = Path::new(rel);
|
||||
let abs = if p.is_absolute() {
|
||||
@@ -124,3 +155,28 @@ impl HostContext {
|
||||
Ok(abs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Write auto-named plot files for CLI runs when `path` was omitted.
|
||||
pub fn flush_auto_plots(source_path: Option<&Path>, plots: &[PlotArtifact]) -> Result<(), String> {
|
||||
let mut auto_i = 0usize;
|
||||
for plot in plots {
|
||||
if plot.path.is_some() {
|
||||
continue;
|
||||
}
|
||||
auto_i += 1;
|
||||
let stem = source_path
|
||||
.and_then(|p| p.file_stem())
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("out");
|
||||
let stem = stem.trim_end_matches(".mq");
|
||||
let name = format!("{stem}-plot-{auto_i}.svg");
|
||||
let dir = source_path
|
||||
.and_then(|p| p.parent())
|
||||
.unwrap_or_else(|| Path::new("."));
|
||||
let dest = dir.join(&name);
|
||||
std::fs::write(&dest, plot.svg.as_bytes())
|
||||
.map_err(|e| format!("failed to write plot {}: {e}", dest.display()))?;
|
||||
println!("plot: {}", dest.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user