@rulecad/variables 0.2.3 → 0.3.1

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.
Files changed (2) hide show
  1. package/package.json +5 -1
  2. package/variables.mjs +93 -43
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/variables",
3
- "version": "0.2.3",
3
+ "version": "0.3.1",
4
4
  "description": "Design values you can trace: every number says where it comes from, and expressions are parsed, never run.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -30,6 +30,10 @@
30
30
  "url": "git+https://github.com/JoniBach/rulecad.git",
31
31
  "directory": "packages/variables"
32
32
  },
33
+ "homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/variables#readme",
34
+ "bugs": {
35
+ "url": "https://github.com/JoniBach/rulecad/issues"
36
+ },
33
37
  "scripts": {
34
38
  "test": "node --test"
35
39
  },
package/variables.mjs CHANGED
@@ -42,37 +42,60 @@ function tokens(src) {
42
42
  return out;
43
43
  }
44
44
 
45
- // evaluate("line * 3", lookup) -> number. lookup(name) gives a name's value.
46
- /**
47
- * One expression: + - * / and brackets, min, max, round, sind, cosd, tand, over numbers and names. Never runs code.
48
- * @param {string | number} src
49
- * @param {(name: string) => number} lookup the value of a name
50
- * @returns {number}
51
- */
52
- export function evaluate(src, lookup = (name) => { throw new Error(`no value for "${name}"`); }) {
53
- if (typeof src === 'number') { if (!Number.isFinite(src)) throw new Error('is not a finite number'); return src; }
54
- const t = tokens(String(src));
45
+ // One grammar: an expression parsed once to a tree, which evaluate() and unitsOf() each walk. Nodes: { n } a number,
46
+ // { id } a name, { op: '+' | '-' | '*' | '/', a, b }, { neg: a } (or { pos: a }), { fn, args }.
47
+ // expr = term (('+' | '-') term)* · term = unary (('*' | '/') unary)* · unary = ('-' | '+') unary | atom
48
+ // atom = number | name | name '(' expr (',' expr)* ')' (a function of FNS) | '(' expr ')'
49
+ const trees = new Map(); // (a design reads the same expressions over and over: each is parsed once)
50
+ function parse(src) {
51
+ const key = String(src);
52
+ if (trees.has(key)) return trees.get(key);
53
+ const t = tokens(key);
55
54
  let i = 0;
56
55
  const peek = () => t[i], take = (op) => (t[i]?.op === op ? (i++, true) : false);
57
- const expr = () => { let v = term(); for (;;) { if (take('+')) v += term(); else if (take('-')) v -= term(); else return v; } };
58
- const term = () => { let v = unary(); for (;;) { if (take('*')) v *= unary(); else if (take('/')) v /= unary(); else return v; } };
59
- const unary = () => (take('-') ? -unary() : take('+') ? unary() : atom());
56
+ const expr = () => { let v = term(); for (;;) { if (take('+')) v = { op: '+', a: v, b: term() }; else if (take('-')) v = { op: '-', a: v, b: term() }; else return v; } };
57
+ const term = () => { let v = unary(); for (;;) { if (take('*')) v = { op: '*', a: v, b: unary() }; else if (take('/')) v = { op: '/', a: v, b: unary() }; else return v; } };
58
+ const unary = () => (take('-') ? { neg: unary() } : take('+') ? { pos: unary() } : atom());
60
59
  const atom = () => {
61
60
  const k = t[i++];
62
61
  if (!k) throw new Error('ends too soon');
63
- if (k.n != null) return k.n;
62
+ if (k.n != null) return { n: k.n };
64
63
  if (k.op === '(') { const v = expr(); if (!take(')')) throw new Error('missing )'); return v; }
65
64
  if (k.id && Object.hasOwn(FNS, k.id) && take('(')) {
66
65
  const args = [expr()];
67
66
  while (take(',')) args.push(expr());
68
67
  if (!take(')')) throw new Error('missing )');
69
- return FNS[k.id](...args);
68
+ return { fn: k.id, args };
70
69
  }
71
- if (k.id) return lookup(k.id);
70
+ if (k.id) return { id: k.id };
72
71
  throw new Error(`unexpected "${k.op}"`);
73
72
  };
74
- const v = expr();
73
+ const tree = expr();
75
74
  if (peek()) throw new Error(`unexpected "${peek().op ?? peek().id ?? peek().n}"`);
75
+ if (trees.size > 5000) trees.clear();
76
+ trees.set(key, tree);
77
+ return tree;
78
+ }
79
+
80
+ // evaluate("line * 3", lookup) -> number. lookup(name) gives a name's value.
81
+ /**
82
+ * One expression: + - * / and brackets, min, max, round, sind, cosd, tand, over numbers and names. Never runs code.
83
+ * @param {string | number} src
84
+ * @param {(name: string) => number} lookup the value of a name
85
+ * @returns {number}
86
+ */
87
+ export function evaluate(src, lookup = (name) => { throw new Error(`no value for "${name}"`); }) {
88
+ if (typeof src === 'number') { if (!Number.isFinite(src)) throw new Error('is not a finite number'); return src; }
89
+ const walk = (x) => {
90
+ if (x.n != null) return x.n;
91
+ if (x.id != null) return lookup(x.id);
92
+ if (x.neg) return -walk(x.neg);
93
+ if (x.pos) return walk(x.pos);
94
+ if (x.fn) return FNS[x.fn](...x.args.map(walk));
95
+ const a = walk(x.a), b = walk(x.b);
96
+ return x.op === '+' ? a + b : x.op === '-' ? a - b : x.op === '*' ? a * b : a / b;
97
+ };
98
+ const v = walk(parse(src));
76
99
  if (!Number.isFinite(v)) throw new Error('is not a finite number');
77
100
  return v;
78
101
  }
@@ -94,7 +117,7 @@ function parseUnit(u) {
94
117
  }
95
118
  const showUnit = (x) => (x == null ? 'a number' : Object.keys(x).length ? Object.entries(x).map(([k, n]) => (n === 1 ? k : n === 2 ? `${k}²` : n === 3 ? `${k}³` : `${k}^${n}`)).join('·') : 'a plain number');
96
119
  const sameUnit = (a, b) => a == null || b == null || (Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, n]) => b[k] === n));
