@matheos/core 0.2.3 → 0.3.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.
@@ -0,0 +1,5 @@
1
+ /** Checks that `to` can apply to a value (units.md wording) and converts; vectors and matrices element by element. */
2
+ export declare function convert(v: unknown, to?: string): unknown;
3
+ /** Result-line LaTeX of a value in its display unit (`to`, else the units.md rule), `digits` significant. Throws the
4
+ * units.md wording when `to` cannot apply, so a statement fails before its name is bound. */
5
+ export declare function display(v: unknown, to?: string, digits?: number): string;
@@ -0,0 +1,69 @@
1
+ import { math, isUnit, isNA, isForeignUnit, isDimensionless, isMatrixLike, displayUnit, displayName, unitLatex } from './units.js';
2
+ import { print, formatNumber, text } from './printer.js';
3
+ /** Checks that `to` can apply to a value (units.md wording) and converts; vectors and matrices element by element. */
4
+ export function convert(v, to) {
5
+ if (!to || isNA(v))
6
+ return v;
7
+ if (to === '%') {
8
+ if (typeof v === 'number' || isDimensionless(v))
9
+ return v;
10
+ throw new Error('only a dimensionless value can be shown in %');
11
+ }
12
+ for (const sym of math.parse(to).filter((x) => x.type === 'SymbolNode'))
13
+ if (isForeignUnit(sym.name) || !math.Unit.isValuelessUnit(sym.name))
14
+ throw new Error(`unknown unit "${sym.name}"`); // outside the table, or no unit at all
15
+ if (isMatrixLike(v))
16
+ return math.map(v, (e) => convert(e, to));
17
+ if (!isUnit(v))
18
+ throw new Error(`cannot convert a number to ${to}`);
19
+ try {
20
+ return v.to(to);
21
+ }
22
+ catch {
23
+ throw new Error(`cannot convert ${displayName(v.formatUnits())} to ${to}`);
24
+ }
25
+ }
26
+ /** Result-line LaTeX of a value in its display unit (`to`, else the units.md rule), `digits` significant. Throws the
27
+ * units.md wording when `to` cannot apply, so a statement fails before its name is bound. */
28
+ export function display(v, to, digits = 4) {
29
+ v = convert(v, to);
30
+ if (to === '%') {
31
+ const n = typeof v === 'number' ? v : isDimensionless(v) ? Number(v.value) : NaN;
32
+ return `${formatNumber(n * 100, digits)}\\,\\%`;
33
+ }
34
+ if (typeof v === 'number')
35
+ return formatNumber(v, digits);
36
+ if (typeof v === 'boolean')
37
+ return `\\mathrm{${v}}`;
38
+ if (isNA(v))
39
+ return '\\text{n/a}';
40
+ if (typeof v === 'function')
41
+ return `\\text{${v.syntax ?? 'function'}}`; // a bare function name: its signature, not the compiled JS
42
+ if (typeof v === 'string')
43
+ return text(v);
44
+ if (typeof v === 'object' && v !== null && v.isNode)
45
+ return print(v, 'formula', { isVar: () => true }); // derivative / simplify: a symbolic result, every symbol a variable
46
+ if (isUnit(v)) {
47
+ const unit = displayUnit(v, to);
48
+ const n = v.toNumber(unit);
49
+ return `${formatNumber(n, digits)}\\,${unitLatex(unit)}`;
50
+ }
51
+ if (isMatrixLike(v)) {
52
+ const rows = (Array.isArray(v) ? v : v.toArray());
53
+ // one unit shared by every element is written once, after the bracket: [5.6 0.0066] kN/mm
54
+ const flat = rows.flat();
55
+ const units = flat.map((x) => (isUnit(x) ? displayUnit(x, to) : null));
56
+ const shared = flat.length && units.every((u) => u !== null && u === units[0]) ? units[0] : undefined;
57
+ const cell = (x) => (shared ? formatNumber(x.toNumber(shared), digits) : display(x, to, digits));
58
+ const row = (r) => (Array.isArray(r) ? r : [r]).map(cell).join(' & ');
59
+ const body = !rows.some(Array.isArray) ? row(rows) : rows.map(row).join(' \\\\ '); // a vector reads as a row
60
+ return `\\begin{bmatrix} ${body} \\end{bmatrix}${shared ? `\\,${unitLatex(shared)}` : ''}`;
61
+ }
62
+ if (typeof v === 'object' && v !== null) { // a catalogue row: its name, or the first keys
63
+ const o = v;
64
+ const name = o['Name'] ?? o['name'] ?? o['id'];
65
+ return text(String(name ?? `${Object.keys(o).slice(0, 4).join(', ')}, …`));
66
+ }
67
+ return String(v);
68
+ }
69
+ //# sourceMappingURL=display.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"display.js","sourceRoot":"","sources":["../src/display.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,IAAI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are left alone. */
9
9
  export declare function primes(s: string): string;
