lawspec 0.23.0 → 0.25.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 +167 -1
- package/README.md +29 -22
- package/UNICODE-LICENSE.txt +39 -0
- package/api.mjs +14 -23
- package/bin/lawspec.mjs +200 -67
- package/build.json +381 -155
- package/builtin-data-names.mjs +73 -0
- package/compatibility.json +21 -0
- package/core.wasm +2 -2
- package/doctor.mjs +98 -1
- package/examples/native-payments/clojure/lawspec.json +62 -0
- package/examples/native-payments/clojure/src/domain/payments.clj +11 -0
- package/examples/native-payments/clojure/test/domain/payment_generators.clj +9 -0
- package/examples/native-payments/csharp/lawspec.json +13 -2
- package/examples/native-payments/elixir/lawspec.json +14 -3
- package/examples/native-payments/erlang/lawspec.json +14 -3
- package/examples/native-payments/fsharp/lawspec.json +14 -3
- package/examples/native-payments/gleam/lawspec.json +14 -3
- package/examples/native-payments/go/lawspec.json +14 -3
- package/examples/native-payments/groovy/lawspec.json +176 -0
- package/examples/native-payments/groovy/src/main/groovy/domain/PaymentsDomain.groovy +49 -0
- package/examples/native-payments/groovy/src/test/groovy/domain/PaymentGenerators.groovy +15 -0
- package/examples/native-payments/haskell/lawspec.json +14 -3
- package/examples/native-payments/java/lawspec.json +14 -3
- package/examples/native-payments/javascript/lawspec.json +14 -3
- package/examples/native-payments/kotlin/lawspec.json +14 -3
- package/examples/native-payments/python/lawspec.json +14 -3
- package/examples/native-payments/rust/lawspec.json +14 -3
- package/examples/native-payments/scala/lawspec.json +176 -0
- package/examples/native-payments/scala/src/main/scala/domain/PaymentsDomain.scala +18 -0
- package/examples/native-payments/scala/src/test/scala/domain/PaymentGenerators.scala +8 -0
- package/examples/native-payments/swift/lawspec.json +165 -0
- package/examples/native-payments/swift/src/Native/PaymentsDomain.swift +35 -0
- package/examples/native-payments/swift/tests/Native/PaymentGenerators.swift +12 -0
- package/examples/native-payments/typescript/lawspec.json +14 -3
- package/examples/packages/orders/lawspec.json +25 -5
- package/examples/packages/orders/orders.lawspec +36 -34
- package/examples/packages/shop-domain/src/domain.lawspec +23 -21
- package/examples/packages/shop-tax-1/src/rates.lawspec +4 -4
- package/examples/packages/shop-tax-2/src/rates.lawspec +5 -4
- package/examples/rc1/authorization-snapshots.lawspec +112 -0
- package/examples/rc1/banner-filenames.lawspec +63 -0
- package/examples/rc1/bit-codec.lawspec +56 -0
- package/examples/rc1/bounded-witness-search.lawspec +144 -0
- package/examples/rc1/conflicting-requirements.lawspec +30 -0
- package/examples/rc1/constructive-witnesses.lawspec +113 -0
- package/examples/rc1/documentary-review.lawspec +42 -0
- package/examples/rc1/empty-domains.lawspec +46 -0
- package/examples/rc1/finite-integer-domains.lawspec +75 -0
- package/examples/rc1/law-metadata.lawspec +29 -0
- package/examples/rc1/native-payments.lawspec +107 -0
- package/examples/rc1/nesting/rrr.lawspec +33 -0
- package/examples/rc1/nesting/rru.lawspec +56 -0
- package/examples/rc1/nesting/rur.lawspec +57 -0
- package/examples/rc1/nesting/ruu.lawspec +77 -0
- package/examples/rc1/nesting/urr.lawspec +52 -0
- package/examples/rc1/nesting/uru.lawspec +72 -0
- package/examples/rc1/nesting/uur.lawspec +73 -0
- package/examples/rc1/nesting/uuu.lawspec +95 -0
- package/examples/rc1/order-workflow.lawspec +126 -0
- package/examples/rc1/parcel-measurements.lawspec +92 -0
- package/examples/rc1/picture-records.lawspec +51 -0
- package/examples/rc1/picture-tuples.lawspec +47 -0
- package/examples/rc1/record-payloads.lawspec +56 -0
- package/examples/rc1/recursive-records.lawspec +64 -0
- package/examples/rc1/refund-conformance.lawspec +44 -0
- package/examples/rc1/refund-policy.lawspec +88 -0
- package/examples/rc1/requirement-composition.lawspec +89 -0
- package/examples/rc1/structural-records.lawspec +53 -0
- package/examples/rc1-authoring.lawspec +56 -0
- package/examples-command.mjs +11 -5
- package/explain.mjs +112 -0
- package/expression-presentation.mjs +333 -0
- package/files.mjs +16 -0
- package/index.d.ts +934 -12
- package/lsp.mjs +231 -0
- package/migrate.mjs +135 -0
- package/migration-bindings.mjs +86 -0
- package/migration-cases.mjs +45 -0
- package/migration-collections.mjs +54 -0
- package/migration-correspondence.mjs +275 -0
- package/migration-generation.mjs +99 -0
- package/migration-laws.mjs +102 -0
- package/migration-records.mjs +166 -0
- package/migration-source.mjs +247 -0
- package/migration-write.mjs +156 -0
- package/native-evidence.mjs +187 -0
- package/native-examples.mjs +8 -1
- package/node-events-reporter.mjs +23 -0
- package/package.json +8 -1
- package/positional-fields.mjs +13 -0
- package/proof.d.ts +35 -0
- package/proof.mjs +174 -0
- package/scala-coverage.mjs +56 -0
- package/starter-rc1.lawspec +25 -0
- package/templates.mjs +65 -3
- package/test-command.mjs +177 -29
- package/typed-presentation.mjs +165 -0
package/explain.mjs
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Generated from templates/npm/explain.mjs by lawspec-dev generate. Do not edit.
|
|
2
|
+
// All presentations read the same typed law and its evidence. No view parses
|
|
3
|
+
// business wording or changes an obligation.
|
|
4
|
+
import { createTypePresentation } from './typed-presentation.mjs';
|
|
5
|
+
|
|
6
|
+
export const explanationViews = ['developer', 'business', 'formal', 'evidence'];
|
|
7
|
+
const presentationProposition = ({ typeName, expressionText }, inputs) => function proposition(assertion, business = false, scope = inputs) {
|
|
8
|
+
const term = expression => expressionText(expression, scope);
|
|
9
|
+
const recurse = (body, wording = business) => proposition(body, wording, scope);
|
|
10
|
+
switch (assertion.kind) {
|
|
11
|
+
case 'equal': return `${term(assertion.left)} ${business ? 'must be' : '='} ${term(assertion.right)}`;
|
|
12
|
+
case 'implies': return business
|
|
13
|
+
? `If ${term(assertion.guard)}, then ${recurse(assertion.body, true)}`
|
|
14
|
+
: `(${term(assertion.guard)}) implies (${recurse(assertion.body)})`;
|
|
15
|
+
case 'all': return assertion.items.map(a => `(${recurse(a)})`).join(' and ');
|
|
16
|
+
case 'not': {
|
|
17
|
+
// The compiler's ordinary negation/conjunction representation also
|
|
18
|
+
// expresses disjunction and implications with proposition premises.
|
|
19
|
+
const items = assertion.body.kind === 'all' ? assertion.body.items : [];
|
|
20
|
+
if (items.length > 1 && items.every(item => item.kind === 'not'))
|
|
21
|
+
return items.map(item => `(${recurse(item.body)})`).join(' or ');
|
|
22
|
+
if (items.length === 2 && items[1].kind === 'not') return business
|
|
23
|
+
? `If (${recurse(items[0], true)}), then (${recurse(items[1].body, true)})`
|
|
24
|
+
: `(${recurse(items[0])}) implies (${recurse(items[1].body)})`;
|
|
25
|
+
return business && assertion.body.kind === 'exists'
|
|
26
|
+
? recurse(assertion.body, true).replace(/^There must exist/, 'There must not exist')
|
|
27
|
+
: `${business ? 'Must not' : 'not'} (${recurse(assertion.body, false)})`;
|
|
28
|
+
}
|
|
29
|
+
case 'forall':
|
|
30
|
+
case 'exists': {
|
|
31
|
+
const universal = assertion.kind === 'forall';
|
|
32
|
+
const binder = `${assertion.binder.name} of type ${typeName(assertion.binder.type)}`;
|
|
33
|
+
const nested = new Map([...scope, [assertion.binder.id, assertion.binder.name]]);
|
|
34
|
+
const restrictions = assertion.predicates.map(p => expressionText(p, nested));
|
|
35
|
+
const restricted = restrictions.length ? ` where ${restrictions.join(' and ')}` : '';
|
|
36
|
+
if (business) return `${universal ? 'For every' : 'There must exist'} ${binder}${restricted}, ${proposition(assertion.body, true, nested)}`;
|
|
37
|
+
return `${universal ? 'for all' : 'there exists'} (${binder}${restricted}) ${universal ? '=>' : 'such that'}\n${proposition(assertion.body, false, nested)}\nend`;
|
|
38
|
+
}
|
|
39
|
+
default: throw new Error(`Unsupported typed assertion ${assertion.kind}`);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
export function explainLaw(law, result, view = 'developer') {
|
|
43
|
+
if (!explanationViews.includes(view)) throw new Error(`Choose --view ${explanationViews.join('|')}`);
|
|
44
|
+
const presentation = createTypePresentation(result);
|
|
45
|
+
const { typeName, expressionText, valueText } = presentation;
|
|
46
|
+
const examples = law.examples ?? [];
|
|
47
|
+
const scope = new Map(law.inputs.map(input => [input.id, input.name]));
|
|
48
|
+
const proposition = presentationProposition(presentation, scope);
|
|
49
|
+
const evidence = (result.evidence ?? []).filter(e => e.declaration === law.id);
|
|
50
|
+
const quantifiers = law.inputs.map(input => `${input.name} of type ${typeName(input.type)}`);
|
|
51
|
+
const restrictions = law.inputs.flatMap(input => input.predicates.map(p => expressionText(p, scope)));
|
|
52
|
+
const metadata = law.metadata ?? {};
|
|
53
|
+
const references = law.references ?? [];
|
|
54
|
+
const witnesses = law.harness?.witnesses ?? [];
|
|
55
|
+
const searches = law.harness?.searches ?? [];
|
|
56
|
+
const strategies = [
|
|
57
|
+
...witnesses.map(witness => `Configured witness (not completed evidence): definition.${witness.path.join('.')} = ${expressionText(witness.expression, scope)}`),
|
|
58
|
+
...searches.map(search => `Configured search (not completed evidence): definition.${search.path.join('.')} uses ${search.strategy}`),
|
|
59
|
+
];
|
|
60
|
+
const documentary = [metadata.id === undefined ? '' : `Requirement: ${metadata.id}`,
|
|
61
|
+
metadata.owner === undefined ? '' : `Owner: ${metadata.owner}`,
|
|
62
|
+
...references.map(reference => `Reference: ${referenceText(reference)}`)].filter(Boolean);
|
|
63
|
+
let text;
|
|
64
|
+
if (view === 'evidence') text = evidence.length
|
|
65
|
+
? evidence.map(e => `${e.status.toUpperCase()}: ${e.reason}`+(e.nativeEvidence?'\n'+nativeEvidenceText(e):'')).join('\n')
|
|
66
|
+
: 'No completed evidence has been supplied for this law.';
|
|
67
|
+
else if (view === 'business') text = [...documentary, law.description,
|
|
68
|
+
quantifiers.length ? `For every ${quantifiers.join(' and ')}` : '',
|
|
69
|
+
restrictions.length ? `When ${restrictions.join(' and ')}` : '',
|
|
70
|
+
proposition(law.assertion, true), law.rationale ? `Reason: ${law.rationale}` : ''].filter(Boolean).join('\n');
|
|
71
|
+
else if (view === 'formal') text = [quantifiers.length ? `for all (${quantifiers.join(') (')}) =>` : '',
|
|
72
|
+
restrictions.length ? `(${restrictions.join(' and ')}) implies` : '',
|
|
73
|
+
proposition(law.assertion), ...(quantifiers.length ? ['end'] : [])].filter(Boolean).join('\n');
|
|
74
|
+
else text = [law.id, ...documentary, ...law.trace, ...strategies,
|
|
75
|
+
...(quantifiers.length ? [`Inputs: ${quantifiers.join('; ')}`] : []),
|
|
76
|
+
...(restrictions.length ? [`Restrictions: ${restrictions.join(' and ')}`] : []), proposition(law.assertion),
|
|
77
|
+
`Source: ${law.location.file}:${law.location.line}:${law.location.column}`,
|
|
78
|
+
`Examples: ${examples.length}`,
|
|
79
|
+
...examples.flatMap(example => {
|
|
80
|
+
const locals = new Map([...scope, ...example.bindings.map(binding => [binding.id, binding.name])]);
|
|
81
|
+
return [`example ${JSON.stringify(example.name)}`,
|
|
82
|
+
...example.bindings.map(binding => ` ${binding.name} = ${valueText(binding.value, locals)}`),
|
|
83
|
+
...example.expectations.map(expectation => ` expect ${proposition(expectation, false, locals)}`)];
|
|
84
|
+
})].join('\n');
|
|
85
|
+
if(view==='developer')for(const item of evidence)if(item.nativeEvidence)text+='\n'+nativeEvidenceText(item);
|
|
86
|
+
if (view === 'evidence' && strategies.length) text += '\n' + strategies.join('\n');
|
|
87
|
+
return { view, law: law.id, metadata, references, witnesses, searches, examples, inputs: law.inputs, assertion: law.assertion, evidence, text };
|
|
88
|
+
}
|
|
89
|
+
function referenceText(reference) {
|
|
90
|
+
if (typeof reference === 'string') return reference;
|
|
91
|
+
if (reference.kind === 'external') return `${reference.name ? `${reference.name}: ` : ''}${reference.resource}`;
|
|
92
|
+
const selector = reference.selector;
|
|
93
|
+
const section = selector?.kind === 'named-reference' ? ` references.${selector.name}` : selector ? ` ${selector.kind}` : '';
|
|
94
|
+
const raw = reference.target.name;
|
|
95
|
+
// Built-in laws retain legacy source names internally; present their
|
|
96
|
+
// canonical phrase spelling just as ordinary authored names are presented.
|
|
97
|
+
const name = raw.startsWith('"|') || /^\p{L}[\p{L}\p{N}_]*$/u.test(raw)
|
|
98
|
+
? raw : `"|${raw.replace(/[\\|]/g, '\\$&')}|`;
|
|
99
|
+
return `ref ${reference.kind} ${reference.target.unit}.${name}${section}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function nativeEvidenceText(item){
|
|
103
|
+
if(!item.nativeEvidence)return '';
|
|
104
|
+
const summary=item.nativeEvidence;
|
|
105
|
+
return [`Native conformance: ${summary.status}; search completeness: ${summary.searchCompleteness}`,
|
|
106
|
+
...summary.observations.map(row=>`${row.target} (${row.root}): ${row.outcome}; ${row.freshness}`+
|
|
107
|
+
(row.attempt?`; seed ${row.attempt.seed}; ${row.attempt.at}`:'')+`; ${row.reason}`),
|
|
108
|
+
...summary.observations.flatMap(row=>(row.attempt?.tests??[]).filter(test=>test.status==='failed')
|
|
109
|
+
.map(test=>`${test.name}: ${test.reason??test.failure??test.message??'native test failed'}`)),
|
|
110
|
+
...summary.observations.filter(row=>row.attempt?.invocation.output)
|
|
111
|
+
.map(row=>'Native invocation output (scoped to that invocation):\n'+row.attempt.invocation.output)].join('\n');
|
|
112
|
+
}
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// Generated from templates/npm/expression-presentation.mjs by lawspec-dev generate. Do not edit.
|
|
2
|
+
// Render checked terms, without evaluating them or changing their evidence.
|
|
3
|
+
// Constructor(field = term) is presentation notation, not authoring syntax.
|
|
4
|
+
import { positionalFields } from './positional-fields.mjs';
|
|
5
|
+
export function createExpressionPresentation(result, { constructors, typeName, storageView, isStoredValue = () => false }) {
|
|
6
|
+
const unavailable = Symbol('unavailable expression presentation');
|
|
7
|
+
const values = new Map();
|
|
8
|
+
for (const unit of result.units ?? []) for (const declaration of unit.declarations) {
|
|
9
|
+
const source = declaration.source;
|
|
10
|
+
values.set(declaration.id, { name: source?.name ?? declaration.name,
|
|
11
|
+
owner: source?.unit ?? (declaration.id.includes('::') ? declaration.id.slice(0, declaration.id.indexOf('::')) : unit.id),
|
|
12
|
+
identity: source ? JSON.stringify([source.unit, source.name]) : declaration.id,
|
|
13
|
+
canonicalName: source?.canonicalName });
|
|
14
|
+
}
|
|
15
|
+
for (const [id, entry] of constructors) if (entry.declaration.structure?.kind !== 'record')
|
|
16
|
+
values.set(id, { name: entry.constructor.name, owner: entry.declaration.id.replace('::type::', '.') });
|
|
17
|
+
const identities = new Map();
|
|
18
|
+
for (const [id, value] of values) {
|
|
19
|
+
if (!identities.has(value.name)) identities.set(value.name, new Set());
|
|
20
|
+
identities.get(value.name).add(value.identity ?? id);
|
|
21
|
+
}
|
|
22
|
+
const counts = new Map([...identities].map(([name, owners]) => [name, owners.size]));
|
|
23
|
+
const abilities = new Map((result.units ?? []).flatMap(unit => (unit.abilities ?? []).map(ability =>
|
|
24
|
+
[ability.id, { name: ability.name, owner: ability.id.split('::')[0] }])));
|
|
25
|
+
const abilityCounts = new Map();
|
|
26
|
+
for (const { name } of abilities.values()) abilityCounts.set(name, (abilityCounts.get(name) ?? 0) + 1);
|
|
27
|
+
const abilityIds = [...abilities.keys()].sort((a, b) => b.length - a.length);
|
|
28
|
+
const spelling = name => name.startsWith('"|') || /^[\p{L}_][\p{L}\p{N}_]*$/u.test(name)
|
|
29
|
+
? name : `"|${name.replace(/[\\|]/g, '\\$&')}|`;
|
|
30
|
+
const resultText = (text, atomic = false) => ({ text, atomic });
|
|
31
|
+
const argument = value => value.atomic ? value.text : `(${value.text})`;
|
|
32
|
+
|
|
33
|
+
function abilityName(key) {
|
|
34
|
+
// The wire key appends parenthesized type arguments to the identity. Name
|
|
35
|
+
// the known identity, retaining argument keys verbatim rather than guessing
|
|
36
|
+
// types from text. Longest identity wins when phrase bodies contain '('.
|
|
37
|
+
const id = abilityIds.find(id => key === id || key.startsWith(id + '('));
|
|
38
|
+
if (id === undefined) return key;
|
|
39
|
+
const ability = abilities.get(id), name = spelling(ability.name);
|
|
40
|
+
return (abilityCounts.get(ability.name) > 1 ? `${ability.owner}.${name}` : name) + key.slice(id.length);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function globalName(id, scope) {
|
|
44
|
+
const value = values.get(id);
|
|
45
|
+
if (!value) throw unavailable;
|
|
46
|
+
if (value.canonicalName) return value.canonicalName;
|
|
47
|
+
const name = spelling(value.name);
|
|
48
|
+
return counts.get(value.name) > 1 || [...scope.values()].includes(name)
|
|
49
|
+
? `${value.owner}.${name}` : name;
|
|
50
|
+
}
|
|
51
|
+
function children(expression, bound, onLocal) {
|
|
52
|
+
const node = expression.node;
|
|
53
|
+
if (!node) throw unavailable;
|
|
54
|
+
const visit = (value, scope = bound) => children(value, scope, onLocal);
|
|
55
|
+
const scoped = binders => new Set([...bound, ...binders.map(b => b.id)]);
|
|
56
|
+
switch (node.kind) {
|
|
57
|
+
case 'constant': return;
|
|
58
|
+
case 'local': if (!bound.has(node.id)) onLocal(expression); return;
|
|
59
|
+
case 'let': visit(node.value); visit(node.body, scoped([node.binder])); return;
|
|
60
|
+
case 'match': visit(node.value); for (const branch of node.cases) visit(branch.body, scoped(branch.binders)); return;
|
|
61
|
+
case 'allElements': visit(node.value); visit(node.predicate, scoped([node.binder])); return;
|
|
62
|
+
case 'allPayloads': visit(node.value); for (const p of node.predicates) visit(p.predicate, scoped([p.binder])); return;
|
|
63
|
+
case 'field': visit(node.value); return;
|
|
64
|
+
case 'update': visit(node.value); visit(node.field); return;
|
|
65
|
+
case 'binary':
|
|
66
|
+
case 'shortCircuit': visit(node.left); visit(node.right); return;
|
|
67
|
+
case 'unary':
|
|
68
|
+
case 'convert': visit(node.argument); return;
|
|
69
|
+
case 'if': visit(node.condition); visit(node.then); visit(node.else); return;
|
|
70
|
+
case 'handle': visit(node.body); return;
|
|
71
|
+
case 'construct':
|
|
72
|
+
case 'call':
|
|
73
|
+
case 'helper':
|
|
74
|
+
case 'perform':
|
|
75
|
+
case 'calls': for (const value of node.arguments ?? []) visit(value); return;
|
|
76
|
+
default: throw unavailable;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function freeLocals(expression) {
|
|
80
|
+
const free = new Map();
|
|
81
|
+
children(expression, new Set(), local => free.set(local.node.id, local.text));
|
|
82
|
+
return free;
|
|
83
|
+
}
|
|
84
|
+
function bind(binder, scope, reserved) {
|
|
85
|
+
// Source binders keep their spelling unless that would capture a name.
|
|
86
|
+
// Generated temporaries have no authoring significance.
|
|
87
|
+
const base = /^(?:~|_)?lawspec/.test(binder.name) ? 'value' : binder.name;
|
|
88
|
+
const used = new Set([...scope.values(), ...reserved]);
|
|
89
|
+
let name = base, suffix = 1;
|
|
90
|
+
while (used.has(name)) name = `${base.startsWith('"|') ? 'value' : base}${suffix++}`;
|
|
91
|
+
return { name, scope: new Map([...scope, [binder.id, name]]) };
|
|
92
|
+
}
|
|
93
|
+
function unwrap(expression) {
|
|
94
|
+
let view;
|
|
95
|
+
while ((view = storageView(expression)) !== undefined) expression = view;
|
|
96
|
+
return expression;
|
|
97
|
+
}
|
|
98
|
+
// Flatten only the complete built-in list spine; unknown tails, conversions
|
|
99
|
+
// and arbitrary computations remain explicit. Every head keeps source order.
|
|
100
|
+
function listElements(expression) {
|
|
101
|
+
const items = [];
|
|
102
|
+
while (expression?.type?.kind === 'constructor' && expression.type.name === 'List') {
|
|
103
|
+
const node = expression.node;
|
|
104
|
+
if (node?.kind !== 'construct') return undefined;
|
|
105
|
+
if (node.constructor === 'List::Nil' && node.arguments.length === 0) return items;
|
|
106
|
+
if (node.constructor !== 'List::Cons' || node.arguments.length !== 2) return undefined;
|
|
107
|
+
items.push(node.arguments[0]);
|
|
108
|
+
expression = node.arguments[1];
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
function freshComponent(base, scope, reserved) {
|
|
113
|
+
const used = new Set([...scope.values(), ...reserved, ...[...values.values()].map(value => value.name)]);
|
|
114
|
+
let name = base, suffix = 1;
|
|
115
|
+
while (used.has(name)) name = `${base}_${suffix++}`;
|
|
116
|
+
reserved.add(name);
|
|
117
|
+
return name;
|
|
118
|
+
}
|
|
119
|
+
function constructed(tag, entries, scope, reserved, stored = false) {
|
|
120
|
+
const entry = constructors.get(tag);
|
|
121
|
+
if (!entry) throw unavailable;
|
|
122
|
+
const positions = positionalFields(entry.declaration);
|
|
123
|
+
if (positions) {
|
|
124
|
+
const byName = new Map(entries);
|
|
125
|
+
if (entries.length !== positions.length || byName.size !== positions.length
|
|
126
|
+
|| !positions.every(field => byName.has(field.name))) throw unavailable;
|
|
127
|
+
if (stored || positions.every((field, i) => field.name === entries[i][0]))
|
|
128
|
+
return resultText(`(${positions.map(field => byName.get(field.name).text).join(', ')})`, true);
|
|
129
|
+
// Canonical field order can differ from position order. Keep every
|
|
130
|
+
// computation in its actual order before presenting its tuple positions.
|
|
131
|
+
const used = new Set(reserved), bindings = new Map();
|
|
132
|
+
const lets = entries.map(([label, value]) => {
|
|
133
|
+
const name = freshComponent(`component${positions.findIndex(field => field.name === label) + 1}`, scope, used);
|
|
134
|
+
bindings.set(label, name);
|
|
135
|
+
return `let ${name} = ${value.text} in `;
|
|
136
|
+
});
|
|
137
|
+
return resultText(lets.join('') + `(${positions.map(field => bindings.get(field.name)).join(', ')})`);
|
|
138
|
+
}
|
|
139
|
+
if (entry.declaration.structure?.kind === 'record')
|
|
140
|
+
return resultText(`record{${entries.map(([label, value]) => `${label} = ${value.text}`).join(', ')}}`, true);
|
|
141
|
+
const name = globalName(tag, scope);
|
|
142
|
+
return resultText(entries.length ? `${name}(${entries.map(([label, value]) => `${label} = ${value.text}`).join(', ')})` : name, true);
|
|
143
|
+
}
|
|
144
|
+
function projection(expression) {
|
|
145
|
+
const node = expression.node;
|
|
146
|
+
if (node.kind !== 'match' || node.cases.length !== 1) return undefined;
|
|
147
|
+
const branch = node.cases[0], entry = constructors.get(branch.constructor);
|
|
148
|
+
if (!entry || entry.declaration.constructors.length !== 1
|
|
149
|
+
|| branch.binders.length !== entry.constructor.fields.length || branch.body.node?.kind !== 'local') return undefined;
|
|
150
|
+
const index = branch.binders.findIndex(binder => binder.id === branch.body.node.id);
|
|
151
|
+
return index < 0 ? undefined : { value: node.value, entry, label: entry.constructor.fields[index].name };
|
|
152
|
+
}
|
|
153
|
+
function selectedField(entry, label, value, scope, reserved) {
|
|
154
|
+
const positions = positionalFields(entry.declaration);
|
|
155
|
+
if (!positions) return resultText(`${argument(value)}.${label}`, true);
|
|
156
|
+
const used = new Set(reserved), name = freshComponent('component', scope, used);
|
|
157
|
+
const pattern = positions.map(field => field.name === label ? name : '#any').join(', ');
|
|
158
|
+
return resultText(`first matching case of ${value.text}: when (${pattern}) then ${name} end case`);
|
|
159
|
+
}
|
|
160
|
+
function iterationCollection(expression) {
|
|
161
|
+
const node = expression?.node;
|
|
162
|
+
if (node?.kind === 'helper' && node.name === 'prelude.octets' && node.arguments.length === 1
|
|
163
|
+
&& node.arguments[0].type?.name === 'Bytes') return node.arguments[0];
|
|
164
|
+
if (node?.kind !== 'match' || node.cases.length !== 1) return expression;
|
|
165
|
+
const branch = node.cases[0], entry = constructors.get(branch.constructor);
|
|
166
|
+
const types = ['EqSet', 'Set', 'Queue', 'Stack', 'Deque', 'KeyVal'].map(name => `lawspec.collections::type::${name}`);
|
|
167
|
+
if (!entry || !types.includes(entry.declaration.id) || node.value.type?.name !== entry.declaration.id
|
|
168
|
+
|| entry.constructor.fields.length !== 1 || branch.binders.length !== 1
|
|
169
|
+
|| branch.body.node?.kind !== 'local' || branch.body.node.id !== branch.binders[0].id) return expression;
|
|
170
|
+
return node.value;
|
|
171
|
+
}
|
|
172
|
+
function membership(expression, scope, reserved) {
|
|
173
|
+
const outer = expression.node, inner = outer?.body?.node;
|
|
174
|
+
if (outer?.kind !== 'let' || inner?.kind !== 'let' || outer.binder.id === inner.binder.id
|
|
175
|
+
|| freeLocals(inner.value).has(outer.binder.id)) return undefined;
|
|
176
|
+
const negated = inner.body.node, iteration = negated?.argument?.node;
|
|
177
|
+
if (negated?.kind !== 'unary' || negated.operator !== '!' || iteration?.kind !== 'allElements') return undefined;
|
|
178
|
+
const collection = iterationCollection(iteration.value), comparison = iteration.predicate.node;
|
|
179
|
+
if (collection.node?.kind !== 'local' || collection.node.id !== inner.binder.id
|
|
180
|
+
|| comparison?.kind !== 'binary' || comparison.operator !== '!='
|
|
181
|
+
|| comparison.left.node?.kind !== 'local' || comparison.left.node.id !== outer.binder.id
|
|
182
|
+
|| comparison.right.node?.kind !== 'local' || comparison.right.node.id !== iteration.binder.id) return undefined;
|
|
183
|
+
// The exact typed shape consumes each strict argument once. Do not inline
|
|
184
|
+
// dependent bindings, conversions, unknown tails or other computations.
|
|
185
|
+
return resultText(`(${argument(render(outer.value, scope, reserved))} in ${argument(render(inner.value, scope, reserved))})`, true);
|
|
186
|
+
}
|
|
187
|
+
function literal(expression, scope, reserved) {
|
|
188
|
+
const bindings = [];
|
|
189
|
+
let body = expression;
|
|
190
|
+
while (body.node?.kind === 'let') {
|
|
191
|
+
bindings.push(body.node);
|
|
192
|
+
body = body.node.body;
|
|
193
|
+
}
|
|
194
|
+
body = unwrap(body);
|
|
195
|
+
const node = body.node, entry = constructors.get(node?.constructor);
|
|
196
|
+
if (node?.kind !== 'construct' || !entry || node.arguments.length !== bindings.length
|
|
197
|
+
|| node.arguments.length !== entry.constructor.fields.length) return undefined;
|
|
198
|
+
const positions = new Map();
|
|
199
|
+
for (let i = 0; i < node.arguments.length; i++) {
|
|
200
|
+
const value = unwrap(node.arguments[i]);
|
|
201
|
+
if (value.node?.kind !== 'local' || positions.has(value.node.id)) return undefined;
|
|
202
|
+
positions.set(value.node.id, i);
|
|
203
|
+
}
|
|
204
|
+
if (new Set(bindings.map(binding => binding.binder.id)).size !== bindings.length) return undefined;
|
|
205
|
+
const preceding = new Set(), entries = [];
|
|
206
|
+
for (const binding of bindings) {
|
|
207
|
+
if (!positions.has(binding.binder.id) || [...freeLocals(binding.value).keys()].some(id => preceding.has(id))) return undefined;
|
|
208
|
+
const index = positions.get(binding.binder.id);
|
|
209
|
+
entries.push([entry.constructor.fields[index].name, render(binding.value, scope, reserved)]);
|
|
210
|
+
preceding.add(binding.binder.id);
|
|
211
|
+
}
|
|
212
|
+
// Each strict binding occurs exactly once, only as its constructor field.
|
|
213
|
+
// Entries stay in binding/evaluation order, independently of field order.
|
|
214
|
+
return constructed(node.constructor, entries, scope, reserved);
|
|
215
|
+
}
|
|
216
|
+
function render(expression, scope, reserved) {
|
|
217
|
+
expression = unwrap(expression);
|
|
218
|
+
const node = expression.node;
|
|
219
|
+
if (!node) throw unavailable;
|
|
220
|
+
const go = (value, bindings = scope) => render(value, bindings, reserved);
|
|
221
|
+
const args = values => values.map(value => argument(go(value))).join(' ');
|
|
222
|
+
const list = listElements(expression);
|
|
223
|
+
if (list !== undefined) return resultText(`[${list.map(value => go(value).text).join(', ')}]`, true);
|
|
224
|
+
const select = projection(expression);
|
|
225
|
+
if (select) return selectedField(select.entry, select.label, go(select.value), scope, reserved);
|
|
226
|
+
switch (node.kind) {
|
|
227
|
+
case 'constant': return node.value?.type === 'Unit' ? resultText('()', true)
|
|
228
|
+
: resultText(expression.text, /^(?:[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false)$/.test(expression.text) || expression.text.startsWith('"'));
|
|
229
|
+
case 'local': return resultText(scope.get(node.id) ?? expression.text, true);
|
|
230
|
+
case 'construct': {
|
|
231
|
+
if (node.constructor === 'lawspec.collections::type::EqSet::EqSetItems' && isStoredValue(expression)
|
|
232
|
+
&& node.arguments.length === 1) {
|
|
233
|
+
const items = listElements(node.arguments[0]);
|
|
234
|
+
if (items !== undefined) return resultText(`#S{${items.map(value => go(value).text).join(', ')}}`, true);
|
|
235
|
+
}
|
|
236
|
+
const entry = constructors.get(node.constructor);
|
|
237
|
+
if (!entry || entry.constructor.fields.length !== node.arguments.length) throw unavailable;
|
|
238
|
+
return constructed(node.constructor, node.arguments.map((value, i) => [entry.constructor.fields[i].name, go(value)]), scope, reserved, isStoredValue(expression));
|
|
239
|
+
}
|
|
240
|
+
case 'let': {
|
|
241
|
+
const member = membership(expression, scope, reserved);
|
|
242
|
+
if (member) return member;
|
|
243
|
+
const record = literal(expression, scope, reserved);
|
|
244
|
+
if (record) return record;
|
|
245
|
+
const bound = bind(node.binder, scope, reserved);
|
|
246
|
+
return resultText(`let ${bound.name} = ${go(node.value).text} in ${go(node.body, bound.scope).text}`);
|
|
247
|
+
}
|
|
248
|
+
case 'field': {
|
|
249
|
+
const entry = constructors.get(node.constructor), field = entry?.constructor.fields[node.index];
|
|
250
|
+
if (!field) throw unavailable;
|
|
251
|
+
return selectedField(entry, field.name, go(node.value), scope, reserved);
|
|
252
|
+
}
|
|
253
|
+
case 'update': {
|
|
254
|
+
const entry = constructors.get(node.constructor), field = entry?.constructor.fields[node.index];
|
|
255
|
+
if (!field) throw unavailable;
|
|
256
|
+
const positions = positionalFields(entry.declaration);
|
|
257
|
+
if (positions) {
|
|
258
|
+
const used = new Set(reserved), replacement = freshComponent('replacement', scope, used);
|
|
259
|
+
const names = positions.map((_, i) => freshComponent(`component${i + 1}`, scope, used));
|
|
260
|
+
const result = positions.map((position, i) => position.name === field.name ? replacement : names[i]);
|
|
261
|
+
return resultText(`let ${replacement} = ${go(node.field).text} in first matching case of ${go(node.value).text}: when (${names.join(', ')}) then (${result.join(', ')}) end case`);
|
|
262
|
+
}
|
|
263
|
+
return resultText(`${argument(go(node.value))} with ${field.name} = ${go(node.field).text}`);
|
|
264
|
+
}
|
|
265
|
+
case 'call': {
|
|
266
|
+
// A checked public set constructor and a literal list have exactly the
|
|
267
|
+
// authoring meaning of #S, including duplicate handling and order.
|
|
268
|
+
if (values.get(node.declaration)?.canonicalName === 'prelude.setOf' && node.arguments.length === 1) {
|
|
269
|
+
const items = listElements(node.arguments[0]);
|
|
270
|
+
if (items !== undefined) return resultText(`#S{${items.map(value => go(value).text).join(', ')}}`, true);
|
|
271
|
+
}
|
|
272
|
+
return resultText(globalName(node.declaration, scope) + (node.arguments.length ? ` ${args(node.arguments)}` : ''));
|
|
273
|
+
}
|
|
274
|
+
case 'helper': return resultText(node.name + (node.arguments.length ? ` ${args(node.arguments)}` : ''));
|
|
275
|
+
case 'binary':
|
|
276
|
+
case 'shortCircuit': return resultText(`(${argument(go(node.left))} ${{ '==': '=', '&&': 'and', '||': 'or' }[node.operator] ?? node.operator} ${argument(go(node.right))})`, true);
|
|
277
|
+
case 'unary': {
|
|
278
|
+
const iteration = node.argument.node, predicate = iteration?.predicate?.node;
|
|
279
|
+
if (node.operator === '!' && iteration?.kind === 'allElements' && predicate?.kind === 'unary' && predicate.operator === '!') {
|
|
280
|
+
const bound = bind(iteration.binder, scope, reserved);
|
|
281
|
+
return resultText(`any ${bound.name} in (${go(iterationCollection(iteration.value)).text}) satisfies (${go(predicate.argument, bound.scope).text})`);
|
|
282
|
+
}
|
|
283
|
+
return resultText(`${node.operator === '!' ? 'not' : node.operator} (${go(node.argument).text})`);
|
|
284
|
+
}
|
|
285
|
+
case 'if': return resultText(`if ${go(node.condition).text} then ${go(node.then).text} else ${go(node.else).text} end if`);
|
|
286
|
+
case 'convert': return resultText(`${node.conversion} conversion of (${go(node.argument).text}) to ${typeName(expression.type)}`);
|
|
287
|
+
case 'match': return resultText(`case ${argument(go(node.value))} of {${node.cases.map(branch => {
|
|
288
|
+
let bindings = scope;
|
|
289
|
+
const names = branch.binders.map(binder => {
|
|
290
|
+
const bound = bind(binder, bindings, reserved);
|
|
291
|
+
bindings = bound.scope;
|
|
292
|
+
return bound.name;
|
|
293
|
+
});
|
|
294
|
+
const entry = constructors.get(branch.constructor);
|
|
295
|
+
if (!entry || entry.constructor.fields.length !== names.length) throw unavailable;
|
|
296
|
+
const positions = positionalFields(entry.declaration);
|
|
297
|
+
const fieldNames = new Map(entry.constructor.fields.map((field, i) => [field.name, names[i]]));
|
|
298
|
+
const pattern = positions ? `(${positions.map(field => fieldNames.get(field.name)).join(', ')})` : entry.declaration.structure?.kind === 'record'
|
|
299
|
+
? `record{${names.map((name, i) => `${entry.constructor.fields[i].name} = ${name}`).join(', ')}}`
|
|
300
|
+
: globalName(branch.constructor, scope) + (names.length ? `(${names.join(', ')})` : '');
|
|
301
|
+
return `${pattern}: ${go(branch.body, bindings).text}`;
|
|
302
|
+
}).join('; ')}}`);
|
|
303
|
+
case 'allElements': {
|
|
304
|
+
const bound = bind(node.binder, scope, reserved);
|
|
305
|
+
return resultText(`every ${bound.name} in (${go(node.value).text}) satisfies (${go(node.predicate, bound.scope).text})`);
|
|
306
|
+
}
|
|
307
|
+
case 'allPayloads': return resultText(`allPayloads (${go(node.value).text}) [${node.predicates.map(predicate => {
|
|
308
|
+
const bound = bind(predicate.binder, scope, reserved);
|
|
309
|
+
return `${bound.name} of type ${typeName(predicate.binder.type)} => ${go(predicate.predicate, bound.scope).text}`;
|
|
310
|
+
}).join('; ')}]`);
|
|
311
|
+
case 'perform': return resultText(`perform ${abilityName(node.ability)}.${node.operation}(${node.arguments.map(value => go(value).text).join(', ')})`);
|
|
312
|
+
case 'handle': {
|
|
313
|
+
if (node.handling === 'catchFailure') return resultText(`catch failure of ${abilityName(node.ability)} in (${go(node.body).text})`);
|
|
314
|
+
if (node.handling === 'withHandler') return resultText(`handle (${go(node.body).text}) with ${node.handler} for ${abilityName(node.ability)}`);
|
|
315
|
+
throw unavailable;
|
|
316
|
+
}
|
|
317
|
+
case 'calls': return resultText(`calls of ${abilityName(node.ability)}.${node.operation}${node.arguments === null ? '' : ` with (${node.arguments.map(value => go(value).text).join(', ')})`}`);
|
|
318
|
+
default: throw unavailable;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return function expressionText(expression, scope = new Map()) {
|
|
322
|
+
try {
|
|
323
|
+
const free = freeLocals(expression);
|
|
324
|
+
const reserved = new Set([...free].filter(([id]) => !scope.has(id)).map(([, name]) => name));
|
|
325
|
+
return render(expression, new Map([...free, ...scope]), reserved).text;
|
|
326
|
+
} catch (error) {
|
|
327
|
+
// Fall back for the entire expression, including its original binders.
|
|
328
|
+
// Mixing renamed binders with opaque child text could capture a local.
|
|
329
|
+
if (error === unavailable) return expression.text;
|
|
330
|
+
throw error;
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
}
|
package/files.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Generated from templates/npm/files.mjs by lawspec-dev generate. Do not edit.
|
|
2
2
|
import {
|
|
3
3
|
readFile,
|
|
4
|
+
readdir,
|
|
5
|
+
stat,
|
|
4
6
|
mkdir,
|
|
5
7
|
writeFile,
|
|
6
8
|
rename,
|
|
@@ -13,6 +15,20 @@ import path from "node:path";
|
|
|
13
15
|
import crypto from "node:crypto";
|
|
14
16
|
export const digest = (text) =>
|
|
15
17
|
crypto.createHash("sha256").update(text).digest("hex");
|
|
18
|
+
// Keep source discovery identical for CLI checking and migration revalidation.
|
|
19
|
+
export async function collectSources(root,entries,relativeTo=root){
|
|
20
|
+
const files=[];
|
|
21
|
+
async function visit(file){
|
|
22
|
+
const info=await stat(file);
|
|
23
|
+
if(info.isDirectory())for(const entry of (await readdir(file)).sort())await visit(path.join(file,entry));
|
|
24
|
+
else if(file.endsWith('.lawspec'))files.push(file);
|
|
25
|
+
}
|
|
26
|
+
if(!Array.isArray(entries)||entries.some(entry=>typeof entry!=='string'))throw new Error('sources must be an array of paths');
|
|
27
|
+
for(const source of entries)await visit(path.resolve(root,source));
|
|
28
|
+
if(!files.length)throw new Error('No .lawspec source files found');
|
|
29
|
+
return Promise.all([...new Set(files)].sort().map(async file=>({
|
|
30
|
+
path:path.relative(relativeTo,file).split(path.sep).join('/'),content:await readFile(file,'utf8')})));
|
|
31
|
+
}
|
|
16
32
|
export async function readOptional(file) {
|
|
17
33
|
try {
|
|
18
34
|
return await readFile(file, "utf8");
|