97
- const combine = (a, b, sign) => { if (a == null) return sign > 0 ? b : null; if (b == null) return a; const o = { ...a }; for (const [k, n] of Object.entries(b)) { o[k] = (o[k] || 0) + sign * n; if (!o[k]) delete o[k]; } return o; };
120
+ const combine = (a, b, sign) => { if (a == null) return sign > 0 ? b : b == null ? null : Object.fromEntries(Object.entries(b).map(([k, n]) => [k, -n])); /* (a plain number over a unit: 2 / w is per mm) */ if (b == null) return a; const o = { ...a }; for (const [k, n] of Object.entries(b)) { o[k] = (o[k] || 0) + sign * n; if (!o[k]) delete o[k]; } return o; };
98
121
 
99
122
  /**
100
123
  * The unit an expression comes to, and any mixing of units on the way (mm added to degrees, a sine of millimetres).
@@ -103,29 +126,25 @@ const combine = (a, b, sign) => { if (a == null) return sign > 0 ? b : null; if
103
126
  */
104
127
  export function unitsOf(src, unitOf) {
105
128
  if (typeof src === 'number') return { unit: null, problems: [] };
106
- const t = tokens(String(src)), problems = [];
107
- let i = 0;
108
- const take = (op) => (t[i]?.op === op ? (i++, true) : false);
129
+ let tree;
130
+ try { tree = parse(src); } catch { return { unit: null, problems: [] }; } // (an expression that doesn't parse: evaluate says so)
131
+ const problems = [];
109
132
  const add = (a, b, op) => { if (!sameUnit(a, b)) problems.push(`${op === '+' ? 'adds' : 'takes'} ${showUnit(b)} ${op === '+' ? 'to' : 'from'} ${showUnit(a)}`); return a ?? b; };
110
- const expr = () => { let v = term(); for (;;) { if (take('+')) v = add(v, term(), '+'); else if (take('-')) v = add(v, term(), '-'); else return v; } };
111
- const term = () => { let v = unary(); for (;;) { if (take('*')) v = combine(v, unary(), 1); else if (take('/')) v = combine(v, unary(), -1); else return v; } };
112
- const unary = () => (take('-') || take('+') ? unary() : atom());
113
- const atom = () => {
114
- const k = t[i++];
115
- if (!k) return null;
116
- if (k.n != null) return null;
117
- if (k.op === '(') { const v = expr(); take(')'); return v; }
118
- if (k.id && Object.hasOwn(FNS, k.id) && take('(')) {
119
- const args = [expr()];
120
- while (take(',')) args.push(expr());
121
- take(')');
122
- if (['sind', 'cosd', 'tand'].includes(k.id)) { if (args[0] && !sameUnit(args[0], { deg: 1 })) problems.push(`takes ${k.id} of ${showUnit(args[0])}, not degrees`); return {}; }
123
- if (k.id === 'round') return args[0];
133
+ const walk = (x) => {
134
+ if (x.n != null) return null;
135
+ if (x.id != null) return parseUnit(unitOf(x.id));
136
+ if (x.neg) return walk(x.neg);
137
+ if (x.pos) return walk(x.pos);
138
+ if (x.fn) {
139
+ const args = x.args.map(walk);
140
+ if (['sind', 'cosd', 'tand'].includes(x.fn)) { if (args[0] && !sameUnit(args[0], { deg: 1 })) problems.push(`takes ${x.fn} of ${showUnit(args[0])}, not degrees`); return {}; }
141
+ if (x.fn === 'round') return args[0];
124
142
  return args.reduce((a, b) => add(a, b, '+'));
125
143
  }
126
- return k.id ? parseUnit(unitOf(k.id)) : null;
144
+ const a = walk(x.a), b = walk(x.b);
145
+ return x.op === '+' || x.op === '-' ? add(a, b, x.op) : combine(a, b, x.op === '*' ? 1 : -1);
127
146
  };
128
- const v = expr();
147
+ const v = walk(tree);
129
148
  return { unit: v == null ? null : showUnit(v), problems, value: v };
130
149
  }
131
150
 
@@ -251,11 +270,42 @@ export const fmt = (n) => (typeof n === 'number' ? String(Number(n.toFixed(2)))
251
270
  * @returns {{ line: number, text: string }[]}
252
271
  */
253
272
  export function lint(source) {
254
- const code = source.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/\/\/.*$/gm, '')
255
- .replace(/(['"`])(?:\\.|(?!\1).)*\1/g, (m) => m.replace(/./g, ' '));
256
- const found = [];
257
- code.split('\n').forEach((l, i) => {
258
- for (const m of l.matchAll(/(?<![\w.])(\d+\.\d+|\.\d+|\d+)(?![\w.])/g)) if (!['0', '1', '2'].includes(m[1])) found.push({ line: i + 1, text: m[1] });
259
- });
273
+ // A small tokeniser, so a // inside a string doesn't hide the rest of the line, code inside a template's ${…} is read
274
+ // as code, and every way of writing a number is seen (1e3, 0x1F, 1_000, .5)
275
+ const found = [], n = source.length, NUM = /^(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?)n?/;
276
+ let line = 1, i = 0;
277
+ const depth = []; // open template literals: the brace depth their ${ started at
278
+ let braces = 0;
279
+ const skipString = (q) => { i++; while (i < n && source[i] !== q) { if (source[i] === '\\') i++; else if (source[i] === '\n') line++; i++; } i++; };
280
+ const template = () => { // from just after a backtick (or a closing } of ${…}) to the next ${ or the closing backtick
281
+ while (i < n) {
282
+ const c = source[i];
283
+ if (c === '\\') { i += 2; continue; }
284
+ if (c === '\n') line++;
285
+ if (c === '`') { i++; return; }
286
+ if (c === '$' && source[i + 1] === '{') { i += 2; depth.push(braces); braces++; return; }
287
+ i++;
288
+ }
289
+ };
290
+ while (i < n) {
291
+ const c = source[i];
292
+ if (c === '\n') { line++; i++; continue; }
293
+ if (c === '/' && source[i + 1] === '/') { while (i < n && source[i] !== '\n') i++; continue; }
294
+ if (c === '/' && source[i + 1] === '*') { const end = source.indexOf('*/', i + 2), stop = end < 0 ? n : end + 2; for (let k = i; k < stop; k++) if (source[k] === '\n') line++; i = stop; continue; }
295
+ if (c === '"' || c === "'") { skipString(c); continue; }
296
+ if (c === '`') { i++; template(); continue; }
297
+ if (c === '{') { braces++; i++; continue; }
298
+ if (c === '}') { braces--; i++; if (depth.length && braces === depth.at(-1)) { depth.pop(); template(); } continue; }
299
+ if (/[\w$]/.test(c) && !/\d/.test(c)) { while (i < n && /[\w$]/.test(source[i])) i++; continue; } // a name (x1, v2: not numbers)
300
+ if (/\d/.test(c) || (c === '.' && /\d/.test(source[i + 1] || '') && !/[\w$)\]]/.test(source[i - 1] || ''))) {
301
+ if (c === '.' && /[\w$)\].]/.test(source[i - 1] || '')) { i++; continue; } // (a property after a dot)
302
+ const m = source.slice(i).match(NUM), text = m[0];
303
+ const value = Number(text.replace(/_/g, '').replace(/n$/, ''));
304
+ if (!(value === 0 || value === 1 || value === 2)) found.push({ line, text });
305
+ i += text.length;
306
+ continue;
307
+ }
308
+ i++;
309
+ }
260
310
  return found;
261
311
  }