10
10
  export declare function evaluate(doc: Document, options?: EvalOptions): Rendered;
11
+ /** Front-matter catalogues → bindings: each JSON table (an array, or `{ rows, units }`) becomes an object of rows keyed by
12
+ * the key column (`Name`, else name / id / position), numeric columns carrying the units given (the table's own, then the
13
+ * front matter's). Errors are messages; the caller places them. */
14
+ export declare function catalogueTables(catalogs: Record<string, {
15
+ file: string;
16
+ units?: Record<string, string>;
17
+ key?: string;
18
+ }>, resolve?: EvalOptions['resolve']): {
19
+ bindings: Map<string, unknown>;
20
+ errors: string[];
21
+ };
22
+ /** The second pass's source: every prose loop's expansion in place of its lines, and the map from a line of the spliced
23
+ * text back to the source line (every expanded line points at the loop's first line) for the preview and the CLI. */
24
+ export declare function spliceLoops(source: string, loops: {
25
+ start: number;
26
+ end: number;
27
+ text: string;
28
+ }[]): {
29
+ text: string;
30
+ line: (n: number) => number;
31
+ };
32
+ /** The `?`-marked inputs of a document, in order, inside branches and loops too: what the parameters view edits in place. */
33
+ export declare function parameters(doc: Document): {
34
+ name: string;
35
+ expr: string;
36
+ caption?: string;
37
+ line: number;
38
+ options?: string[];
39
+ }[];
40
+ /** The loop variable as text, inside `{…}` placeholders and inside fenced math/plot lines; prose text is left alone. */
41
+ export declare function substituteVar(body: string, variable: string, value: number): string;
11
42
  /** Every rendered statement, loops included, in document order. */
12
43
  export declare function statements(r: Rendered): RenderedStatement[];
13
44
  export type { Pos };
package/dist/evaluate.js CHANGED
@@ -1,9 +1,9 @@
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';
1
+ import { math, isUnit, isNA, NA, wording, unitLatex, isForeignUnit, isDimensionless, displayUnit, isMatrixLike } from './units.js';
2
+ import { print, identifier, stamp, negate, plainText, comparison, implies, not as notTex, text as textTex, literalEcho, range as rangeTex } from './printer.js';
3
+ import { display as displayValue } from './display.js';
3
4
  import { plotSvg } from './plot.js';
4
5
  import { parse } from './parse.js';
5
6
  const CMP_FN = { '<=': 'smallerEq', '>=': 'largerEq', '<': 'smaller', '>': 'larger', '==': 'equal', '!=': 'unequal' };
6
- const CMP_TEX = { '<=': '\\le', '>=': '\\ge', '<': '<', '>': '>', '==': '=', '!=': '\\ne' };
7
7
  class DependsError extends Error {
8
8
  constructor(dep) { super(`depends on ${dep}`); }
9
9
  }
