lawspec 0.30.0 → 0.31.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 (78) hide show
  1. package/CHANGELOG.md +377 -1
  2. package/README.md +9 -3
  3. package/api.mjs +1 -0
  4. package/beam-doctor.mjs +2 -2
  5. package/bin/lawspec.mjs +93 -95
  6. package/build.json +497 -405
  7. package/component-packages.mjs +339 -0
  8. package/component.d.ts +46 -0
  9. package/component.mjs +208 -0
  10. package/core.wasm +2 -2
  11. package/core_jsffi.js +5 -5
  12. package/examples/native-payments/clojure/lawspec.edn +48 -0
  13. package/examples/native-payments/clojure/src/domain/payments.clj +1 -1
  14. package/examples/native-payments/clojure/test/domain/payment_generators.clj +1 -1
  15. package/examples/native-payments/csharp/lawspec.edn +48 -0
  16. package/examples/native-payments/elixir/lawspec.edn +123 -0
  17. package/examples/native-payments/erlang/lawspec.edn +128 -0
  18. package/examples/native-payments/fsharp/lawspec.edn +123 -0
  19. package/examples/native-payments/gleam/lawspec.edn +123 -0
  20. package/examples/native-payments/go/lawspec.edn +123 -0
  21. package/examples/native-payments/groovy/lawspec.edn +123 -0
  22. package/examples/native-payments/haskell/lawspec.edn +123 -0
  23. package/examples/native-payments/java/lawspec.edn +123 -0
  24. package/examples/native-payments/javascript/lawspec.edn +123 -0
  25. package/examples/native-payments/kotlin/lawspec.edn +123 -0
  26. package/examples/native-payments/prolog/lawspec.edn +48 -0
  27. package/examples/native-payments/python/lawspec.edn +123 -0
  28. package/examples/native-payments/rust/lawspec.edn +124 -0
  29. package/examples/native-payments/scala/lawspec.edn +123 -0
  30. package/examples/native-payments/swift/lawspec.edn +123 -0
  31. package/examples/native-payments/typescript/lawspec.edn +123 -0
  32. package/examples/packages/orders/lawspec.edn +25 -0
  33. package/examples/packages/shop-domain/lawspec.edn +13 -0
  34. package/examples/packages/shop-tax-1/lawspec.edn +9 -0
  35. package/examples/packages/shop-tax-2/lawspec.edn +9 -0
  36. package/examples/specs/handler_bindings.lawspec +2 -2
  37. package/files.mjs +2 -1
  38. package/go.mod +4 -0
  39. package/index.d.ts +135 -2
  40. package/input-files.mjs +47 -0
  41. package/launcher.mjs +33 -13
  42. package/lsp.mjs +10 -5
  43. package/native-evidence.mjs +50 -15
  44. package/native-examples.mjs +8 -7
  45. package/native-host.mjs +71 -0
  46. package/package.json +8 -3
  47. package/proof.d.ts +8 -2
  48. package/proof.mjs +183 -31
  49. package/scala-build-state.mjs +59 -0
  50. package/templates.mjs +242 -2
  51. package/test-command.mjs +192 -60
  52. package/builtin-data-names.mjs +0 -73
  53. package/examples/native-payments/clojure/lawspec.json +0 -62
  54. package/examples/native-payments/csharp/lawspec.json +0 -62
  55. package/examples/native-payments/elixir/lawspec.json +0 -160
  56. package/examples/native-payments/erlang/lawspec.json +0 -159
  57. package/examples/native-payments/fsharp/lawspec.json +0 -178
  58. package/examples/native-payments/gleam/lawspec.json +0 -160
  59. package/examples/native-payments/go/lawspec.json +0 -147
  60. package/examples/native-payments/groovy/lawspec.json +0 -176
  61. package/examples/native-payments/haskell/lawspec.json +0 -160
  62. package/examples/native-payments/java/lawspec.json +0 -176
  63. package/examples/native-payments/javascript/lawspec.json +0 -160
  64. package/examples/native-payments/kotlin/lawspec.json +0 -176
  65. package/examples/native-payments/prolog/lawspec.json +0 -20
  66. package/examples/native-payments/python/lawspec.json +0 -160
  67. package/examples/native-payments/rust/lawspec.json +0 -178
  68. package/examples/native-payments/scala/lawspec.json +0 -176
  69. package/examples/native-payments/swift/lawspec.json +0 -165
  70. package/examples/native-payments/typescript/lawspec.json +0 -160
  71. package/examples/packages/orders/lawspec.json +0 -27
  72. package/examples/packages/shop-domain/lawspec-package.json +0 -7
  73. package/examples/packages/shop-tax-1/lawspec-package.json +0 -5
  74. package/examples/packages/shop-tax-2/lawspec-package.json +0 -5
  75. package/explain.mjs +0 -114
  76. package/expression-presentation.mjs +0 -333
  77. package/positional-fields.mjs +0 -13
  78. package/typed-presentation.mjs +0 -165
