@matheos/core 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -2
- package/dist/evaluate.d.ts +13 -0
- package/dist/evaluate.js +580 -0
- package/dist/evaluate.js.map +1 -0
- package/dist/html.d.ts +8 -0
- package/dist/html.js +230 -0
- package/dist/html.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/model.d.ts +215 -0
- package/dist/model.js +2 -0
- package/dist/model.js.map +1 -0
- package/dist/parse.d.ts +2 -0
- package/dist/parse.js +280 -0
- package/dist/parse.js.map +1 -0
- package/dist/plot.d.ts +17 -0
- package/dist/plot.js +79 -0
- package/dist/plot.js.map +1 -0
- package/dist/printer.d.ts +26 -0
- package/dist/printer.js +319 -0
- package/dist/printer.js.map +1 -0
- package/dist/units.d.ts +21 -0
- package/dist/units.js +164 -0
- package/dist/units.js.map +1 -0
- package/package.json +67 -4
package/README.md
CHANGED
|
@@ -1,3 +1,45 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @matheos/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The engine behind [Matheos](https://matheos.fly.dev): plain-text `.mth` calculation documents for
|
|
4
|
+
structural engineers. Markdown prose plus unit-aware math blocks, checks with utilization,
|
|
5
|
+
catalogues, loops, plots; rendered to a printable A4 report. No DOM: runs in Node and in the
|
|
6
|
+
browser.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { parse, evaluate, statements } from '@matheos/core';
|
|
10
|
+
import { toHtml } from '@matheos/core/html';
|
|
11
|
+
|
|
12
|
+
const text = `
|
|
13
|
+
---
|
|
14
|
+
title: Floor beam
|
|
15
|
+
---
|
|
16
|
+
\`\`\`math
|
|
17
|
+
L = 6.0 m ? # span
|
|
18
|
+
q_Ed = 25 kN/m ?
|
|
19
|
+
M_Ed = q_Ed L^2 / 8 to kNm
|
|
20
|
+
W_pl_y = 628.4 cm^3
|
|
21
|
+
f_y = 355 MPa
|
|
22
|
+
M_c_Rd = W_pl_y f_y / 1.0 to kNm
|
|
23
|
+
check M_Ed <= M_c_Rd warn 80%
|
|
24
|
+
\`\`\`
|
|
25
|
+
`;
|
|
26
|
+
|
|
27
|
+
const doc = parse(text);
|
|
28
|
+
const rendered = evaluate(doc, { resolve: (file) => catalogues[file] }); // catalogues: JSON tables named in the front matter
|
|
29
|
+
const failed = statements(rendered).filter((s) => s.kind === 'check' && !s.verdict);
|
|
30
|
+
const html = toHtml(rendered); // a self-contained page: KaTeX from a CDN unless `head` is given
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
- `parse(text)` → `Document` (front matter, blocks, statements with positions).
|
|
34
|
+
- `evaluate(doc, { resolve? })` → `Rendered`: per statement the LaTeX line (`name = formula = substituted = result`),
|
|
35
|
+
verdict and η for checks, errors with positions, warnings, the final scope.
|
|
36
|
+
- `toHtml(rendered, { head?, assets? })` → the report. `head` replaces the CDN KaTeX link (inline the CSS for
|
|
37
|
+
offline use); `assets` resolves relative image paths.
|
|
38
|
+
- `statements(rendered)` → every statement in document order, loops included.
|
|
39
|
+
|
|
40
|
+
Grammar and authoring guide: the `matheos guide` command of `@matheos/cli`, or
|
|
41
|
+
[SKILL.md](https://github.com/Suharevillya/matheos-issues/blob/main/SKILL.md). Bugs:
|
|
42
|
+
[matheos-issues](https://github.com/Suharevillya/matheos-issues/issues).
|
|
43
|
+
|
|
44
|
+
Versioning: semantic; the grammar is additive within a major. The web app, the CLI and the FrameLab
|
|
45
|
+
integration pin a version and upgrade by bumping it.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Document, Pos, Rendered, RenderedStatement } from './model.js';
|
|
2
|
+
export interface EvalOptions {
|
|
3
|
+
/** Loads a catalogue file named in the front matter (`catalogs:`); undefined means not found. */
|
|
4
|
+
resolve?: (path: string) => unknown;
|
|
5
|
+
/** internal: recursion depth of the loop expansion pass */
|
|
6
|
+
depth?: number;
|
|
7
|
+
}
|
|
8
|
+
/** `c_z'` in an expression: the prime is part of the name (`c_z$p` for math.js, which would read `'` as transpose); strings are left alone. */
|
|
9
|
+
export declare function primes(s: string): string;
|
|
10
|
+
export declare function evaluate(doc: Document, options?: EvalOptions): Rendered;
|
|
11
|
+
/** Every rendered statement, loops included, in document order. */
|
|
12
|
+
export declare function statements(r: Rendered): RenderedStatement[];
|
|
13
|
+
export type { Pos };
|
package/dist/evaluate.js
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
import { math, isUnit, isNA, NA, wording, unitLatex, isForeignUnit, displayUnit, isMatrixLike } from './units.js';
|
|
2
|
+
import { print, identifier, formatValue, formatEta, literalsOf, negate, plainText } from './printer.js';
|
|
3
|
+
import { plotSvg } from './plot.js';
|
|
4
|
+
import { parse } from './parse.js';
|
|
5
|
+
const CMP_FN = { '<=': 'smallerEq', '>=': 'largerEq', '<': 'smaller', '>': 'larger', '==': 'equal', '!=': 'unequal' };
|
|
6
|
+
const CMP_TEX = { '<=': '\\le', '>=': '\\ge', '<': '<', '>': '>', '==': '=', '!=': '\\ne' };
|
|
7
|
+
class DependsError extends Error {
|
|
8
|
+
constructor(dep) { super(`depends on ${dep}`); }
|
|
9
|
+
}
|
|
10
|
+
/** `pi (d - t)` is a product: math.js constants that are not functions. */
|
|
11
|
+
const isConstant = (name) => name in math && typeof math[name] !== 'function' && !/^[A-Z]/.test(name);
|
|
12
|
+
/** `c_z'` in an expression: the prime is part of the name (`c_z$p` for math.js, which would read `'` as transpose); strings are left alone. */
|
|
13
|
+
export function primes(s) {
|
|
14
|
+
let out = '', quote;
|
|
15
|
+
for (let i = 0; i < s.length; i++) {
|
|
16
|
+
const ch = s[i];
|
|
17
|
+
if (quote) {
|
|
18
|
+
out += ch;
|
|
19
|
+
if (ch === quote)
|
|
20
|
+
quote = undefined;
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (ch === "'" && /[\wͰ-Ͽ']/.test(s[i - 1] ?? '')) {
|
|
24
|
+
out += '$p';
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (ch === '"' || ch === "'")
|
|
28
|
+
quote = ch;
|
|
29
|
+
out += ch;
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
/** `integrate(expr, x, …)`, `derivative(expr, x)`, `simplify(expr)`: the named variable (all symbols for simplify) may be unbound. */
|
|
34
|
+
const SYMBOLIC = new Set(['integrate', 'derivative', 'simplify', 'solve']);
|
|
35
|
+
/** The one precedence trap: `a / b (c)` is a/(b·c). A hint when the denominator's implicit product carries a bracket or a call
|
|
36
|
+
* (plain chains like `/ 384 E I` are almost always meant as the denominator and stay quiet). Not an error. */
|
|
37
|
+
function lint(node) {
|
|
38
|
+
const factors = (x) => (x.type === 'OperatorNode' && x.op === '*' && x.implicit ? x.args.flatMap((a) => factors(a)) : [x]);
|
|
39
|
+
for (const d of node.filter((x) => x.type === 'OperatorNode' && (x.op === '/' || x.op === './'))) {
|
|
40
|
+
const den = d.args[1];
|
|
41
|
+
if (den.type !== 'OperatorNode' || den.op !== '*' || !den.implicit)
|
|
42
|
+
continue;
|
|
43
|
+
const fs = factors(den);
|
|
44
|
+
if (fs.slice(1).some((f) => f.type === 'ParenthesisNode' || f.type === 'FunctionNode'))
|
|
45
|
+
return `"${d.toString()}" divides by the whole product "${den.toString()}"; write "/ ${fs[0].toString()} * …" if the rest belongs to the numerator`;
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
function freeSymbols(node) {
|
|
50
|
+
const free = new Set();
|
|
51
|
+
for (const call of node.filter((x) => x.type === 'FunctionNode')) {
|
|
52
|
+
if (!SYMBOLIC.has(call.fn.name))
|
|
53
|
+
continue;
|
|
54
|
+
if (call.fn.name === 'simplify')
|
|
55
|
+
for (const s of call.args[0].filter((x) => x.type === 'SymbolNode'))
|
|
56
|
+
free.add(s.name);
|
|
57
|
+
const v = call.args[1];
|
|
58
|
+
if (v?.type === 'SymbolNode')
|
|
59
|
+
free.add(v.name);
|
|
60
|
+
}
|
|
61
|
+
return free;
|
|
62
|
+
}
|
|
63
|
+
export function evaluate(doc, options = {}) {
|
|
64
|
+
const depth = options.depth ?? 0;
|
|
65
|
+
const scope = new Map();
|
|
66
|
+
const display = new Map(); // result-line LaTeX per bound name
|
|
67
|
+
const failed = new Set();
|
|
68
|
+
const errors = [];
|
|
69
|
+
const digits = typeof doc.frontMatter.digits === 'number' ? doc.frontMatter.digits : 4;
|
|
70
|
+
scope.set('na', NA); // `na`: a value that does not apply (min/max skip it, checks report n/a)
|
|
71
|
+
// catalogues: each JSON table becomes an object of rows keyed by name, numeric columns carrying the units given
|
|
72
|
+
const catalogs = doc.frontMatter.catalogs;
|
|
73
|
+
if (catalogs && typeof catalogs === 'object') {
|
|
74
|
+
for (const [name, cat] of Object.entries(catalogs)) {
|
|
75
|
+
try {
|
|
76
|
+
if (!cat || typeof cat !== 'object' || typeof cat.file !== 'string')
|
|
77
|
+
throw new Error(`catalog ${name}: needs a file`);
|
|
78
|
+
const data = options.resolve?.(cat.file);
|
|
79
|
+
if (data === undefined)
|
|
80
|
+
throw new Error(`catalog ${name}: cannot load ${cat.file}`);
|
|
81
|
+
const rows = Array.isArray(data) ? data : typeof data === 'object' && data !== null && Array.isArray(data.rows) ? data.rows : undefined;
|
|
82
|
+
if (!rows)
|
|
83
|
+
throw new Error(`catalog ${name}: ${cat.file} is not a table`);
|
|
84
|
+
const units = { ...(data.units ?? {}), ...(cat.units ?? {}) };
|
|
85
|
+
for (const u of Object.values(units))
|
|
86
|
+
for (const sym of math.parse(u).filter((x) => x.type === 'SymbolNode'))
|
|
87
|
+
if (isForeignUnit(sym.name))
|
|
88
|
+
throw new Error(`catalog ${name}: unknown unit "${u}"`);
|
|
89
|
+
const key = cat.key ?? 'Name';
|
|
90
|
+
const table = {};
|
|
91
|
+
for (const row of rows) {
|
|
92
|
+
const id = String(row[key] ?? row['name'] ?? row['id'] ?? Object.keys(table).length + 1);
|
|
93
|
+
const o = {};
|
|
94
|
+
for (const [k, v] of Object.entries(row))
|
|
95
|
+
o[k] = typeof v === 'number' && units[k] ? math.unit(v, units[k]) : v;
|
|
96
|
+
table[id] = o;
|
|
97
|
+
}
|
|
98
|
+
scope.set(name, table);
|
|
99
|
+
}
|
|
100
|
+
catch (e) {
|
|
101
|
+
errors.push({ message: wording(e), pos: { start: { line: 1, column: 1, offset: 0 }, end: { line: 1, column: 1, offset: 0 } } });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const ctx = {
|
|
106
|
+
isVar: (n) => scope.has(n),
|
|
107
|
+
value: (n) => display.get(n),
|
|
108
|
+
cond: (c) => { try {
|
|
109
|
+
return Boolean(c.compile().evaluate(scope));
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return undefined;
|
|
113
|
+
} },
|
|
114
|
+
};
|
|
115
|
+
/** `a (b + c)` with a bound variable `a` is a product, not a call: math.js would call `a`. Functions keep call syntax. */
|
|
116
|
+
const prep = (expr, extra) => primes(expr).replace(/([A-Za-z_Ͱ-Ͽ][\wͰ-Ͽ$]*)\s+\(/g, (m, name) => (extra?.has(name) || (scope.has(name) && typeof scope.get(name) !== 'function') || isConstant(name)) ? `${name} * (` : m);
|
|
117
|
+
const parseExpr = (expr, params) => {
|
|
118
|
+
const node = math.parse(prep(expr, params));
|
|
119
|
+
const bound = new Set([...(params ?? []), ...(node.type === 'FunctionAssignmentNode' ? node.params : []), ...freeSymbols(node)]);
|
|
120
|
+
for (const sym of node.filter((x) => x.type === 'SymbolNode')) {
|
|
121
|
+
if (bound.has(sym.name))
|
|
122
|
+
continue;
|
|
123
|
+
if (failed.has(sym.name))
|
|
124
|
+
throw new DependsError(sym.name);
|
|
125
|
+
if (!scope.has(sym.name) && isForeignUnit(sym.name))
|
|
126
|
+
throw new Error(`unknown unit "${sym.name}"`);
|
|
127
|
+
}
|
|
128
|
+
return node;
|
|
129
|
+
};
|
|
130
|
+
const run = (node) => node.compile().evaluate(scope);
|
|
131
|
+
const convert = (v, to) => {
|
|
132
|
+
if (!to || isNA(v))
|
|
133
|
+
return v;
|
|
134
|
+
if (to === '%') {
|
|
135
|
+
if (typeof v === 'number' || (isUnit(v) && v.dimensions.every((d) => d === 0)))
|
|
136
|
+
return v;
|
|
137
|
+
throw new Error(`only a dimensionless value can be shown in %`);
|
|
138
|
+
}
|
|
139
|
+
for (const sym of math.parse(to).filter((x) => x.type === 'SymbolNode'))
|
|
140
|
+
if (isForeignUnit(sym.name))
|
|
141
|
+
throw new Error(`unknown unit "${sym.name}"`);
|
|
142
|
+
if (Array.isArray(v) || (typeof v === 'object' && v !== null && 'toArray' in v)) { // vectors and matrices convert element by element
|
|
143
|
+
return math.map(v, (e) => convert(e, to));
|
|
144
|
+
}
|
|
145
|
+
if (!isUnit(v))
|
|
146
|
+
throw new Error(`cannot convert a number to ${to}`);
|
|
147
|
+
try {
|
|
148
|
+
return v.to(to);
|
|
149
|
+
}
|
|
150
|
+
catch (e) {
|
|
151
|
+
throw new Error(`cannot convert ${v.formatUnits()} to ${to}`);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const fmt = (v, to) => formatValue(v, to, digits);
|
|
155
|
+
const isLiteral = (n) => {
|
|
156
|
+
const u = n.type === 'ParenthesisNode' ? n.content : n;
|
|
157
|
+
return u.type === 'ConstantNode' || (u.type === 'OperatorNode' && u.op === '*' && !!u.implicit
|
|
158
|
+
&& u.args[0].type === 'ConstantNode' && u.args[1].type === 'SymbolNode' && !scope.has(u.args[1].name));
|
|
159
|
+
};
|
|
160
|
+
const collapse = (pieces) => pieces.filter((p, i) => i === 0 || p !== pieces[i - 1]);
|
|
161
|
+
/** Result text of an expression: a bound name keeps its own display unit, anything else uses the default rule. */
|
|
162
|
+
const shown = (node, value) => (node.type === 'SymbolNode' && display.get(node.name)) || fmt(value);
|
|
163
|
+
/** One side of a check or condition: its formula (absent for a literal), its value text, and `formula = value`. */
|
|
164
|
+
const side = (expr) => {
|
|
165
|
+
const node = parseExpr(expr);
|
|
166
|
+
const value = run(node);
|
|
167
|
+
const v = shown(node, value);
|
|
168
|
+
if (isLiteral(node))
|
|
169
|
+
return { v, latex: v, value };
|
|
170
|
+
const formula = print(node, 'formula', { ...ctx, literals: literalsOf(expr) });
|
|
171
|
+
return { formula, v, latex: collapse([formula, v]).join(' = '), value };
|
|
172
|
+
};
|
|
173
|
+
/** Condition line: `condition → evaluated` (docs/spec/conditionals.md). */
|
|
174
|
+
const condLine = (cond, negated) => {
|
|
175
|
+
const node = parseExpr(cond);
|
|
176
|
+
const value = Boolean(run(node));
|
|
177
|
+
if (node.type === 'OperatorNode' && CMP_FN[node.op]) {
|
|
178
|
+
const [a, b] = node.args;
|
|
179
|
+
const op = negated ? negate(node.op) : node.op;
|
|
180
|
+
const L = side(a.toString()), R = side(b.toString());
|
|
181
|
+
if (op === '==' && (isLiteral(b) && R.v === fmt(L.value) || isLiteral(a) && L.v === fmt(R.value)))
|
|
182
|
+
return { latex: isLiteral(b) ? L.latex : R.latex, value };
|
|
183
|
+
const evaluated = `${L.v} ${CMP_TEX[op]} ${R.v}`;
|
|
184
|
+
if (!L.formula && !R.formula)
|
|
185
|
+
return { latex: evaluated, value };
|
|
186
|
+
return { latex: `${L.formula ?? L.v} ${CMP_TEX[op]} ${R.formula ?? R.v} \\;\\rightarrow\\; ${evaluated}`, value };
|
|
187
|
+
}
|
|
188
|
+
const latex = print(node, 'formula', { ...ctx, literals: literalsOf(cond) });
|
|
189
|
+
return { latex: negated ? `\\text{not } \\left(${latex}\\right)` : latex, value };
|
|
190
|
+
};
|
|
191
|
+
/** `1 : n` or `1 : 2 : n` → the values of a loop variable (inclusive, at most 10 000). */
|
|
192
|
+
const rangeValues = (range) => {
|
|
193
|
+
const parts = range.split(':').map((p) => { const v = run(parseExpr(p.trim())); return typeof v === 'number' ? v : isUnit(v) && v.dimensions.every((d) => d === 0) ? Number(v.value) : NaN; });
|
|
194
|
+
if (parts.length < 2 || parts.length > 3 || parts.some((p) => !Number.isFinite(p)))
|
|
195
|
+
throw new Error(`loop range must be "from : to" or "from : step : to", got "${range}"`);
|
|
196
|
+
const [from, step, to] = parts.length === 3 ? parts : [parts[0], 1, parts[1]];
|
|
197
|
+
if (step === 0)
|
|
198
|
+
throw new Error('loop step must not be 0');
|
|
199
|
+
const out = [];
|
|
200
|
+
for (let v = from; step > 0 ? v <= to + 1e-9 : v >= to - 1e-9; v += step) {
|
|
201
|
+
out.push(Number(v.toFixed(10)));
|
|
202
|
+
if (out.length > 10000)
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
};
|
|
207
|
+
const fail = (st, e, items, indent) => {
|
|
208
|
+
const message = e instanceof DependsError ? e.message : wording(e);
|
|
209
|
+
if (st.kind === 'input' || st.kind === 'derived') {
|
|
210
|
+
failed.add(st.name);
|
|
211
|
+
scope.delete(st.name);
|
|
212
|
+
}
|
|
213
|
+
if (!(e instanceof DependsError))
|
|
214
|
+
errors.push({ message, pos: st.pos });
|
|
215
|
+
if (st.kind === 'function') {
|
|
216
|
+
failed.add(st.name);
|
|
217
|
+
scope.delete(st.name);
|
|
218
|
+
}
|
|
219
|
+
if (st.kind !== 'comment' && st.kind !== 'if' && st.kind !== 'for')
|
|
220
|
+
items.push({ kind: st.kind, latex: '', error: message, pos: st.pos, ...(st.caption !== undefined && { caption: st.caption }), ...(indent && { indent }) });
|
|
221
|
+
else if (st.kind === 'for')
|
|
222
|
+
items.push({ kind: 'cond', latex: '', error: message, pos: st.pos, ...(indent && { indent }) });
|
|
223
|
+
};
|
|
224
|
+
const renderStatements = (statements, opts, items, indent = false) => {
|
|
225
|
+
for (const st of statements) {
|
|
226
|
+
try {
|
|
227
|
+
const plain = st.kind !== 'comment' && st.kind !== 'if' && st.kind !== 'for';
|
|
228
|
+
const cap = plain && st.caption !== undefined ? { caption: st.caption } : {};
|
|
229
|
+
const ind = indent ? { indent } : {};
|
|
230
|
+
const silent = opts.hide || (plain && st.modifier === ';');
|
|
231
|
+
const resultOnly = opts.results || (plain && st.modifier === ':');
|
|
232
|
+
const derived = (s) => {
|
|
233
|
+
if (s.kind === 'derived' && s.name.includes('[')) { // `K[i, j] = …` mutates the matrix in scope
|
|
234
|
+
const node = parseExpr(`${s.name} = ${s.expr}`);
|
|
235
|
+
const value = run(node);
|
|
236
|
+
if (silent)
|
|
237
|
+
return;
|
|
238
|
+
const lits = literalsOf(s.expr);
|
|
239
|
+
const head = print(node.object, 'formula', ctx) + print(node.index, 'formula', { ...ctx, literals: literalsOf(s.name) });
|
|
240
|
+
const vectorOperand = node.value.filter((x) => x.type === 'SymbolNode').some((x) => isMatrixLike(scope.get(x.name)));
|
|
241
|
+
const stages = vectorOperand ? [print(node.value, 'formula', { ...ctx, literals: lits }), fmt(value)]
|
|
242
|
+
: [print(node.value, 'formula', { ...ctx, literals: lits }), print(node.value, 'subst', { ...ctx, literals: lits }), fmt(value)];
|
|
243
|
+
const pieces = resultOnly ? [fmt(value)] : collapse(stages);
|
|
244
|
+
items.push({ kind: 'derived', latex: [head, ...pieces].join(' = '), pieces: [head, ...pieces], pos: s.pos, ...cap, ...ind });
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const node = parseExpr(s.expr);
|
|
248
|
+
const value = run(node);
|
|
249
|
+
convert(value, s.to); // throws early when `to` cannot apply
|
|
250
|
+
const result = fmt(value, s.to);
|
|
251
|
+
if (s.kind === 'derived') {
|
|
252
|
+
scope.set(s.name, value);
|
|
253
|
+
failed.delete(s.name);
|
|
254
|
+
display.set(s.name, result);
|
|
255
|
+
}
|
|
256
|
+
if (silent)
|
|
257
|
+
return;
|
|
258
|
+
const warning = lint(node);
|
|
259
|
+
const lits = literalsOf(s.expr);
|
|
260
|
+
// a vector operand would make the substituted line unreadable: formula = result then
|
|
261
|
+
// a vector operand or a `solve` (whose variable is now bound to the root) would make the substituted line unreadable
|
|
262
|
+
const vectorOperand = node.filter((x) => x.type === 'SymbolNode').some((x) => isMatrixLike(scope.get(x.name)))
|
|
263
|
+
|| node.filter((x) => x.type === 'FunctionNode' && x.fn.name === 'solve').length > 0;
|
|
264
|
+
const stages = vectorOperand ? [print(node, 'formula', { ...ctx, literals: lits }), result]
|
|
265
|
+
: [print(node, 'formula', { ...ctx, literals: lits }), print(node, 'subst', { ...ctx, literals: lits }), result];
|
|
266
|
+
const pieces = resultOnly ? [result] : collapse(stages);
|
|
267
|
+
const head = s.kind === 'derived' ? [identifier(s.name)] : [];
|
|
268
|
+
items.push({ kind: s.kind, latex: [...head, ...pieces].join(' = '), pieces: [...head, ...pieces], pos: s.pos, ...cap, ...ind, ...(warning && { warning }) });
|
|
269
|
+
};
|
|
270
|
+
switch (st.kind) {
|
|
271
|
+
case 'comment': break;
|
|
272
|
+
case 'input': {
|
|
273
|
+
// echo the literal as typed: number (or a row vector of numbers), then the unit text upright
|
|
274
|
+
const m = /^([-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?|\[[^\]]*\])\s*(.*)$/i.exec(st.expr);
|
|
275
|
+
if (m[2] && scope.has(m[2])) {
|
|
276
|
+
derived({ ...st, kind: 'derived' });
|
|
277
|
+
break;
|
|
278
|
+
} // `25 t` with t bound: a product, not a unit
|
|
279
|
+
const node = parseExpr(st.expr);
|
|
280
|
+
const value = run(node);
|
|
281
|
+
const lit = m[1].startsWith('[')
|
|
282
|
+
? `\\begin{bmatrix} ${m[1].slice(1, -1).split(';').map((r) => r.split(',').map((x) => x.trim().replace(/e\+?(-?\d+)/i, '\\cdot10^{$1}')).join(' & ')).join(' \\\\ ')} \\end{bmatrix}`
|
|
283
|
+
: m[1].replace(/e\+?(-?\d+)/i, '\\cdot10^{$1}');
|
|
284
|
+
const latex = lit + (m[2] ? `\\,${unitLatex(m[2])}` : '');
|
|
285
|
+
scope.set(st.name, value);
|
|
286
|
+
failed.delete(st.name);
|
|
287
|
+
display.set(st.name, latex);
|
|
288
|
+
if (!silent)
|
|
289
|
+
items.push({ kind: 'input', latex: `${identifier(st.name)} = ${latex}`, pos: st.pos, ...cap, ...ind });
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
case 'derived':
|
|
293
|
+
case 'bare':
|
|
294
|
+
derived(st);
|
|
295
|
+
break;
|
|
296
|
+
case 'for': {
|
|
297
|
+
const values = rangeValues(st.range);
|
|
298
|
+
const at = items.length;
|
|
299
|
+
if (!silent && !resultOnly)
|
|
300
|
+
items.push({ kind: 'cond', latex: `${identifier(st.variable)} = ${values.length ? `${values[0]} \\ldots ${values[values.length - 1]}` : '\\varnothing'}`, pos: st.pos, ...ind });
|
|
301
|
+
for (const v of values) {
|
|
302
|
+
scope.set(st.variable, v);
|
|
303
|
+
failed.delete(st.variable);
|
|
304
|
+
renderStatements(st.statements, opts, items, true);
|
|
305
|
+
}
|
|
306
|
+
if (items.length === at + 1)
|
|
307
|
+
items.pop(); // a loop whose body prints nothing prints no header either
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
case 'function': {
|
|
311
|
+
const node = parseExpr(`${st.name}(${st.params.join(', ')}) = ${st.expr}`, new Set(st.params));
|
|
312
|
+
run(node); // binds the function in scope; the body is evaluated per call
|
|
313
|
+
failed.delete(st.name);
|
|
314
|
+
if (!silent)
|
|
315
|
+
items.push({ kind: 'function', latex: print(node, 'formula', { ...ctx, literals: literalsOf(st.expr) }), pos: st.pos, ...cap, ...ind });
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
case 'check': {
|
|
319
|
+
if (st.only !== undefined && !run(parseExpr(st.only))) { // `check … if cond` with cond false: shown as n/a
|
|
320
|
+
const tex = (e) => { try {
|
|
321
|
+
return print(parseExpr(e), 'formula', { ...ctx, literals: literalsOf(e) });
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
return `\\text{${e}}`;
|
|
325
|
+
} };
|
|
326
|
+
if (!silent)
|
|
327
|
+
items.push({ kind: 'check', latex: `${tex(st.left)} ${CMP_TEX[st.op]} ${tex(st.right)}`, verdict: true, na: true, pos: st.pos, ...cap, ...ind });
|
|
328
|
+
break;
|
|
329
|
+
}
|
|
330
|
+
const L = side(st.left), R = side(st.right);
|
|
331
|
+
if (isNA(L.value) || isNA(R.value)) { // a side that does not apply
|
|
332
|
+
if (!silent)
|
|
333
|
+
items.push({ kind: 'check', latex: `${L.latex} ${CMP_TEX[st.op]} ${R.latex}`, verdict: true, na: true, pos: st.pos, ...cap, ...ind });
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
const warning = lint(parseExpr(st.left)) ?? lint(parseExpr(st.right));
|
|
337
|
+
const verdict = Boolean(math[CMP_FN[st.op]](L.value, R.value));
|
|
338
|
+
const ratio = st.op === '>=' || st.op === '>' ? math.divide(R.value, L.value) : math.divide(L.value, R.value);
|
|
339
|
+
const r = typeof ratio === 'number' ? ratio : isUnit(ratio) ? ratio.toNumber('') : NaN;
|
|
340
|
+
const eta = formatEta(r);
|
|
341
|
+
const warn = verdict && st.warn !== undefined && r > st.warn; // passed, but closer to the limit than the author wants
|
|
342
|
+
if (!silent)
|
|
343
|
+
items.push({ kind: 'check', latex: `${L.latex} ${CMP_TEX[st.op]} ${R.latex}`, verdict, eta, ...(warn && { warn }), ...(warning && { warning }), pos: st.pos, ...cap, ...ind });
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
case 'if': {
|
|
347
|
+
let taken, last, line;
|
|
348
|
+
for (const b of st.branches) {
|
|
349
|
+
if (b.condition === undefined) {
|
|
350
|
+
taken = b;
|
|
351
|
+
line = last !== undefined ? condLine(last, true) : undefined;
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
const c = condLine(b.condition, false);
|
|
355
|
+
last = b.condition;
|
|
356
|
+
if (c.value) {
|
|
357
|
+
taken = b;
|
|
358
|
+
line = c;
|
|
359
|
+
break;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (!taken)
|
|
363
|
+
break;
|
|
364
|
+
if (line && !silent && !resultOnly)
|
|
365
|
+
items.push({ kind: 'cond', latex: line.latex, verdict: line.value, pos: taken.pos, ...ind });
|
|
366
|
+
renderStatements(taken.statements, opts, items, true);
|
|
367
|
+
break;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
catch (e) {
|
|
372
|
+
fail(st, e, items, indent);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
const renderBlocks = (blockList, blocks) => {
|
|
377
|
+
for (const block of blockList) {
|
|
378
|
+
if (block.kind === 'loop') {
|
|
379
|
+
// the body repeats per value with the variable substituted as text; the blocks it yields run here so
|
|
380
|
+
// later statements see what the loop defines; the splice into the source happens in the second pass
|
|
381
|
+
const errs = [];
|
|
382
|
+
let values = [];
|
|
383
|
+
if (block.condition !== undefined) { // ```if cond: shown once or not at all
|
|
384
|
+
try {
|
|
385
|
+
values = run(parseExpr(block.condition)) ? [1] : [];
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
errs.push(e instanceof DependsError ? e.message : wording(e));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
else {
|
|
392
|
+
try {
|
|
393
|
+
values = rangeValues(block.range);
|
|
394
|
+
}
|
|
395
|
+
catch (e) {
|
|
396
|
+
errs.push(wording(e));
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
const text = block.condition !== undefined ? (values.length ? block.body : '') : values.map((v) => substituteVar(block.body, block.variable, v)).join('\n');
|
|
400
|
+
const inner = [];
|
|
401
|
+
const errBefore = errors.length;
|
|
402
|
+
if (values.length)
|
|
403
|
+
renderBlocks(parse(text).blocks, inner);
|
|
404
|
+
for (let k = errBefore; k < errors.length; k++)
|
|
405
|
+
errors[k].pos = block.pos;
|
|
406
|
+
const fixPos = (bs) => { for (const b of bs) {
|
|
407
|
+
b.pos = block.pos;
|
|
408
|
+
if (b.kind === 'calc')
|
|
409
|
+
for (const it of b.items)
|
|
410
|
+
it.pos = block.pos;
|
|
411
|
+
if (b.kind === 'loop')
|
|
412
|
+
fixPos(b.blocks);
|
|
413
|
+
} };
|
|
414
|
+
fixPos(inner);
|
|
415
|
+
for (const m of errs)
|
|
416
|
+
errors.push({ message: m, pos: block.pos });
|
|
417
|
+
blocks.push({ kind: 'loop', count: values.length, text, blocks: inner, errors: errs, pos: block.pos });
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
if (block.kind === 'plot') {
|
|
421
|
+
const errs = [];
|
|
422
|
+
const X = new Set(['x']);
|
|
423
|
+
// a plot value as a number: quantities in their display unit (the first sample fixes the unit of an axis)
|
|
424
|
+
const asNum = (v, unit) => {
|
|
425
|
+
if (typeof v === 'number')
|
|
426
|
+
return v;
|
|
427
|
+
if (typeof v === 'boolean')
|
|
428
|
+
return v ? 1 : 0;
|
|
429
|
+
if (isUnit(v)) {
|
|
430
|
+
if (v.dimensions.every((d) => d === 0))
|
|
431
|
+
return Number(v.value);
|
|
432
|
+
unit && (unit.u ??= displayUnit(v));
|
|
433
|
+
return v.toNumber(unit?.u ?? displayUnit(v));
|
|
434
|
+
}
|
|
435
|
+
return NaN;
|
|
436
|
+
};
|
|
437
|
+
const value = (expr) => run(parseExpr(expr, X));
|
|
438
|
+
let x0 = 0, x1 = 1;
|
|
439
|
+
const ux = {};
|
|
440
|
+
try {
|
|
441
|
+
const r = /^(.+?)\s*(?:\.\.|:)\s*(.+)$/.exec(block.options.x ?? '0 .. 1');
|
|
442
|
+
if (r) {
|
|
443
|
+
x0 = value(r[1]);
|
|
444
|
+
x1 = value(r[2]);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
catch (e) {
|
|
448
|
+
errs.push(wording(e));
|
|
449
|
+
}
|
|
450
|
+
const span = math.subtract(x1, x0);
|
|
451
|
+
const xAt = (t) => math.add(x0, math.multiply(span, t)); // keeps the unit of x
|
|
452
|
+
const series = block.series.map((s) => {
|
|
453
|
+
const pts = [];
|
|
454
|
+
const uy = {};
|
|
455
|
+
try {
|
|
456
|
+
const compiled = parseExpr(s.expr, X).compile();
|
|
457
|
+
for (let i = 0; i <= 120; i++) {
|
|
458
|
+
const x = xAt(i / 120);
|
|
459
|
+
const y = asNum(compiled.evaluate(new Map([...scope, ['x', x]])), uy);
|
|
460
|
+
if (Number.isFinite(y))
|
|
461
|
+
pts.push([asNum(x, ux), y]);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
catch (e) {
|
|
465
|
+
errs.push(`${s.expr}: ${wording(e)}`);
|
|
466
|
+
}
|
|
467
|
+
return { label: s.caption ?? plainText(print(math.parse(s.expr), 'formula', ctx)), pts };
|
|
468
|
+
});
|
|
469
|
+
const num = (expr) => asNum(value(expr), ux);
|
|
470
|
+
const points = block.points.map((p) => {
|
|
471
|
+
try {
|
|
472
|
+
return { label: p.caption, x: num(p.x), y: num(p.y) };
|
|
473
|
+
}
|
|
474
|
+
catch (e) {
|
|
475
|
+
errs.push(`(${p.x}, ${p.y}): ${wording(e)}`);
|
|
476
|
+
return undefined;
|
|
477
|
+
}
|
|
478
|
+
}).filter((p) => !!p);
|
|
479
|
+
for (const m of errs)
|
|
480
|
+
errors.push({ message: m, pos: block.pos });
|
|
481
|
+
blocks.push({ kind: 'plot', svg: plotSvg({ ...block.options, series, points }), errors: errs, pos: block.pos });
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
if (block.kind === 'calc') {
|
|
485
|
+
const items = [];
|
|
486
|
+
renderStatements(block.statements, block.options, items);
|
|
487
|
+
blocks.push({ kind: 'calc', items, pos: block.pos });
|
|
488
|
+
}
|
|
489
|
+
else {
|
|
490
|
+
const inlines = block.inlines.map((inl) => {
|
|
491
|
+
try {
|
|
492
|
+
const tm = /\s+to\s+([A-Za-z%][\w^*/ .-]*)$/.exec(inl.expr); // `{U to %}`, `{M to kNm}`
|
|
493
|
+
const node = parseExpr(tm ? inl.expr.slice(0, tm.index) : inl.expr);
|
|
494
|
+
const value = run(node);
|
|
495
|
+
const v = tm ? fmt(convert(value, tm[1].trim()), tm[1].trim()) : shown(node, value);
|
|
496
|
+
return { raw: inl.raw, latex: inl.showName ? `${identifier(inl.expr)} = ${v}` : v, pos: inl.pos, ...(inl.plain && { plain: true }) };
|
|
497
|
+
}
|
|
498
|
+
catch (e) {
|
|
499
|
+
const message = e instanceof DependsError ? e.message : wording(e);
|
|
500
|
+
errors.push({ message, pos: inl.pos });
|
|
501
|
+
return { raw: inl.raw, latex: '?', error: message, pos: inl.pos, ...(inl.plain && { plain: true }) };
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
blocks.push({ kind: 'prose', mdast: block.mdast, inlines, pos: block.pos });
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
const blocks = [];
|
|
509
|
+
renderBlocks(doc.blocks, blocks);
|
|
510
|
+
const rendered = { frontMatter: doc.frontMatter, blocks, errors, scope };
|
|
511
|
+
// second pass: splice every prose loop's expansion into the source, so table rows and SVG elements inside a loop
|
|
512
|
+
// join the table or drawing around it; positions map back to the source lines for the preview and the CLI
|
|
513
|
+
const loops = doc.blocks.map((b, i) => (b.kind === 'loop' ? { b, r: blocks[i] } : undefined)).filter((x) => !!x);
|
|
514
|
+
if (loops.length && depth < 4) {
|
|
515
|
+
const src = doc.text.split('\n');
|
|
516
|
+
const out = [], map = [];
|
|
517
|
+
let cursor = 1;
|
|
518
|
+
for (const { b, r } of loops) {
|
|
519
|
+
for (let n = cursor; n < b.pos.start.line; n++) {
|
|
520
|
+
out.push(src[n - 1] ?? '');
|
|
521
|
+
map.push(n);
|
|
522
|
+
}
|
|
523
|
+
for (const l of r.text.split('\n')) {
|
|
524
|
+
out.push(l);
|
|
525
|
+
map.push(b.pos.start.line);
|
|
526
|
+
}
|
|
527
|
+
cursor = b.pos.end.line + 1;
|
|
528
|
+
}
|
|
529
|
+
for (let n = cursor; n <= src.length; n++) {
|
|
530
|
+
out.push(src[n - 1] ?? '');
|
|
531
|
+
map.push(n);
|
|
532
|
+
}
|
|
533
|
+
const r2 = evaluate(parse(out.join('\n')), { ...options, depth: depth + 1 });
|
|
534
|
+
const line = (n) => map[n - 1] ?? n;
|
|
535
|
+
const mapPos = (p) => ({ start: { ...p.start, line: line(p.start.line) }, end: { ...p.end, line: line(p.end.line) } });
|
|
536
|
+
const fix = (bs) => { for (const b of bs) {
|
|
537
|
+
b.pos = mapPos(b.pos);
|
|
538
|
+
if (b.kind === 'calc')
|
|
539
|
+
for (const it of b.items)
|
|
540
|
+
it.pos = mapPos(it.pos);
|
|
541
|
+
if (b.kind === 'prose')
|
|
542
|
+
for (const it of b.inlines)
|
|
543
|
+
it.pos = mapPos(it.pos);
|
|
544
|
+
if (b.kind === 'loop')
|
|
545
|
+
fix(b.blocks);
|
|
546
|
+
} };
|
|
547
|
+
const deepest = r2.expanded ?? r2;
|
|
548
|
+
fix(deepest.blocks);
|
|
549
|
+
for (const e of deepest.errors)
|
|
550
|
+
e.pos = mapPos(e.pos);
|
|
551
|
+
rendered.expanded = deepest;
|
|
552
|
+
}
|
|
553
|
+
return rendered;
|
|
554
|
+
}
|
|
555
|
+
/** The loop variable as text, inside `{…}` placeholders and inside fenced math/plot lines; prose text is left alone. */
|
|
556
|
+
function substituteVar(body, variable, value) {
|
|
557
|
+
const re = new RegExp(`(?<![\\w\\u0370-\\u03FF])${variable}(?![\\w\\u0370-\\u03FF'])`, 'g');
|
|
558
|
+
const sub = (s) => s.replace(re, `(${value})`); // parenthesised, so `3 j` stays a product after substitution
|
|
559
|
+
let inFence = false;
|
|
560
|
+
return body.split('\n').map((l) => {
|
|
561
|
+
if (/^\s*`{3,}/.test(l)) {
|
|
562
|
+
inFence = !inFence;
|
|
563
|
+
return l;
|
|
564
|
+
}
|
|
565
|
+
return inFence ? sub(l) : l.replace(/\{[^{}]*\}/g, sub);
|
|
566
|
+
}).join('\n');
|
|
567
|
+
}
|
|
568
|
+
/** Every rendered statement, loops included, in document order. */
|
|
569
|
+
export function statements(r) {
|
|
570
|
+
const out = [];
|
|
571
|
+
const walk = (bs) => { for (const b of bs) {
|
|
572
|
+
if (b.kind === 'calc')
|
|
573
|
+
out.push(...b.items);
|
|
574
|
+
if (b.kind === 'loop')
|
|
575
|
+
walk(b.blocks);
|
|
576
|
+
} };
|
|
577
|
+
walk(r.blocks);
|
|
578
|
+
return out;
|
|
579
|
+
}
|
|
580
|
+
//# sourceMappingURL=evaluate.js.map
|