@@ -69,38 +69,12 @@ export function evaluate(doc, options = {}) {
69
69
  const digits = typeof doc.frontMatter.digits === 'number' ? doc.frontMatter.digits : 4;
70
70
  scope.set('na', NA); // `na`: a value that does not apply (min/max skip it, checks report n/a)
71
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
- }
72
+ if (doc.frontMatter.catalogs && typeof doc.frontMatter.catalogs === 'object') {
73
+ const c = catalogueTables(doc.frontMatter.catalogs, options.resolve);
74
+ for (const [k, v] of c.bindings)
75
+ scope.set(k, v);
76
+ for (const message of c.errors)
77
+ errors.push({ message, pos: { start: { line: 1, column: 1, offset: 0 }, end: { line: 1, column: 1, offset: 0 } } });
104
78
  }
105
79
  // includes: front matter `include: helpers.mth` (or a list). Each file is evaluated on its own and its bindings
106
80
  // (variables, functions, catalogues) land in this scope; nothing of it is printed.
@@ -151,33 +125,10 @@ export function evaluate(doc, options = {}) {
151
125
  if (!scope.has(sym.name) && isForeignUnit(sym.name))
152
126
  throw new Error(`unknown unit "${sym.name}"`);
153
127
  }
154
- return node;
128
+ return stamp(node, expr); // the printer echoes the literals as typed
155
129
  };
156
130
  const run = (node) => node.compile().evaluate(scope);
157
- const convert = (v, to) => {
158
- if (!to || isNA(v))
159
- return v;
160
- if (to === '%') {
161
- if (typeof v === 'number' || (isUnit(v) && v.dimensions.every((d) => d === 0)))
162
- return v;
163
- throw new Error(`only a dimensionless value can be shown in %`);
164
- }
165
- for (const sym of math.parse(to).filter((x) => x.type === 'SymbolNode'))
166
- if (isForeignUnit(sym.name))
167
- throw new Error(`unknown unit "${sym.name}"`);
168
- if (Array.isArray(v) || (typeof v === 'object' && v !== null && 'toArray' in v)) { // vectors and matrices convert element by element
169
- return math.map(v, (e) => convert(e, to));
170
- }
171
- if (!isUnit(v))
172
- throw new Error(`cannot convert a number to ${to}`);
173
- try {
174
- return v.to(to);
175
- }
176
- catch (e) {
177
- throw new Error(`cannot convert ${v.formatUnits()} to ${to}`);
178
- }
179
- };
180
- const fmt = (v, to) => formatValue(v, to, digits);
131
+ const fmt = (v, to) => displayValue(v, to, digits); // throws when `to` cannot apply
181
132
  const isLiteral = (n) => {
182
133
  const u = n.type === 'ParenthesisNode' ? n.content : n;
183
134
  return u.type === 'ConstantNode' || (u.type === 'OperatorNode' && u.op === '*' && !!u.implicit
@@ -193,7 +144,7 @@ export function evaluate(doc, options = {}) {
193
144
  const v = shown(node, value);
194
145
  if (isLiteral(node))
195
146
  return { v, latex: v, value };
196
- const formula = print(node, 'formula', { ...ctx, literals: literalsOf(expr) });
147
+ const formula = print(node, 'formula', ctx);
197
148
  return { formula, v, latex: collapse([formula, v]).join(' = '), value };
198
149
  };
199
150
  /** Condition line: `condition → evaluated` (docs/spec/conditionals.md). */
@@ -206,17 +157,17 @@ export function evaluate(doc, options = {}) {
206
157
  const L = side(a.toString()), R = side(b.toString());
207
158
  if (op === '==' && (isLiteral(b) && R.v === fmt(L.value) || isLiteral(a) && L.v === fmt(R.value)))
208
159
  return { latex: isLiteral(b) ? L.latex : R.latex, value };
209
- const evaluated = `${L.v} ${CMP_TEX[op]} ${R.v}`;
160
+ const evaluated = comparison(L.v, op, R.v);
210
161
  if (!L.formula && !R.formula)
211
162
  return { latex: evaluated, value };
212
- return { latex: `${L.formula ?? L.v} ${CMP_TEX[op]} ${R.formula ?? R.v} \\;\\rightarrow\\; ${evaluated}`, value };
163
+ return { latex: implies(comparison(L.formula ?? L.v, op, R.formula ?? R.v), evaluated), value };
213
164
  }
214
- const latex = print(node, 'formula', { ...ctx, literals: literalsOf(cond) });
215
- return { latex: negated ? `\\text{not } \\left(${latex}\\right)` : latex, value };
165
+ const latex = print(node, 'formula', ctx);
166
+ return { latex: negated ? notTex(latex) : latex, value };
216
167
  };
217
168
  /** `1 : n` or `1 : 2 : n` → the values of a loop variable (inclusive, at most 10 000). */
218
169
  const rangeValues = (range) => {
219
- 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; });
170
+ const parts = range.split(':').map((p) => { const v = run(parseExpr(p.trim())); return typeof v === 'number' ? v : isDimensionless(v) ? Number(v.value) : NaN; });
220
171
  if (parts.length < 2 || parts.length > 3 || parts.some((p) => !Number.isFinite(p)))
