@rulecad/variables 0.3.0 → 0.3.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/variables",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
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": {
package/variables.d.mts CHANGED
@@ -31,6 +31,28 @@ export function resolve(object: DesignObject, { sets, set, display, load }?: {
31
31
  entries: Entry[];
32
32
  deps: Record<string, string[]>;
33
33
  };
34
+ /**
35
+ * @param {RuleSet & { part?: string, interface?: Record<string, string> }} set
36
+ * @param {{ units: string[], prefixes: string[], fields: Record<string, { unit?: string, choice?: string[] }>, parts: Record<string, string[]> }} vocabulary
37
+ * @returns {{ level: 'fail', code: string, text: string, rule?: string }[]} what's wrong with it: nothing, if it passes
38
+ */
39
+ export function checkRuleSet(set: RuleSet & {
40
+ part?: string;
41
+ interface?: Record<string, string>;
42
+ }, vocabulary: {
43
+ units: string[];
44
+ prefixes: string[];
45
+ fields: Record<string, {
46
+ unit?: string;
47
+ choice?: string[];
48
+ }>;
49
+ parts: Record<string, string[]>;
50
+ }): {
51
+ level: "fail";
52
+ code: string;
53
+ text: string;
54
+ rule?: string;
55
+ }[];
34
56
  /**
35
57
  * Number literals in a design's code other than 0, 1 and 2 (outside comments and strings).
36
58
  * @param {string} source
@@ -43,7 +65,7 @@ export function lint(source: string): {
43
65
  export const ANCHORS: string[];
44
66
  export function isName(d: any): boolean;
45
67
  export function options(d: any): any;
46
- export function fmt(n: number | string): string;
68
+ export function fmt(n: any): string;
47
69
  export type Variable = {
48
70
  value: number | string;
49
71
  unit?: string;
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
  }
@@ -103,29 +126,25 @@ const combine = (a, b, sign) => { if (a == null) return sign > 0 ? b : b == null
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
 
@@ -241,6 +260,49 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
241
260
 
242
261
  // Round for display: at most 2 decimals, no trailing zeros.
243
262
  /** A number to two decimals at most; a name as it is. @param {number | string} n @returns {string} */
263
+ // A published rule set, held to what makes it traceable: every value says what it is, how far to trust it, where it
264
+ // comes from and when it was checked. A set with "part" (a motor) uses the shared names in vocabulary (the rule sets'
265
+ // vocabulary.json), every required one, each in its unit; an older set says which of its rules is which in "interface".
266
+ const KINDS = ['measured', 'spec', 'community', 'default', 'derived', 'estimate'];
267
+ /**
268
+ * @param {RuleSet & { part?: string, interface?: Record<string, string> }} set
269
+ * @param {{ units: string[], prefixes: string[], fields: Record<string, { unit?: string, choice?: string[] }>, parts: Record<string, string[]> }} vocabulary
270
+ * @returns {{ level: 'fail', code: string, text: string, rule?: string }[]} what's wrong with it: nothing, if it passes
271
+ */
272
+ export function checkRuleSet(set, vocabulary) {
273
+ const out = [], f = (code, text, rule) => out.push({ level: 'fail', code, text, ...(rule ? { rule } : {}) }), { units, prefixes, fields, parts } = vocabulary, rules = set?.rules;
274
+ if (!rules || typeof rules !== 'object' || !Object.keys(rules).length) { f('rules.shape', 'it has no rules'); return out; }
275
+ for (const [name, r] of Object.entries(rules)) {
276
+ if (!(typeof r.value === 'number' ? Number.isFinite(r.value) : typeof r.value === 'string' && r.value)) f('rules.value', `${name} has no value`, name);
277
+ if (!(typeof r.rule === 'string' && r.rule.length > 5)) f('rules.says', `${name} doesn't say what it is ("rule")`, name);
278
+ if (!KINDS.includes(r.kind)) f('rules.kind', `${name}: kind ${JSON.stringify(r.kind)} is not one of ${KINDS.join(', ')}`, name);
279
+ if (!(typeof r.source === 'string' && r.source)) f('rules.source', `${name} has no source`, name);
280
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(String(r.checked))) f('rules.checked', `${name}: checked is the date it was last checked, YYYY-MM-DD (got ${JSON.stringify(r.checked)})`, name);
281
+ if (set.part) {
282
+ if (r.unit != null && !units.includes(r.unit)) f('rules.unit', `${name}: unit ${JSON.stringify(r.unit)} is not one of ${units.filter(Boolean).join(', ')}`, name);
283
+ if (typeof r.value === 'number' && r.unit == null) f('rules.unit', `${name} is a number with no unit (give "unit", "" if it has none)`, name);
284
+ const field = fields[name];
285
+ if (prefixes.some((p) => name.startsWith(p)) && !field) f('rules.name', `${name} is not in the vocabulary (a name starting ${prefixes.join(', ')} says how a part mounts, so everything reads it the same way)`, name);
286
+ if (field?.unit != null && r.unit !== field.unit) f('rules.unit', `${name} is in ${JSON.stringify(field.unit)}, not ${JSON.stringify(r.unit ?? null)}`, name);
287
+ if (field?.choice && !field.choice.includes(r.value)) f('rules.choice', `${name} is one of ${field.choice.join(', ')} (got ${JSON.stringify(r.value)})`, name);
288
+ }
289
+ }
290
+ if (set.part) {
291
+ if (!parts[set.part]) f('rules.part', `part ${JSON.stringify(set.part)} is not one of ${Object.keys(parts).join(', ')}`);
292
+ else for (const name of parts[set.part]) if (!rules[name]) f('rules.missing', `a ${set.part} needs ${name}`, name);
293
+ }
294
+ for (const [shared, own] of Object.entries(set.interface || {})) {
295
+ if (!fields[shared]) f('rules.name', `interface: ${shared} is not in the vocabulary`, own);
296
+ if (!rules[own]) f('rules.interface', `interface: ${shared} names ${own}, which isn't one of its rules`, own);
297
+ }
298
+ for (const [name, v] of Object.entries(set.variants || {})) {
299
+ if (!KINDS.includes(v.kind)) f('rules.kind', `variant ${name}: kind ${JSON.stringify(v.kind)} is not one of ${KINDS.join(', ')}`);
300
+ if (!(typeof v.source === 'string' && v.source)) f('rules.source', `variant ${name} has no source`);
301
+ for (const rule of Object.keys(v.values || {})) if (!rules[rule]) f('rules.variant', `variant ${name} changes ${rule}, which isn't one of its rules`, rule);
302
+ }
303
+ return out;
304
+ }
305
+
244
306
  export const fmt = (n) => (typeof n === 'number' ? String(Number(n.toFixed(2))) : String(n)); // choices are names
245
307
 
246
308
  // lint(source) -> [{ line, text }]: number literals in a design's code that should be variables. Every measurement