lawspec 0.24.0 → 0.26.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.
Files changed (148) hide show
  1. package/CHANGELOG.md +109 -1
  2. package/README.md +34 -26
  3. package/UNICODE-LICENSE.txt +39 -0
  4. package/api.mjs +6 -23
  5. package/bin/lawspec.mjs +148 -65
  6. package/build.json +245 -177
  7. package/builtin-data-names.mjs +73 -0
  8. package/core.wasm +2 -2
  9. package/core_jsffi.js +5 -0
  10. package/examples/native-payments/clojure/lawspec.json +13 -2
  11. package/examples/native-payments/csharp/lawspec.json +13 -2
  12. package/examples/native-payments/elixir/lawspec.json +14 -3
  13. package/examples/native-payments/erlang/lawspec.json +14 -3
  14. package/examples/native-payments/fsharp/lawspec.json +14 -3
  15. package/examples/native-payments/gleam/lawspec.json +14 -3
  16. package/examples/native-payments/go/lawspec.json +14 -3
  17. package/examples/native-payments/groovy/lawspec.json +14 -3
  18. package/examples/native-payments/haskell/lawspec.json +14 -3
  19. package/examples/native-payments/java/lawspec.json +14 -3
  20. package/examples/native-payments/javascript/lawspec.json +14 -3
  21. package/examples/native-payments/kotlin/lawspec.json +14 -3
  22. package/examples/native-payments/python/lawspec.json +14 -3
  23. package/examples/native-payments/rust/lawspec.json +14 -3
  24. package/examples/native-payments/scala/lawspec.json +14 -3
  25. package/examples/native-payments/swift/lawspec.json +14 -3
  26. package/examples/native-payments/typescript/lawspec.json +14 -3
  27. package/examples/packages/orders/lawspec.json +25 -5
  28. package/examples/packages/orders/orders.lawspec +57 -53
  29. package/examples/packages/shop-domain/src/domain.lawspec +36 -33
  30. package/examples/packages/shop-tax-1/src/api.lawspec +1 -0
  31. package/examples/packages/shop-tax-1/src/rates.lawspec +5 -4
  32. package/examples/packages/shop-tax-2/src/api.lawspec +1 -0
  33. package/examples/packages/shop-tax-2/src/rates.lawspec +6 -4
  34. package/examples/rc1/authorization-snapshots.lawspec +113 -0
  35. package/examples/rc1/banner-filenames.lawspec +64 -0
  36. package/examples/rc1/bit-codec.lawspec +57 -0
  37. package/examples/rc1/bounded-witness-search.lawspec +151 -0
  38. package/examples/rc1/conflicting-requirements.lawspec +31 -0
  39. package/examples/rc1/constructive-witnesses.lawspec +120 -0
  40. package/examples/rc1/documentary-review.lawspec +43 -0
  41. package/examples/rc1/empty-domains.lawspec +47 -0
  42. package/examples/rc1/finite-integer-domains.lawspec +76 -0
  43. package/examples/rc1/law-metadata.lawspec +30 -0
  44. package/examples/rc1/native-payments.lawspec +108 -0
  45. package/examples/rc1/nesting/rrr.lawspec +34 -0
  46. package/examples/rc1/nesting/rru.lawspec +57 -0
  47. package/examples/rc1/nesting/rur.lawspec +58 -0
  48. package/examples/rc1/nesting/ruu.lawspec +78 -0
  49. package/examples/rc1/nesting/urr.lawspec +53 -0
  50. package/examples/rc1/nesting/uru.lawspec +73 -0
  51. package/examples/rc1/nesting/uur.lawspec +74 -0
  52. package/examples/rc1/nesting/uuu.lawspec +96 -0
  53. package/examples/rc1/order-workflow.lawspec +127 -0
  54. package/examples/rc1/parcel-measurements.lawspec +93 -0
  55. package/examples/rc1/picture-records.lawspec +52 -0
  56. package/examples/rc1/picture-tuples.lawspec +48 -0
  57. package/examples/rc1/record-payloads.lawspec +57 -0
  58. package/examples/rc1/recursive-records.lawspec +65 -0
  59. package/examples/rc1/refund-conformance.lawspec +45 -0
  60. package/examples/rc1/refund-policy.lawspec +89 -0
  61. package/examples/rc1/requirement-composition.lawspec +90 -0
  62. package/examples/rc1/structural-records.lawspec +54 -0
  63. package/examples/rc1-authoring.lawspec +57 -0
  64. package/examples/specs/abilities.lawspec +67 -65
  65. package/examples/specs/ability_imports.lawspec +58 -57
  66. package/examples/specs/actors.lawspec +23 -22
  67. package/examples/specs/algebra.lawspec +142 -141
  68. package/examples/specs/approvals.lawspec +16 -15
  69. package/examples/specs/async_bindings.lawspec +10 -9
  70. package/examples/specs/async_fetch.lawspec +12 -11
  71. package/examples/specs/atoi_codec.lawspec +16 -15
  72. package/examples/specs/boolean_flags.lawspec +10 -9
  73. package/examples/specs/builtins.lawspec +73 -72
  74. package/examples/specs/canonical_url.lawspec +14 -13
  75. package/examples/specs/collections.lawspec +153 -154
  76. package/examples/specs/composition.lawspec +70 -66
  77. package/examples/specs/concurrent_collections.lawspec +8 -7
  78. package/examples/specs/consistency.lawspec +4 -3
  79. package/examples/specs/contracts.lawspec +80 -79
  80. package/examples/specs/crypto.lawspec +26 -25
  81. package/examples/specs/ctc.lawspec +148 -0
  82. package/examples/specs/currying.lawspec +32 -31
  83. package/examples/specs/data_types.lawspec +50 -49
  84. package/examples/specs/distribution.lawspec +57 -56
  85. package/examples/specs/domain_modeling.lawspec +48 -47
  86. package/examples/specs/durations.lawspec +39 -38
  87. package/examples/specs/equivalent.lawspec +25 -24
  88. package/examples/specs/failures.lawspec +64 -63
  89. package/examples/specs/finite_data.lawspec +32 -31
  90. package/examples/specs/flow_stack.lawspec +64 -63
  91. package/examples/specs/gadt_expressions.lawspec +50 -49
  92. package/examples/specs/generation.lawspec +115 -114
  93. package/examples/specs/handler_bindings.lawspec +42 -40
  94. package/examples/specs/handles.lawspec +2 -1
  95. package/examples/specs/harness.lawspec +45 -43
  96. package/examples/specs/harness_testing.lawspec +18 -13
  97. package/examples/specs/indexed_arithmetic.lawspec +401 -126
  98. package/examples/specs/indexed_families.lawspec +182 -66
  99. package/examples/specs/keywords.lawspec +22 -21
  100. package/examples/specs/limits.lawspec +6 -5
  101. package/examples/specs/list_contracts.lawspec +121 -120
  102. package/examples/specs/list_refinements.lawspec +43 -42
  103. package/examples/specs/lists.lawspec +45 -44
  104. package/examples/specs/matchers.lawspec +79 -78
  105. package/examples/specs/matching.lawspec +43 -42
  106. package/examples/specs/mixed_inputs.lawspec +25 -24
  107. package/examples/specs/models.lawspec +44 -43
  108. package/examples/specs/parse_port.lawspec +28 -27
  109. package/examples/specs/payments.lawspec +55 -54
  110. package/examples/specs/railway.lawspec +59 -58
  111. package/examples/specs/records.lawspec +149 -148
  112. package/examples/specs/records_inner.lawspec +5 -4
  113. package/examples/specs/recursive_refinements.lawspec +30 -29
  114. package/examples/specs/refined_definitions.lawspec +24 -23
  115. package/examples/specs/refinements.lawspec +58 -57
  116. package/examples/specs/resilience.lawspec +159 -158
  117. package/examples/specs/resources.lawspec +61 -60
  118. package/examples/specs/scalar_adapters.lawspec +60 -59
  119. package/examples/specs/scalar_catalog.lawspec +165 -164
  120. package/examples/specs/scalars.lawspec +78 -77
  121. package/examples/specs/scheduling_order.lawspec +8 -7
  122. package/examples/specs/scheduling_overlap.lawspec +5 -4
  123. package/examples/specs/sequences.lawspec +66 -65
  124. package/examples/specs/sessions.lawspec +13 -12
  125. package/examples/specs/slug.lawspec +16 -15
  126. package/examples/specs/sum_refinements.lawspec +42 -41
  127. package/examples/specs/tables.lawspec +29 -28
  128. package/examples/specs/total_functions.lawspec +71 -70
  129. package/examples/specs/workflows.lawspec +101 -100
  130. package/examples-command.mjs +8 -4
  131. package/explain.mjs +114 -0
  132. package/expression-presentation.mjs +333 -0
  133. package/files.mjs +16 -0
  134. package/index.d.ts +406 -11
  135. package/launcher.mjs +9 -2
  136. package/lsp.mjs +235 -0
  137. package/native-evidence.mjs +187 -0
  138. package/native-examples.mjs +8 -1
  139. package/node-events-reporter.mjs +23 -0
  140. package/package.json +8 -1
  141. package/positional-fields.mjs +13 -0
  142. package/proof.d.ts +35 -0
  143. package/proof.mjs +174 -0
  144. package/starter-rc1.lawspec +26 -0
  145. package/starter.lawspec +16 -15
  146. package/templates.mjs +6 -4
  147. package/test-command.mjs +107 -35
  148. package/typed-presentation.mjs +165 -0