221
172
  throw new Error(`loop range must be "from : to" or "from : step : to", got "${range}"`);
222
173
  const [from, step, to] = parts.length === 3 ? parts : [parts[0], 1, parts[1]];
@@ -245,7 +196,7 @@ export function evaluate(doc, options = {}) {
245
196
  if (st.kind !== 'comment' && st.kind !== 'if' && st.kind !== 'for')
246
197
  items.push({ kind: st.kind, latex: '', error: message, pos: st.pos, ...(st.caption !== undefined && { caption: st.caption }), ...(indent && { indent }) });
247
198
  else if (st.kind === 'for')
248
- items.push({ kind: 'cond', latex: '', error: message, pos: st.pos, ...(indent && { indent }) });
199
+ items.push({ kind: 'loop', latex: '', error: message, pos: st.pos, ...(indent && { indent }) });
249
200
  };
250
201
  const renderStatements = (statements, opts, items, indent = false) => {
251
202
  for (const st of statements) {
@@ -261,19 +212,17 @@ export function evaluate(doc, options = {}) {
261
212
  const value = run(node);
262
213
  if (silent)
263
214
  return;
264
- const lits = literalsOf(s.expr);
265
- const head = print(node.object, 'formula', ctx) + print(node.index, 'formula', { ...ctx, literals: literalsOf(s.name) });
215
+ const head = print(node.object, 'formula', ctx) + print(node.index, 'formula', ctx);
266
216
  const vectorOperand = node.value.filter((x) => x.type === 'SymbolNode').some((x) => isMatrixLike(scope.get(x.name)));
267
- const stages = vectorOperand ? [print(node.value, 'formula', { ...ctx, literals: lits }), fmt(value)]
268
- : [print(node.value, 'formula', { ...ctx, literals: lits }), print(node.value, 'subst', { ...ctx, literals: lits }), fmt(value)];
217
+ const stages = vectorOperand ? [print(node.value, 'formula', ctx), fmt(value)]
218
+ : [print(node.value, 'formula', ctx), print(node.value, 'subst', ctx), fmt(value)];
269
219
  const pieces = resultOnly ? [fmt(value)] : collapse(stages);
270
220
  items.push({ kind: 'derived', latex: [head, ...pieces].join(' = '), pieces: [head, ...pieces], pos: s.pos, ...cap, ...ind });
271
221
  return;
272
222
  }
273
223
  const node = parseExpr(s.expr);
274
224
  const value = run(node);
275
- convert(value, s.to); // throws early when `to` cannot apply
276
- const result = fmt(value, s.to);
225
+ const result = fmt(value, s.to); // throws before the name is bound when `to` cannot apply
277
226
  // bound after printing, so `x = x + 1` substitutes the old x
278
227
  const bind = () => { if (s.kind === 'derived') {
279
228
  scope.set(s.name, value);
@@ -285,13 +234,12 @@ export function evaluate(doc, options = {}) {
285
234
  return;
286
235
  }
287
236
  const warning = lint(node);
288
- const lits = literalsOf(s.expr);
289
237
  // a vector operand would make the substituted line unreadable: formula = result then
290
238
  // a vector operand or a `solve` (whose variable is now bound to the root) would make the substituted line unreadable
291
239
  const vectorOperand = node.filter((x) => x.type === 'SymbolNode').some((x) => isMatrixLike(scope.get(x.name)))
292
240
  || node.filter((x) => x.type === 'FunctionNode' && x.fn.name === 'solve').length > 0;
293
- const stages = vectorOperand ? [print(node, 'formula', { ...ctx, literals: lits }), result]
294
- : [print(node, 'formula', { ...ctx, literals: lits }), print(node, 'subst', { ...ctx, literals: lits }), result];
241
+ const stages = vectorOperand ? [print(node, 'formula', ctx), result]
242
+ : [print(node, 'formula', ctx), print(node, 'subst', ctx), result];
295
243
  const pieces = resultOnly ? [result] : collapse(stages);
296
244
  const head = s.kind === 'derived' ? [identifier(s.name)] : [];
297
245
  bind();
@@ -307,16 +255,22 @@ export function evaluate(doc, options = {}) {
307
255
  break;
308
256
  } // `25 t` with t bound: a product, not a unit
309
257
  const node = parseExpr(st.expr);
310
- const value = run(node);
311
- const lit = m[1].startsWith('[')
312
- ? `\\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}`
313
- : m[1].replace(/e\+?(-?\d+)/i, '\\cdot10^{$1}');
314
- const latex = lit + (m[2] ? `\\,${unitLatex(m[2])}` : '');
258
+ let value;
259
+ try {
260
+ value = run(node);
261
+ }
262
+ catch (e) { // `1 kpa`: the word after the literal was meant as a unit
263
+ const sym = /^Undefined symbol (\S+)/.exec(e instanceof Error ? e.message : '')?.[1];
264
+ if (sym && m[2] && m[2].split(/[\s/^*()]+/).includes(sym))
265
+ throw new Error(`unknown unit "${sym}"`);
266
+ throw e;
267
+ }
268
+ const latex = literalEcho(m[1], m[2] || undefined);
315
269
  scope.set(st.name, value);
316
270
  failed.delete(st.name);
317
271
  display.set(st.name, latex);
318
272
  if (!silent)
319
- items.push({ kind: 'input', latex: `${identifier(st.name)} = ${latex}`, pos: st.pos, ...cap, ...ind });
273
+ items.push({ kind: 'input', latex: `${identifier(st.name)} = ${latex}`, pieces: [identifier(st.name), latex], pos: st.pos, ...cap, ...ind });
320
274
  break;
321
275
  }
322
276
  case 'derived':
@@ -327,7 +281,7 @@ export function evaluate(doc, options = {}) {
327
281
  const values = rangeValues(st.range);
328
282
  const at = items.length;
329
283
  if (!silent && !resultOnly)
330
- items.push({ kind: 'cond', latex: `${identifier(st.variable)} = ${values.length ? `${values[0]} \\ldots ${values[values.length - 1]}` : '\\varnothing'}`, pos: st.pos, ...ind });
284
+ items.push({ kind: 'loop', latex: `${identifier(st.variable)} = ${rangeTex(values[0], values[values.length - 1])}`, pos: st.pos, ...ind });
331
285
  for (const v of values) {
332
286
  scope.set(st.variable, v);
333
287
  failed.delete(st.variable);
@@ -341,26 +295,27 @@ export function evaluate(doc, options = {}) {
341
295
  const node = parseExpr(`${st.name}(${st.params.join(', ')}) = ${st.expr}`, new Set(st.params));
342
296
  run(node); // binds the function in scope; the body is evaluated per call
343
297
  failed.delete(st.name);
298
+ const latex = print(node, 'formula', ctx), at = latex.indexOf(' = '); // ponytail: head and body split at the first ' = ' (the head is a call, it has none); printing them apart is the upgrade
344
299
  if (!silent)
345
- items.push({ kind: 'function', latex: print(node, 'formula', { ...ctx, literals: literalsOf(st.expr) }), pos: st.pos, ...cap, ...ind });
300
+ items.push({ kind: 'function', latex, pieces: [latex.slice(0, at), latex.slice(at + 3)], pos: st.pos, ...cap, ...ind });
346
301
  break;
347
302
  }
348
303
  case 'check': {
349
304
  if (st.only !== undefined && !run(parseExpr(st.only))) { // `check … if cond` with cond false: shown as n/a
350
305
  const tex = (e) => { try {
351
- return print(parseExpr(e), 'formula', { ...ctx, literals: literalsOf(e) });
306
+ return print(parseExpr(e), 'formula', ctx);
352
307
  }
353
308
  catch {
354
- return `\\text{${e}}`;
309
+ return textTex(e);
355
310
  } };
356
311
  if (!silent)
357
- items.push({ kind: 'check', latex: `${tex(st.left)} ${CMP_TEX[st.op]} ${tex(st.right)}`, verdict: true, na: true, pos: st.pos, ...cap, ...ind });
312
+ items.push({ kind: 'check', latex: comparison(tex(st.left), st.op, tex(st.right)), verdict: true, na: true, pos: st.pos, ...cap, ...ind });
358
313
  break;
359
314
  }
360
315
  const L = side(st.left), R = side(st.right);
361
316
  if (isNA(L.value) || isNA(R.value)) { // a side that does not apply
362
317
  if (!silent)
363
- items.push({ kind: 'check', latex: `${L.latex} ${CMP_TEX[st.op]} ${R.latex}`, verdict: true, na: true, pos: st.pos, ...cap, ...ind });
318
+ items.push({ kind: 'check', latex: comparison(L.latex, st.op, R.latex), verdict: true, na: true, pos: st.pos, ...cap, ...ind });
364
319
  break;
365
320
  }
366
321
  const warning = lint(parseExpr(st.left)) ?? lint(parseExpr(st.right));
@@ -368,11 +323,11 @@ export function evaluate(doc, options = {}) {
368
323
  const numeric = typeof L.value !== 'string' && typeof L.value !== 'boolean' && typeof R.value !== 'string' && typeof R.value !== 'boolean'; // `check curve == "b"` has no η
369
324
  const ratio = !numeric ? NaN : st.op === '>=' || st.op === '>' ? math.divide(R.value, L.value) : math.divide(L.value, R.value);
370
325
  const r = typeof ratio === 'number' ? ratio : isUnit(ratio) ? ratio.toNumber('') : NaN;
371
- const eta = numeric ? formatEta(r) : undefined;
326
+ const eta = numeric ? Math.round(r * 100) / 100 : undefined;
372
327
  const warn = verdict && st.warn !== undefined && r > st.warn; // passed, but closer to the limit than the author wants
373
328
  const same = st.op === '==' && !R.formula && L.v === R.v; // `check curve == "b"` holding: `curve = b`, not `curve = b = b`
374
329
  if (!silent)
375
- items.push({ kind: 'check', latex: same ? L.latex : `${L.latex} ${CMP_TEX[st.op]} ${R.latex}`, verdict, ...(eta !== undefined && { eta }), ...(warn && { warn }), ...(warning && { warning }), pos: st.pos, ...cap, ...ind });
330
+ items.push({ kind: 'check', latex: same ? L.latex : comparison(L.latex, st.op, R.latex), verdict, ...(eta !== undefined && { eta }), ...(warn && { warn }), ...(warning && { warning }), pos: st.pos, ...cap, ...ind });
376
331
  break;
377
332
  }
378
333
  case 'if': {
@@ -459,7 +414,7 @@ export function evaluate(doc, options = {}) {
459
414
  if (typeof v === 'boolean')
460
415
  return v ? 1 : 0;
461
416
  if (isUnit(v)) {
462
- if (v.dimensions.every((d) => d === 0))
417
+ if (isDimensionless(v))
463
418
  return Number(v.value);
464
419
  unit && (unit.u ??= displayUnit(v));
465
420
  return v.toNumber(unit?.u ?? displayUnit(v));
@@ -521,10 +476,9 @@ export function evaluate(doc, options = {}) {
521
476
  else {
522
477
  const inlines = block.inlines.map((inl) => {
523
478
  try {
524
- const tm = /\s+to\s+([A-Za-z%][\w^*/ .-]*)$/.exec(inl.expr); // `{U to %}`, `{M to kNm}`
525
- const node = parseExpr(tm ? inl.expr.slice(0, tm.index) : inl.expr);
479
+ const node = parseExpr(inl.expr);
526
480
  const value = run(node);
527
- const v = tm ? fmt(convert(value, tm[1].trim()), tm[1].trim()) : shown(node, value);
481
+ const v = inl.to ? fmt(value, inl.to) : shown(node, value);
528
482
  return { raw: inl.raw, latex: inl.showName ? `${identifier(inl.expr)} = ${v}` : v, pos: inl.pos, ...(inl.plain && { plain: true }) };
529
483
  }
530
484
  catch (e) {
@@ -544,26 +498,8 @@ export function evaluate(doc, options = {}) {
544
498
  // join the table or drawing around it; positions map back to the source lines for the preview and the CLI
545
499
  const loops = doc.blocks.map((b, i) => (b.kind === 'loop' ? { b, r: blocks[i] } : undefined)).filter((x) => !!x);
546
500
  if (loops.length && depth < 4) {
547
- const src = doc.text.split('\n');
548
- const out = [], map = [];
549
- let cursor = 1;
550
- for (const { b, r } of loops) {
551
- for (let n = cursor; n < b.pos.start.line; n++) {
552
- out.push(src[n - 1] ?? '');
553
- map.push(n);
554
- }
555
- for (const l of r.text.split('\n')) {
556
- out.push(l);
557
- map.push(b.pos.start.line);
558
- }
559
- cursor = b.pos.end.line + 1;
560
- }
561
- for (let n = cursor; n <= src.length; n++) {
562
- out.push(src[n - 1] ?? '');
563
- map.push(n);
564
- }
565
- const r2 = evaluate(parse(out.join('\n')), { ...options, depth: depth + 1 });
566
- const line = (n) => map[n - 1] ?? n;
501
+ const { text, line } = spliceLoops(doc.text, loops.map(({ b, r }) => ({ start: b.pos.start.line, end: b.pos.end.line, text: r.text })));
502
+ const r2 = evaluate(parse(text), { ...options, depth: depth + 1 });
567
503
  const mapPos = (p) => ({ start: { ...p.start, line: line(p.start.line) }, end: { ...p.end, line: line(p.end.line) } });
568
504
  const fix = (bs) => { for (const b of bs) {
569
505
  b.pos = mapPos(b.pos);
@@ -584,8 +520,86 @@ export function evaluate(doc, options = {}) {
584
520
  }
585
521
  return rendered;
586
522
  }
523
+ /** Front-matter catalogues → bindings: each JSON table (an array, or `{ rows, units }`) becomes an object of rows keyed by
524
+ * the key column (`Name`, else name / id / position), numeric columns carrying the units given (the table's own, then the
525
+ * front matter's). Errors are messages; the caller places them. */
526
+ export function catalogueTables(catalogs, resolve) {
527
+ const bindings = new Map(), errors = [];
528
+ for (const [name, cat] of Object.entries(catalogs)) {
529
+ try {
530
+ if (!cat || typeof cat !== 'object' || typeof cat.file !== 'string')
531
+ throw new Error(`catalog ${name}: needs a file`);
532
+ const data = resolve?.(cat.file);
533
+ if (data === undefined)
534
+ throw new Error(`catalog ${name}: cannot load ${cat.file}`);
535
+ const rows = Array.isArray(data) ? data : typeof data === 'object' && data !== null && Array.isArray(data.rows) ? data.rows : undefined;
536
+ if (!rows)
537
+ throw new Error(`catalog ${name}: ${cat.file} is not a table`);
538
+ const units = { ...(data.units ?? {}), ...(cat.units ?? {}) };
539
+ for (const u of Object.values(units))
540
+ for (const sym of math.parse(u).filter((x) => x.type === 'SymbolNode'))
541
+ if (isForeignUnit(sym.name) || !math.Unit.isValuelessUnit(sym.name))
542
+ throw new Error(`catalog ${name}: unknown unit "${u}"`); // outside the table, or no unit at all
543
+ const key = cat.key ?? 'Name';
544
+ const table = {};
545
+ for (const row of rows) {
546
+ const id = String(row[key] ?? row['name'] ?? row['id'] ?? Object.keys(table).length + 1);
547
+ const o = {};
548
+ for (const [k, v] of Object.entries(row))
549
+ o[k] = typeof v === 'number' && units[k] ? math.unit(v, units[k]) : v;
550
+ table[id] = o;
551
+ }
552
+ bindings.set(name, table);
553
+ }
554
+ catch (e) {
555
+ errors.push(wording(e));
556
+ }
557
+ }
558
+ return { bindings, errors };
559
+ }
560
+ /** The second pass's source: every prose loop's expansion in place of its lines, and the map from a line of the spliced
561
+ * text back to the source line (every expanded line points at the loop's first line) for the preview and the CLI. */
562
+ export function spliceLoops(source, loops) {
563
+ const src = source.split('\n');
564
+ const out = [], map = [];
565
+ let cursor = 1;
566
+ for (const l of loops) {
567
+ for (let n = cursor; n < l.start; n++) {
568
+ out.push(src[n - 1] ?? '');
569
+ map.push(n);
570
+ }
571
+ for (const x of l.text.split('\n')) {
572
+ out.push(x);
573
+ map.push(l.start);
574
+ }
575
+ cursor = l.end + 1;
576
+ }
577
+ for (let n = cursor; n <= src.length; n++) {
578
+ out.push(src[n - 1] ?? '');
579
+ map.push(n);
580
+ }
581
+ return { text: out.join('\n'), line: (n) => map[n - 1] ?? n };
582
+ }
583
+ /** The `?`-marked inputs of a document, in order, inside branches and loops too: what the parameters view edits in place. */
584
+ export function parameters(doc) {
585
+ const out = [];
586
+ const walk = (sts) => {
587
+ for (const st of sts) {
588
+ if ((st.kind === 'input' || st.kind === 'derived') && st.param)
589
+ out.push({ name: st.name, expr: st.expr, caption: st.caption, line: st.pos.start.line, options: st.options });
590
+ if (st.kind === 'if')
591
+ st.branches.forEach((b) => walk(b.statements));
592
+ if (st.kind === 'for')
593
+ walk(st.statements);
594
+ }
595
+ };
596
+ for (const b of doc.blocks)
597
+ if (b.kind === 'calc')
598
+ walk(b.statements);
599
+ return out;
600
+ }
587
601
  /** The loop variable as text, inside `{…}` placeholders and inside fenced math/plot lines; prose text is left alone. */
588
- function substituteVar(body, variable, value) {
602
+ export function substituteVar(body, variable, value) {
589
603
  const re = new RegExp(`(?<![\\w\\u0370-\\u03FF])${variable}(?![\\w\\u0370-\\u03FF'])`, 'g');
590
604
  const sub = (s) => s.replace(re, `(${value})`); // parenthesised, so `3 j` stays a product after substitution
591
605
  let inFence = false;