@skillstech/thunderlang 1.0.4 → 1.2.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/CHANGELOG.md +221 -0
- package/README.md +4 -1
- package/dist/core.cjs +2568 -462
- package/dist/index.cjs +7562 -5084
- package/dist/learn.cjs +16994 -8339
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli-home.mjs +242 -0
- package/src/cli.mjs +241 -89
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +184 -0
- package/src/core/diagnostics.mjs +82 -0
- package/src/core/engine-core.mjs +572 -0
- package/src/core/engine-values.mjs +1054 -0
- package/src/core/engine-worker.mjs +15 -0
- package/src/core/engine.mjs +63 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +39 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +177 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/runtime-typescript.mjs +119 -0
- package/src/core/target-python.mjs +487 -0
- package/src/core/target-typescript.mjs +466 -0
- package/src/core/typescript-run.mjs +114 -0
- package/src/core.d.ts +5 -2
- package/src/core.mjs +5 -2
- package/src/data-schema.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +1 -1
- package/src/expr.mjs +81 -4
- package/src/form-words.mjs +2 -0
- package/src/index.d.ts +8 -1
- package/src/index.mjs +5 -1
- package/src/intent-schema.mjs +1 -0
- package/src/learn-lessons.mjs +245 -1
- package/src/learn.d.mts +8 -0
- package/src/learn.mjs +40 -4
- package/src/mcp.mjs +23 -0
- package/src/meaning.mjs +45 -6
- package/src/model.d.mts +7 -3
- package/src/model.mjs +19 -6
- package/src/money.d.mts +18 -0
- package/src/money.mjs +124 -0
- package/src/plain-contract.mjs +18 -2
- package/src/read-level.mjs +146 -0
- package/src/read.d.mts +11 -0
- package/src/read.mjs +40 -6
- package/src/review-comment.d.mts +16 -0
- package/src/review-comment.mjs +145 -0
- package/src/say-less.mjs +1432 -0
- package/src/system.mjs +153 -44
- package/src/target-cs.mjs +39 -34
- package/src/target-elixir.mjs +40 -30
- package/src/target-go.mjs +41 -36
- package/src/target-java.mjs +34 -27
- package/src/target-kotlin.mjs +43 -35
- package/src/target-py.mjs +57 -55
- package/src/target-result.d.mts +48 -0
- package/src/target-result.mjs +112 -0
- package/src/target-rust.mjs +42 -38
- package/src/target-scala.mjs +45 -35
- package/src/target-ts.mjs +37 -45
- package/src/target-types.mjs +41 -5
- package/src/target-util.mjs +55 -2
- package/src/term.mjs +89 -0
- package/src/trace-cli.mjs +58 -0
- package/src/trace-fs.mjs +76 -0
- package/src/trace.mjs +261 -0
- package/src/translate.d.mts +3 -0
- package/src/translate.mjs +62 -32
- package/src/try-cli.mjs +225 -0
- package/src/why-cli.mjs +41 -0
- package/src/why.d.mts +38 -0
- package/src/why.mjs +613 -0
- package/src/write-steps.mjs +22 -5
package/src/mcp.mjs
CHANGED
|
@@ -18,6 +18,8 @@ import { runTests } from './testing.mjs';
|
|
|
18
18
|
import { resolveObligations } from './obligations.mjs';
|
|
19
19
|
import { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode } from './review-atlas.mjs';
|
|
20
20
|
import { evaluateDecision } from './runtime.mjs';
|
|
21
|
+
import { buildTrace, traceImpact, traceImpactOf, renderImpact } from './trace.mjs';
|
|
22
|
+
import { readRepoDir, gitChanges } from './trace-fs.mjs';
|
|
21
23
|
import { buildIntentGraph } from './intent-graph.mjs';
|
|
22
24
|
import { buildConformance } from './conformance.mjs';
|
|
23
25
|
import { checkDrift } from './drift.mjs';
|
|
@@ -261,6 +263,27 @@ const TOOLS = [
|
|
|
261
263
|
return { ...rest, files: files.length, matched: items.length, items: items.slice(0, Math.max(1, Math.min(500, Number(limit) || 50))) };
|
|
262
264
|
},
|
|
263
265
|
},
|
|
266
|
+
{
|
|
267
|
+
name: 'intent_trace',
|
|
268
|
+
description: 'ASK THUNDER TRACE BEFORE CHANGING CODE THAT OTHER REPOSITORIES USE (local only). Give the repository folders. With "thing" (a route like "POST /api/orders", an event name, or "repo:file[:line]") or "diff": true (the branch and uncommitted changes), it answers what the change can affect in the OTHER repositories: callers of a changed or removed route, listeners of a published event, ranked high/medium/low, one hop out, every item cited repo@sha:file:line. With neither, it gives the links between the repositories. Read from code; nothing is run; a call whose address is worked out when it runs is listed as not linked, never guessed.',
|
|
269
|
+
inputSchema: {
|
|
270
|
+
type: 'object', required: ['paths'],
|
|
271
|
+
properties: {
|
|
272
|
+
paths: { type: 'array', minItems: 1, maxItems: 50, items: { ...str, description: 'a repository folder' } },
|
|
273
|
+
thing: { ...str, description: 'what changes: "POST /api/orders", "order.placed", or "repo:src/file.ts:12"' },
|
|
274
|
+
diff: { type: 'boolean', description: 'use the current changes (since the branch left main, plus uncommitted)' },
|
|
275
|
+
base: { ...str, description: 'with diff: the commit or branch to compare against' },
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
run: ({ paths, thing, diff = false, base }) => {
|
|
279
|
+
if (!Array.isArray(paths) || !paths.length || paths.length > 50) throw new Error('Give 1 to 50 repository folders in "paths".');
|
|
280
|
+
const repos = paths.map((p) => readRepoDir(resolve(String(p))));
|
|
281
|
+
const trace = buildTrace(repos);
|
|
282
|
+
if (!thing && !diff) return { trace };
|
|
283
|
+
const r = thing ? traceImpactOf(trace, String(thing)) : traceImpact(trace, repos.flatMap((repo) => gitChanges(repo, base).changes));
|
|
284
|
+
return { ...r, text: renderImpact(r) };
|
|
285
|
+
},
|
|
286
|
+
},
|
|
264
287
|
{
|
|
265
288
|
name: 'intent_promote',
|
|
266
289
|
description: 'Turn a decision recovered from code into a readable ThunderLang contract with starter examples chosen at every rule and threshold. The examples record what the code does TODAY (computed from the recovered rule), so a person must confirm each answer; after that, intent_verify_diff can hold every change to it. Give the source code and the decision (function) name.',
|
package/src/meaning.mjs
CHANGED
|
@@ -521,6 +521,7 @@ class Parser {
|
|
|
521
521
|
if (t.v === '...' && (fam === 'c')) { this.next(); return { kind: 'spread', value: this.expr(1), form: '...' }; }
|
|
522
522
|
if ((t.v === '*' || t.v === '**') && (fam === 'py' || fam === 'rb' || this.lang === 'kotlin')) { this.next(); return { kind: 'spread', value: this.expr(fam === 'py' ? 13 : 15), form: t.v }; }
|
|
523
523
|
if (t.v === '&' && fam === 'rb') { this.next(); return { kind: 'spread', value: this.expr(15), form: '&' }; }
|
|
524
|
+
if ((t.v === '*' || t.v === '&') && (this.lang === 'c' || this.lang === 'cpp')) { this.next(); return { kind: 'unary', op: t.v, value: this.expr(17) }; }
|
|
524
525
|
if ((t.v === '*' || t.v === '&' || t.v === '<-') && (fam === 'go' || fam === 'rs')) {
|
|
525
526
|
this.next();
|
|
526
527
|
if (t.v === '&' && fam === 'rs' && this.isId('mut')) { this.next(); return { kind: 'unary', op: '&mut', value: this.expr(16) }; }
|
|
@@ -754,6 +755,13 @@ class Parser {
|
|
|
754
755
|
node = { kind: 'member', object: node, property: p.v };
|
|
755
756
|
continue;
|
|
756
757
|
}
|
|
758
|
+
if (t.v === '->' && (lang === 'c' || lang === 'cpp')) {
|
|
759
|
+
this.next();
|
|
760
|
+
const p = this.next();
|
|
761
|
+
if (p.t !== 'id') fail('expected a name after ->');
|
|
762
|
+
node = { kind: 'member', object: node, property: p.v, arrow: true };
|
|
763
|
+
continue;
|
|
764
|
+
}
|
|
757
765
|
if (t.v === '&.' && fam === 'rb') { this.next(); const pn = this.next(); if (pn.t !== 'id') fail('a name after &.'); node = { kind: 'member', object: node, property: pn.v, optional: true }; continue; }
|
|
758
766
|
if (t.v === '?.' && fam === 'c') {
|
|
759
767
|
this.next();
|
|
@@ -776,7 +784,7 @@ class Parser {
|
|
|
776
784
|
if (t.v === '!!' && lang === 'kotlin') { this.next(); node = { kind: 'unary', op: '!!', value: node, postfix: true }; continue; }
|
|
777
785
|
if (t.v === '?' && fam === 'rs' && !t.sp) { this.next(); node = { kind: 'unary', op: '?', value: node, postfix: true }; continue; }
|
|
778
786
|
if ((t.v === '++' || t.v === '--') && !t.nl && fam !== 'py') { this.next(); node = { kind: 'unary', op: t.v, value: node, postfix: true }; continue; }
|
|
779
|
-
if (t.v === '<' && (lang === 'typescript' || lang === 'csharp' || lang === 'java' || lang === 'kotlin') && !t.sp && this.looksLikeTypeArgs()) { node = { ...node, typeArgs: this.typeArgs() }; continue; }
|
|
787
|
+
if (t.v === '<' && (lang === 'typescript' || lang === 'csharp' || lang === 'java' || lang === 'kotlin' || lang === 'cpp') && !t.sp && this.looksLikeTypeArgs()) { node = { ...node, typeArgs: this.typeArgs() }; continue; }
|
|
780
788
|
if (t.v === '{' && !this.noBrace && (fam === 'go' || fam === 'rs') && this.isTypeName(node)) { node = this.compositeLit(node); continue; }
|
|
781
789
|
if (t.v === '{' && lang === 'kotlin' && !this.noBrace && (node.kind === 'call' || node.kind === 'name' || node.kind === 'member')) { node = this.withTrailing(node, this.kotlinLambda()); continue; }
|
|
782
790
|
// Ruby: braces after a call are its block (`items.each { |x| … }`, `loop { … }`); a hash is only ever an argument.
|
|
@@ -810,7 +818,7 @@ class Parser {
|
|
|
810
818
|
if (t.t === 'op') {
|
|
811
819
|
if (t.v === '<') depth++;
|
|
812
820
|
else if (t.v === '>' || t.v === '>>') { depth -= t.v.length; if (depth <= 0) { const nx = this.peek(o + 1); return nx.t === 'op' && (nx.v === '(' || (nx.v === '{' && this.lang === 'csharp')); } }
|
|
813
|
-
else if (!/^(?:,|\.|\[|\]|\||&|\?|=>|\(|\)|:)$/.test(t.v)) return false;
|
|
821
|
+
else if (!/^(?:,|\.|\[|\]|\||&|\?|=>|\(|\)|:)$/.test(t.v) && !(this.lang === 'cpp' && /^(?:::|\*|&&)$/.test(t.v))) return false;
|
|
814
822
|
} else if (t.t !== 'id' && t.t !== 'str' && t.t !== 'num') return false;
|
|
815
823
|
}
|
|
816
824
|
return false;
|
|
@@ -881,6 +889,8 @@ class Parser {
|
|
|
881
889
|
}
|
|
882
890
|
|
|
883
891
|
paren() {
|
|
892
|
+
// C / C++: a cast `(redisPollEvents *)data`, `(int)n`, `(const char *)p`.
|
|
893
|
+
if (this.lang === 'c' || this.lang === 'cpp') { const c = this.cCast(); if (c) return c; }
|
|
884
894
|
// An arrow function `(a, b) => …` / `(a: T): R => …`?
|
|
885
895
|
if (this.fam === 'c' && (isJs(this.lang) || this.lang === 'csharp' || this.lang === 'java')) {
|
|
886
896
|
// JSX inside brackets (`return (\n <div>…`) is read as JSX, not scanned as code.
|
|
@@ -890,6 +900,22 @@ class Parser {
|
|
|
890
900
|
}
|
|
891
901
|
return this.plainParen();
|
|
892
902
|
}
|
|
903
|
+
cCast() {
|
|
904
|
+
const src = this.L.src, open = this.peek().s;
|
|
905
|
+
const close = src.indexOf(')', open);
|
|
906
|
+
if (close < 0) return null;
|
|
907
|
+
const inner = src.slice(open + 1, close);
|
|
908
|
+
const m = /^\s*((?:(?:const|volatile|struct|enum|union|unsigned|signed|long|short)\s+)*)([A-Za-z_][\w:]*)(\s*<[^()]*>)?((?:\s*(?:const\s*)?[*&])*)\s*$/.exec(inner);
|
|
909
|
+
if (!m) return null;
|
|
910
|
+
const clearlyType = /\*|&/.test(m[4]) || !!m[1] || /^(?:int|char|long|short|float|double|void|bool|size_t|ssize_t|unsigned|signed|u?int\d+_t|uintptr_t|intptr_t|ptrdiff_t|time_t|off_t|wchar_t|char\d+_t|uint|uchar|BOOL|DWORD|HANDLE)$/.test(m[2]) || /_t$/.test(m[2]);
|
|
911
|
+
if (!clearlyType) return null;
|
|
912
|
+
const after = src.slice(close + 1).trimStart();
|
|
913
|
+
if (!/^[A-Za-z_\d("'*&!~-]/.test(after)) return null;
|
|
914
|
+
while (this.peek().t !== 'eof' && this.peek().s < close) this.next();
|
|
915
|
+
if (!this.isOp(')')) return null;
|
|
916
|
+
this.next();
|
|
917
|
+
return { kind: 'cast', type: inner.trim(), value: this.expr(16), form: 'c' };
|
|
918
|
+
}
|
|
893
919
|
arrowOrParen() {
|
|
894
920
|
// Find the matching ) and look for => (or ->, Java) after it, past an optional return type.
|
|
895
921
|
let depth = 0, o = 0;
|
|
@@ -1563,6 +1589,8 @@ function statement(p) {
|
|
|
1563
1589
|
return node;
|
|
1564
1590
|
}
|
|
1565
1591
|
if (v === 'default' && fam !== 'py' && (p.isOp(':', 1) || p.isOp('->', 1))) { p.next(); p.next(); return p.peek().t === 'eof' ? { kind: 'case', default: true } : { kind: 'case', default: true, inline: true }; }
|
|
1592
|
+
// Swift `try f()` / `try? f()` / Rust-like `try await f()`: an expression that may throw, not a try block.
|
|
1593
|
+
if (v === 'try' && lang === 'swift' && !p.isOp('{', 1)) { p.next(); if (p.isOp('?') || p.isOp('!')) p.next(); if (p.isId('await')) p.next(); return statement(p); }
|
|
1566
1594
|
if (v === 'try' || v === 'begin') { p.next(); return { kind: 'try' }; }
|
|
1567
1595
|
if (v === 'return' && !(p.isOp('=', 1))) {
|
|
1568
1596
|
p.next();
|
|
@@ -1613,6 +1641,7 @@ function statement(p) {
|
|
|
1613
1641
|
if (v === 'async' && fam === 'py' && (p.isId('with', 1) || p.isId('for', 1) || p.isId('def', 1))) { p.next(); const s = statement(p); return { ...s, async: true }; }
|
|
1614
1642
|
if (v === 'pass' && fam === 'py') { p.next(); return endStatement(p, { kind: 'pass' }); }
|
|
1615
1643
|
if (v === 'def' || (v === 'function' && p.peek(1).t === 'id') || (v === 'func' && p.peek(1).t === 'id') || (v === 'fn' && fam === 'rs') || (v === 'fun' && lang === 'kotlin') || (v === 'async' && isJs(lang) && p.isId('function', 1) && p.peek(2).t === 'id')) return functionHeader(p);
|
|
1644
|
+
if ((lang === 'c' || lang === 'cpp') && /^(?:const|static|struct|enum|union|constexpr|unsigned|signed|long|short|register|extern|volatile|inline|mutable)$/.test(v) && typedDeclAhead(p)) return typedDeclaration(p);
|
|
1616
1645
|
if (/^(?:class|struct|interface|enum|impl|trait|object|record|module|type|namespace|import|export|from|package|use|using|lock|synchronized|unsafe|goto|static|public|private|protected|internal|abstract|override|virtual|final|readonly|global|nonlocal|extern|template|typedef|label)$/.test(v) && !(p.isOp('(', 1) && !/^(?:using|lock|synchronized)$/.test(v)) && !(p.isOp('.', 1)) && !(p.peek(1).t === 'op' && (ASSIGN_OPS.has(p.peek(1).v) || p.peek(1).v === ',' || p.peek(1).v === '['))) {
|
|
1617
1646
|
if (v === 'export' && (p.isId('const', 1) || p.isId('let', 1) || p.isId('function', 1))) { p.next(); return statement(p); }
|
|
1618
1647
|
if ((v === 'global' || v === 'nonlocal') && fam === 'py') { p.next(); const names = []; while (p.peek().t === 'id') { names.push(p.next().v); if (p.isOp(',')) p.next(); } return endStatement(p, { kind: 'declare', names, scope: v }); }
|
|
@@ -1820,14 +1849,15 @@ function methodHeader(p) {
|
|
|
1820
1849
|
function typedDeclAhead(p, method = false) {
|
|
1821
1850
|
// Type name = …; Type<A, B>[] name; final Type name = …
|
|
1822
1851
|
let o = 0;
|
|
1823
|
-
|
|
1852
|
+
const cLike = p.lang === 'c' || p.lang === 'cpp';
|
|
1853
|
+
while (p.peek(o).t === 'id' && (/^(?:final|static|readonly|const|volatile|var|unsigned|signed)$/.test(p.peek(o).v) || (cLike && /^(?:struct|enum|union|constexpr|long|short|register|extern|inline|mutable|thread_local)$/.test(p.peek(o).v))) && p.peek(o + 1).t === 'id') o++;
|
|
1824
1854
|
if (p.peek(o).t !== 'id') return false;
|
|
1825
1855
|
if (/^(?:return|throw|new|await|yield|case|goto|else|in|is|as|out|ref|params|this|base|super)$/.test(p.peek(o).v)) return false;
|
|
1826
1856
|
o++;
|
|
1827
1857
|
let depth = 0;
|
|
1828
1858
|
for (let guard = 0; guard < 40; guard++) {
|
|
1829
1859
|
const t = p.peek(o);
|
|
1830
|
-
if (t.t === 'op' && (t.v === '.' || t.v === '?' || t.v === '*' || t.v === '&') && depth === 0) { o++; if (p.peek(o).t === 'id' && t.v === '.') o++; continue; }
|
|
1860
|
+
if (t.t === 'op' && (t.v === '.' || t.v === '?' || t.v === '*' || t.v === '&' || (cLike && (t.v === '::' || t.v === '&&'))) && depth === 0) { o++; if (p.peek(o).t === 'id' && (t.v === '.' || t.v === '::')) o++; continue; }
|
|
1831
1861
|
if (t.t === 'op' && t.v === '<') { depth++; o++; continue; }
|
|
1832
1862
|
if (t.t === 'op' && (t.v === '>' || t.v === '>>')) { depth -= t.v.length; o++; continue; }
|
|
1833
1863
|
if (t.t === 'op' && t.v === '[' && p.isOp(']', o + 1)) { o += 2; continue; }
|
|
@@ -1837,7 +1867,7 @@ function typedDeclAhead(p, method = false) {
|
|
|
1837
1867
|
if (depth !== 0 || p.peek(o).t !== 'id') return false;
|
|
1838
1868
|
const after = p.peek(o + 1);
|
|
1839
1869
|
if (method) return after.t === 'op' && after.v === '(' ? o : false;
|
|
1840
|
-
return after.t === 'eof' || (after.t === 'op' && (after.v === '=' || after.v === ';' || after.v === ',')) ? o : false;
|
|
1870
|
+
return after.t === 'eof' || (after.t === 'op' && (after.v === '=' || after.v === ';' || after.v === ',' || (cLike && after.v === '['))) ? o : false;
|
|
1841
1871
|
}
|
|
1842
1872
|
function typedDeclaration(p, inner = false) {
|
|
1843
1873
|
const a = p.k;
|
|
@@ -1848,6 +1878,10 @@ function typedDeclaration(p, inner = false) {
|
|
|
1848
1878
|
const items = [];
|
|
1849
1879
|
for (;;) {
|
|
1850
1880
|
const name = p.next().v;
|
|
1881
|
+
// C / C++ arrays: `char port[6];`
|
|
1882
|
+
let dims = '';
|
|
1883
|
+
while ((p.lang === 'c' || p.lang === 'cpp') && p.isOp('[')) { const d0 = p.k; let depth = 0; do { const x = p.next(); if (x.t === 'eof') fail('array size'); if (x.v === '[') depth++; else if (x.v === ']') depth--; } while (depth > 0); dims += p.text(d0, p.k); }
|
|
1884
|
+
if (dims) { if (p.isOp('=')) fail('array initializer'); items.push({ kind: 'declare', declare: 'typed', type: `${type}${dims}`, names: [name] }); if (p.isOp(',')) { p.next(); continue; } break; }
|
|
1851
1885
|
if (p.isOp('=')) { p.next(); items.push({ kind: 'assign', op: '=', declare: 'typed', type, target: { kind: 'name', name }, value: p.isOp('{') ? p.objectLit() : p.expr(0.6) }); }
|
|
1852
1886
|
else items.push({ kind: 'declare', declare: 'typed', type, names: [name] });
|
|
1853
1887
|
if (p.isOp(',')) { p.next(); continue; }
|
|
@@ -1938,12 +1972,17 @@ function forHeader(p) {
|
|
|
1938
1972
|
}
|
|
1939
1973
|
let declare = null;
|
|
1940
1974
|
if (p.peek().t === 'id' && /^(?:const|let|var|val|final|auto)$/.test(p.peek().v) && (p.peek(1).t === 'id' || p.isOp('[', 1) || p.isOp('{', 1) || p.isOp('(', 1))) declare = p.next().v;
|
|
1975
|
+
// C++: `auto &t : threads` / `auto* p : ps`.
|
|
1976
|
+
if (declare === 'auto' && (lang === 'cpp' || lang === 'c')) while (p.isOp('&') || p.isOp('*') || p.isOp('&&')) p.next();
|
|
1977
|
+
if (declare === 'const' && (lang === 'cpp' || lang === 'c')) declare = null;
|
|
1941
1978
|
// Java/C#: the element's type before its name.
|
|
1942
1979
|
let type = null;
|
|
1943
1980
|
if (p.peek().t === 'id' && !declare) {
|
|
1944
1981
|
const k0 = p.k;
|
|
1945
1982
|
let o = 0;
|
|
1946
|
-
|
|
1983
|
+
// (C++: `const auto& item`, `std::string *s`.)
|
|
1984
|
+
const cLike = lang === 'c' || lang === 'cpp';
|
|
1985
|
+
while (p.peek(o).t === 'id' || (p.peek(o).t === 'op' && (/^(?:\.|<|>|\[|\]|,|\?)$/.test(p.peek(o).v) || (cLike && /^(?:&|\*|&&|::)$/.test(p.peek(o).v))))) { if (p.peek(o).t === 'id' && (/^(?:of|in)$/.test(p.peek(o).v))) break; if (p.isOp(':', o)) break; o++; }
|
|
1947
1986
|
if (o >= 2 && p.peek(o - 1).t === 'id') { type = p.text(k0, k0 + o - 1); p.k = k0 + o - 1; }
|
|
1948
1987
|
}
|
|
1949
1988
|
const targets = [];
|
package/src/model.d.mts
CHANGED
|
@@ -7,7 +7,9 @@ export interface FlowNode { id: string; kind: 'start' | 'decision' | 'step' | 'l
|
|
|
7
7
|
/** A yes/no question as a statement on each side, when it splits cleanly: { yes: "the x header is the KEY setting", no: "… is not …" }. */
|
|
8
8
|
holds?: { yes: string; no: string };
|
|
9
9
|
/** The step's full meaning (thunder-expr-v1). */ expr?: Expr;
|
|
10
|
-
/** What the short words leave out, one level down: "with: order, { validate: false }". Shown in Details and the full Thunder Text. */ detail?: string
|
|
10
|
+
/** What the short words leave out, one level down: "with: order, { validate: false }". Shown in Details and the full Thunder Text. */ detail?: string;
|
|
11
|
+
/** False for a node shown as code ("code, not explained"); true for every node in Thunder's own words. Always set. */ explained: boolean;
|
|
12
|
+
/** When `explained` is false: why, in a few plain words. */ notExplainedWhy?: string }
|
|
11
13
|
export interface FlowEdge { from: string; to: string; label?: 'yes' | 'no' | 'each' | 'next' | 'done' | 'error' | 'case' | 'nested'; /** On a 'case' edge: the case it takes ("When it is from 90 to 100", "Otherwise", "None of these"). */ text?: string }
|
|
12
14
|
export interface FlowBlock { id: string; yes?: FlowBlock[]; no?: FlowBlock[]; each?: FlowBlock[]; body?: FlowBlock[];
|
|
13
15
|
/** A choice among several cases (switch, when, match, select): one side per case, in order. The decision node has `cases: true`. */
|
|
@@ -42,8 +44,10 @@ export interface Link { from: string; to: string; kind: LinkKind; node?: string;
|
|
|
42
44
|
export type ModelLink = Link;
|
|
43
45
|
export interface Member { id: string; kind: 'action' | 'rule' | 'steps' | 'setup' | 'not-read' | 'pipeline' | 'image-build'; /** Pipelines: when it runs, in words. */ when?: string; name: string; label: string; owner?: string; file: string; language: string; lines: [number, number]; doc?: string; route?: string;
|
|
44
46
|
/** JS/TS: what the function is assigned to (`exports.normalizeType`, `View.prototype.lookup`, `res.json`). */ assignedTo?: string;
|
|
45
|
-
/** JS/TS: an anonymous function passed to a call (named `<parent> › callback at line N`); `passedTo` is the call. */ callback?: true; passedTo?: string; youGive: string[]; /** Each input's kind in words, by its label, when the code says it. */ inputKinds?: Record<string, string>; youGetBack?: string; rule?: unknown; question?: string; yesNo?: boolean; flow: Flow;
|
|
46
|
-
|
|
47
|
+
/** JS/TS: an anonymous function passed to a call (named `<parent> › callback at line N`); `passedTo` is the call. */ callback?: true; passedTo?: string; youGive: string[]; /** Each input's kind in words, by its label, when the code says it. */ inputKinds?: Record<string, string>; youGetBack?: string; rule?: unknown; question?: string; yesNo?: boolean; flow: Flow;
|
|
48
|
+
/** How sure: steps put into words, of every step Thunder read in this member (absent for rules). */ explainedSteps?: number; totalSteps?: number; /** Set by proof by running (executed.mjs markExecuted) only where a run proved the reading. */ completeness?: { level: 'executed'; reasons: string[] } }
|
|
49
|
+
export interface ThunderModel { schema: 'thunder-model-v1'; name: string; files: { path: string; language: string; purpose?: string; category: 'application' | 'infrastructure' | 'delivery'; /** Why this file could not be read. */ skipped?: string }[]; things: Thing[]; members: Member[]; links: Link[]; unknowns: { id?: string; file: string; line: number; why: string }[]; permissions: Permission[]; settings: Setting[]; facts: Fact[]; notLinked?: NotLinked[];
|
|
50
|
+
/** How sure, for the whole app: steps put into words, of every step read. */ explainedSteps: number; totalSteps: number }
|
|
47
51
|
/** A call, request, event, or import worth linking that was not linked, and why (dynamic import, computed URL, external package, two routes match, an interface). */
|
|
48
52
|
export interface NotLinked { from?: string; node?: string; file: string | null; line: number | null; call?: string; import?: string; why: string; /** For an external package: how many imports of it. */ files?: number }
|
|
49
53
|
/** Which areas (folders, two levels deep) call which, from cross-file and service links. */
|
package/src/model.mjs
CHANGED
|
@@ -270,7 +270,8 @@ const possessiveWords = (text) => String(text)
|
|
|
270
270
|
.replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words(m)); // days_late, daysLate -> days late
|
|
271
271
|
/** An answer as words: NoFee -> "No fee", true -> "Yes". */
|
|
272
272
|
// (Quoted text is an answer as written: its case, signs, and spaces are kept.)
|
|
273
|
-
|
|
273
|
+
// (A short name that would split into one-letter pieces, such as NaN, is kept as written: "Na n" is not a word.)
|
|
274
|
+
const answerWords = (r) => (/^true$/i.test(r) ? 'Yes' : /^false$/i.test(r) ? 'No' : /^(["'`]).*\1$/s.test(String(r).trim()) ? String(r).trim() : /^[A-Za-z]{2,4}$/.test(String(r).trim()) && /[a-z][A-Z]|[A-Z][a-z]+[A-Z]/.test(String(r)) ? String(r).trim() : cap(words(r)));
|
|
274
275
|
|
|
275
276
|
/**
|
|
276
277
|
* A branch as a question a kid can answer with yes or no, asked the positive way round. "If book.status is not on
|
|
@@ -286,7 +287,9 @@ export function askAsQuestion(step, ruleLabel) {
|
|
|
286
287
|
const held = [];
|
|
287
288
|
const says = String(step.says).replace(/"(?:\\.|[^"\\])*"|`[^`]*`|«[^»]*»/g, (m) => (isCodeWords(String(step.says).replace(/^If (?:not: )?/, '')) ? m : `\u0001${held.push(m) - 1}\u0002`));
|
|
288
289
|
const r = askWords({ ...step, says }, ruleLabel);
|
|
289
|
-
|
|
290
|
+
// (Every text made from the held words gets them back: the question and both sides of `holds`, which a review quotes.)
|
|
291
|
+
const back = (t) => String(t).replace(/\u0001(\d+)\u0002/g, (m, k) => held[Number(k)]);
|
|
292
|
+
return { ...r, text: back(r.text), ...(r.holds ? { holds: { yes: back(r.holds.yes), no: back(r.holds.no) } } : {}) };
|
|
290
293
|
}
|
|
291
294
|
function askWords(step, ruleLabel) {
|
|
292
295
|
let c = String(step.says).replace(/^If /, '').replace(/ \(\d+ steps? inside\)$/, '').trim();
|
|
@@ -334,7 +337,7 @@ function compoundWords(c) {
|
|
|
334
337
|
export function ruleFlow(item, start) {
|
|
335
338
|
const nodes = [], edges = [];
|
|
336
339
|
let n = 0;
|
|
337
|
-
const node = (kind, text, extra = {}) => { const id = `n${n++}`; nodes.push({ id, kind, text, row: nodes.length, ...extra }); return id; };
|
|
340
|
+
const node = (kind, text, extra = {}) => { const id = `n${n++}`; nodes.push({ id, kind, text, row: nodes.length, explained: true, ...extra }); return id; };
|
|
338
341
|
let prev = node('start', start, { lane: 0, does: 'start' });
|
|
339
342
|
let label;
|
|
340
343
|
for (const r of item.rules || []) {
|
|
@@ -379,6 +382,10 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
379
382
|
const id = `n${n++}`;
|
|
380
383
|
const { [DETAIL_OF]: of, ...rest } = extra;
|
|
381
384
|
const nd = { id, kind, text, ...rest };
|
|
385
|
+
// `explained`: false for every node shown as code ("code, not explained"), with `notExplainedWhy` when known.
|
|
386
|
+
nd.explained = !(kind === 'code' || nd.code || rest.explained === false);
|
|
387
|
+
if (nd.explained) delete nd.notExplainedWhy;
|
|
388
|
+
else if (!nd.notExplainedWhy) nd.notExplainedWhy = 'the reader did not recognize this form';
|
|
382
389
|
if (of) lazyDetail(nd, of);
|
|
383
390
|
nodes.push(nd);
|
|
384
391
|
return id;
|
|
@@ -411,7 +418,7 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
411
418
|
const does = stepDoes(st);
|
|
412
419
|
// Every node keeps its step's meaning tree (`expr`) and, when the short words leave something out, `detail`:
|
|
413
420
|
// the rest, one level down ("with: order, { validate: false }"). Details and the full Thunder Text show it.
|
|
414
|
-
const base = { line: st.line, lane, does, ...(usesOf(st) ? { uses: usesOf(st) } : {}), ...(st.expr ? { expr: st.expr, [DETAIL_OF]: { says: st.says, kind: st.kind, code: st.code, restates: st.restates, expr: st.expr } } : {}) };
|
|
421
|
+
const base = { line: st.line, lane, does, ...(st.explained === false ? { explained: false, ...(st.notExplainedWhy ? { notExplainedWhy: st.notExplainedWhy } : {}) } : {}), ...(st.codeWords ? { code: true } : {}), ...(usesOf(st) ? { uses: usesOf(st) } : {}), ...(st.expr ? { expr: st.expr, [DETAIL_OF]: { says: st.says, kind: st.kind, code: st.code, restates: st.restates, expr: st.expr } } : {}) };
|
|
415
422
|
// A choice among several cases (switch, when, match, select): one question with one side per case.
|
|
416
423
|
const arms = st.kind === 'branch' && st.children?.length && st.children.every((c) => c.kind === 'check' && c.caseLabel) ? st.children : null;
|
|
417
424
|
if (arms) {
|
|
@@ -718,6 +725,8 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
718
725
|
...(rule ? { rule, question: rule.question } : {}),
|
|
719
726
|
// A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
|
|
720
727
|
...(kind === 'rule' ? { yesNo: [...(item.rules || []).map((r) => r.result), item.otherwise?.result].every((r) => r == null || /^(true|false)$/i.test(r)) } : {}),
|
|
728
|
+
// How sure: of the steps Thunder read, how many it put into words (the rest are shown as code, not explained).
|
|
729
|
+
...(item.totalSteps != null ? { explainedSteps: item.explainedSteps, totalSteps: item.totalSteps } : {}),
|
|
721
730
|
_steps: item.steps || [], _item: item, ...(item.qualifier && !owner ? { _qualifier: item.qualifier } : {}),
|
|
722
731
|
};
|
|
723
732
|
if (owner) owner.can.push(m.id);
|
|
@@ -793,7 +802,10 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
793
802
|
if (t.kind !== 'thing' || t.knows.length || owners.has(t.id)) continue;
|
|
794
803
|
if (/(Exception|Error)$/.test(t.name)) things.splice(i, 1); else t.kind = 'record';
|
|
795
804
|
}
|
|
796
|
-
|
|
805
|
+
// How sure, for the whole app: steps put into words, of all steps read.
|
|
806
|
+
const totalSteps = members.reduce((n, m) => n + (m.totalSteps ?? 0), 0);
|
|
807
|
+
const explainedSteps = members.reduce((n, m) => n + (m.explainedSteps ?? 0), 0);
|
|
808
|
+
const model = { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns, permissions, settings, facts, explainedSteps, totalSteps };
|
|
797
809
|
// The whole system: calls that go to another file, HTTP requests to this repo's routes, events to listeners.
|
|
798
810
|
try { linkSystem(model, files); } catch (e) { model.notLinked = [{ file: fileInfo[0]?.path ?? null, line: 1, why: `Calls across files could not be linked: ${e.message}` }]; }
|
|
799
811
|
return model;
|
|
@@ -809,7 +821,8 @@ function flowLines(flow, depth = 1, note = null, full = false) {
|
|
|
809
821
|
// `note` (optional) adds words after a node: the running system's counts (running.mjs).
|
|
810
822
|
const at = (n) => `${n.line ? ` (line ${n.line})` : ''}${(note && note(n)) || ''}`;
|
|
811
823
|
// (A value given back that could not be put into words still says it is given back: the ending is never hidden.)
|
|
812
|
-
|
|
824
|
+
// (A restated ending that is not a value — `exit 0`, `exec prog`, `die` — is shown as its code, never as "Gives back".)
|
|
825
|
+
const say = (n) => (n.kind === 'end' && n.code && !/^(?:return|yield|exit|exec|die|abort|quit|halt|throw|raise|panic|break|continue|Exit|Throw|Write-Error)\b/.test(String(n.text).trim()) ? `Gives back \`${n.text}\` (code, not explained)` : n.kind === 'code' || (n.kind === 'end' && n.code) ? `\`${n.text}\` (code, not explained)` : (n.kind === 'loop' || n.kind === 'stop' || n.kind === 'step') && n.code ? `${n.text} (code, not explained)` : n.kind === 'decision' && n.cases ? `${n.text}${n.code ? ' (code, not explained)' : ''}` : n.kind === 'decision' ? `Ask: ${n.text}${n.code ? ' (code, not explained)' : ''}` : n.kind === 'end' && n.answer ? `Answer: ${n.text}` : n.text);
|
|
813
826
|
const go = (blocks, d) => {
|
|
814
827
|
for (const b of blocks || []) {
|
|
815
828
|
const n = byId.get(b.id);
|
package/src/money.d.mts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Thunder Money: an exact decimal amount in minor units, never binary floating point. */
|
|
2
|
+
export class MoneyError extends Error {}
|
|
3
|
+
export const MONEY_DEFAULT_MINOR_UNITS: 2;
|
|
4
|
+
/** Minor units for an ISO 4217 code (2 when unknown or absent): JPY 0, USD 2, KWD 3. */
|
|
5
|
+
export function minorUnitsFor(currency?: string | null): number;
|
|
6
|
+
/** Minor units when `type` is `Money` or `Money(XXX)`, else null. */
|
|
7
|
+
export function moneyTypeMinorUnits(type: string): number | null;
|
|
8
|
+
/** Parse "12.30" (or "$12.30" with allowDollar) to exact minor units. Extra precision throws; nothing is rounded. */
|
|
9
|
+
export function parseMoney(text: string | number, opts?: { minorUnits?: number; allowDollar?: boolean }): bigint;
|
|
10
|
+
/** Render minor units as a decimal string with exactly `minorUnits` places. */
|
|
11
|
+
export function formatMoney(minor: bigint | number, opts?: { minorUnits?: number }): string;
|
|
12
|
+
/** Round half up (a half goes away from zero, as in Thunder Core) to `minorUnits` places. Use only where a spec asks for rounding. */
|
|
13
|
+
export function roundHalfUp(text: string | number, opts?: { minorUnits?: number }): bigint;
|
|
14
|
+
export function numberToDecimalText(n: number): string;
|
|
15
|
+
/** The exact Money literal for a target dialect, or null when the target has none wired up. */
|
|
16
|
+
export function moneyLiteral(dialect: string, text: string | number, minorUnits?: number): string | null;
|
|
17
|
+
export const MONEY_TYPES: Record<string, string>;
|
|
18
|
+
export function moneyCompare(dialect: string, op: string, a: string, b: string): string;
|
package/src/money.mjs
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Thunder Money: an exact decimal amount, never binary floating point. Browser-safe, no deps.
|
|
2
|
+
//
|
|
3
|
+
// Semantics (see docs/spec.md, "Money"):
|
|
4
|
+
// - A Money value is a decimal with a fixed number of minor units: 2 by default (cents), or the
|
|
5
|
+
// currency's own when the type names one (Money(JPY) has 0, Money(KWD) has 3).
|
|
6
|
+
// - Parsing is string-exact. An amount with more decimal places than the minor units is an error,
|
|
7
|
+
// never silently rounded. Rounding happens only where a spec explicitly asks for it, and then it
|
|
8
|
+
// is round half up, a half going away from zero (roundHalfUp below), the same rule as Thunder Core's
|
|
9
|
+
// `round`: 2.345 is 2.35, -2.345 is -2.35.
|
|
10
|
+
// - Each target uses an exact representation: TypeScript/JavaScript bigint minor units, Python
|
|
11
|
+
// decimal.Decimal, Java java.math.BigDecimal, C# decimal, Go int64 minor units, Rust i64 minor
|
|
12
|
+
// units. A target with no exact representation wired up refuses (IL-GEN-001), it never falls back
|
|
13
|
+
// to a float.
|
|
14
|
+
|
|
15
|
+
export class MoneyError extends Error {}
|
|
16
|
+
|
|
17
|
+
export const MONEY_DEFAULT_MINOR_UNITS = 2;
|
|
18
|
+
|
|
19
|
+
// ISO 4217 currencies whose minor units differ from 2. Everything else uses 2.
|
|
20
|
+
const MINOR_UNITS = {
|
|
21
|
+
BIF: 0, CLP: 0, DJF: 0, GNF: 0, ISK: 0, JPY: 0, KMF: 0, KRW: 0, PYG: 0, RWF: 0, UGX: 0,
|
|
22
|
+
UYI: 0, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0,
|
|
23
|
+
BHD: 3, IQD: 3, JOD: 3, KWD: 3, LYD: 3, OMR: 3, TND: 3,
|
|
24
|
+
CLF: 4, UYW: 4,
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Minor units for a currency code (2 when unknown or absent). */
|
|
28
|
+
export function minorUnitsFor(currency) {
|
|
29
|
+
if (!currency) return MONEY_DEFAULT_MINOR_UNITS;
|
|
30
|
+
const code = String(currency).trim().toUpperCase();
|
|
31
|
+
return Object.prototype.hasOwnProperty.call(MINOR_UNITS, code) ? MINOR_UNITS[code] : MONEY_DEFAULT_MINOR_UNITS;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** If `type` is a Money type (`Money`, `Money(USD)`), its minor units; otherwise null. */
|
|
35
|
+
export function moneyTypeMinorUnits(type) {
|
|
36
|
+
const m = String(type ?? '').trim().match(/^Money(?:\s*\(\s*([A-Za-z]{3})\s*\))?$/);
|
|
37
|
+
return m ? minorUnitsFor(m[1]) : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const DECIMAL = /^([+-])?(\d+)(?:\.(\d+))?$/;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Parse a decimal amount ("12.30", "-0.1", "$1,234.5" with allowDollar) into exact minor units.
|
|
44
|
+
* Returns a bigint. Throws MoneyError for anything that is not an exact amount at these minor units.
|
|
45
|
+
*/
|
|
46
|
+
export function parseMoney(text, { minorUnits = MONEY_DEFAULT_MINOR_UNITS, allowDollar = false } = {}) {
|
|
47
|
+
let t = typeof text === 'number' ? numberToDecimalText(text) : String(text ?? '').trim();
|
|
48
|
+
if (allowDollar) {
|
|
49
|
+
const d = t.replace(/,/g, '').match(/^(-?)\$(-?)(\d+(?:\.\d+)?)$/);
|
|
50
|
+
if (d) t = `${d[1] || d[2] ? '-' : ''}${d[3]}`;
|
|
51
|
+
}
|
|
52
|
+
const m = t.match(DECIMAL);
|
|
53
|
+
if (!m) throw new MoneyError(`"${text}" is not an amount. Write digits with an optional decimal point, such as 12.30.`);
|
|
54
|
+
const frac = m[3] || '';
|
|
55
|
+
const extra = frac.slice(minorUnits);
|
|
56
|
+
if (/[1-9]/.test(extra)) throw new MoneyError(`${t} has more decimal places than Money's ${minorUnits} minor unit${minorUnits === 1 ? '' : 's'}; Thunder will not round it silently.`);
|
|
57
|
+
const minor = BigInt(m[2] + frac.slice(0, minorUnits).padEnd(minorUnits, '0'));
|
|
58
|
+
return m[1] === '-' ? -minor : minor;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Render exact minor units as a decimal string with exactly `minorUnits` places ("12.30"). */
|
|
62
|
+
export function formatMoney(minor, { minorUnits = MONEY_DEFAULT_MINOR_UNITS } = {}) {
|
|
63
|
+
const v = BigInt(minor);
|
|
64
|
+
const neg = v < 0n;
|
|
65
|
+
const digits = (neg ? -v : v).toString().padStart(minorUnits + 1, '0');
|
|
66
|
+
const whole = minorUnits ? digits.slice(0, -minorUnits) : digits;
|
|
67
|
+
const frac = minorUnits ? `.${digits.slice(-minorUnits)}` : '';
|
|
68
|
+
return `${neg ? '-' : ''}${whole}${frac}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Round a decimal string to `minorUnits` places, half up: a half goes away from zero (2.345 is 2.35, -2.345 is
|
|
73
|
+
* -2.35), the rule people learn in school and the one Thunder Core's `round` uses in every target.
|
|
74
|
+
* Use only where a spec explicitly asks for rounding. Returns exact minor units (bigint).
|
|
75
|
+
*/
|
|
76
|
+
export function roundHalfUp(text, { minorUnits = MONEY_DEFAULT_MINOR_UNITS } = {}) {
|
|
77
|
+
const t = typeof text === 'number' ? numberToDecimalText(text) : String(text).trim();
|
|
78
|
+
const m = t.match(DECIMAL);
|
|
79
|
+
if (!m) throw new MoneyError(`"${text}" is not an amount.`);
|
|
80
|
+
const frac = m[3] || '';
|
|
81
|
+
let minor = BigInt(m[2] + frac.slice(0, minorUnits).padEnd(minorUnits, '0'));
|
|
82
|
+
const rest = frac.slice(minorUnits);
|
|
83
|
+
if (rest && rest[0] >= '5') minor += 1n; // the magnitude rounds up; the sign is put back after
|
|
84
|
+
return m[1] === '-' ? -minor : minor;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A JS number as plain decimal text, refusing exponent forms that cannot be an exact amount. */
|
|
88
|
+
export function numberToDecimalText(n) {
|
|
89
|
+
if (typeof n !== 'number' || !Number.isFinite(n)) throw new MoneyError(`${n} is not a finite amount.`);
|
|
90
|
+
const s = String(n);
|
|
91
|
+
if (/e/i.test(s)) throw new MoneyError(`${s} is too large or too small to be an exact amount.`);
|
|
92
|
+
return s;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The exact Money literal for a target, from decimal text. `dialect` matches expr.mjs dialect names.
|
|
97
|
+
* Returns null when the target has no exact Money representation wired up.
|
|
98
|
+
*/
|
|
99
|
+
export function moneyLiteral(dialect, text, minorUnits = MONEY_DEFAULT_MINOR_UNITS) {
|
|
100
|
+
const minor = parseMoney(text, { minorUnits });
|
|
101
|
+
const dec = formatMoney(minor, { minorUnits });
|
|
102
|
+
switch (dialect) {
|
|
103
|
+
case 'js': return `${minor}n`;
|
|
104
|
+
case 'python': return `Decimal(${JSON.stringify(dec)})`;
|
|
105
|
+
case 'csharp': return `${dec}m`;
|
|
106
|
+
case 'java': return `new java.math.BigDecimal(${JSON.stringify(dec)})`;
|
|
107
|
+
case 'go': return `int64(${minor})`;
|
|
108
|
+
case 'rust': return `${minor}i64`;
|
|
109
|
+
default: return null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Exact Money type per target dialect (null when the target has none wired up). */
|
|
114
|
+
export const MONEY_TYPES = {
|
|
115
|
+
js: 'bigint', python: 'Decimal', csharp: 'decimal', java: 'java.math.BigDecimal', go: 'int64', rust: 'i64',
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** Render a Money comparison for a dialect from already-rendered operands. */
|
|
119
|
+
export function moneyCompare(dialect, op, a, b) {
|
|
120
|
+
if (dialect === 'java') return `(${a}.compareTo(${b}) ${op} 0)`;
|
|
121
|
+
if (dialect === 'js' && op === '==') return `(${a} === ${b})`;
|
|
122
|
+
if (dialect === 'js' && op === '!=') return `(${a} !== ${b})`;
|
|
123
|
+
return `(${a} ${op} ${b})`;
|
|
124
|
+
}
|
package/src/plain-contract.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { parseIntent } from './parse.mjs';
|
|
|
7
7
|
import { compileExpr } from './expr.mjs';
|
|
8
8
|
import { runTests } from './testing.mjs';
|
|
9
9
|
import { evaluateDecision } from './runtime.mjs';
|
|
10
|
+
import { parseMoney, formatMoney, MoneyError } from './money.mjs';
|
|
10
11
|
|
|
11
12
|
export const PLAIN_SCHEMA = 'thunder-plain-v1';
|
|
12
13
|
|
|
@@ -33,16 +34,31 @@ const RESERVED = new Set(['and', 'or', 'not', 'in', 'true', 'false', 'case', 'ex
|
|
|
33
34
|
export function formatValue(input, value) {
|
|
34
35
|
if (input.kind === 'yesno') return value ? input.yes : input.no;
|
|
35
36
|
if (input.kind === 'text') return value === '' ? 'empty' : JSON.stringify(String(value));
|
|
36
|
-
if (input.kind === 'dollars') return `${value < 0 ? '-' : ''}$${Math.abs(value)}`;
|
|
37
|
+
if (input.kind === 'dollars') return `${value < 0 ? '-' : ''}$${dollarText(Math.abs(value))}`;
|
|
37
38
|
return String(value);
|
|
38
39
|
}
|
|
39
40
|
|
|
41
|
+
// Dollars read exactly from cents: $12.30 (not $12.3), whole dollars stay $100.
|
|
42
|
+
function dollarText(value) {
|
|
43
|
+
try {
|
|
44
|
+
const minor = parseMoney(value);
|
|
45
|
+
return minor % 100n === 0n ? String(minor / 100n) : formatMoney(minor);
|
|
46
|
+
} catch { return String(value); }
|
|
47
|
+
}
|
|
48
|
+
|
|
40
49
|
function parseNumber(text, input, line) {
|
|
41
50
|
const t = text.trim().replace(/,/g, '');
|
|
42
51
|
const dollars = t.match(/^(-?)\$(-?)(\d+(?:\.\d+)?)$/);
|
|
43
52
|
if (input.kind === 'dollars') {
|
|
44
53
|
if (!dollars) fail(line, `${input.label} is in dollars. Write an amount such as $100.`);
|
|
45
|
-
|
|
54
|
+
// Thunder Money: the amount is read as exact cents from its text (never through a float), and an
|
|
55
|
+
// amount finer than a cent is an error instead of being rounded. The decision engine then
|
|
56
|
+
// compares the amount at cent precision, where every comparison is exact.
|
|
57
|
+
let minor;
|
|
58
|
+
try { minor = parseMoney(t, { allowDollar: true }); }
|
|
59
|
+
catch (e) { if (e instanceof MoneyError) fail(line, `${input.label} is in dollars and cents. ${t} is finer than a cent; write at most two decimal places, such as $12.30.`); throw e; }
|
|
60
|
+
if (minor > BigInt(Number.MAX_SAFE_INTEGER) || -minor > BigInt(Number.MAX_SAFE_INTEGER)) fail(line, `${t} is too large to compare exactly.`);
|
|
61
|
+
return Number(formatMoney(minor));
|
|
46
62
|
}
|
|
47
63
|
if (dollars) fail(line, `${input.label} is a plain number, not dollars. Write it without $.`);
|
|
48
64
|
if (!/^-?\d+(?:\.\d+)?$/.test(t)) fail(line, `Write a number for ${input.label}, such as 18.`);
|