package/explain.mjs ADDED
@@ -0,0 +1,114 @@
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 exampleName = name => name.startsWith('"|') && name.endsWith('|') ? name
8
+ : '"|' + name.replace(/\\/gu, '\\\\').replace(/\|/gu, '\\|') + '|';
9
+ const presentationProposition = ({ typeName, expressionText }, inputs) => function proposition(assertion, business = false, scope = inputs) {
10
+ const term = expression => expressionText(expression, scope);
11
+ const recurse = (body, wording = business) => proposition(body, wording, scope);
12
+ switch (assertion.kind) {
13
+ case 'equal': return `${term(assertion.left)} ${business ? 'must be' : '='} ${term(assertion.right)}`;
14
+ case 'implies': return business
15
+ ? `If ${term(assertion.guard)}, then ${recurse(assertion.body, true)}`
16
+ : `(${term(assertion.guard)}) implies (${recurse(assertion.body)})`;
17
+ case 'all': return assertion.items.map(a => `(${recurse(a)})`).join(' and ');
18
+ case 'not': {
19
+ // The compiler's ordinary negation/conjunction representation also
20
+ // expresses disjunction and implications with proposition premises.
21
+ const items = assertion.body.kind === 'all' ? assertion.body.items : [];
22
+ if (items.length > 1 && items.every(item => item.kind === 'not'))
23
+ return items.map(item => `(${recurse(item.body)})`).join(' or ');
24
+ if (items.length === 2 && items[1].kind === 'not') return business
25
+ ? `If (${recurse(items[0], true)}), then (${recurse(items[1].body, true)})`
26
+ : `(${recurse(items[0])}) implies (${recurse(items[1].body)})`;
27
+ return business && assertion.body.kind === 'exists'
28
+ ? recurse(assertion.body, true).replace(/^There must exist/, 'There must not exist')
29
+ : `${business ? 'Must not' : 'not'} (${recurse(assertion.body, false)})`;
30
+ }
31
+ case 'forall':
32
+ case 'exists': {
33
+ const universal = assertion.kind === 'forall';
34
+ const binder = `${assertion.binder.name} of type ${typeName(assertion.binder.type)}`;
35
+ const nested = new Map([...scope, [assertion.binder.id, assertion.binder.name]]);
36
+ const restrictions = assertion.predicates.map(p => expressionText(p, nested));
37
+ const restricted = restrictions.length ? ` where ${restrictions.join(' and ')}` : '';
38
+ if (business) return `${universal ? 'For every' : 'There must exist'} ${binder}${restricted}, ${proposition(assertion.body, true, nested)}`;
39
+ return `${universal ? 'for all' : 'there exists'} (${binder}${restricted}) ${universal ? '=>' : 'such that'}\n${proposition(assertion.body, false, nested)}\nend ${universal ? 'for all' : 'exists'}`;
40
+ }
41
+ default: throw new Error(`Unsupported typed assertion ${assertion.kind}`);
42
+ }
43
+ };
44
+ export function explainLaw(law, result, view = 'developer') {
45
+ if (!explanationViews.includes(view)) throw new Error(`Choose --view ${explanationViews.join('|')}`);
46
+ const presentation = createTypePresentation(result);
47
+ const { typeName, expressionText, valueText } = presentation;
48
+ const examples = law.examples ?? [];
49
+ const scope = new Map(law.inputs.map(input => [input.id, input.name]));
50
+ const proposition = presentationProposition(presentation, scope);
51
+ const evidence = (result.evidence ?? []).filter(e => e.declaration === law.id);
52
+ const quantifiers = law.inputs.map(input => `${input.name} of type ${typeName(input.type)}`);
53
+ const restrictions = law.inputs.flatMap(input => input.predicates.map(p => expressionText(p, scope)));
54
+ const metadata = law.metadata ?? {};
55
+ const references = law.references ?? [];
56
+ const witnesses = law.harness?.witnesses ?? [];
57
+ const searches = law.harness?.searches ?? [];
58
+ const strategies = [
59
+ ...witnesses.map(witness => `Configured witness (not completed evidence): definition.${witness.path.join('.')} = ${expressionText(witness.expression, scope)}`),
60
+ ...searches.map(search => `Configured search (not completed evidence): definition.${search.path.join('.')} uses ${search.strategy}`),
61
+ ];
62
+ const documentary = [metadata.id === undefined ? '' : `Requirement: ${metadata.id}`,
63
+ metadata.owner === undefined ? '' : `Owner: ${metadata.owner}`,
64
+ ...references.map(reference => `Reference: ${referenceText(reference)}`)].filter(Boolean);
65
+ let text;
66
+ if (view === 'evidence') text = evidence.length
67
+ ? evidence.map(e => `${e.status.toUpperCase()}: ${e.reason}`+(e.nativeEvidence?'\n'+nativeEvidenceText(e):'')).join('\n')
68
+ : 'No completed evidence has been supplied for this law.';
69
+ else if (view === 'business') text = [...documentary, law.description,
70
+ quantifiers.length ? `For every ${quantifiers.join(' and ')}` : '',
71
+ restrictions.length ? `When ${restrictions.join(' and ')}` : '',
72
+ proposition(law.assertion, true), law.rationale ? `Reason: ${law.rationale}` : ''].filter(Boolean).join('\n');
73
+ else if (view === 'formal') text = [quantifiers.length ? `for all (${quantifiers.join(') (')}) =>` : '',
74
+ restrictions.length ? `(${restrictions.join(' and ')}) implies` : '',
75
+ proposition(law.assertion), ...(quantifiers.length ? ['end for all'] : [])].filter(Boolean).join('\n');
76
+ else text = [law.id, ...documentary, ...law.trace, ...strategies,
77
+ ...(quantifiers.length ? [`Inputs: ${quantifiers.join('; ')}`] : []),
78
+ ...(restrictions.length ? [`Restrictions: ${restrictions.join(' and ')}`] : []), proposition(law.assertion),
79
+ `Source: ${law.location.file}:${law.location.line}:${law.location.column}`,
80
+ `Examples: ${examples.length}`,
81
+ ...examples.flatMap(example => {
82
+ const locals = new Map([...scope, ...example.bindings.map(binding => [binding.id, binding.name])]);
83
+ return [`example ${exampleName(example.name)}:`,
84
+ ...example.bindings.map(binding => ` ${binding.name} = ${valueText(binding.value, locals)}`),
85
+ ...example.expectations.map(expectation => ` expect ${proposition(expectation, false, locals)}`), 'end example'];
86
+ })].join('\n');
87
+ if(view==='developer')for(const item of evidence)if(item.nativeEvidence)text+='\n'+nativeEvidenceText(item);
88
+ if (view === 'evidence' && strategies.length) text += '\n' + strategies.join('\n');
89
+ return { view, law: law.id, metadata, references, witnesses, searches, examples, inputs: law.inputs, assertion: law.assertion, evidence, text };
90
+ }
91
+ function referenceText(reference) {
92
+ if (typeof reference === 'string') return reference;
93
+ if (reference.kind === 'external') return `${reference.name ? `${reference.name}: ` : ''}${reference.resource}`;
94
+ const selector = reference.selector;
95
+ const section = selector?.kind === 'named-reference' ? ` references.${selector.name}` : selector ? ` ${selector.kind}` : '';
96
+ const raw = reference.target.name;
97
+ // Built-in laws retain legacy source names internally; present their
98
+ // canonical phrase spelling just as ordinary authored names are presented.
99
+ const name = raw.startsWith('"|') || /^\p{L}[\p{L}\p{N}_]*$/u.test(raw)
100
+ ? raw : `"|${raw.replace(/[\\|]/g, '\\$&')}|`;
101
+ return `ref ${reference.kind} ${reference.target.unit}.${name}${section}`;
102
+ }
103
+
104
+ export function nativeEvidenceText(item){
105
+ if(!item.nativeEvidence)return '';
106
+ const summary=item.nativeEvidence;
107
+ return [`Native conformance: ${summary.status}; search completeness: ${summary.searchCompleteness}`,
108
+ ...summary.observations.map(row=>`${row.target} (${row.root}): ${row.outcome}; ${row.freshness}`+
109
+ (row.attempt?`; seed ${row.attempt.seed}; ${row.attempt.at}`:'')+`; ${row.reason}`),
110
+ ...summary.observations.flatMap(row=>(row.attempt?.tests??[]).filter(test=>test.status==='failed')
111
+ .map(test=>`${test.name}: ${test.reason??test.failure??test.message??'native test failed'}`)),
112
+ ...summary.observations.filter(row=>row.attempt?.invocation.output)
113
+ .map(row=>'Native invocation output (scoped to that invocation):\n'+row.attempt.invocation.output)].join('\n');
114
+ }
@@ -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(', ')})` + ' end let'.repeat(lets.length));
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} end let`);
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 end let`);
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(`first matching case of ${argument(go(node.value))}: ${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 `when ${pattern} then ${go(branch.body, bindings).text}`;
302
+ }).join(' ')} end case`);
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)} end handle`);
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
+ // Share source discovery between CLI commands.
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");