@@ -1,333 +0,0 @@
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
- }
@@ -1,13 +0,0 @@
1
- // Generated from templates/npm/positional-fields.mjs by lawspec-dev generate. Do not edit.
2
- // Positions come from checked compiler metadata, never from guessing labels.
3
- export function positionalFields(declaration) {
4
- const structure = declaration?.structure, constructors = declaration?.constructors;
5
- const positions = structure?.positions;
6
- if (structure?.kind !== 'record' || !Array.isArray(positions) || positions.length < 2
7
- || constructors?.length !== 1 || new Set(positions).size !== positions.length) return undefined;
8
- const fields = constructors[0].fields;
9
- if (fields.length !== positions.length) return undefined;
10
- const byName = new Map(fields.map(field => [field.name, field]));
11
- if (byName.size !== positions.length || !positions.every(label => byName.has(label))) return undefined;
12
- return positions.map(label => byName.get(label));
13
- }
@@ -1,165 +0,0 @@
1
- // Generated from templates/npm/typed-presentation.mjs by lawspec-dev generate. Do not edit.
2
- // Presentation only: identities, constraints and proof evidence remain in Core.
3
- // In particular, a nominal record is never expanded into a structural product.
4
- import { createExpressionPresentation } from './expression-presentation.mjs';
5
- import { builtinDataNames } from './builtin-data-names.mjs';
6
- import { showScalar } from './scalars.mjs';
7
- import { positionalFields } from './positional-fields.mjs';
8
-
9
- export function createTypePresentation(result) {
10
- const declarations = new Map([...builtinDataNames, ...(result.dataTypes ?? [])].map(d => [d.id, d]));
11
- const constructors = new Map([...declarations.values()].flatMap(d =>
12
- d.constructors.map(c => [c.id, { declaration: d, constructor: c }])));
13
- const shortName = name => ({ BigUInt: 'Whole', BigInt: 'Integer', Natural: 'Whole' })[name]
14
- ?? declarations.get(name)?.name ?? name.split('::type::').at(-1);
15
- const names = new Map();
16
- for (const d of declarations.values()) {
17
- const name = shortName(d.id);
18
- names.set(name, (names.get(name) ?? 0) + 1);
19
- }
20
- const nominalName = name => {
21
- const display = shortName(name), separator = name.indexOf('::type::');
22
- return names.get(display) > 1 && separator >= 0
23
- ? `${name.slice(0, separator)}.${display}` : display;
24
- };
25
-
26
- // The compiler marks ordinary checked recursive representation definitions.
27
- // Names alone do not authorize hiding a call, and its full signature must
28
- // agree with the typed application. The wire assertion is never rewritten.
29
- const recursiveViews = new Map((result.units ?? []).flatMap(unit => unit.declarations
30
- .filter(d => d.representation === 'structural-record-storage' && d.source === undefined
31
- && d.origin?.kind === 'generated' && d.origin.declaration === d.id && d.type.kind === 'function')
32
- .map(d => [d.id, d.type])));
33
- function sameType(left, right) {
34
- if (!left || !right || left.kind !== right.kind) return false;
35
- if (left.kind === 'variable') return left.id === right.id;
36
- if (left.kind === 'function') return sameType(left.parameter, right.parameter) && sameType(left.result, right.result);
37
- if (left.kind !== 'constructor' || left.name !== right.name || left.arguments.length !== right.arguments.length) return false;
38
- return left.arguments.every((a, i) => {
39
- const b = right.arguments[i];
40
- return a.kind === b.kind && (a.kind === 'type' ? sameType(a.type, b.type)
41
- : a.kind === 'natural' ? a.value === b.value : a.kind === 'indexVariable' && a.id === b.id);
42
- });
43
- }
44
-
45
- // Recognize only compiler-generated storage views which copy every field in
46
- // order. Do not simplify user matches, erase conversions or discard unused
47
- // constructor arguments: those may contain checks or undefined computations.
48
- function storageView(expression) {
49
- const node = expression.node;
50
- if (node?.kind === 'call') {
51
- const signature = recursiveViews.get(node.declaration);
52
- return signature && node.arguments.length === 1
53
- && sameType(signature.parameter, node.arguments[0].type) && sameType(signature.result, expression.type)
54
- ? node.arguments[0] : undefined;
55
- }
56
- if (node?.kind !== 'match' || node.cases.length !== 1) return undefined;
57
- const branch = node.cases[0], body = branch.body.node;
58
- const source = constructors.get(branch.constructor), target = constructors.get(body?.constructor);
59
- if (body?.kind !== 'construct' || !source || !target
60
- || source.declaration.structure?.kind !== 'record' || target.declaration.structure?.kind !== 'record'
61
- || expression.origin?.kind !== 'generated'
62
- || !branch.binders.length || !branch.binders.every(b => b.id.startsWith('lawspec::record-view::'))
63
- || branch.binders.length !== source.constructor.fields.length
64
- || body.arguments.length !== branch.binders.length
65
- || target.constructor.fields.length !== branch.binders.length) return undefined;
66
- for (let i = 0; i < branch.binders.length; i++) {
67
- if (source.constructor.fields[i].name !== target.constructor.fields[i].name) return undefined;
68
- let argument = body.arguments[i], unwrapped;
69
- while ((unwrapped = storageView(argument)) !== undefined) argument = unwrapped;
70
- if (argument.node?.kind !== 'local' || argument.node.id !== branch.binders[i].id) return undefined;
71
- }
72
- return node.value;
73
- }
74
-
75
- function expressionText(expression, locals) {
76
- const view = storageView(expression);
77
- if (view) return expressionText(view, locals);
78
- const node = expression.node;
79
- switch (node?.kind) {
80
- case 'local': return locals.get(node.id) ?? expression.text;
81
- case 'field': {
82
- const field = constructors.get(node.constructor)?.constructor.fields[node.index];
83
- if (!field) return expression.text;
84
- let value = node.value, unwrapped;
85
- while ((unwrapped = storageView(value)) !== undefined) value = unwrapped;
86
- const text = expressionText(value, locals);
87
- return `${['local', 'field'].includes(value.node?.kind) ? text : `(${text})`}.${field.name}`;
88
- }
89
- case 'binary':
90
- case 'shortCircuit': return `(${expressionText(node.left, locals)} ${{ '==': '=', '&&': 'and', '||': 'or' }[node.operator] ?? node.operator} ${expressionText(node.right, locals)})`;
91
- case 'unary': return `${node.operator === '!' ? 'not' : node.operator} (${expressionText(node.argument, locals)})`;
92
- // Keep unfamiliar expressions verbatim; never omit a restriction because
93
- // a presentation does not yet know its typed node.
94
- default: return expression.text;
95
- }
96
- }
97
-
98
- function typeName(type, substitutions = new Map(), active = new Set()) {
99
- if (type.kind === 'variable') {
100
- const replacement = substitutions.get(type.id);
101
- return replacement ? typeName(replacement) : type.id;
102
- }
103
- if (type.kind === 'function') return `(${typeName(type.parameter, substitutions, active)} -> ${typeName(type.result, substitutions, active)})`;
104
- if (type.kind !== 'constructor') return type.id;
105
- const declaration = declarations.get(type.name);
106
- const argumentsText = () => type.arguments.map(a => {
107
- if (a.kind !== 'type') return a.value ?? a.id;
108
- const text = typeName(a.type, substitutions, active);
109
- return a.type.kind === 'constructor' && a.type.arguments.length ? `(${text})` : text;
110
- }).join(' ');
111
- const named = () => nominalName(type.name) + (type.arguments.length ? ` ${argumentsText()}` : '');
112
- if (declaration?.structure?.kind !== 'record' || active.has(type.name)) return named();
113
- const constructor = declaration.constructors[0];
114
- const bindings = new Map(substitutions);
115
- declaration.parameters.forEach((parameter, i) => {
116
- const argument = type.arguments[i];
117
- if (argument?.kind === 'type') bindings.set(parameter, substitute(argument.type, substitutions));
118
- });
119
- const nested = new Set([...active, type.name]);
120
- const positions = positionalFields(declaration);
121
- const ordered = positions ?? constructor.fields;
122
- const locals = new Map(ordered.map((f, index) => [f.id, positions ? `component${index + 1}` : f.name]));
123
- const fields = ordered.map(field => {
124
- const base = typeName(field.type, bindings, nested);
125
- const predicates = declaration.structure.fields.find(f => f.name === field.name)?.predicates ?? [];
126
- const name = locals.get(field.id);
127
- const refined = predicates.length
128
- ? `(${name} of type ${base} where ${predicates.map(p => expressionText(p, locals)).join(' and ')})`
129
- : base;
130
- return positions ? refined : `${field.name} of type ${refined}`;
131
- });
132
- if (positions) return `(${fields.join(', ')})`;
133
- return `record{${fields.join(', ')}}`;
134
- }
135
- function substitute(type, bindings) {
136
- if (type.kind === 'variable') return bindings.get(type.id) ?? type;
137
- if (type.kind === 'function') return { ...type, parameter: substitute(type.parameter, bindings), result: substitute(type.result, bindings) };
138
- if (type.kind === 'constructor') return { ...type, arguments: type.arguments.map(a => a.kind === 'type'
139
- ? { ...a, type: substitute(a.type, bindings) } : a) };
140
- return type;
141
- }
142
- // Only concrete bindings have already passed the compiler's stored-value
143
- // validation. Keep that fact outside the wire expression objects.
144
- const storedValues = new WeakSet();
145
- const checkedExpressionText = createExpressionPresentation(result, { constructors, typeName, storageView,
146
- isStoredValue: expression => storedValues.has(expression) });
147
- // Example bindings are already checked concrete values. Render their stored
148
- // structure through the same constructor metadata; do not execute anything.
149
- function valueExpression(value) {
150
- const text = JSON.stringify(value);
151
- if (value?.kind === 'data') {
152
- const expression = {type: value.type, text,
153
- node: {kind: 'construct', constructor: value.constructor,
154
- arguments: value.fields.map(valueExpression)}};
155
- storedValues.add(expression);
156
- return expression;
157
- }
158
- return {type: {kind: 'constructor', name: value.type, arguments: []},
159
- text: showScalar(value), node: {kind: 'constant', value}};
160
- }
161
- function valueText(value, scope = new Map()) {
162
- return checkedExpressionText(valueExpression(value), scope);
163
- }
164
- return { typeName, expressionText: checkedExpressionText, valueText };
165
- }